body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I ran into a problem, I'm using MyIsam tables in mysql database, using PDO to connect.</p>
<p>In all my tests (calling for 1 user everything works fine), now having around 300 users connected at the same time all day making requests is really really slowing down mySQL. Ive got my.cnf with (key_buffer=512M and max_connections=200) my server is VPS with 2GB RAM and 3 cores. And each table has around 40K records</p>
<p>All queries/updates/inserts are super slow, but I've discovered that this PHP file is the root of the problem, it's requested every 10 seconds for every user (not at the same time, and if the call fails it's delayed another 10 seconds):</p>
<pre><code> //User Info -----------------------
$sqlcommand = "SELECT * FROM tbl_User WHERE FB_ID='". $FB_ID . "'";
$statement = $pdo->query($sqlcommand);
$row = $statement->fetch(PDO::FETCH_ASSOC);
if($row) {
//Do its thing
}
//How Many Gifts are there-----------------
$sqlcommand = "SELECT * FROM tbl_Gifts_Sent WHERE FB_ID='". $FB_ID . "'";
$statement = $pdo->query($sqlcommand);
$row = $statement->fetchAll();
if (!$row) {
$amountOfGifts=0;
} else {
foreach ($pdo->query($sqlcommand) as $row){
$amountOfGifts=$amountOfGifts+1;
}
}
//Daily Leaderboard King---------------
$sqlcommand = "SELECT * FROM tbl_Leaderboard_DAY WHERE Today = " . $midnight . " ORDER BY XP_Gain DESC";
$statement = $pdo->query($sqlcommand);
$row = $statement->fetch(PDO::FETCH_ASSOC);
if ($row) {
//Do its thing
}
//-------- THE STATE ON ALL Themes WITH GIFTS AND ALL
$sqlcommand = "SELECT * FROM tbl_User_Reel WHERE FB_ID='". $FB_ID . "'";
foreach ($pdo->query($sqlcommand) as $db_gmInfo){
//DO its thing
}
</code></pre>
<p>this 4 queries are on the same php file.</p>
<p>Im a newbie in this and this is my first php mysql project, so I'm thinking there's gotta be a better way to do this, :S any recommendations, help or pointers on how to make it work super fast are greatly appreciated! thank you</p>
|
[] |
[
{
"body": "<p>One thing I can see right off the bat is that you're likely to be selecting more data than you need. A good rule of thumb is to <em>never</em> use <code>SELECT * FROM</code>. Only select the columns that you need for your query.</p>\n\n<p>For example, in your gifts query you could change the query to <code>\"SELECT COUNT(*) FROM tbl_Gifts_Sent WHERE FB_ID='\". $FB_ID . \"'\";</code> and only ever get one row with one field to check. You could then use <code>$row = $statement->fetch(PDO::FETCH_NUM);</code> and examine <code>$row[0]</code> to find out whether there are any rows that match that <code>$FB_ID</code> and use that value for <code>$amountOfGifts</code>. That will save you from loading too much data (all the fields in <code>tbl_Gifts_Sent</code> as well as saving you from looping over a potentially large resultset in PHP (much slower than letting MySQL do the work). Revised full (untested) code below:</p>\n\n<pre><code>//How Many Gifts are there----------------- \n $sqlcommand = \"SELECT COUNT(*) FROM tbl_Gifts_Sent WHERE FB_ID='\". $FB_ID . \"'\";\n\n $statement = $pdo->query($sqlcommand);\n $row = $statement->fetch();\n\n if (!$row) {\n $amountOfGifts=0;\n } else {\n $amountOfGifts = $row[0];\n }\n</code></pre>\n\n<p>Also, I don't know where you're getting your query variables like <code>$FB_ID</code>, but it's probably a bad idea to trust them not to be <a href=\"http://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow\">SQL Injection</a> vectors. You should probably be using <a href=\"http://www.php.net/manual/en/pdo.prepare.php\" rel=\"nofollow\">PDO::prepare</a> to build your statements; that will at least minimise the injection risk.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T21:32:22.273",
"Id": "40298",
"Score": "0",
"body": "Thanks Cori I'll definitely try it out :) thanks for the PDO::prepare comment, I'll also check it out."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:32:18.380",
"Id": "26043",
"ParentId": "25993",
"Score": "1"
}
},
{
"body": "<p>Followed Cori's suggestions to prevent SQL Injections\nbut what really sped up mySQL was that the column FB_ID was not indexed, after I modified my code to not search for FB_ID but rather the ID (primary,indexed,autoincrement) mysql results suddenly became MUCH faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T15:27:05.427",
"Id": "26108",
"ParentId": "25993",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T17:07:11.423",
"Id": "25993",
"Score": "2",
"Tags": [
"php",
"mysql",
"pdo"
],
"Title": "PHP PDO mysql multiple queries mak"
}
|
25993
|
<p>I am creating new elements for a webpage at run-time and I have code like this:</p>
<pre><code> var dynDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("Div") {ID = "dynDiv"};
dynDiv.Style.Add(HtmlTextWriterStyle.BackgroundColor, "Red");
dynDiv.Style.Add(HtmlTextWriterStyle.Position, "absolute; left: 500px; top: 500px");
dynDiv.Style.Add(HtmlTextWriterStyle.Height, "30px");
dynDiv.Style.Add(HtmlTextWriterStyle.Width, "300px");
dynDiv.InnerHtml = "New Object";
PlaceHolder1.Controls.Add(dynDiv);
</code></pre>
<p>Is there a shorthand method to adding these value? I.e. something like:</p>
<pre><code>dynDiv.Style.Add(HtmlTextWriterStyle {BackgroundColor = "Red", Position = "absolute; left: 500px; top: 500px", Height = "30px", Width="300px"});
</code></pre>
<p>Or any other easier way that anyone can suggest?</p>
|
[] |
[
{
"body": "<p>Under normal circumstances, you could use collection initializer to write your code this way:</p>\n\n<pre><code>var dynDiv = new HtmlGenericControl(\"Div\")\n{\n ID = \"dynDiv\",\n Style =\n {\n { HtmlTextWriterStyle.BackgroundColor, \"Red\" },\n { HtmlTextWriterStyle.Position, \"absolute; left: 500px; top: 500px\" },\n { HtmlTextWriterStyle.Height, \"30px\" },\n { HtmlTextWriterStyle.Width, \"300px\" }\n },\n InnerHtml = \"New Object\"\n};\n</code></pre>\n\n<p>Unfortunately, this code won't compile, because <a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/786670/cssstylecollection-should-implement-ienumerable\" rel=\"nofollow\"><code>CssStyleCollection</code> doesn't implement <code>IEnumerable</code></a>, which is a requirement for collection initializers.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:54:02.520",
"Id": "40213",
"Score": "0",
"body": "OK, I'll have to stick with writing it the way I am. It just seems very verbose. As you state, there's normally shorter ways to do this type of thing."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:28:55.843",
"Id": "26001",
"ParentId": "25994",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26001",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T17:37:43.747",
"Id": "25994",
"Score": "2",
"Tags": [
"c#",
"html",
"asp.net"
],
"Title": "Is there a method to add multiple properties to HtmlTextWriterStyle?"
}
|
25994
|
<p>How do I elegantly check for null before calling a method on an object? This is how I do it right now:</p>
<pre><code>var title = document.querySelector('title');
title = title ? title.text : '';
</code></pre>
<p>Null Object pattern would be nice in this case but I don't own the <code>document.querySelector</code> code.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:21:42.053",
"Id": "40208",
"Score": "2",
"body": "`var title = document.querySelector('title') || {text:''};`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:26:21.203",
"Id": "40209",
"Score": "1",
"body": "@Shmiddty that's wrong. The OP wanted to get either title text or blank. Your code returns either the title object or an object with a property `text` with a blank string."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:27:04.023",
"Id": "40210",
"Score": "2",
"body": "@JosephtheDreamer That's a replacement for the first line, not the second. Then title.text works as the OP expects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T21:51:41.207",
"Id": "40217",
"Score": "0",
"body": "@JosephtheDreamer what Fizzy said. OP could do this: ...................................................................... `var title = (document.querySelector('title') || {text:''}).text;`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T22:15:43.100",
"Id": "40219",
"Score": "0",
"body": "@Shmiddty I got it. I just preserved the comment for future clarification."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T23:34:56.503",
"Id": "40222",
"Score": "0",
"body": "@Shmiddty You should re-post your comment as a proper answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T08:52:20.670",
"Id": "40260",
"Score": "0",
"body": "It might be worth pointing out, for other readers if not for you Sven, that the answer depends on the rest of your system. It's likely that @Shmiddty's answer is what you are looking for. But if a missing title is an error that should be dealt with, then the solution is to write *more* code than you have done."
}
] |
[
{
"body": "<p>You can do this:</p>\n\n<pre><code>var title = document.querySelector('title') || {text:''};\n</code></pre>\n\n<p>then just use <code>title.text</code> in-line.</p>\n\n<p>Alternatively, you could use this one-liner:</p>\n\n<pre><code>var title = (document.querySelector('title') || {text:''}).text;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T01:08:53.897",
"Id": "26010",
"ParentId": "26000",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "26010",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:14:21.213",
"Id": "26000",
"Score": "4",
"Tags": [
"javascript"
],
"Title": "Elegantly check for null before method call"
}
|
26000
|
<p>Preamble: it's a self-assigned and pure syntetic task to learn (and remember what I already knew) C# threads and synchronization and data structures.</p>
<p>The original question was here <a href="https://stackoverflow.com/questions/16458937/synchronization-of-remote-files-download">https://stackoverflow.com/questions/16458937/synchronization-of-remote-files-download</a></p>
<p>The short task explanation:</p>
<p>Let's say I have a dictionary <code><string, string></code> that represents a path (http) to a file by some key, ie:</p>
<pre><code>foo => http://domain.tld/file1
bar => http://domain2.tld/file2
</code></pre>
<p>And I'd like to implement a class that will implement an interface with 2 methods:</p>
<pre><code>String Rand();
String Get(String key);
</code></pre>
<p>The first method would pick the file randomly from all the available, and the <code>Get</code> would return a particular file, or to be precise - local path to a downloaded file.</p>
<p>The class should be thread-safe, so that if several threads request the same <code>key</code> with <code>Get()</code> or the <code>Rand()</code> picks the same item - then <strong>only one thread</strong> should actually download a file to a local drive, or the path should be retrieved immediately if a file has already been downloaded.</p>
<p>My proof of concept solution is:</p>
<pre><code>class Downloader
{
private readonly IDictionary<string, string> _map;
private IDictionary<string, string> _storage = new Dictionary<string, string>();
private ConcurrentDictionary<string, Task<string>> _progress = new ConcurrentDictionary<string,Task<string>>();
public Downloader(IDictionary<string, string> map)
{
_map = map ?? new Dictionary<string, string>();
}
public string Get(string key)
{
if (_storage.ContainsKey(key))
{
return _storage[key];
}
Task<string> task;
if (_progress.TryGetValue(key, out task))
{
return task.Result;
}
task = _retrieveFile(key);
if (!_progress.TryAdd(key, task))
{
return Get(key);
}
task.Start();
_storage[key] = task.Result;
return task.Result;
}
private Task<string> _retrieveFile(string key)
{
string path;
if (!_map.TryGetValue(key, out path))
{
throw new ArgumentException("The specified key wasn't found");
}
return new Task<string>(k =>
{
Console.WriteLine("Started retrieving {0}", k.ToString());
System.Threading.Thread.Sleep(3000);
Console.WriteLine("Finished retrieving {0}", k.ToString());
return k.ToString() + " local path";
}, path);
}
}
</code></pre>
<p>The copy is at <a href="http://pastebin.com/LJnK7FB6" rel="nofollow noreferrer">http://pastebin.com/LJnK7FB6</a></p>
<p>How could I make it better? Any particular problems with the code?</p>
<p>In the comments @I4V pointed out to some problems at <a href="https://stackoverflow.com/questions/16458937/synchronization-of-remote-files-download#comment23617420_16460673">https://stackoverflow.com/questions/16458937/synchronization-of-remote-files-download#comment23617420_16460673</a> but seems like I'm missing the point</p>
|
[] |
[
{
"body": "<p>If you change <code>_retrieveFile</code> to return a <code>Task</code> that's already started, you could simplify the whole <code>Get()</code> into just:</p>\n\n<pre><code>return _progress.GetOrAdd(key, _retrieveFile).Result;\n</code></pre>\n\n<p>Also, it seems that <code>Downloader</code> with empty <code>map</code> doesn't make sense, so you should check for that in your constructor, instead of using <code>??</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T21:37:41.500",
"Id": "40215",
"Score": "0",
"body": "That's a nice point actually, but shouldn't it be `_retrieveFile()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T21:43:52.187",
"Id": "40216",
"Score": "0",
"body": "@zerkms No, there is an overload that accepts `Func`. Though I assumed that it's guaranteed that the delegate won't be executed more than once, which, according to [the documentation](http://msdn.microsoft.com/en-us/library/ee378677.aspx) is not true. So my code might not be good enough for you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T21:22:57.787",
"Id": "26004",
"ParentId": "26002",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26004",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:46:18.850",
"Id": "26002",
"Score": "2",
"Tags": [
"c#",
"multithreading",
"thread-safety"
],
"Title": "Synchronization of remote files download"
}
|
26002
|
<p>I am struggling with the basic concepts of SASS.</p>
<p>I have a page that has multiple section, all of them are sharing properties like <code>width</code>, <code>font-size</code> etc.</p>
<p>I would like to optimize my code and do one of the following:</p>
<p><strong>1. Use an extendable silent class</strong></p>
<pre><code>%main-section{
width: 100%;
//... more styles
}
.about {
// this is a main-section
@extend %main-section;
}
</code></pre>
<p><strong>2. mixin</strong></p>
<pre><code>@mixin main-section($text-color, $bg-color) {
//some paramaters would provide a flexible module
width: 100%;
// etc.
}
</code></pre>
<p><strong>3. just a simple class to apply in my HTML</strong></p>
<pre><code>.main-section{
width: 100%;
//... more styles
}
</code></pre>
<p>I don't know which one i should choose. Maybe there's even a better solution i didn't mention. What is your opinion?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-27T19:48:03.740",
"Id": "97290",
"Score": "0",
"body": "I would def. go with option 3. It seems like an attempt to over complicate your code just to use cool SASS features."
}
] |
[
{
"body": "<p>Calling a mix-in for each section will duplicate the rules. Remember, you want to keep your code as D.R.Y (do not repeat) as possible. Inuit.css does something similar with the margins of elements. They use a %rhythm silent class that defines a global margin for anything that extends it. </p>\n\n<p>I don't know if there is a benefit to @extending slient class vs regular classes or tags. I \"believe\" it is more preference than anything.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T01:11:37.240",
"Id": "26011",
"ParentId": "26003",
"Score": "1"
}
},
{
"body": "<p>Best solution: Create a single section class and add it to all sections. </p>\n\n<p>Second best solution: Write a specific section class and @extend on other sections (in case you do not have control of HTML)</p>\n\n<p>Worst solution: Writing a mixin (duplicates styles)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T10:32:40.020",
"Id": "27191",
"ParentId": "26003",
"Score": "2"
}
},
{
"body": "<p>There is no hard right or wrong answer here. Using <code>@extend</code> is the obvious choice, but it can work against you. The only way to tell is to compile it both ways and see which one gives you the smaller result.</p>\n\n<p>The following code compiles to 340 bytes:</p>\n\n<pre><code>%width {\n width: 100%;\n}\n\n%font-size {\n font-size: 1.2em;\n}\n\n.foo {\n @extend %width;\n @extend %font-size;\n}\n\n.bar {\n @extend %width;\n color: red;\n}\n\n.baz {\n @extend %width;\n\n p {\n @extend %font-size;\n }\n}\n\n.fizz {\n @extend %width;\n border: 1px solid;\n}\n\n.boo {\n @extend %font-size;\n border-radius: 1em;\n}\n</code></pre>\n\n<p>Here's a non-extended version that compiles to 436 bytes (a savings of 4 bytes):</p>\n\n<pre><code>.foo {\n width: 100%;\n font-size: 1.2em;\n}\n\n.bar {\n width: 100%;\n color: red;\n}\n\n.baz {\n width: 100%;\n\n p {\n font-size: 1.2em;\n }\n}\n\n.fizz {\n width: 100%;\n border: 1px solid;\n}\n\n.boo {\n font-size: 1.2em;\n border-radius: 1em;\n}\n</code></pre>\n\n<p>The more often you extend something small, the less efficient it becomes. This is especially true when you've got non-extended code to go with it or multiple extends for the same selector since Sass has to write out the same selector twice.</p>\n\n<p>If all you want to do is have consistent values, using variables just might be your best option:</p>\n\n<pre><code>$width: 100%;\n\n$font-size: 1.2em;\n\n.foo {\n width: $width;\n font-size: $font-size;\n}\n\n.bar {\n width: $width;\n color: red;\n}\n\n.baz {\n width: $width;\n\n p {\n font-size: $font-size;\n }\n}\n\n.fizz {\n width: $width;\n border: 1px solid;\n}\n\n.boo {\n font-size: $font-size;\n border-radius: 1em;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T17:31:34.240",
"Id": "27910",
"ParentId": "26003",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T20:48:31.820",
"Id": "26003",
"Score": "4",
"Tags": [
"optimization",
"design-patterns",
"sass"
],
"Title": "Mixin, @extend or (silent) class?"
}
|
26003
|
<p>I am looking for someone to review my solution to a jQuery DOM manipulation exercise on appendto.com: <a href="http://learn.appendto.com/lesson/dom-manipulation-101#exercise" rel="nofollow">http://learn.appendto.com/lesson/dom-manipulation-101#exercise</a></p>
<p>I'm wondering if there is a way I can optimize or if there are other aspects I need to consider when building a solution like this.</p>
<p>The problem is outlined in the fiddle: <a href="http://jsfiddle.net/KhwZS/1283/" rel="nofollow">http://jsfiddle.net/KhwZS/1283/</a></p>
<p>Here is my solution:</p>
<pre><code>var getFirstTwoWords = function(str) {
return str.split(/\s+/).slice(1,3).join(" ");
}
var tabLinks = $("<ul></ul>");
$("div.tab").each( function( idx ) {
var id = "tabs-" + (idx + 1);
var text = $(this)
.removeClass("tab")
.attr("id", id)
.text();
var tabLabel = getFirstTwoWords(text);
// Create corresponding tab link
tabLinks.append("<li><a href=\"#" + id + "\">" + tabLabel + "</a></li>");
});
$(".tabs div:first").before(tabLinks);
$( ".tabs" ).tabs();
</code></pre>
<p>Optimized version:</p>
<pre><code>var tabLinks = $("<ul></ul>");
$("div.tab").each( function( idx ) {
var id = "tabs-" + (idx + 1);
var tabLabel = $(this)
.removeClass("tab")
.attr("id", id)
.find("h3")
.remove()
.text();
// Create corresponding tab link
tabLinks.append("<li><a href=\"#" + id + "\">" + tabLabel + "</a></li>");
});
$(".tabs")
.prepend(tabLinks)
.tabs();
</code></pre>
|
[] |
[
{
"body": "<p>Your code's very nice. My points below are mostly of the \"but what if...\" variety concerning the DOM manipulation, rather than the JavaScript itself. In other words, your solution seems spot on for the given exercise, whereas my comments mostly refer to situations which are not part of the exercise, but could arise in the real world.</p>\n\n<p><em>Aside: The exercise could be clearer in its naming. The container element (singular) has a class called <code>tabs</code> (plural), while the DIVs (plural) within it have a class called <code>tab</code> (singular). It's sort of logical, but it gets confusing nonetheless. And I say \"sort of logical\", because the <code>.tab</code> elements aren't actually tabs - they're \"panels\" in jQuery UI's terminology. Hence, their class name should really be \"panel\". But I digress...</em></p>\n\n<p>First off, what would happen if the page contains several \"tabable\" sections? The fact that <code>.tabs</code> is a class name - not an ID - suggests that there might be multiple <code>div.tabs</code> container elements, each with their own set of <code>div.tab</code> elements.</p>\n\n<p>Well, with your code, things go a little awry (<a href=\"http://jsfiddle.net/Zgryz/\" rel=\"nofollow\">see here</a>): Both tab containers get tab links for <em>all</em> the panels on the page, even those belonging to another container.</p>\n\n<p>The trick would be to go through each <code>div.tabs</code> (i.e. tab container) element in turn, and manipulate their individual structures one by one:</p>\n\n<pre><code>$(\"div.tabs\").each(function (containerIndex) {\n var container = $(this),\n tabLinks = $(\"<ul></ul>\");\n\n container.find(\"div.tab\").each(function (tabIndex) {\n var id = \"tabs-\" + containerIndex + \"-panel-\" + tabIndex; // more precise ID\n\n // your code here ...\n });\n\n container\n .prepend(tabLinks)\n .tabs();\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/Zgryz/1/\" rel=\"nofollow\">See the result here</a></p>\n\n<p>Second, what might happen if an <code><h3></code> heading has HTML in its text or has its own child elements? Here are examples of each of those cases:</p>\n\n<ul>\n<li>Literal HTML: <code><h3>When to use &lt;div&gt; elements</h3></code></li>\n<li>HTML formatting: <code><h3>When to use <code>div</code> elements</h3></code></li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/M8nfx/\" rel=\"nofollow\">Here's the result, using your code</a></p>\n\n<p>Now, this is something where there may not be \"one right answer\" - it all depends on the content you're working with. However, it's worth considering.</p>\n\n<p>In your case, you use <code>.text()</code> to get the text out of the heading, but you don't use <code>.text()</code> to put that text into the the link; you \"manually\" create a link by concatenating strings.<br>\nSo, in the first case, the string you get out is <code>When to use <div> elements</code>. Notice that the entity-encoded <code><</code> and <code>></code> have become plain characters. When you then concatenate that with other strings of HTML to make the link, you end up more HTML than you intended; there's an unclosed DIV in the middle of your link!<br>\nIn the second case, <code>.text()</code> completely ignores the <code><code></code> tag. That doesn't break the link, but you lose the formatting and semantics of the <code><code></code> tag, which - one might assume - was put there for a reason by whoever wrote the heading. Since you also remove the original <code><h3></code>, that formatting is now nowhere to be found.</p>\n\n<p>I said there was no right answer, because to fix the first case, you'd need to use <code>.text()</code> to extract <em>and</em> insert the heading's content, as it prevents the string from being interpreted as HTML. But to fix the other case, you'd need to use <code>.html()</code> instead, to ensure the string <em>is</em> interpreted that way. Now, using <code>.html()</code> would actually solve both cases (preserving already-encoded entities and tags), but the next question is whether you actually want that. What if the heading itself contains a link? Then you'll end up with a link inside a link... This of course doesn't apply only to tabs and headings, but to any situation where you're extracting and inserting content, which is why I brought it up.</p>\n\n<p>But again, I'm just trying to poke holes in things here, so don't let it discourage you. It's more to illustrate the sort of things you might run in to. The possible solutions I can think are outside the scope of this answer though (it'd involve some different approaches), and very much outside the scope of the original exercise.</p>\n\n<p>Speaking of \"out of scope\", I've rambled plenty here, so I'll stop. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T22:07:03.220",
"Id": "40300",
"Score": "0",
"body": "Nice explanation +1 for it :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T20:55:13.113",
"Id": "26049",
"ParentId": "26006",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T22:52:16.493",
"Id": "26006",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"jquery-ui"
],
"Title": "Using jquery to prepare jQuery UI tabs, optimize?"
}
|
26006
|
<p>I need objects in python that I can compare, reference to and hash.</p>
<p>In principal a tuple or list would be good enough just that
a list I cannot hash and the tuple I cannot change,
except replacing it which means losing references to it.</p>
<p>So I created a class for it, but still have the feeling there should be a simpler/better solution to it.</p>
<pre><code>class MyClass:
def __init__(self, k, l=0, m=0):
self.k = k
self.l = l
self.m = m
def __hash__(self):
n_attr = len(self.__dict__)
return sum(hash(attr)/n_attr for attr in self.__dict__.values())
def __eq__(self, other):
return all(sa==oa for sa, oa in zip(self.__dict__.values(),
other.__dict__.values()))
</code></pre>
<p>Now I can do what I need: creating some objects</p>
<pre><code>x = MyClass(1,2,3)
y = MyClass(7)
z = MyClass(7,1,0)
</code></pre>
<p>and some references</p>
<pre><code>a = x; b = y; c = y; d = z
</code></pre>
<p>and compare, manipulate ...</p>
<pre><code>b == c # True
b == d # False
b.l = 1
b == c # still True
b == d # now True
s = {a, d, (a,b)}
b in s # True
c in s # True
(a,c) in s # True
</code></pre>
<p>I wished I could just forget about the class and do </p>
<pre><code>x = 1,2,3
y = 7,
z = 7,1
</code></pre>
<p>etc ...</p>
<p>Is writing this class the best way to approach this problem? Or did I miss something?</p>
<p><em>edit</em>:</p>
<p>After the comment by WinstonEwert I confirmed that the objects cause breakage as keys in dictionary</p>
<pre><code>s = {a: 'a', b: 'b'}
s[c] # 'b'
c.l = 99
s[c] # key error
s # key error
</code></pre>
<p>and decided to replace dictionaries that use these objects as keys by</p>
<pre><code>class MyDict:
def __init__(self, d={}):
self._data = d.items()
def __getitem__(self, key):
for k, v in self._data:
if k == key: return v
raise KeyError
def __setitem__(self, key, value):
for i, (k, v) in enumerate(self._data):
if k == key:
self._data[i] = key, value
return
self._data.append((key,value))
def __contains__(self, key):
for k, v in self._data:
if k == key: return True
return False
</code></pre>
<p>Now I have the desired behavior</p>
<pre><code>s = MyDict()
s[a] = 'a'
s[b] = 'b'
s[c] # 'b'
c.l = 99
s[c] # still 'b'
</code></pre>
<p>And I do not need <code>MyClass</code> any more and can use list</p>
<pre><code>x = [1,2,3]
y = [7,0,0]
z = [7,1,0]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T00:26:33.767",
"Id": "40227",
"Score": "0",
"body": "Why do you want the object to be hashable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T00:33:30.167",
"Id": "40228",
"Score": "0",
"body": "currently I'm using the objects as keys in a dictionary"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T00:37:01.850",
"Id": "40229",
"Score": "0",
"body": "That's going to break when you change the object you are using as a key."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T00:37:19.903",
"Id": "40230",
"Score": "0",
"body": "There are always just 4-5 elements in a dictionary so O(n) lookup would be ok, maybe I could replace the dictionaries by list of tuples and search by comparing. Dictionaries were just so comfortable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T00:50:15.673",
"Id": "40232",
"Score": "0",
"body": "@WinstonEwert Seems you are right, there is a problem (extended to question). I was expecting the second `s[c]` to still give `b`. I was assuming that the keys in the dictionary are connected to `c` and change if I change c."
}
] |
[
{
"body": "<p>The python dictionary assumes that the keys are immutable. It assumes they will not change. That's why mutable classes in python (such as lists) don't hash. Its to prevent you from putting them in dicts which just won't work. </p>\n\n<p>As a result the entire premise of your class is wrong. You shouldn't do that. To follow what python expects, an object should return the same hash and be equal to the same objects throughout its lifetime. If it can't it shouldn't support hashing.</p>\n\n<p>We might be able to suggest a better way to do this, but you'll need to show more of how you want to use this class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T01:57:22.647",
"Id": "40233",
"Score": "0",
"body": "I now agree that I should not use `MyClass` and now changed the way I'm using it instead (see edit). Thanks for pointing out the problem"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T02:00:24.940",
"Id": "40234",
"Score": "0",
"body": "@Matthias009, the only issue I see is that you'll have slightly odd behavior if you make an object equal to another object after adding them both to your dictionary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T02:45:26.857",
"Id": "40235",
"Score": "0",
"body": "Also true. And this behavior will actually cause me problems. I have to give it some more thinking what exactly I want."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T01:53:29.197",
"Id": "26013",
"ParentId": "26008",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26013",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-09T23:21:26.020",
"Id": "26008",
"Score": "3",
"Tags": [
"python"
],
"Title": "Class for simple python object to be hashed and referenced"
}
|
26008
|
<p>when we need to add some javascript code to html, where we have to put it?</p>
<p>What is the best practice:</p>
<p>in line:</p>
<pre><code><script type="text/javascript">document.write(new Date().getFullYear())</script>
</code></pre>
<p></p>
<p>or centralized:</p>
<pre><code><header><script type=text/javascript> document.getelementbyid('someid').innerhtml='date'.....</script></header>
</code></pre>
|
[] |
[
{
"body": "<p>Optimally, it's loaded just before the body tag closes</p>\n\n<pre><code> <!-- all html above here -->\n <script src=\"...\"></script>\n</body>\n</code></pre>\n\n<p>for the following common reasons:</p>\n\n<ul>\n<li><p>The DOM elements that you are operating are safely parsed by then.</p></li>\n<li><p>Script tags block execution. If they delay in loading and/or parsing, the things that follow it will have to wait. Thus, to prevent delay and from seeing a blank screen while scripts load, we load the page first, scripts last.</p></li>\n</ul>\n\n<p><a href=\"https://stackoverflow.com/a/10661977/575527\">I have a similar answer</a>, along with other answers, at StackOverflow which should explain more.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T10:47:58.670",
"Id": "40265",
"Score": "0",
"body": "Thanks for your answer, but it mean that all scripts in header shuold be placed in the bottom of the page? or only the scripts that interacts with elements in the page like my above example? Common functions should be placed in header? eg function setCookie(cname, value) {\n document.cookie = cname + \"=\" + value; //+\"; path=/; expires=Wed, 1 Jan 2020 00:00:00 GMT\";\n\n\n}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T11:04:12.937",
"Id": "40266",
"Score": "0",
"body": "@user2119955 Usually they are placed at the bottom since loading and parsing could potentially block the page. For embedded scripts (scripts in the HTML itself), they are excused from the loading time, but still, parsing could still take time. Besides, it's recommended to use external JS rather than embedded JS."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T10:41:01.587",
"Id": "26021",
"ParentId": "26020",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T10:34:25.497",
"Id": "26020",
"Score": "2",
"Tags": [
"javascript",
"dom"
],
"Title": "when we need to add some javascript code to html, where we have to put it?"
}
|
26020
|
<p>.NET does not support generic numbers. It is not possible to enforce a generic method with generic argument T that T is a number. The following code will simply not compile:</p>
<pre><code>public T DifficultCalculation<T>(T a, T b)
{
T result = a * b + a; // <== WILL NOT COMPILE!
return result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Should result in 8.
</code></pre>
<p>To overcome this problem I created a class to overcome this, a generic Calculator. Using this calculator, you can do arithmatic operations on a generic type. It is at that moment assumed that the programmer knows what he is doing. The usage would look like:</p>
<pre><code>public T DifficultCalculation<T>(T a, T b)
{
T result = Calculator<T>.Add(Calculator<T>.Multiply(a, b), a);
return result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Results in 8.
</code></pre>
<p>Of coure... this makes the code less readable, so I created another struct to overcome this: <code>Number<T></code>. In this struct I created every operator I could think of. The code could now be revised as:</p>
<pre><code>public T DifficultCalculation<T>(Number<T> a, Number<T> b)
{
Number<T> result = a * b + a;
return (T)result;
}
Console.WriteLine(DifficultCalculation(2, 3)); // Results in 8.
</code></pre>
<p>I think this can be very handy for some other developers. Before I broadcast it to the world, I want it to be reviewed. If you have any comments about it (about functionality, performance, usability), please let me know!</p>
<h1>Calculator</h1>
<pre><code>/// <summary>
/// Class to allow operations (like Add, Multiply, etc.) for generic types. This type should allow these operations themselves.
/// If a type does not support an operation, an exception is throw when using this operation, not during construction of this class.
/// </summary>
/// <typeparam name="T"></typeparam>
public static class Calculator<T>
{
static Calculator()
{
Add = CreateDelegate<T>(Expression.AddChecked, "Addition", true);
Subtract = CreateDelegate<T>(Expression.SubtractChecked, "Substraction", true);
Multiply = CreateDelegate<T>(Expression.MultiplyChecked, "Multiply", true);
Divide = CreateDelegate<T>(Expression.Divide, "Divide", true);
Modulo = CreateDelegate<T>(Expression.Modulo, "Modulus", true);
Negate = CreateDelegate(Expression.NegateChecked, "Negate", true);
Plus = CreateDelegate(Expression.UnaryPlus, "Plus", true);
Increment = CreateDelegate(Expression.Increment, "Increment", true);
Decrement = CreateDelegate(Expression.Decrement, "Decrement", true);
LeftShift = CreateDelegate<int>(Expression.LeftShift, "LeftShift", false);
RightShift = CreateDelegate<int>(Expression.RightShift, "RightShift", false);
OnesComplement = CreateDelegate(Expression.OnesComplement, "OnesComplement", false);
And = CreateDelegate<T>(Expression.And, "BitwiseAnd", false);
Or = CreateDelegate<T>(Expression.Or, "BitwiseOr", false);
Xor = CreateDelegate<T>(Expression.ExclusiveOr, "ExclusiveOr", false);
}
static private Func<T, T2, T> CreateDelegate<T2>(Func<Expression, Expression, Expression> @operator, string operatorName, bool isChecked)
{
try
{
Type convertToTypeA = ConvertTo(typeof(T));
Type convertToTypeB = ConvertTo(typeof(T2));
ParameterExpression parameterA = Expression.Parameter(typeof(T), "a");
ParameterExpression parameterB = Expression.Parameter(typeof(T2), "b");
Expression valueA = (convertToTypeA != null) ? Expression.Convert(parameterA, convertToTypeA) : (Expression)parameterA;
Expression valueB = (convertToTypeB != null) ? Expression.Convert(parameterB, convertToTypeB) : (Expression)parameterB;
Expression body = @operator(valueA, valueB);
if (convertToTypeA != null)
{
if (isChecked)
body = Expression.ConvertChecked(body, typeof(T));
else
body = Expression.Convert(body, typeof(T));
}
return Expression.Lambda<Func<T, T2, T>>(body, parameterA, parameterB).Compile();
}
catch
{
return (a, b) =>
{
throw new InvalidOperationException("Operator " + operatorName + " is not supported by type " + typeof(T).FullName + ".");
};
}
}
static private Func<T, T> CreateDelegate(Func<Expression, Expression> @operator, string operatorName, bool isChecked)
{
try
{
Type convertToType = ConvertTo(typeof(T));
ParameterExpression parameter = Expression.Parameter(typeof(T), "a");
Expression value = (convertToType != null) ? Expression.Convert(parameter, convertToType) : (Expression)parameter;
Expression body = @operator(value);
if (convertToType != null)
{
if (isChecked)
body = Expression.ConvertChecked(body, typeof(T));
else
body = Expression.Convert(body, typeof(T));
}
return Expression.Lambda<Func<T, T>>(body, parameter).Compile();
}
catch
{
return (a) =>
{
throw new InvalidOperationException("Operator " + operatorName + " is not supported by type " + typeof(T).FullName + ".");
};
}
}
static private Type ConvertTo(Type type)
{
switch (Type.GetTypeCode(type))
{
case TypeCode.Char:
case TypeCode.Byte:
case TypeCode.SByte:
case TypeCode.Int16:
case TypeCode.UInt16:
return typeof(int);
}
return null;
}
/// <summary>
/// Adds two values of the same type.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Add;
/// <summary>
/// Subtracts two values of the same type.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Subtract;
/// <summary>
/// Multiplies two values of the same type.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Multiply;
/// <summary>
/// Divides two values of the same type.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Divide;
/// <summary>
/// Divides two values of the same type and returns the remainder.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Modulo;
/// <summary>
/// Gets the negative value of T.
/// Supported by: All numeric values, but will throw an OverflowException on unsigned values which are not 0.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T> Negate;
/// <summary>
/// Gets the negative value of T.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T> Plus;
/// <summary>
/// Gets the negative value of T.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T> Increment;
/// <summary>
/// Gets the negative value of T.
/// Supported by: All numeric values.
/// </summary>
/// <exception cref="OverflowException"/>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T> Decrement;
/// <summary>
/// Shifts the number to the left.
/// Supported by: All integral types.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, int, T> LeftShift;
/// <summary>
/// Shifts the number to the right.
/// Supported by: All integral types.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, int, T> RightShift;
/// <summary>
/// Inverts all bits inside the value.
/// Supported by: All integral types.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T> OnesComplement;
/// <summary>
/// Performs a bitwise OR.
/// Supported by: All integral types.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Or;
/// <summary>
/// Performs a bitwise AND
/// Supported by: All integral types.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> And;
/// <summary>
/// Performs a bitwise Exclusive OR.
/// Supported by: All integral types.
/// </summary>
/// <exception cref="InvalidOperationException"/>
public static readonly Func<T, T, T> Xor;
}
</code></pre>
<h1>Number</h1>
<pre><code>public struct Number<T>
where T : IComparable<T>, IEquatable<T>
{
private readonly T _Value;
public Number(T value)
{
_Value = value;
}
#region Comparison
public bool Equals(Number<T> other)
{
return _Value.Equals(other._Value);
}
public bool Equals(T other)
{
return _Value.Equals(other);
}
public int CompareTo(Number<T> other)
{
return _Value.CompareTo(other._Value);
}
public int CompareTo(T other)
{
return _Value.CompareTo(other);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (obj is T)
return _Value.Equals((T)obj);
if (obj is Number<T>)
return _Value.Equals(((Number<T>)obj)._Value);
return false;
}
public override int GetHashCode()
{
return (_Value == null) ? 0 : _Value.GetHashCode();
}
static public bool operator ==(Number<T> a, Number<T> b)
{
return a._Value.Equals(b._Value);
}
static public bool operator !=(Number<T> a, Number<T> b)
{
return !a._Value.Equals(b._Value);
}
static public bool operator <(Number<T> a, Number<T> b)
{
return a._Value.CompareTo(b._Value) < 0;
}
static public bool operator <=(Number<T> a, Number<T> b)
{
return a._Value.CompareTo(b._Value) <= 0;
}
static public bool operator >(Number<T> a, Number<T> b)
{
return a._Value.CompareTo(b._Value) > 0;
}
static public bool operator >=(Number<T> a, Number<T> b)
{
return a._Value.CompareTo(b._Value) >= 0;
}
static public Number<T> operator !(Number<T> a)
{
return new Number<T>(Calculator<T>.Negate(a._Value));
}
#endregion
#region Arithmatic operations
static public Number<T> operator +(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Add(a._Value, b._Value));
}
static public Number<T> operator -(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Subtract(a._Value, b._Value));
}
static public Number<T> operator *(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Multiply(a._Value, b._Value));
}
static public Number<T> operator /(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Divide(a._Value, b._Value));
}
static public Number<T> operator %(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Modulo(a._Value, b._Value));
}
static public Number<T> operator -(Number<T> a)
{
return new Number<T>(Calculator<T>.Negate(a._Value));
}
static public Number<T> operator +(Number<T> a)
{
return new Number<T>(Calculator<T>.Plus(a._Value));
}
static public Number<T> operator ++(Number<T> a)
{
return new Number<T>(Calculator<T>.Increment(a._Value));
}
static public Number<T> operator --(Number<T> a)
{
return new Number<T>(Calculator<T>.Decrement(a._Value));
}
#endregion
#region Bitwise operations
static public Number<T> operator <<(Number<T> a, int b)
{
return new Number<T>(Calculator<T>.LeftShift(a._Value, b));
}
static public Number<T> operator >>(Number<T> a, int b)
{
return new Number<T>(Calculator<T>.RightShift(a._Value, b));
}
static public Number<T> operator &(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.And(a._Value, b._Value));
}
static public Number<T> operator |(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Or(a._Value, b._Value));
}
static public Number<T> operator ^(Number<T> a, Number<T> b)
{
return new Number<T>(Calculator<T>.Xor(a._Value, b._Value));
}
static public Number<T> operator ~(Number<T> a)
{
return new Number<T>(Calculator<T>.OnesComplement(a._Value));
}
#endregion
#region Casts
static public implicit operator Number<T>(T value)
{
return new Number<T>(value);
}
static public explicit operator T(Number<T> value)
{
return value._Value;
}
#endregion
#region Other members
public override string ToString()
{
return (_Value == null) ? string.Empty : _Value.ToString();
}
#endregion
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-24T13:53:13.147",
"Id": "148358",
"Score": "0",
"body": "It is not currently possible to multiply a double with an integer with automatic widening."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-04T10:35:47.107",
"Id": "149548",
"Score": "1",
"body": "@Kerem: Correct. Calculation with different numeric datatypes does not work. It only works when the types 'T' are the same. I am open for suggestions."
}
] |
[
{
"body": "<p>This is a nifty implementation! Only one thought I came up with: I think <code>Number</code> is too tightly coupled with <code>Calculator</code>. Now I couldn't decouple it completely, due to the operator overloads in <code>Number</code>, but I think I made it such that you could sub in mock or different <code>Calculator</code>s as needed. I also added <code>struct</code> as a generic constraint on <code>Number<T></code> so that <code>null</code> checks weren't needed. I don't know of any numerics that aren't represented as <code>struct</code>s, so I think that's a reasonable change.</p>\n\n<p><code>ICalculator<T></code> interface:</p>\n\n<pre><code>public interface ICalculator<T>\n{\n /// <summary>\n /// Adds two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Add { get; }\n\n /// <summary>\n /// Subtracts two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Subtract { get; }\n\n /// <summary>\n /// Multiplies two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Multiply { get; }\n\n /// <summary>\n /// Divides two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Divide { get; }\n\n /// <summary>\n /// Divides two values of the same type and returns the remainder.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Modulo { get; }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values, but will throw an OverflowException on unsigned values which are not 0.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T> Negate { get; }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T> Plus { get; }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T> Increment { get; }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T> Decrement { get; }\n\n /// <summary>\n /// Shifts the number to the left.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, int, T> LeftShift { get; }\n\n /// <summary>\n /// Shifts the number to the right.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, int, T> RightShift { get; }\n\n /// <summary>\n /// Inverts all bits inside the value.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T> OnesComplement { get; }\n\n /// <summary>\n /// Performs a bitwise OR.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Or { get; }\n\n /// <summary>\n /// Performs a bitwise AND\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> And { get; }\n\n /// <summary>\n /// Performs a bitwise Exclusive OR.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n Func<T, T, T> Xor { get; }\n}\n</code></pre>\n\n<p><code>Calculator<T></code> class:</p>\n\n<pre><code>/// <summary>\n/// Class to allow operations (like Add, Multiply, etc.) for generic types. This type should allow these operations themselves.\n/// If a type does not support an operation, an exception is throw when using this operation, not during construction of this class.\n/// </summary>\n/// <typeparam name=\"T\"></typeparam>\npublic class Calculator<T> : ICalculator<T>\n{\n private static readonly ICalculator<T> instance = new Calculator<T>();\n\n /// <summary>\n /// Adds two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> add;\n\n /// <summary>\n /// Subtracts two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> subtract;\n\n /// <summary>\n /// Multiplies two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> multiply;\n\n /// <summary>\n /// Divides two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> divide;\n\n /// <summary>\n /// Divides two values of the same type and returns the remainder.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> modulo;\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values, but will throw an OverflowException on unsigned values which are not 0.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T> negate;\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T> plus;\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T> increment;\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T> decrement;\n\n /// <summary>\n /// Shifts the number to the left.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, int, T> leftShift;\n\n /// <summary>\n /// Shifts the number to the right.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, int, T> rightShift;\n\n /// <summary>\n /// Inverts all bits inside the value.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T> onesComplement;\n\n /// <summary>\n /// Performs a bitwise OR.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> or;\n\n /// <summary>\n /// Performs a bitwise AND\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> and;\n\n /// <summary>\n /// Performs a bitwise Exclusive OR.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n private readonly Func<T, T, T> xor;\n\n public Calculator()\n {\n this.add = CreateDelegate<T>(Expression.AddChecked, \"Addition\", true);\n this.subtract = CreateDelegate<T>(Expression.SubtractChecked, \"Substraction\", true);\n this.multiply = CreateDelegate<T>(Expression.MultiplyChecked, \"Multiply\", true);\n this.divide = CreateDelegate<T>(Expression.Divide, \"Divide\", true);\n this.modulo = CreateDelegate<T>(Expression.Modulo, \"Modulus\", true);\n this.negate = CreateDelegate(Expression.NegateChecked, \"Negate\", true);\n this.plus = CreateDelegate(Expression.UnaryPlus, \"Plus\", true);\n this.increment = CreateDelegate(Expression.Increment, \"Increment\", true);\n this.decrement = CreateDelegate(Expression.Decrement, \"Decrement\", true);\n this.leftShift = CreateDelegate<int>(Expression.LeftShift, \"LeftShift\", false);\n this.rightShift = CreateDelegate<int>(Expression.RightShift, \"RightShift\", false);\n this.onesComplement = CreateDelegate(Expression.OnesComplement, \"OnesComplement\", false);\n this.and = CreateDelegate<T>(Expression.And, \"BitwiseAnd\", false);\n this.or = CreateDelegate<T>(Expression.Or, \"BitwiseOr\", false);\n this.xor = CreateDelegate<T>(Expression.ExclusiveOr, \"ExclusiveOr\", false);\n }\n\n public static ICalculator<T> Instance\n {\n get\n {\n return instance;\n }\n }\n\n /// <summary>\n /// Adds two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Add\n {\n get\n {\n return this.add;\n }\n }\n\n /// <summary>\n /// Subtracts two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Subtract\n {\n get\n {\n return this.subtract;\n }\n }\n\n /// <summary>\n /// Multiplies two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Multiply\n {\n get\n {\n return this.multiply;\n }\n }\n\n /// <summary>\n /// Divides two values of the same type.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Divide\n {\n get\n {\n return this.divide;\n }\n }\n\n /// <summary>\n /// Divides two values of the same type and returns the remainder.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Modulo\n {\n get\n {\n return this.modulo;\n }\n }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values, but will throw an OverflowException on unsigned values which are not 0.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T> Negate\n {\n get\n {\n return this.negate;\n }\n }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T> Plus\n {\n get\n {\n return this.plus;\n }\n }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T> Increment\n {\n get\n {\n return this.increment;\n }\n }\n\n /// <summary>\n /// Gets the negative value of T.\n /// Supported by: All numeric values.\n /// </summary>\n /// <exception cref=\"OverflowException\"/>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T> Decrement\n {\n get\n {\n return this.decrement;\n }\n }\n\n /// <summary>\n /// Shifts the number to the left.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, int, T> LeftShift\n {\n get\n {\n return this.leftShift;\n }\n }\n\n /// <summary>\n /// Shifts the number to the right.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, int, T> RightShift\n {\n get\n {\n return this.rightShift;\n }\n }\n\n /// <summary>\n /// Inverts all bits inside the value.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T> OnesComplement\n {\n get\n {\n return this.onesComplement;\n }\n }\n\n /// <summary>\n /// Performs a bitwise OR.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Or\n {\n get\n {\n return this.or;\n }\n }\n\n /// <summary>\n /// Performs a bitwise AND\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> And\n {\n get\n {\n return this.and;\n }\n }\n\n /// <summary>\n /// Performs a bitwise Exclusive OR.\n /// Supported by: All integral types.\n /// </summary>\n /// <exception cref=\"InvalidOperationException\"/>\n public Func<T, T, T> Xor\n {\n get\n {\n return this.xor;\n }\n }\n\n private static Func<T, T2, T> CreateDelegate<T2>(Func<Expression, Expression, Expression> @operator, string operatorName, bool isChecked)\n {\n try\n {\n var convertToTypeA = ConvertTo(typeof(T));\n var convertToTypeB = ConvertTo(typeof(T2));\n var parameterA = Expression.Parameter(typeof(T), \"a\");\n var parameterB = Expression.Parameter(typeof(T2), \"b\");\n var valueA = (convertToTypeA != null) ? Expression.Convert(parameterA, convertToTypeA) : (Expression)parameterA;\n var valueB = (convertToTypeB != null) ? Expression.Convert(parameterB, convertToTypeB) : (Expression)parameterB;\n var body = @operator(valueA, valueB);\n\n if (convertToTypeA != null)\n {\n body = isChecked ? Expression.ConvertChecked(body, typeof(T)) : Expression.Convert(body, typeof(T));\n }\n\n return Expression.Lambda<Func<T, T2, T>>(body, parameterA, parameterB).Compile();\n }\n catch\n {\n return (a, b) =>\n {\n throw new InvalidOperationException(\"Operator \" + operatorName + \" is not supported by type \" + typeof(T).FullName + \".\");\n };\n }\n }\n\n private static Func<T, T> CreateDelegate(Func<Expression, Expression> @operator, string operatorName, bool isChecked)\n {\n try\n {\n var convertToType = ConvertTo(typeof(T));\n var parameter = Expression.Parameter(typeof(T), \"a\");\n var value = (convertToType != null) ? Expression.Convert(parameter, convertToType) : (Expression)parameter;\n var body = @operator(value);\n\n if (convertToType != null)\n {\n body = isChecked ? Expression.ConvertChecked(body, typeof(T)) : Expression.Convert(body, typeof(T));\n }\n\n return Expression.Lambda<Func<T, T>>(body, parameter).Compile();\n }\n catch\n {\n return a =>\n {\n throw new InvalidOperationException(\"Operator \" + operatorName + \" is not supported by type \" + typeof(T).FullName + \".\");\n };\n }\n }\n\n private static Type ConvertTo(Type type)\n {\n switch (Type.GetTypeCode(type))\n {\n case TypeCode.Char:\n case TypeCode.Byte:\n case TypeCode.SByte:\n case TypeCode.Int16:\n case TypeCode.UInt16:\n return typeof(int);\n }\n\n return null;\n }\n}\n</code></pre>\n\n<p><code>Number<T></code> class:</p>\n\n<pre><code>public struct Number<T> where T : struct, IComparable<T>, IEquatable<T>\n{\n private static readonly ICalculator<T> defaultCalculator = Calculator<T>.Instance;\n\n private readonly T value;\n\n public Number(T value)\n {\n this.value = value;\n }\n\n public bool Equals(Number<T> other)\n {\n return this.value.Equals(other.value);\n }\n\n public bool Equals(T other)\n {\n return this.value.Equals(other);\n }\n\n public int CompareTo(Number<T> other)\n {\n return this.value.CompareTo(other.value);\n }\n\n public int CompareTo(T other)\n {\n return this.value.CompareTo(other);\n }\n\n public override bool Equals(object obj)\n {\n return obj != null && (obj is T\n ? this.value.Equals((T)obj)\n : obj is Number<T> && this.value.Equals(((Number<T>)obj).value));\n }\n\n public override int GetHashCode()\n {\n return this.value.GetHashCode();\n }\n\n public static bool operator ==(Number<T> a, Number<T> b)\n {\n return a.value.Equals(b.value);\n }\n\n public static bool operator !=(Number<T> a, Number<T> b)\n {\n return !a.value.Equals(b.value);\n }\n\n public static bool operator <(Number<T> a, Number<T> b)\n {\n return a.value.CompareTo(b.value) < 0;\n }\n\n public static bool operator <=(Number<T> a, Number<T> b)\n {\n return a.value.CompareTo(b.value) <= 0;\n }\n\n public static bool operator >(Number<T> a, Number<T> b)\n {\n return a.value.CompareTo(b.value) > 0;\n }\n\n public static bool operator >=(Number<T> a, Number<T> b)\n {\n return a.value.CompareTo(b.value) >= 0;\n }\n\n public static Number<T> operator !(Number<T> a)\n {\n return new Number<T>(defaultCalculator.Negate(a.value));\n }\n\n public static Number<T> operator +(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Add(a.value, b.value));\n }\n\n public static Number<T> operator -(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Subtract(a.value, b.value));\n }\n\n public static Number<T> operator *(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Multiply(a.value, b.value));\n }\n\n public static Number<T> operator /(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Divide(a.value, b.value));\n }\n\n public static Number<T> operator %(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Modulo(a.value, b.value));\n }\n\n public static Number<T> operator -(Number<T> a)\n {\n return new Number<T>(defaultCalculator.Negate(a.value));\n }\n\n public static Number<T> operator +(Number<T> a)\n {\n return new Number<T>(defaultCalculator.Plus(a.value));\n }\n\n public static Number<T> operator ++(Number<T> a)\n {\n return new Number<T>(defaultCalculator.Increment(a.value));\n }\n\n public static Number<T> operator --(Number<T> a)\n {\n return new Number<T>(defaultCalculator.Decrement(a.value));\n }\n\n public static Number<T> operator <<(Number<T> a, int b)\n {\n return new Number<T>(defaultCalculator.LeftShift(a.value, b));\n }\n\n public static Number<T> operator >>(Number<T> a, int b)\n {\n return new Number<T>(defaultCalculator.RightShift(a.value, b));\n }\n\n public static Number<T> operator &(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.And(a.value, b.value));\n }\n\n public static Number<T> operator |(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Or(a.value, b.value));\n }\n\n public static Number<T> operator ^(Number<T> a, Number<T> b)\n {\n return new Number<T>(defaultCalculator.Xor(a.value, b.value));\n }\n\n public static Number<T> operator ~(Number<T> a)\n {\n return new Number<T>(defaultCalculator.OnesComplement(a.value));\n }\n\n public static implicit operator Number<T>(T value)\n {\n return new Number<T>(value);\n }\n\n public static explicit operator T(Number<T> value)\n {\n return value.value;\n }\n\n public override string ToString()\n {\n return this.value.ToString();\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T17:21:31.693",
"Id": "40279",
"Score": "0",
"body": "Monad? I don't see any monad in there. The definition of monad is that it has `bind` and `return` functions that behave in a specific way and there is nothing like that here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:18:37.720",
"Id": "40290",
"Score": "0",
"body": "@svick you're right."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:25:22.513",
"Id": "40291",
"Score": "0",
"body": "@Jesse: Thank for you review. I greatly appreciate it. I also though about put the struct as a contraint. But what if somebody decides to create his own numeric class (like a vector, or complex or whatever. And he does not create a struct but a class. Than this system would not work anymore. So I left it out, because it costs only one compare with `null` (if I remember correctly). Can you please explain to me how your code is losely coupled?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:28:12.630",
"Id": "40292",
"Score": "0",
"body": "@MartinMulder it's looser - not completely decoupled. The key is creating an interface out of `Calculator`. My line `private static readonly ICalculator<T> defaultCalculator = Calculator<T>.Instance;` is what keeps it coupled to the implementation."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T15:40:41.213",
"Id": "26032",
"ParentId": "26022",
"Score": "6"
}
},
{
"body": "<ol>\n<li>Have you considered using <a href=\"https://jonskeet.uk/csharp/genericoperators.html\" rel=\"nofollow noreferrer\"><code>Operator</code> from MiscUtil</a> instead of your <code>Calculator</code>?</li>\n<li>You should never use general <code>catch</code>. Instead, catch only the specific exception you're expecting.</li>\n<li>Since <code>operatorName</code> is used just for the exception, I would consider getting the name from the <code>operator</code>'s <a href=\"http://msdn.microsoft.com/en-us/library/system.delegate.method.aspx\" rel=\"nofollow noreferrer\"><code>Method</code></a>.</li>\n<li><code>_Value</code> probably should be exposed as a read-only property, since the cast is not very discoverable.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T17:43:20.333",
"Id": "40280",
"Score": "0",
"body": "1. Good one: Did not know about it. And since generic numbers is a common problem, I guess more people don't. 2. You are absolutely right. I will try to find out which exception is thrown if an operator is not supported. 3. I ve choosen to use the names op .NET (like `op_Modulus`) without the prefix. These name are sometimes different. 4. Why does it has to be exposed? Do you know about the internals of a TimeSpan or DateTime? If someone wants to access the internal value, he can cast the Number to the original type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T18:08:29.217",
"Id": "40283",
"Score": "0",
"body": "@MartinMulder Re 4. this is not about exposing internals, as you pointed out, you can already access the value using the cast. But I think it's a good idea to have an alternative way. If you have a `Number<int>`, it's usually simpler to find out that there is a `Value` property than to find that the cast works. Also, some .Net languages (like F#) treat casts differently, though that might not be relevant to you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-05-10T17:30:31.747",
"Id": "26039",
"ParentId": "26022",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T11:00:32.777",
"Id": "26022",
"Score": "14",
"Tags": [
"c#",
"linq",
"generics",
"calculator",
"overloading"
],
"Title": "Generic Calculator and Generic Number"
}
|
26022
|
<p>I am new to Java programming, and to help me learn, I created a simple telephone address book. The code runs as expected, but I would be interested to here from more advanced programmers if they think I should do it differently.</p>
<pre><code>import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.bson.types.ObjectId;
public class MongodbPhonebook {
public static void main(String[] args) {
boolean boolContinue = true;
String stringCommand;
Scanner input = new Scanner(System.in);
try {
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB( "myphonelist" );
DBCollection coll = db.getCollection("myphonelist");
do {
System.out.println("Enter command (add, find, show, quit): ");
stringCommand = input.nextLine();
if(stringCommand.equals("quit")){
boolContinue = false;
}
else if(stringCommand.equals("show")){
displayAll(coll);
}
else if(stringCommand.equals("add")){
insertNumber(coll);
}
else if(stringCommand.equals("find")){
findNumber(coll);
}
else {
System.out.println("Unknown command!");
}
} while(boolContinue == true);
}
catch (UnknownHostException e) {
e.printStackTrace();
}
catch (MongoException e) {
e.printStackTrace();
}
}
public static void displayAll(DBCollection collDisplay) {
DBCursor cursor = collDisplay.find();
try {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
} finally {
cursor.close();
}
return;
}
public static void insertNumber (DBCollection collInsert) {
Scanner input = new Scanner(System.in);
ObjectId stringID;
String stringName = "";
String stringNumber = "";
System.out.println("Enter name: ");
stringName = input.nextLine();
System.out.println("Enter number: ");
stringNumber = input.nextLine();
BasicDBObject doc = new BasicDBObject("name", stringName).
append("number", stringNumber);
collInsert.insert(doc);
stringID = (ObjectId)doc.get( "_id" );
System.out.println("Result: " + stringID.toString());
return;
}
public static void findNumber (DBCollection collFind) {
Scanner input = new Scanner(System.in);
String stringName = "";
System.out.println("Enter name: ");
stringName = input.nextLine();
BasicDBObject query = new BasicDBObject("name", stringName);
DBCursor cursor = collFind.find();
cursor = collFind.find(query);
try {
while(cursor.hasNext()) {
System.out.println("found " + cursor.next());
}
} finally {
cursor.close();
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T12:11:45.697",
"Id": "40268",
"Score": "1",
"body": "You did good. I like that you have methods that do exactly as you say they should. ie `displayAll` displays all your entries. My only small suggestion is to make all your methods not static and make the main method just make a instance of your class. For further learning and fun you could look into inheritance and separating your Database code from your main program so you can switch to different types of DB's"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T08:43:31.697",
"Id": "118340",
"Score": "0",
"body": "You might want to use a [ODM like Morphia](https://github.com/mongodb/morphia) for modeling your data as a next step. So you would create a Model for an address book entry and use the methods to manipulate that model. This makes the code more readable and maintainable on the long run."
}
] |
[
{
"body": "<p>I'm not sure what version of the JDK you are using, but in Java 7 they introduced switch statements on a String variable instead of just integers. Your code could instead read like this, to make it a little bit more readable. </p>\n\n<pre><code>do {\n System.out.println(\"Enter command (add, find, show, quit): \");\n stringCommand = input.nextLine();\n switch(stringCommand)\n {\n case \"quit\":\n boolContinue = false;\n break;\n case \"show\":\n displayAll(coll);\n break;\n case \"add\":\n insertNumber(coll);\n break;\n case \"find\":\n findNumber(coll);\n break;\n default:\n System.out.println(\"Unknown command!\");\n break;\n }\n } while(boolContinue); // A boolean variable by itself can be used as an expression. The == true expression is redundant.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T11:58:23.130",
"Id": "40465",
"Score": "0",
"body": "I'd get rid of `boolContinue` and `return` directly inside `case \"quit\"`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T16:05:51.453",
"Id": "26037",
"ParentId": "26023",
"Score": "2"
}
},
{
"body": "<p>Overall, it looks pretty good. Here are some points to consider:</p>\n\n<p>There is no need to explicitly <code>return</code> at the end of <code>void</code> methods, for example, at the end of <code>displayAll()</code>.</p>\n\n<p>Keep your variable declarations close to where they are used. For example, in <code>insertNumber()</code>, I would change this...</p>\n\n<pre><code>String stringName = \"\";\nString stringNumber = \"\";\nSystem.out.println(\"Enter name: \");\nstringName = input.nextLine();\nSystem.out.println(\"Enter number: \");\nstringNumber = input.nextLine();\n</code></pre>\n\n<p>...to this...</p>\n\n<pre><code>System.out.println(\"Enter name: \");\nString stringName = input.nextLine();\nSystem.out.println(\"Enter number: \");\nString stringNumber = input.nextLine();\n</code></pre>\n\n<p>Also, limit the scope of variables to the block where they are used. This follows from the point above. For example, in <code>main()</code>, <code>stringCommand</code> is declared near the top, but is only used inside the <code>do/while</code> block. I would remove the declaration above and change this line...</p>\n\n<pre><code>stringCommand = input.nextLine();\n</code></pre>\n\n<p>...to this...</p>\n\n<pre><code>String stringCommand = input.nextLine();\n</code></pre>\n\n<p>These will reduce the number of lines slightly, but will also make reading and debugging the code easier.</p>\n\n<p>As a slighter bigger project, you could change the methods to be non-static, then create an instance of <code>MongodbPhonebook</code> in <code>main()</code> to interact with instead. It may also make sense to move some of the code from <code>main()</code> somewhere else. For example, you could make the mongo variables private members of <code>MongodbPhonebook</code> and initialize them in the constructor.</p>\n\n<pre><code>public class MongodbPhonebook {\n\n private MongoClient mongoClient;\n private DB db;\n private DBCollection coll;\n\n public MongodbPhonebook() {\n this.mongoClient = new MongoClient();\n this.db = mongoClient.getDB( \"myphonelist\" );\n this.coll = db.getCollection(\"myphonelist\");\n }\n\n ...\n\n}\n</code></pre>\n\n<p>If you did this, you would no longer need to pass the <code>DBCollection</code> around to the other functions.</p>\n\n<p>Beyond that, consider separating the user interaction and database logic into separate functions. For example, split <code>findNumber()</code> into two functions: one to ask the user for input and display the results, the other to perform the search based on the supplied input. This would allow the database logic functions to be reused in different circumstances, for example, a web application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T20:52:56.260",
"Id": "26048",
"ParentId": "26023",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T11:58:26.347",
"Id": "26023",
"Score": "6",
"Tags": [
"java",
"beginner",
"mongodb"
],
"Title": "Simple telephone address book"
}
|
26023
|
<p>I have a running program. That accepts 1 to 15 variables
The goal of the program was a simplifier. Based on the <strong><em>Quine–McCluskey algorithm</em></strong></p>
<p>Consider 3 variables</p>
<pre><code>000
001
010
011
100
101
110
111
</code></pre>
<p>I group them by number of 1</p>
<pre><code>000
001
010
100
011
101
110
111
</code></pre>
<p>Then I compare each string from the group to the next group</p>
<pre><code>group 1
000
group 2
001
010
100
group 3
011
101
110
group1 -> group2
------------------
000 -> 001 = 00-
000 -> 010 = 0-0
000 -> 100 = -00
------------------
group2 ->group3
--------------------
001 -> 011 = 0-1
001 -> 101 = -01
001 -> 110 = no output
010 -> 011 = 01-
010 -> 101 = no output
010 -> 110 = -10
100 -> 011 = no output
100 -> 101 = 10-
100 -> 110 = 1-0
---------------------
etc.
</code></pre>
<p>then group the output again by number of 1 and compare them again until no strings can be compared.</p>
<p>I need to achieve a 15 variable but it take for ever for the program to finish.Any Idea how to speed it up. I was testing it on threading but just a little improvement.</p>
<blockquote>
<p>Number of Strings: 2048 Length of variable: 11 Time: 10 minutes</p>
</blockquote>
<p><em><strong>Need to Achieved</em></strong></p>
<blockquote>
<p>Number of Strings: 32767 Length of variable: 15 Time: cannot be achieved</p>
</blockquote>
<pre><code> List<List<string>> ImplicantsByOneFinal = new List<List<string>>();
List<List<string>> TermsByOne = new List<List<string>>();
</code></pre>
<p><em><strong>is there a way or algorithm to improve this code. it becomes slower on 11 to 15 variables.</em></strong> </p>
<pre><code>bool CombineAndGroup(List<List<string>> ImplicantsByOne)
{
TermsByOne = new List<List<string>>();
int combined = 0;
for (int i = 0; i < ImplicantsByOne.Count - 1; i++)
{
List<string> termsGrouped = new List<string>();
for (int j = 0; j < ImplicantsByOne[i].Count; j++)
{
int combination = 0;
int num1 = Convert.ToInt32((ImplicantsByOne[i][j]).Replace('-','0'), 2);
for (int k = 0; k < ImplicantsByOne[i + 1].Count; k++)
{
int num2 = Convert.ToInt32((ImplicantsByOne[i + 1][k]).Replace('-', '0'), 2);
int num3 = num2 - num1;
double num4 = Math.Log((double)num3, (double)2);
if (((num4 % 1) == 0) && (num3 > 0) && (Esum(ImplicantsByOne[i][j]) == Esum(ImplicantsByOne[i + 1][k])))
{
string combinedMinterm = CompareString(ImplicantsByOne[i][j], ImplicantsByOne[i + 1][k]);
if (!termsGrouped.Contains(combinedMinterm))
{
termsGrouped.Add(combinedMinterm);
}
}
}
}
if (termsGrouped.Count > 0)
{
combined += termsGrouped.Count;
}
TermsByOne.Add(termsGrouped);
}
return (combined > 0) ? true : false;
}
private int Esum(String binCode)
{
binCode = binCode.Replace('1','0');
binCode = binCode.Replace('-', '1');
int esum = Convert.ToInt32(binCode, 2);
return esum;
}
//Purpose of CompareString is to compare two string and change the unique char to '-'
//like 000 and 001 = 00-
private string CompareString(string str1, string str2)
{
if (str1 == str2)
{
CountCompareStringLoops++;
return str1;
}
else
{
if (str1.Length == 1)
{
return "-";
}
int halflength = str1.Length / 2;
return CompareString(str1.Substring(0, halflength), str2.Substring(0, halflength)) + CompareString(str1.Substring(halflength), str2.Substring(halflength));
}
}
</code></pre>
<p><em><strong>Main Program</em></strong></p>
<pre><code> MintermsByOne = Loaded with string 000 001 and so on
CombineAndGroup(MintermsByOne);
ImplicantsByOneFinal = TermsByOne;
while (CombineAndGroup(TermsByOne))
{
ImplicantsByOneFinal = TermsByOne;
}
</code></pre>
<p><strong>Output ImplicantsByOneFinal</strong> </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T12:39:48.780",
"Id": "40270",
"Score": "0",
"body": "It's good to see you here."
}
] |
[
{
"body": "<p>I don't know how to write C#, but I want to help. So my code is given in Java.</p>\n\n<ol>\n<li><p>I think <code>==</code> is an <code>O(n)</code> operation, your <code>CompareString</code> is <code>O(nlgn)</code> (<code>n = str1.Length</code>). Use a simpler and faster <code>O(n)</code> way and see if the time decreases:</p>\n\n<pre><code>private String CompareString(String str1, String str2) {\n StringBuilder sb = new StringBuilder(str1.length());\n for (int i = 0; i < str1.length(); i++) {\n if (str1.charAt(i) == str2.charAt(i))\n sb.append(str1.charAt(i));\n else\n sb.append('-');\n }\n return sb.toString();\n}\n</code></pre></li>\n<li>Well, I found that there are a lot of <code>ToInt32</code>. Calculate the result of all strings in <code>ImplicantsByOne</code> at once and use it later. Do the same thing to <code>Esum</code>.<br><br></li>\n<li><p>To check if <code>num3</code> is a power of two:</p>\n\n<pre><code>private boolean isPowerOfTwo(int x) {\n return (x > 0 && (x & (x - 1)) == 0);\n}\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T03:21:48.483",
"Id": "40313",
"Score": "0",
"body": "Thanks .I will try to get the time of CompareString if its faster.Also thanks for the Power of two method :)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T12:43:09.587",
"Id": "26025",
"ParentId": "26024",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T12:22:48.553",
"Id": "26024",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Based on Quine–McCluskey algorithm. Improve Nested loop for performance"
}
|
26024
|
<p>What would be the most efficient way to write the following code in Perl:</p>
<pre><code> my $index = 0;
foreach ( @spec ) {
if ( $module =~ m/$_/ ) {
splice(@spec, $index, 0, $module);
last;
}
$index++;
}
</code></pre>
<p>This works fine but just seems a little wordy. The idea is that where I find a match for $module in the array I add an entry. I want to keep the array in a certain order and sorted.</p>
|
[] |
[
{
"body": "<p>You want \"more efficient wordiness\"??? I presume you're not asking for golfing, but for code that's more readable from conciseness.</p>\n\n<pre><code>@spec = map { $_ eq $module ? ($_, $_) : $_ } @spec;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T15:25:11.070",
"Id": "40277",
"Score": "0",
"body": "Yeah this is perfect!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T13:11:58.637",
"Id": "26027",
"ParentId": "26026",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>You manually increment the <code>$index</code>. Just loop over the indices instead:</p>\n\n<pre><code>for my $index (0 .. $#spec) {\n if ($module =~ /$spec[$index]/) {\n splice @spec, $index, 0, $module;\n last;\n }\n}\n</code></pre>\n\n<p>On newer perls (v12+) you can use <code>each</code> on arrays:</p>\n\n<pre><code>use 5.012;\nwhile(my ($i, $str) = each @spec) {\n if ($module =~ /$str/) {\n splice @spec, $i, 0, $module;\n keys @spec; # reset the `each` iterator\n last;\n }\n}\n</code></pre></li>\n<li><p>If the values in <code>@spec</code> are not regexes, but just plain strings, and iff you want to test that <code>$module</code> <em>contains</em> the string in <code>$spec[$index]</code>, then you could use <code>index</code> for better efficiency.</p>\n\n<pre><code>if (-1 != index $module, $spec[$index]) { ... }\n</code></pre>\n\n<p>This also won't treat characters like <code>\\[]()?+*</code> as metacharacters any more. This would be similar to <code>/\\Q$spec[$index]\\E/</code> (see <code>quotemeta</code> function), but more efficient</p>\n\n<p>If you actually want to apply the string as a regex, this point is moot.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T14:36:08.407",
"Id": "40274",
"Score": "0",
"body": "Ad. #1: I'd use foreach loop and increment counter manyally just like OP, so it's rather subjective _(although `each` would be my choice if all production code run on >= v5.12)._"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T01:12:14.763",
"Id": "40355",
"Score": "0",
"body": "It would probably be safer to reset the iterator before you modify the array."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T13:12:55.173",
"Id": "26028",
"ParentId": "26026",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T12:53:29.050",
"Id": "26026",
"Score": "2",
"Tags": [
"perl"
],
"Title": "Adding an entry for a matched $module"
}
|
26026
|
<p>I would like an opinion on my code. I need a random access iterator for my custom container.
If I read the C++ 2011 standard, specially chapter 24, I understood that an implementation
could be the following:</p>
<pre><code>class my_iterator : public std::iterator<std::random_access_iterator_tag, my_element>
{
private:
my_container *_ref;
my_iterator_state state; // some useful state
public:
my_iterator ();
my_iterator (const my_iterator &);
my_iterator (my_iterator &&);
~my_iterator ();
my_iterator &operator = (const my_iterator &);
my_iterator &operator = (my_iterator &&);
reference operator * ();
my_iterator &operator ++ ();
bool operator != (my_iterator);
value_type operator * ();
pointer operator -> ();
my_iterator &operator * ();
void operator ++ (int);
value_type operator ++ (int);
const my_iterator &operator ++ (int);
reference operator ++ (int);
my_iterator &operator -- ();
const my_iterator operator -- (int);
reference operator -- (int);
my_iterator &operator += (difference_type);
my_iterator operator + (difference_type);
my_iterator operator - (difference_type);
reference operator [] (difference_type);
bool operator < (my_iterator);
bool operator > (my_iterator);
bool operator <= (my_iterator);
bool operator >= (my_iterator);
friend difference_type (my_iterator, my_iterator);
friend my_iterator operator + (difference_type, my_iterator);
friend void swap (iterator &, iterator &);
};
void swap (iterator &, iterator &);
difference_type (my_iterator, my_iterator);
my_iterator operator + (difference_type, my_iterator);
</code></pre>
<p>The above implementation is correct and full-featured? There are too members?</p>
|
[] |
[
{
"body": "<p>Sure but:</p>\n\n<p>Sure:</p>\n\n<pre><code> my_iterator ();\n bool operator != (my_iterator);\n pointer operator -> ();\n my_iterator& operator ++ ();\n my_iterator& operator -- ();\n my_iterator& operator += (difference_type);\n my_iterator operator + (difference_type);\n my_iterator operator - (difference_type);\n reference operator [] (difference_type);\n bool operator < (my_iterator);\n bool operator > (my_iterator);\n bool operator <= (my_iterator);\n bool operator >= (my_iterator);\n</code></pre>\n\n<p>But most of the above can be defined in terms of each other and are basically forwarding functions to one definition.</p>\n\n<p>The default versions of these look like they should work. So why are you defining them:</p>\n\n<pre><code> my_iterator (const my_iterator &);\n my_iterator (my_iterator &&);\n my_iterator &operator = (const my_iterator &);\n my_iterator &operator = (my_iterator &&);\n</code></pre>\n\n<p>Do you really need a destructor?</p>\n\n<pre><code> ~my_iterator ();\n</code></pre>\n\n<p>Three different version of <code>operator*</code> that only differ by return type!<br>\nThat does not look valid.</p>\n\n<pre><code> reference operator * ();\n value_type operator * ();\n my_iterator& operator * ();\n</code></pre>\n\n<p>Lots of <code>operator++(int)</code> that only differ by return type.<br>\nSo again does not look valid</p>\n\n<pre><code> void operator ++ (int);\n reference operator ++ (int);\n value_type operator ++ (int);\n const my_iterator& operator ++ (int);\n reference operator ++ (int);\n</code></pre>\n\n<p>Lots of <code>operator--(int)</code> that only differ by return type.<br>\nSo again does not look valid</p>\n\n<pre><code> const my_iterator operator -- (int);\n reference operator -- (int);\n</code></pre>\n\n<p>Look <a href=\"http://www.sgi.com/tech/stl/RandomAccessIterator.html\" rel=\"nofollow\">here</a> for a definition of what you need to support.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:31:54.610",
"Id": "26042",
"ParentId": "26030",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T14:46:52.953",
"Id": "26030",
"Score": "3",
"Tags": [
"c++",
"c++11",
"iterator",
"c++0x"
],
"Title": "Creating custom random access iterator in C++ 2011"
}
|
26030
|
<p>Looking for a cleaner (possibly one liner) way to write the following</p>
<pre><code>my $spec_2d = ( );
foreach ( @spec ) {
$spec_2d[$_][0] = $spec[$_];
}
@spec = @spec_2d;
</code></pre>
<p>Basically I'm making an array an array of arrays</p>
|
[] |
[
{
"body": "<pre><code>@spec_2d[@spec] = map [ $spec[$_] ], @spec;\n</code></pre>\n\n<p>but judging from the subject I think you want this,</p>\n\n<pre><code>my @spec_2d = map [ $_ ], @spec;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:53:33.010",
"Id": "26044",
"ParentId": "26031",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T15:28:28.317",
"Id": "26031",
"Score": "1",
"Tags": [
"perl"
],
"Title": "clean way to make array a 2d array"
}
|
26031
|
<p>I wrote John Conway's Game of Life in Java:</p>
<pre><code>class GameOfLife {
static int countSurrounding(int[][] board, int a, int b) {
int count = 0;
int[][] surrounding = {{a - 1, b - 1},
{a - 1, b },
{a - 1, b + 1},
{a , b - 1},
{a , b + 1},
{a + 1, b - 1},
{a + 1, b },
{a + 1, b + 1}};
for (int i[]: surrounding) {
try {
if (board[i[0]][i[1]] == 1) {
count++;
}
}
catch (ArrayIndexOutOfBoundsException e) {}
}
return count;
}
static void printBoard(int[][] board) {
for (int[] i: board) {
for (int j: i) {
if (j == 1) {
System.out.print("#");
}
else {
System.out.print(".");
}
}
System.out.println();
}
System.out.println();
}
public static void main(String[] args) {
int[][] nextBoard = {{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0}};
int[][] board = new int[nextBoard.length][nextBoard[0].length];
for (int gen = 0; gen < 25; gen++) {
for (int i = 0; i < nextBoard.length; i++) {
for (int j = 0; j < nextBoard[i].length; j++) {
board[i][j] = nextBoard[i][j];
}
}
printBoard(board);
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
if (board[i][j] == 1 && !(countSurrounding(board, i, j) == 2 || countSurrounding(board, i, j) == 3)) {
nextBoard[i][j] = 0;
}
else if (board[i][j] == 0 && countSurrounding(board, i, j) == 3) {
nextBoard[i][j] = 1;
}
}
}
}
}
}
</code></pre>
<p>How can I improve and optimize it?</p>
|
[] |
[
{
"body": "<p>A few suggestions:</p>\n\n<ul>\n<li><p>Each cell in the Game of Life has exactly two states: <em>dead</em> or <em>alive</em>. Unless you plan to implement <code>-1</code> as <em>undead</em>, I'd suggest you use booleans instead of integers to indicate the state.</p></li>\n<li><p>The <code>int i[]</code> is a bit odd; <code>i</code> is normally used for indices, not for whole rows.</p></li>\n<li><p>In <code>countSurrounding</code> you are using Exceptions to count the surrounding living cells. This is wasteful and unnecessary; we can determine the correct bounds ourself.</p>\n\n<p>Given an index <code>i</code> in an array <code>row</code>, we can get the lower index <code>min</code> and the upper index <code>max</code> by</p>\n\n<pre><code>int minRow = i == 0 ? 0 : i - 1;\nint maxRow = i == (row.length - 1) ? (row.length - 1) : i + 1;\n</code></pre>\n\n<p>The same thing for columns (<code>j</code> index in an array <code>column</code>):</p>\n\n<pre><code>int minCol = j == 0 ? 0 : j - 1;\nint maxCol = j == (column.length - 1) ? (column.length - 1) : j + 1;\n</code></pre>\n\n<p>This itself assumes that <code>i</code> and <code>j</code> always are inside the bounds. We can then loop over the surrounding cells like</p>\n\n<pre><code>for (int row_idx = minRow; row_idx <= maxRow; row_idx++) {\n for (int idx = minCol; idx <= maxCol; idx++) {\n if (board[row_idx][idx] && !(row_idx == i && idx == j)) { // assumes board is implemented with booleans\n count++\n }\n }\n}\n</code></pre>\n\n<p>While this is longer, this doesn't abuse exceptions for something totally non-exceptional.</p></li>\n<li><p>The <code>printBoard</code> is fine, except for my first two criticisms. The <code>if</code>/<code>else</code> can be condensed to a ternary; I'd find this easier to read:</p>\n\n<pre><code>for (boolean row[] : board) {\n for (boolean cell : row) {\n System.out.print( cell ? \"#\" : \".\" );\n }\n System.out.println();\n}\n</code></pre></li>\n<li><p>In <code>main</code>, you initialize <code>nextBoard</code> with the initial board, then copy it over into <code>board</code>. This is slightly useless. I'd propose to refactor your <code>main</code> into a method <code>boolean[][] nextGeneration(boolean[][] board)</code>. Your <code>main</code> would then look like</p>\n\n<pre><code>int[][] initialBoard = ...;\npublic static void main(String[] args) {\n int[][] board = new int[nextBoard.length][nextBoard[0].length];\n // copy over the initial board\n for (int i = 0; i < initialBoard.length; i++) {\n for (int j = 0; j < initalBoard[i].length; j++) {\n board[i][j] = initialBoard[i][j];\n }\n }\n // loop over 25 generations\n printBoard(board);\n for (int gen = 0; gen < 25; gen++) {\n System.out.println(\"\\nGeneration \" + gen);\n board = nextGeneration(board);\n printBoard(board);\n }\n}\n</code></pre></li>\n<li><p>Now something is becoming obvious: We have collected a few static methods that operate on our <code>board</code> array. This is a sign that we should create a seperate class:</p>\n\n<pre><code>Board\n========\n- board: boolean[][]\n--------\n- countSurrounding(i: int, j: int): int\n+ toString(): String\n+ nextGeneration(): Board\n</code></pre>\n\n<p>The class could be easily extended to have a static default board, or a constructor that creates a random board.</p></li>\n<li><p>Each “Game of Life” can be described by a ruleset like <code>23/3</code>. The digits before the slash determine when a living cell stays alive, the digits after the slash determine when a new cell is born. Generalizing <code>nextGeneration</code> to be able to play with all possible rules is a nice exercise.</p>\n\n<pre><code>private boolean nextCellState(int i, int j) {\n int count = countSurrounding(i, j);\n int rules[] = board[i][j] ? stayAlive : birthNew;\n for (int rule : rules) {\n if (rule == count) {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>then</p>\n\n<pre><code>public Board nextGeneration() {\n boolean next[][] = new boolean[board.length][board[0].length];\n int rows = board.length;\n int cols = board.[0].length;\n for (int i = 0; i < rows; i++) {\n for (int j = 0; j < cols; j++) {\n next[i][j] = nextCellState(i, j);\n }\n }\n return new Board(next);\n}\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-24T14:10:28.830",
"Id": "483212",
"Score": "0",
"body": "You had my `+1` at \"undead\". Great example of excessive value spaces."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T11:09:14.443",
"Id": "26066",
"ParentId": "26033",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "26066",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T15:42:09.860",
"Id": "26033",
"Score": "12",
"Tags": [
"java",
"game-of-life"
],
"Title": "Game of Life in Java"
}
|
26033
|
<p>I have code like the following, which performs a series of replacements on a string, to convert it to its final form.</p>
<pre><code>public String convertString(String string) {
String convertedString = string;
if( string.contains("something")) {
convertedString = convertStringA(string);
return convertedString;
} else if (string.contains("something else")) {
convertedString = convertStringB(string);
return convertedString;
} ...
// many more else if blocks
else if (string.contains("something else")) {
convertedString = convertStringXXX(string);
return convertedString;
} ...
}
</code></pre>
<p>How can I do it better?</p>
|
[] |
[
{
"body": "<p>Your Algorithm is a little bit too abstract to provide a one size fits all solution.</p>\n\n<p>What does it mean, when a string contains \"something\" or \"something else\"?\nAre they completely different strings like \"I know (something)\" and \"He gave me (something else)\"? Or are there similarities like:\n\"Peter knows (something)\" and \"Joe knows (something else)\". So \"knows\" would be the keyword after which your phrase occurs. \"Contains\" is somehow a little bit unprecise.</p>\n\n<p>If it is relativly easy to extract the substring you need -perhaps with a regular expression- you could use a HashMap to provide the correct converter with a simple call with the phrase as the key. </p>\n\n<pre><code>public class Converters {\n\n HashMap<String, Converter> converters=new HashMap<String, Converter>(); \n\n public Converters(){\n // Fill Hashmap here\n }\n\n public Converter getConverterFor(String phrase){\n if (!converters.containsKey(phrase)) throw new NoConverterFoundException();\n return converters(phrase);\n } \n\n}\n</code></pre>\n\n<p>Converter is here an interface, which all of your converters have to implement.\nThis solution provides easy maintenance - a new Converter needs only one new entry in the HashMap. And no unreadable if-else-whattheeckyouwantelse-blocks anymore.</p>\n\n<p>But this is only one possible solution. A better solution requires more information on your phrases.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T07:52:01.417",
"Id": "40319",
"Score": "0",
"body": "Strings are completely different."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T20:14:52.703",
"Id": "26045",
"ParentId": "26041",
"Score": "3"
}
},
{
"body": "<p>I'd start with an interface:</p>\n\n<pre><code>public interface Converter {\n boolean canHandle(String inputString);\n String convert(String inputString);\n}\n</code></pre>\n\n<p>and write a few implementations, like <code>SomethingConverter</code>, <code>OtherConverter</code>, etc. An example:</p>\n\n<pre><code>public class SomethingConverter implements Converter {\n\n public boolean canHandle(final String inputString) {\n return StringUtils.contains(inputString, \"something\");\n }\n\n public String convert(String inputString) {\n ...\n }\n}\n</code></pre>\n\n<p>Then put them into a collection:</p>\n\n<pre><code>final List<Converter> converters = new ArrayList<>();\nconverters.put(new SomethingCoverter());\nconverters.put(new OtherConverter());\n</code></pre>\n\n<p>and finally use them:</p>\n\n<pre><code>for (final Converter converter: converters) {\n if (converter.canHandle(inputString)) {\n return converter.convert(inputString);\n } \n}\nthrow new IllegalArgumentException(\"Unhandled input: \" + inputString); // may not be applicable, depends on the requirements\n</code></pre>\n\n<p>I've used <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#contains%28java.lang.String,%20java.lang.String%29\" rel=\"nofollow\"><code>StringUtils.contains</code></a> beacuse it's null-safe, it does not throw NullPointerException if the <code>inputString</code> is <code>null</code></p>\n\n<p>(The code is not tested, feel free to fix the typos if there is any.)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T07:52:57.873",
"Id": "40320",
"Score": "1",
"body": "Thanks! It looks much better! I will use your solution. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T20:21:37.667",
"Id": "26047",
"ParentId": "26041",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26047",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T19:03:08.573",
"Id": "26041",
"Score": "2",
"Tags": [
"java",
"design-patterns"
],
"Title": "Performing multiple substring replacements on a string"
}
|
26041
|
<p>This is my first "large scale" system I've designed for myself. Since I'm more of a front end developer than backend developer, I'm not sure if my architecture is sound.</p>
<p>I've created a <code>Factory</code> class which I use to create all my classes and connect to the DB. I think I've tried to use used Singelton(?) pattern, but I'm not really sure.</p>
<p>It probably would be easier if you knew more about the system, but in short it's an online directory mixed with user interaction and social media.</p>
<p>It would be great if I could get some feedback on this.</p>
<p>My factory class</p>
<pre><code>include_once('abc.class.php');
class Factory {
// One function for each class I include
// This is the only place I include class files
function new_abc_obj($id = NULL) { return new Abc(Conn::get_conn(), $id); }
}
</code></pre>
<p>My DB connection class</p>
<pre><code>class Conn {
private static $conn = NULL;
/* Establish PDO DB connection */
private static function init() {
$conf = self::config();
try {
self::$conn = new PDO($conf['dsn'], $conf['user'], $conf['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
catch (PDOException $e) {
// We remove the username if we get [1045] Access denied
if (preg_match("/\b1045\b/i", $e->getMessage()))
echo "SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)";
else
echo $e->getMessage();
}
}
/* Get DB connection */
public static function get_conn() {
if (!self::$conn) { self::init(); }
return self::$conn;
}
/* Get username, password and db data from config.php */
private static function config() {
$conf = array();
$conf['user'] = DB_USER;
$conf['pass'] = DB_PASSWORD;
$conf['dsn'] = 'mysql:dbname='.DB_NAME.';host='.DB_HOST;
return $conf;
}
}
</code></pre>
<p>My class interface</p>
<pre><code>interface iAbc {
public function one();
public function two();
}
</code></pre>
<p>My Business Logic Layer (BLL)</p>
<pre><code>class Abc extends AbcDAO implements iAbc {
private $data = array();
protected $db;
function __construct(&$db, $id) {
$this->db = &$db;
if($id) {
$this->setData($id);
}
}
// __set, __get, __isset is here
public function one(){};
public function two(){
$result = parent::get_some_data();
return $result;
};
}
</code></pre>
<p>My Data Access Layer (DLL)</p>
<pre><code>class AbcDAO {
protected function get_some_data($name){
$sql ="SELECT 123;";
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
return $result;
}
}
</code></pre>
<p>And this is how I create the object:</p>
<pre><code>$my_abc = Factory::new_abc_obj();
$test = $my_abc->two();
</code></pre>
|
[] |
[
{
"body": "<h2>Factory</h2>\n\n<p>Three things about this:</p>\n\n<ol>\n<li>Consider using an autoloader (see <a href=\"https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md\" rel=\"nofollow\">PRS-0</a>). Then you don't have to bother about, where files get included.</li>\n<li>A Factory is used to create a set of objects, which depends on some context. For example, you could have a <code>Filter</code> and a <code>Renderer</code> for XHTML or HTML5. In order not having to check which one is needed again and again, you have an <code>XhmtlFactory</code> and an <code>Html5Factory</code> with <code>createFilter()</code> and <code>createRenderer()</code> methods.</li>\n<li>Factory methods usually are named <code>create...</code>.</li>\n</ol>\n\n<p>In your context, a Factory is not helping you.</p>\n\n<h2>DB Connection</h2>\n\n<p>Don't use static methods, if you can avoid it. Inject dependencies whereever possible. Do not (finally) handle errors within your classes. Leave that up to the caller. The method to get an instance is usually called <code>getInstance()</code> (and is one of the few cases, where static calls are reasonable). The initialization is then made in a private constructor.</p>\n\n<pre><code>class Conn\n{\n private $conn = null;\n\n /**\n * Establish PDO DB connection\n */\n private function __construct(Config $conf)\n {\n try { \n self::$conn = new PDO($conf->dsn, $conf->user, $conf->pass, array(PDO::MYSQL_ATTR_INIT_COMMAND => \"SET NAMES utf8\"));\n } catch (PDOException $e) {\n $message = $e->getMessage();\n // We remove the username if we get [1045] Access denied\n if (preg_match('/\\b1045\\b/i', $message)) {\n $message = \"SQLSTATE[28000] [1045] Access denied for user 'name removed' @ 'localhost' (using password: YES)\";\n }\n throw new ErrorException($message);\n }\n }\n\n /**\n * Get DB connection\n */\n public static function getInstance(Config $conf)\n {\n if (is_null($this->$conn)) {\n $this->conn = new Conn($config);\n }\n return $this->conn;\n }\n}\n\nclass Config\n{\n public $dsn = 'mysql:dbname=' . DB_NAME . ';host=' . DB_HOST;\n public $user = DB_USER;\n public $pass = DB_PASSWORD;\n} \n</code></pre>\n\n<p>To make the singleton pattern in <code>Conn</code> complete, the magic method <code>__clone()</code> should made private, so the connection cannot be copied.</p>\n\n<h2>Business Logic Layer</h2>\n\n<p>Keep the business and data access layer separated. The business layer ideally does not know anything about storage. The data access layer is injected into the business layer.</p>\n\n<pre><code>class Abc implements iAbc\n{\n private $data = array();\n protected $dal;\n\n public function __construct($dal, $id = null)\n {\n $this->dal = $dal;\n\n if (!is_null($id)) {\n $this->setData($id);\n }\n }\n\n // __set, __get, __isset is here\n\n public function one(){};\n\n public function two()\n {\n $name = 'foo';\n $result = $this->dal->get_some_data($name);\n return $result;\n };\n}\n</code></pre>\n\n<h2>Data Access Layer</h2>\n\n<pre><code>class AbcDao\n{\n private $db = null;\n\n public function __construct(Conn $db)\n {\n $this->db = $db;\n }\n\n public function get_some_data($name)\n {\n $sql =\"SELECT 123;\";\n $stmt = $this->db->prepare($sql);\n $stmt->bindParam(':name', $name, PDO::PARAM_STR);\n $stmt->execute();\n\n $result = $stmt->fetchAll();\n return $result;\n }\n}\n</code></pre>\n\n<h2>Controller</h2>\n\n<p>In your controller, you now really have control.</p>\n\n<pre><code>$config = new Config; // You could use any other set of config data\n$conn = new Conn($config); // You could use any other storage method\n$my_abc = new Abc($conn);\n$test = $my_abc->two();\n</code></pre>\n\n<p>or, shorter</p>\n\n<pre><code>$my_abc = new Abc(new Conn(new Config));\n$test = $my_abc->two();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T08:25:45.127",
"Id": "40383",
"Score": "0",
"body": "Awesome answer! It's a bit sad that I'm the first upvoter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T17:57:21.320",
"Id": "40577",
"Score": "0",
"body": "@nibra Thanks for in depth answer. One of the reasons why I created the factory was so that I don't have to call the DB connection every time I create a class. Only create the DB connection once, and use it for all the classes. Is this possible? Why can't `new Config` be inside `Conn()`? Do you know if this autoloader will conflict with he autoloader Wordpress is using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T21:29:11.153",
"Id": "40586",
"Score": "0",
"body": "DB Connection: You create it once and inject it into other objects for use. Config: If `new Config` is inside con, you loose the possibility to use another configuration (eg. for testing)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T21:31:18.270",
"Id": "40587",
"Score": "0",
"body": "The autoloader question could be good as new question. That answer does not belong here."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T17:43:08.557",
"Id": "26085",
"ParentId": "26052",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26085",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-10T21:49:25.283",
"Id": "26052",
"Score": "2",
"Tags": [
"php",
"mysql"
],
"Title": "How can this layered PHP architecture be improved?"
}
|
26052
|
<p>I've written a short snippet of code to replace JQuery's $.post ( to get ride of JQuery, mainly ). The function does seem to work. But, since I might be using this function in a couple of other pages, I'm just hoping to get a general review of the code.</p>
<p>I'm not confident the parameter formatting is done properly ( I couldn't find a lot of information on the web concerning how to pass parameters to .send( ). So if anyone sees that I have done it correctly or not, that would help.</p>
<p>Here's the code:</p>
<pre><code>function FileRequest(data, successFunction) {
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else request = new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = function () {
if((request.readyState == 4) && (request.status == 200)) {
if(typeof (successFunction) == "function") successFunction(request.responseText);
}
}
request.open("POST", "fileHandler.php", true);
if(typeof (data) != "undefined") {
var parameterNames = ["command=",
"arg1=",
"arg2="
],
parameters = "";
for(var i = 0; data[i] && (i < 3); i++) {
parameters += parameterNames[i] + encodeURI(data[i]);
if(data[i + 1]) parameters += "&";
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", parameters.length);
request.send(parameters);
} else request.send();
}
</code></pre>
<p>Here's an example of it's use:</p>
<pre><code>FileRequest(["load", "Projects/test.c"], function (data) {
alert(data);
});
</code></pre>
|
[] |
[
{
"body": "<p>First of all, I'd suggest you use a library for several reasons:</p>\n\n<ul>\n<li><p>It's abstracted a lot of cross-browser differences</p></li>\n<li><p>Spread the task of the code to the community. That way you focus more on the task at hand, rather than fixing some bugs.</p></li>\n<li><p>More event and processing support, like on errors, on complete, on success, on beforesend and others.</p></li>\n</ul>\n\n<p>Anyways, moving to your code</p>\n\n<pre><code>function FileRequest(data, successFunction) {\n\n //The compiler pulls up variable and function declarations.\n //To avoid visibility confusion, we'll write them that way as well\n var parameters = '';\n var key;\n\n if(window.XMLHttpRequest)request = new XMLHttpRequest();\n else request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n\n request.onreadystatechange = function () {\n //the early return pattern is best to avoid deep indention\n //so if the request isn't complete and successful, return\n //also, always use strict comparison when possible\n if(!(request.readyState === 4 && request.status === 200)) return;\n\n if(typeof successFunction === \"function\") successFunction(request.responseText);\n }\n\n //the third parameter defaults to true so we can omit\n request.open(\"POST\", \"fileHandler.php\");\n\n //for scalability, you should not hard-code the parameter names\n //allow the user of the API to define the data name.\n //thus we use objects, and the for-in loop\n\n //since we use objects, we'll have to check if it is\n //the simplest check is to check if it's not null, it's an object but not an array\n if(data && typeof data === 'object' && !(data instanceof Array)){\n\n for(key in data){\n //similar to early-return pattern, the early continue\n //which skips early if we the condition is met.\n //if the key isn't from the data but from prototype, we skip\n if(!data.hasOwnProperty(key)) continue;\n\n //append to parameters\n parameters += key + '=' + encodeURI(data[key]) + '&';\n\n }\n request.setRequestHeader(\"Content-type\", \"application/x-www-form-urlencoded\");\n request.setRequestHeader(\"Content-length\", parameters.length);\n }\n\n //so we send either a blank or something\n request.send(parameters);\n}\n\nFileRequest({\n command : 'load',\n arg1 : 'Projects/test.c'\n },\n function (data){\n //when debugging, use console.log if the browser supports it\n console.log(data);\n }\n);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T05:21:29.797",
"Id": "40314",
"Score": "0",
"body": "Thanks Joseph, that helps a lot. I agree with your points about using libraries. I usually just re-implement these functions just for practice, mainly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T05:25:04.263",
"Id": "40315",
"Score": "1",
"body": "I also noticed that you removed encodeURI( ) from the parameter data. I think that should still be there, if you get a chance"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T05:35:06.620",
"Id": "40316",
"Score": "0",
"body": "@TaylorFlores yup, seem to have missed that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T05:06:43.090",
"Id": "26057",
"ParentId": "26054",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26057",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T02:34:04.597",
"Id": "26054",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "XMLRequest Function"
}
|
26054
|
<p>As I am getting my Linq query to a functional point, I start looking at the query and think about all the "ANY" and wonder if those should be a different method and then I have data conversions going on.</p>
<p>Does anything jump out as being a performance issue? What is recommended to make this more performant? (Yes, I need all the <code>&&</code>.)</p>
<pre><code>etchVector =
from vio in list
where excelViolations.Any(excelVio => vio.VioID.Formatted.Equals(excelVio.VioID.ToString()))
&& excelViolations.Any(excelVio => vio.RuleType.Formatted.Equals(excelVio.RuleType))
&& excelViolations.Any(excelVio => vio.VioType.Formatted.Equals(excelVio.VioType))
&& excelViolations.Any(excelVio => vio.EtchVects.Any(x => x.XCoordinate.Equals(excelVio.XCoordinate)))
&& excelViolations.Any(excelVio => vio.EtchVects.Any(y => y.YCoordinate.Equals(excelVio.YCoordinate)))
select new EtchVectorShapes
{
VioID = Convert.ToInt32(vio.EtchVects.Select(x => x.VioID)),
ObjectType = vio.EtchVects.Select(x => x.ObjectType).ToString(),
XCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.XCoordinate)),
YCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.YCoordinate)),
Layer = vio.EtchVects.Select(x => x.Layer).ToString()
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T01:21:33.010",
"Id": "40307",
"Score": "0",
"body": "Do you need to perform the `ToList()` call? This will (of course) freeze the enumerable contents at creation time, so maybe this is hat you require; but maybe not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T01:40:59.733",
"Id": "40308",
"Score": "0",
"body": "I honestly don't see anything to improve regarding the performance of the LINQ portion of the query."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T01:42:15.443",
"Id": "40309",
"Score": "2",
"body": "Though it would be nice to refactor some of those operations into separate methods, IMHO."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T01:54:31.497",
"Id": "40310",
"Score": "0",
"body": "And the universal answer for all performance questions: what did the profiler say was slow?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T02:25:11.913",
"Id": "40311",
"Score": "0",
"body": "I haven't ran it through any profiler, I certainly need to. Just looking to see if there is a code smell or something obvious that someone sees that is a \"yikes\" ( like a cursor in sql server comes to mind). thx"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T11:50:33.400",
"Id": "40326",
"Score": "0",
"body": "1) Does this code even work? `Convert.ToDouble(vio.EtchVects.Select(x => x.YCoordinate))` looks weird. 2) Which variant of LINQ is this? Linq-to-objects? 3) How many entries does `excelViolations` have?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T11:56:34.297",
"Id": "40328",
"Score": "0",
"body": "Your &&Any logic looks weird. Are you sure you want it like that? In your code each property of `vio` needs a matching entry in `excelViolation`, but the matches can be in different entries. For example if for one of the `excelViolation` entries everything except the xCoordinate match, and another entry has almost everything wrong but xCoordinate matches those together allow `vio` to pass."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T20:45:19.223",
"Id": "40349",
"Score": "0",
"body": "Yikes, you are right. Those Convert.ToDoubles and even the ToString() do not work. What can I do to get the correct types?"
}
] |
[
{
"body": "<p>You can definitely optimize this query. If <code>list</code> has M items and <code>excelViolations</code> has N items, the query will iterate <code>excelViolations</code> M*5N times.</p>\n\n<p>It is possible to reduce this to M*N iterations by consuming <code>excelViolations</code> only once per item in <code>list</code>. You can do this with a subquery on <code>excelViolations</code> that checks all five conditions for each <code>excelVio</code>, then ORs each of the five conditions across all <code>excelVio</code> instances.</p>\n\n<p>If that is not clear, hopefully this walkthrough is:</p>\n\n<pre><code>from vio in list\n\n// Perform all five checks for each excelVio\n\nlet checks = excelViolations\n .Select(excelVio => new\n {\n HasVioID = vio.VioID.Formatted.Equals(excelVio.VioID.ToString()),\n HasRuleType = vio.RuleType.Formatted.Equals(excelVio.RuleType),\n HasVioType = vio.VioType.Formatted.Equals(excelVio.VioType),\n HasXCoordinate = vio.EtchVects.Any(x => x.XCoordinate.Equals(excelVio.XCoordinate)),\n HasYCoordinate = vio.EtchVects.Any(y => y.YCoordinate.Equals(excelVio.YCoordinate))\n })\n\n// From left to right, OR each of the five results (equivalent to .Any)\n\n .Aggregate((left, right) => new\n {\n HasVioID = (left.HasVioID || right.HasVioID),\n HasRuleType = (left.HasRuleType || right.HasRuleType),\n HasVioType = (left.HasVioType || right.HasVioType),\n HasXCoordinate = (left.HasXCoordinate || right.HasXCoordinate),\n HasYCoordinate = (left.HasYCoordinate || right.HasYCoordinate)\n })\n\n// Filter to only those that pass every check\n\nwhere checks.HasVioID\n && checks.HasRuleType\n && checks.HasVioType\n && checks.HasXCoordinate\n && checks.HasYCoordinate\n\n// Same projection\n\nselect new EtchVectorShapes\n{\n VioID = Convert.ToInt32(vio.EtchVects.Select(x => x.VioID)),\n ObjectType = vio.EtchVects.Select(x => x.ObjectType).ToString(),\n XCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.XCoordinate)),\n YCoordinate = Convert.ToDouble(vio.EtchVects.Select(x => x.YCoordinate)),\n Layer = vio.EtchVects.Select(x => x.Layer).ToString()\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T02:41:04.123",
"Id": "26056",
"ParentId": "26055",
"Score": "4"
}
},
{
"body": "<p>The underlying problem is that vio.EtchVects is <code>IEnumerable<T></code>, and LINQ <code>IEnumerable<T>.Select</code> functions still return <code>IEnumerable<T></code>. Your <code>Convert.ToX</code> functions are expecting scalar values.</p>\n\n<p>For simplicity, I will build from @Bryan Watts' answer, starting only with the select statement.</p>\n\n<p>If you want only the EtchVectors as a flat list, you can do the following:</p>\n\n<pre><code>from vect in vio.EtchVects\nselect new EtchVectorShapes\n{\n VioID = Convert.ToInt32(vect.VioID),\n ObjectType = vect.ObjectType.ToString(),\n XCoordinate = Convert.ToDouble(vect.XCoordinate),\n YCoordinate = Convert.ToDouble(vect.YCoordinate),\n Layer = vect.Layer.ToString()\n};\n</code></pre>\n\n<p>If you want them to retain the same organizational hierarchy they started with, you can do something similar to the following:</p>\n\n<pre><code>select new EtchVectorShapes\n{\n Shapes = from vect in vio.EtchVects\n select new EtchVectorShape\n {\n VioID = Convert.ToInt32(vect.VioID),\n ObjectType = vect.ObjectType.ToString(),\n XCoordinate = Convert.ToDouble(vect.XCoordinate),\n YCoordinate = Convert.ToDouble(vect.YCoordinate),\n Layer = vect.Layer.ToString()\n }\n};\n</code></pre>\n\n<p>If you only want one of the vectors from each vio, you could use one of the scalar LINQ functions (e.g., First or Last) or one of the aggregate functions (e.g., Max or Sum):</p>\n\n<pre><code>let vect = vio.EtchVects.First ()\nselect new EtchVectorShapes\n{\n VioID = Convert.ToInt32(vect.VioID),\n ObjectType = vect.ObjectType.ToString(),\n XCoordinate = Convert.ToDouble(vect.XCoordinate),\n YCoordinate = Convert.ToDouble(vect.YCoordinate),\n Layer = vect.Layer.ToString()\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:25:07.817",
"Id": "40412",
"Score": "0",
"body": "I still get errors as mentioned above with all the conversions like Convert.ToInt32 etc.. VioID = Convert.ToInt32(vect.VioID),\n ObjectType = vect.ObjectType.ToString(),\n XCoordinate = Convert.ToDouble(vect.XCoordinate),\n YCoordinate = Convert.ToDouble(vect.YCoordinate),\n Layer = vect.Layer.ToString()"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T17:16:27.660",
"Id": "26115",
"ParentId": "26055",
"Score": "0"
}
},
{
"body": "<p>This is without optimizations, but the errors that you describe seem to be in how you are getting the data. </p>\n\n<p>Based on your lists within list and the error message you are getting , try something like this:</p>\n\n<pre><code>etchVector = list.Where(vio => excelViolations.Any(currVio => vio.VioID.Formatted.Equals(currVio.VioID.ToString())\n && vio.RuleType.Formatted.Equals(currVio.RuleType)\n && vio.VioType.Formatted.Equals(currVio.VioType)\n && vio.Bows.Any(bw => bw.XCoordinate.Equals(currVio.XCoordinate))\n && vio.Bows.Any(bw1 => bw1.YCoordinate.Equals(currVio.YCoordinate)))).SelectMany(vi => vi.EtchVects).ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:26:05.867",
"Id": "40413",
"Score": "0",
"body": "that works, interesting. that fixed my data problem, now onto the optimization. thanks"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:23:48.690",
"Id": "26124",
"ParentId": "26055",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26124",
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T01:15:10.773",
"Id": "26055",
"Score": "2",
"Tags": [
"c#",
"performance",
"linq"
],
"Title": "Linq query performance improvements"
}
|
26055
|
<p>I am learning actionscript 3 coding by making a crappy platformer game :)</p>
<p>The problem I am facing is passing lots of options to a construct function that will setup the display object where all of them have default values.</p>
<p>I could send the options the normal way, like this:</p>
<pre><code>function Box(param1:Number=1, param2:Number=2, param3:Number=3, param4:Number=4){
}
</code></pre>
<p>but this seemed to be parameter pollution, so I made this class:</p>
<pre><code>package
{
import flash.display.Sprite;
public class Box extends Sprite {
public var color:Number = 0x000000;
public var tileW:Number = 50;
public var tileH:Number = 50;
public var walkable:Boolean = true;
public var speedY:Number = 0;
public var speedX:Number = 0;
function Box(options:Object) {
for(var i:String in options) {
this[i] = options[i];
}
graphics.beginFill(this.color);
graphics.drawRect(0, 0, this.tileW, this.tileH);
graphics.endFill();
}
}
}
</code></pre>
<p>This works, but I have a feeling that I am missing something very basic, that everything I try to write is wrong...</p>
|
[] |
[
{
"body": "<p>People do this sort of thing all the time in the JavaScript (this.arguments) and Python world (*args); however, by removing type constraints from the parameter list, you have to be wary that you're always providing the types of parameters your function is expecting. If one of your parameters is supposed to be a string, and someone passes in an object, bad things may happen.</p>\n\n<p>Conversely, some very respectable projects use multi-line parameter lists. It's fine to have a lot of parameters, as long as they're all necessary, but it's always good to be skeptical. Long parameter lists is a good code smell – if you see them, the code <em>may</em> need refactoring, but not always.</p>\n\n<p>As far as the attributes of Box's, forget about programming for a second. Conceptually, what are the properties of a box? Can a box still be a box without a color, tileW, tileH, walkable, speedY, and speedX? Can a box still be a box if it doesn't know how to draw itself? If your answer is no to all of these, then your code is fine, and requiring parameters as a single collection/object vs. individual parameters is (arguably) a matter of preference.</p>\n\n<p>That being said, I would move the three <code>graphics.*</code> lines to a separate method <code>Box.draw()</code>. It's best to <em>only</em> do construction in the constructor, and leave the rest – like rendering – to other methods.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T16:29:28.240",
"Id": "40571",
"Score": "0",
"body": "I generally don't like long parameter lists because if one parameter get deprecated you can't remove it without breaking old code, so you have to pass null. So I set myself a limit of 3 params per function call. Also thank you for the Box advice :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:23:07.250",
"Id": "26207",
"ParentId": "26062",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T07:44:14.020",
"Id": "26062",
"Score": "1",
"Tags": [
"actionscript-3"
],
"Title": "Passing lots of options to a function"
}
|
26062
|
<p>How can I improve my jQuery form preview implementation? I'm currently using the <a href="http://potomak.github.io/jquery-instagram/" rel="nofollow">jQuery Instagram Plugin</a> to get the hashtag from Instagram. </p>
<pre><code>var timeoutReference;
var element;
var tagsa;
$(document).ready(function() {
$('input#instagram_hashtag_hashtag').keypress(function() {
if (timeoutReference) clearTimeout(timeoutReference);
timeoutReference = setTimeout(function() {
doneTyping($('input#instagram_hashtag_hashtag').val());
}, 350);
});
$('input#instagram_hashtag_hashtag').blur(function(){
doneTyping($('input#instagram_hashtag_hashtag').val());
});
});
function doneTyping(tags){
if (!timeoutReference){
return;
}
tagsa = null;
tagsa = tags.match(/(^#|\s#)([a-z0-9]+)/gi);
timeoutReference = null;
var length = tagsa.length,
element = null;
for (var i = 0; i < length; i++) {
element = tagsa[i];
$(function(){
var
insta_container = $(".instagram")
, insta_next_url
insta_container.instagram({
hash: element.replace("#", "")
, clientId: 'instagramclientid'
, show : 4
})
});
}
}
</code></pre>
|
[] |
[
{
"body": "<pre><code>//$(document).ready(fn) can be shortened to $(fn)\n//you can use it to avoid global scope pollution so we place everything in here\n$(function () {\n\n //IDs are unique, so we drop input\n //cache values that are static and used more than once\n var instagramHashtag = $('#instagram_hashtag_hashtag');\n var pattern = /(^#|\\s#)([a-z0-9]+)/gi;\n var instaContainer = $('.instagram');\n var timer;\n\n function doneTyping(tags) {\n\n //why create the timer check? besides, if the function was called and\n //tags was blank, the loop wouldn't run since there are no matches\n\n //these variables are only used here, so declare them in here\n var tagsa = tags.match(pattern);\n var length = tagsa.length;\n var i = 0; \n\n while(i < length) {\n instaContainer.instagram({\n hash: tagsa[i++].replace('#', ''),\n clientId: 'instagramclientid',\n show: 4\n });\n }\n }\n\n //use jQuery on, which accepts a map of events\n //that way, you write the selector part only once\n instagramHashtag.on({\n keypress: function () {\n if(timer) clearTimeout(timer);\n timer = setTimeout(function () {\n doneTyping(instagramHashtag.val());\n }, 350);\n },\n blur: function () {\n doneTyping(instagramHashtag.val());\n }\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T09:24:31.733",
"Id": "40321",
"Score": "1",
"body": "Thanks for your great answer. Two issues the first is a syntax error: 'keypress: function () {}' to 'keypress: function () {' the second is my Instagram script no longer shows just 4 images it now shows 10+ - is there any obvious reason for this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T09:30:57.487",
"Id": "40322",
"Score": "0",
"body": "@thmsmxwll thanks for the correction. As for the plugin, that I don't know. I assume your script takes in hash tags, splits them and removes the hash sign. And for each tag, fetch 4 pictures."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T09:33:36.610",
"Id": "40323",
"Score": "0",
"body": "Strange this wasn't happening for my original. Regardless, thanks for the help! Marked correct."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T08:19:19.403",
"Id": "26064",
"ParentId": "26063",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26064",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T07:50:18.447",
"Id": "26063",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"instagram"
],
"Title": "jQuery form preview using the Instagram plugin"
}
|
26063
|
<p>I have set up a basic MVC project which is a student administration application based upon a CSV file as datastore. Each user has a specific role (student, lecturer, professor, leader of degree program). After successful login, the main window should have different actions to be performed based upon each role.</p>
<p>How can I hide the login view after successful login and show the main window depending on each user's role?</p>
<p>What about interfaces and abstract classes? Can I generalize/abstract the code better?</p>
<p>Regarding the different roles, I've thought about <code>User</code> as an abstract class:</p>
<ul>
<li><code>Student</code> inherits from <code>User</code></li>
<li><code>Lecturer</code> inherits from <code>User</code></li>
<li><code>Professor</code> and <code>Leader</code> from <code>Lecturer</code></li>
</ul>
<p></p>
<p>Should the <code>ActionListener</code> be in the view or in the controller?</p>
<p>Is it better to init a frame in the main class or should each view extends/inherits from JFrame instead of JPanel?</p>
<p>General feedback on the code so far is very welcome.</p>
<p><strong>users.csv</strong></p>
<pre><code>user,password,role
user1,password1,student
user2,password2,professor
</code></pre>
<p><strong>Studentenverwaltung.java</strong></p>
<pre><code>package com.studentenverwaltung;
import java.awt.EventQueue;
import javax.swing.JFrame;
import com.studentenverwaltung.controller.UserController;
import com.studentenverwaltung.model.User;
import com.studentenverwaltung.view.LoginPanel;
class Studentenverwaltung implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new Studentenverwaltung());
}
@Override
public void run() {
User user = new User();
LoginPanel loginPanel = new LoginPanel(user);
UserController userController = new UserController(user, loginPanel);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(loginPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
</code></pre>
<p><strong>UserController.java</strong></p>
<pre><code>package com.studentenverwaltung.controller;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.studentenverwaltung.helpers.UserCredentials;
import com.studentenverwaltung.model.User;
import com.studentenverwaltung.persistence.FileUserDAO;
import com.studentenverwaltung.persistence.UserDAO;
import com.studentenverwaltung.view.LoginPanel;
public class UserController {
private User user;
private LoginPanel loginPanel;
public UserController(User user, LoginPanel loginPanel) {
this.user = user;
this.loginPanel = loginPanel;
this.loginPanel.login.addActionListener(new LoginListener());
}
class LoginListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
String id = UserController.this.loginPanel.getId();
String password = UserController.this.loginPanel.getPassword();
if (LoginListener.this.authenticate(new UserCredentials(id,
password))) {
// show main window based upon specific user role and hide login
// window
System.out.println("Successfully logged in...");
}
}
private boolean authenticate(UserCredentials userCredentials) {
UserDAO userDAO = new FileUserDAO("Files/users.csv");
String id = userCredentials.getId();
String password = userCredentials.getPassword();
if (userDAO.getUser(id) != null
&& userDAO.getUser(id).checkPassword(password)) {
return true;
}
return false;
}
}
}
</code></pre>
<p><strong>User.java</strong></p>
<pre><code>package com.studentenverwaltung.model;
import java.util.Observable;
public class User extends Observable {
private String id;
private String password;
private String role;
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
setChanged();
notifyObservers();
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
setChanged();
notifyObservers();
}
public String getRole() {
return this.role;
}
public void setRole(String role) {
this.role = role;
setChanged();
notifyObservers();
}
public boolean checkPassword(String password) {
return this.password.equals(password);
}
}
</code></pre>
<p><strong>LoginPanel.java</strong></p>
<pre><code>package com.studentenverwaltung.view;
import java.awt.GridLayout;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import com.studentenverwaltung.model.User;
public class LoginPanel extends JPanel {
private static final long serialVersionUID = 1L;
private User user;
private JLabel idLbl;
private JTextField idTxt;
private JLabel pwdLbl;
private JTextField pwdTxt;
public JButton login;
public LoginPanel(User user) {
this.user = user;
this.user.addObserver(new UserObserver());
this.init();
}
private void init() {
this.setLayout(new GridLayout(3, 1));
this.idLbl = new JLabel("id");
this.add(idLbl);
this.idTxt = new JTextField(15);
this.add(idTxt);
this.pwdLbl = new JLabel("password");
this.add(pwdLbl);
this.pwdTxt = new JPasswordField(15);
this.add(pwdTxt);
this.login = new JButton("login");
// login.addActionListener(new LoginListener());
this.add(login);
}
public String getId() {
return this.idTxt.getText();
}
public String getPassword() {
return this.pwdTxt.getText();
}
private class UserObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>A great comment from <a href=\"https://codereview.stackexchange.com/a/19459/7076\"><em>@tb-</em>'s answer</a>:</p>\n\n<blockquote>\n <p>Do not extend <code>JPanel</code>, instead have a private <code>JPanel</code> \n attribute and deal with it (Encapsulation). \n There is no need to give access to all \n <code>JPanel</code> methods for code dealing with a <code>UserPanel</code>\n instance. If you extend, you are forced to stay with this forever, \n if you encapsulate, you can change whenever you want without \n taking care of something outside the class.</p>\n</blockquote>\n\n<p>I would make the <code>serialVersionUID</code> field superfluous.</p></li>\n<li><p>I've never heard of <code>Observable</code> before. It might not be a coincidence, <a href=\"https://stackoverflow.com/a/2380694/843804\"><em>Péter Török</em>'s answer on SO</a> has a good explanation about its disadvantages:</p>\n\n<blockquote>\n <p>They are not used, because their design is flawed: \n they are not type safe. You can attach any object \n that implements <code>Observer</code> to any <code>Observable</code>, which \n can result in subtle bugs down the line.</p>\n \n <p>[...]</p>\n</blockquote></li>\n<li><blockquote>\n <p>Each user has a specific role (student, lecturer, professor, leader of degree program).</p>\n</blockquote>\n\n<p>I'd use composition instead (as you do with the <code>role</code> field). It's easier to extend (a professor also could be a lead, or a leader might not be a lecturer, for example).</p>\n\n<p>Check <em>Effective Java, Second Edition</em>, <em>Item 16: Favor composition over inheritance</em> if you haven't read it already.</p></li>\n<li><blockquote>\n<pre><code>public LoginPanel(User user) {\n this.user = user;\n}\n</code></pre>\n</blockquote>\n\n<p>If <code>User</code> is <code>null</code> here I'd throw an exception instead. I guess it's rather a bug on the side of the caller and there is no point to continue the program with invalid state. You'll get an exception anyhow sooner or later. Throwing an exception immediately helps debugging a lot since you get a stacktrace with the frames of the erroneous client, not just a <code>NullPointerException</code> later, maybe from another thread. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><blockquote>\n<pre><code>private JLabel idLbl;\nprivate JTextField idTxt;\n</code></pre>\n</blockquote>\n\n<p>I'd avoid abbreviations like these field names. They make the code harder to read and undermine autocomplete. For example, if you type <code>idLa</code> autocomplete won't find anything. It's often annoying.</p>\n\n<p>Furthermore, they are hard to pronounce.</p>\n\n<blockquote>\n <p>If you can’t pronounce it, you can’t discuss it without sounding like an idiot. “Well,\n over here on the bee cee arr three cee enn tee we have a pee ess zee kyew int, see?” This\n matters because programming is a social activity.</p>\n</blockquote>\n\n<p>Source: <em>Clean Code</em> by <em>Robert C. Martin</em>, <em>Use Pronounceable Names</em>, p21</p></li>\n<li><blockquote>\n<pre><code>this.idLbl = new JLabel(\"id\");\n</code></pre>\n</blockquote>\n\n<p>There is no need of <code>this.</code> here. Modern IDEs use highlighting to separate local variables from instance variables.</p></li>\n<li><blockquote>\n<pre><code>if (userDAO.getUser(id) != null\n && userDAO.getUser(id).checkPassword(password)) {\n return true;\n}\n</code></pre>\n</blockquote>\n\n<p>A local variable for <code>User</code> would be easier to read here:</p>\n\n<pre><code>User user = userDAO.getUser(id);\nif (user != null && user.checkPassword(password)) {\n return true;\n}\n</code></pre></li>\n<li><p>I'd move the <code>main</code> method to a separate class. (For example, <code>StudentAdministrationMain</code>.) It's usually a good idea to separate a class from its clients.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-06T21:35:26.413",
"Id": "43652",
"ParentId": "26065",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "43652",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T10:05:07.037",
"Id": "26065",
"Score": "7",
"Tags": [
"java",
"mvc",
"swing",
"gui"
],
"Title": "Student administration application"
}
|
26065
|
<p>I've tried to create a small OpenGL abstraction layer.</p>
<p>I've tried to favor composition over inheritance but somehow it added extra complexity to my code. I probably overused it.</p>
<p><strong>shader.h</strong></p>
<pre><code>#ifndef SHADER_H
#define SHADER_H
#include "filereader.h"
#include <string>
#include <iostream>
#include <GL/glew.h>
#include <memory>
class HandleInterface {
protected:
GLuint handle_;
public:
virtual void SetHandle( GLuint )=0;
virtual ~HandleInterface() {}
virtual GLuint GetHandle() const=0;
};
class BaseHandle : public HandleInterface {
public:
virtual void SetHandle( GLuint i ) {
handle_ = i;
}
virtual GLuint GetHandle() const {
return handle_;
}
};
class Handle {
std::unique_ptr<HandleInterface> handle_;
protected:
virtual void SetHandle( GLuint i );
public:
Handle();
Handle( std::unique_ptr<HandleInterface> handle_ptr );
virtual void SetHandleInterface( std::unique_ptr<HandleInterface> handle_ptr );
virtual GLuint GetHandle() const;
};
class ShaderInterface {
public:
virtual ~ShaderInterface() {}
virtual void SetShaderSourceFromFile( std::string path ) = 0;
virtual void SetShaderSourceFromString( std::string source ) = 0;
virtual void CreateShader() = 0;
virtual GLenum GetShadertype() = 0;
};
class BaseShader : public Handle ,public ShaderInterface {
std::string shader_source_;
public:
~BaseShader() {
glDeleteShader( GetHandle() );
}
virtual void SetShaderSourceFromFile( std::string path );
virtual void SetShaderSourceFromString( std::string source );
virtual void CreateShader();
};
class VertexShader : public BaseShader {
public:
GLenum GetShadertype() {
return GL_VERTEX_SHADER;
}
};
class FragmentShader : public BaseShader {
public:
GLenum GetShadertype() {
return GL_FRAGMENT_SHADER;
}
};
class ComputeShader : public BaseShader {
public:
GLenum GetShadertype() {
return GL_COMPUTE_SHADER;
}
};
class TesselationControlShader : public BaseShader {
public:
GLenum GetShadertype() {
return GL_TESS_CONTROL_SHADER;
}
};
class TesselationEvaluationShader : public BaseShader {
public:
GLenum GetShadertype() {
return GL_TESS_EVALUATION_SHADER;
}
};
class ShaderProgramInterface {
public:
virtual void AttachShader( const BaseShader &s ) = 0;
virtual void Link() = 0;
virtual void Use() = 0;
};
class ShaderProgram : public Handle , public ShaderProgramInterface {
public:
ShaderProgram();
void AttachShader( const BaseShader &s );
void Link();
void Use();
};
class VertexBufferInterface {
public:
virtual ~VertexBufferInterface() {}
virtual void bind( GLenum ) = 0;
virtual void setBufferData( GLenum,GLsizeiptr,const GLvoid*,GLenum )= 0;
};
class VertexBuffer : public Handle, public VertexBufferInterface {
public:
VertexBuffer();
~VertexBuffer() {}
void bind( GLenum );
void setBufferType( GLenum );
void setBufferData(GLenum target, GLsizeiptr size, const GLvoid*data, GLenum usage );
};
#endif // SHADER_H
</code></pre>
<p><strong>shader.cpp</strong></p>
<pre><code>#include "shader.h"
/*#############################
Base
##############################*/
GLuint Handle::GetHandle() const {
return handle_->GetHandle();
}
void Handle::SetHandle( GLuint i ) {
handle_->SetHandle( i );
}
void Handle::SetHandleInterface( std::unique_ptr<HandleInterface> handle_ptr ) {
handle_ = std::move( handle_ptr );
}
Handle::Handle( std::unique_ptr<HandleInterface> handle_ptr ) {
SetHandleInterface( std::move( handle_ptr ) );
}
Handle::Handle()
: Handle( std::unique_ptr<HandleInterface>( new BaseHandle() ) ) {
}
/*#############################
BaseShader
##############################*/
void BaseShader::CreateShader() {
SetHandle( glCreateShader( GetShadertype() ) );
GLint length[1];
length[0] = BaseShader::shader_source_.size();
const GLchar* p[1];
p[0] = BaseShader::shader_source_.c_str();
glShaderSource( BaseShader::GetHandle(),1,p,length );
glCompileShader( GetHandle() );
GLint success;
glGetShaderiv( GetHandle(), GL_COMPILE_STATUS, &success );
if ( !success ) {
// todo throw something?
}
}
void BaseShader::SetShaderSourceFromFile( std::string path ) {
FileReader fileReader( path );
BaseShader::shader_source_ = fileReader.get();
}
void BaseShader::SetShaderSourceFromString( std::string source ) {
BaseShader::shader_source_ = source;
}
/*#############################
ShaderProgram
##############################*/
void ShaderProgram::AttachShader( const BaseShader &s ) {
glAttachShader( ShaderProgram::GetHandle(), s.GetHandle() );
}
void ShaderProgram::Use() {
glUseProgram( GetHandle() );
}
void ShaderProgram::Link() {
glLinkProgram( GetHandle() );
}
ShaderProgram::ShaderProgram() {
Handle();
SetHandle( glCreateProgram() );
}
/*#############################
VertexBuffer
##############################*/
void VertexBuffer::bind( GLenum buffertype ) {
glBindBuffer( buffertype, GetHandle() );
}
VertexBuffer::VertexBuffer() {
GLuint handle;
glGenBuffers( 1,&handle );
SetHandle( handle );
}
void VertexBuffer::setBufferData(GLenum target, GLsizeiptr s,const GLvoid * data, GLenum usage ) {
glBufferData( target, s, data, usage );
}
</code></pre>
|
[] |
[
{
"body": "<p>Drop all the interface classes. It really only makes sense to have them if you are going to implement them multiple times. But you don't. It just increases the complexity of your code for no gain.</p>\n\n<p><code>BaseHandler</code> does nothing more than hold a GLuint. So its a useless class. It doesn't add anything. Just have <code>Handle</code> hold the <code>GLuint</code>.</p>\n\n<pre><code> virtual void SetShaderSourceFromFile( std::string path );\n virtual void SetShaderSourceFromString( std::string source );\n</code></pre>\n\n<p>Don't set static parameters, that's just asking for trouble. Pass any needed parameter to the correct method.</p>\n\n<pre><code> virtual void CreateShader();\n</code></pre>\n\n<p>Use a constructor, its for creating objects. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T14:52:04.983",
"Id": "26069",
"ParentId": "26067",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T13:18:38.570",
"Id": "26067",
"Score": "2",
"Tags": [
"c++",
"beginner",
"c++11",
"opengl"
],
"Title": "OpenGL abstraction layer"
}
|
26067
|
<p>Here is the question followed by my working program:</p>
<blockquote>
<p>Given a string, return a version without the first 2 chars. Except
keep the first char if it is 'a' and keep the second char if it is
'b'. The string may be any length. Harder than it looks. </p>
<pre><code>deFront("Hello") → "llo"
deFront("java") → "va"
deFront("away") → "aay"
</code></pre>
</blockquote>
<p>Can this code be improved?</p>
<pre><code>public String deFront(String str) {
if (str.length() >= 2) {
char firstCharacter = str.charAt(0);
char secondCharacter = str.charAt(1);
if (firstCharacter == 'a' && secondCharacter == 'b') {
// donot skip
return str;
} else if (firstCharacter == 'a' && secondCharacter != 'b') {
// skip first character only
return str.substring(0, 1) + str.substring(2);
} else if (firstCharacter != 'a' && secondCharacter == 'b') {
// skip second character only
return str.substring(1);
} else {
return str.substring(2);
}
} else if (str.length() == 1 && str.charAt(0) == 'a') {
return str;
} else {
return str;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T14:57:48.040",
"Id": "40333",
"Score": "0",
"body": "Yes. Fix the indentation so it's easier to read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T16:34:03.683",
"Id": "40335",
"Score": "0",
"body": "Also please fix the title and replace it with something meaningful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T17:03:40.997",
"Id": "40337",
"Score": "1",
"body": "You should write some unit tests to check your function."
}
] |
[
{
"body": "<p>First, is this part correct?</p>\n\n<pre><code>} else if (str.length() == 1 && str.charAt(0) == 'a') {\n return str;\n} else {\n return str;\n}\n</code></pre>\n\n<p>This will return a string of length 1, unchanged, regardless of the character. What should happen if you pass \"z\"? Since the first character is not 'a', should it be removed?</p>\n\n<p>I suspect it was supposed to be something like this:</p>\n\n<pre><code>} else if (str.length() == 1 && str.charAt(0) != 'a') {\n return \"\";\n} else {\n return str;\n}\n</code></pre>\n\n<p>The rest of this answer assumes it should remove the character</p>\n\n<p>You could use a <code>StringBuilder</code> and delete the characters as necessary:</p>\n\n<pre><code>public String deFront(String str) {\n StringBuilder sb = new StringBuilder(str);\n if (sb.length() > 1 && sb.charAt(1) != 'b') {\n sb.deleteCharAt(1);\n }\n if (sb.length() > 0 && sb.charAt(0) != 'a') {\n sb.deleteCharAt(0);\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>Or you could use a regular expression search & replace:</p>\n\n<pre><code>public String deFront(String str) {\n str = str.replaceFirst(\"^(.)[^b]\", \"$1\");\n str = str.replaceFirst(\"^[^a]\", \"\");\n return str;\n}\n</code></pre>\n\n<p>Note: The order of deletion is important in both of these solutions. The <code>b</code> is deleted first to prevent the deletion of <code>a</code> from shifting the <code>b</code> by one position.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T15:16:18.127",
"Id": "26070",
"ParentId": "26068",
"Score": "4"
}
},
{
"body": "<p>Just recoded it, doing simply what your explanation said </p>\n\n<blockquote>\n <p>Except keep the first char if it is 'a' and keep the second char if\n it is 'b'.</p>\n</blockquote>\n\n<p>Since a possible deletion of a character will affect indices, we check the second character before we check the first.\nThe resulting code is much simpler and readable simply because the extracted method <code>deleteCharIfNotEqualTo()</code> does away with some code duplication and at the same time heightens readability of the <code>deFront()</code> method, by explaining what is happening.</p>\n\n<pre><code>public String deFront(String str) {\n StringBuilder builder = new StringBuilder(str);\n deleteCharIfNotEqualTo(builder, 1, 'b');\n deleteCharIfNotEqualTo(builder, 0, 'a');\n return builder.toString();\n}\n\nprivate void deleteCharIfNotEqualTo(StringBuilder builder, int index, char character) {\n if (builder.length() > index && character != builder.charAt(index)) {\n builder.deleteCharAt(index);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T21:40:24.083",
"Id": "26073",
"ParentId": "26068",
"Score": "10"
}
},
{
"body": "<p>You could do a number of interesting things with this problem. I chose to have a little fun with the fact that A and B are basically self-indicators of which position in the string they may stay in. It also allows you to expand the progressive character search throughout any length of string with just a one-line change. Forgive if my syntax isn't correct, my native language is C#.</p>\n\n<pre><code>public String deFront(String str) {\n StringBuilder sb = new StringBuilder();\n int a = (int)'a';\n\n for(int i = 0; i < 2 && i < str.length()) {\n char cur = str.charAt(i);\n if (i < 2 && (int)cur - a != i) {\n continue;\n }\n sb.append(cur);\n }\n\n return sb.toString();\n}\n</code></pre>\n\n<p>And to apply this to the entire alphabet (repeating after the 26th character):</p>\n\n<pre><code>public String deFront(String str) {\n StringBuilder sb = new StringBuilder();\n int a = (int)'a';\n\n for(int i = 0; i < 2 && i < str.length()) {\n char cur = str.charAt(i);\n if ((int)cur - a != i % 26) { // changed this line here\n continue;\n }\n sb.append(cur);\n }\n\n return sb.toString();\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T03:10:29.597",
"Id": "26075",
"ParentId": "26068",
"Score": "1"
}
},
{
"body": "<p>How about this?</p>\n\n<pre><code>public static String deFront(String str)\n{\n String one = (str.length() > 0 && str.charAt(0) == 'a') ? \"a\" : \"\";\n String two = (str.length() > 1 && str.charAt(1) == 'b') ? \"b\" : \"\";\n\n return one+two+((str.length() > 2) ? str.substring(2) : \"\"); \n}\n</code></pre>\n\n<p>Note that only the parentheses around the entire ternary operation in the return are actually necessary, the others are for readability, as per @abuzittingillifirca's suggestion.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T16:54:20.020",
"Id": "40404",
"Score": "0",
"body": "This throws a `StringIndexOutOfBoundsException` for strings of length 0 and 1."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T06:05:22.267",
"Id": "40432",
"Score": "0",
"body": "True. I only tested strings of length 2. Fixed my code above. Sorry for all the ternary crap, but I find a bunch of ifs would needlessly clutter this simple function."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T06:40:26.200",
"Id": "40436",
"Score": "0",
"body": "Why create substrings for single character equality tests, rather than, e.g, `str.charAt(0)=='a'`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:27:54.410",
"Id": "40440",
"Score": "0",
"body": "+1 for closely matching the description, conciseness and robustness (w.r.t. @bowmore's order dependent deletion).\nIn addition to @SoftwareMonkey's `charAt` critique:\nTernary operators are OK, But use parentheses and spaces around operators to improve readability of expressions. Also you should declare variables where they are assigned, this is not C or javascript. Use English names whenever international readers may *possibly* see the code (that is always on codereview)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:11:05.917",
"Id": "40448",
"Score": "0",
"body": "Thanks! Edited. I had actually used chars and `charAt` first, but since you can't have empty chars, I switched. You're right, chars do fine for the comparison."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T10:29:20.190",
"Id": "40459",
"Score": "0",
"body": "+1 I like this better now. My solutions also had order dependent deletion, which I didn't really like. Nice work!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:15:46.513",
"Id": "26104",
"ParentId": "26068",
"Score": "5"
}
},
{
"body": "<p>Well, this algorithm can be at least improved by adding option to check for any list characters at position 0 and 1.</p>\n\n<hr>\n\n<pre><code>public class DeFront {\n\n //if character is one of these, it will be removed\n private static char[] firstLetterExcluded = \"a\".toCharArray();\n private static char[] secondLetterExcluded = \"bcdef\".toCharArray();\n\n public static String deFront(String str) {\n boolean removeFirst = false, removeSecond = false;\n\n for (char c : firstLetterExcluded) {\n if (str.charAt(0) == c) {\n removeFirst = true;\n break;\n }\n }\n\n for (char c : secondLetterExcluded) {\n if (str.charAt(1) == c) {\n removeSecond = true;\n break;\n }\n }\n //Before calling the stripping method, it's better to check if we need to\n if (removeFirst || removeSecond) {\n return stripString(str, removeFirst, removeSecond);\n } else {\n return str;\n }\n }\n\n private static String stripString(String str, boolean removeFirst, boolean removeSecond) {\n\n if (removeFirst && removeSecond) {\n return str.substring(2);\n } else if (removeFirst) {\n return str.substring(1);\n } else {\n //Using Stringbuilder takes more time\n return str.charAt(0) + str.substring(2);\n }\n\n\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T11:48:51.563",
"Id": "26147",
"ParentId": "26068",
"Score": "1"
}
},
{
"body": "<p>Not necessarily efficient, but compact:</p>\n\n<pre><code>public static String deFront(String s)\n{\n return Pattern.compile(\"(?:(a)|[^a])(?:(?:(b)|[^b])(.*))?\").matcher(s).replaceFirst(\"$1$2$3\");\n}\n</code></pre>\n\n<p>Note that there is a significant performance penalty with this solution, so don't use it if you call the function frequently. This is just to show an alternative using a regular expression.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-17T16:52:45.293",
"Id": "170874",
"Score": "0",
"body": "why would you do this instead of what the original post does? please put that into your answer. thank you"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-17T16:23:18.600",
"Id": "93889",
"ParentId": "26068",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T14:42:41.147",
"Id": "26068",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "String manipulation in Java"
}
|
26068
|
<p>Does the code below respect Python programming conventions? (and if not, which one does it disrespect?) The objective would be to publish this code as part of a scientific article, as "reproducible research".</p>
<p>In 1998, Moffat and Turpin described in "<a href="http://ieeexplore.ieee.org/xpl/login.jsp?tp=&arnumber=681345&url=http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=681345" rel="nofollow">Efficient Construction of Minimum Redundancy Codes for Large Alphabets</a>" (which I reviewed <a href="http://lejyby.wordpress.com/2012/09/23/efficient-construction-of-minimum-redundancy-codes-for-large-alphabets-by-moffat-and-turpin-1998/" rel="nofollow">here</a>) how to compute prefix free codes from sorted weights with many repeated weight values in reduced space and time (once the weights are sorted). I am planning to reproduce and describe their first experiment (compressing some TREC data set) in a fully reproducible way, as an exercize in reproducible research. Their algorithm should be implementable (they did implement it and ran it for their experiment but did not share their code) but I found that I needed to make large modifications when programming it in Python, and I wonder if I am doing it properly (I am more of a mathematician than a programmer).</p>
<pre><code>def assertEqual(x,y):
assert x==y, str(x)+" should be "+str(y)
# A function to simulate one sorted list from two:
def sourceOfFirstOfTwo(leaves,graphs):
"""Given two lists of 4-uple, returns a pointer to the one with the list with the smallest first element, sorted by first value."""
assert(len(leaves)>0 or len(graphs)>0)
if len(leaves)==0:
return graphs
elif len(graphs)==0:
return leaves
else:
(firstLeafWeight,firstLeafFrequency,firstLeafLeft,firstLeafRight) = leaves[0]
(firstGraphWeight,firstGraphFrequency,firstGraphLeft,firstGraphRight) = graphs[0]
if firstLeafWeight<firstGraphWeight:
return leaves
else:
return graphs
assertEqual(sourceOfFirstOfTwo([(1,1,0,0)],[]),[(1,1,0,0)])
assertEqual(sourceOfFirstOfTwo([],[(2,1,0,0)]),[(2,1,0,0)])
assertEqual(sourceOfFirstOfTwo([(1,1,0,0)],[(2,1,0,0)]),[(1,1,0,0)])
assertEqual(sourceOfFirstOfTwo([(2,1,0,0)],[(1,1,0,0)]),[(1,1,0,0)])
def Meld(leaves):
assert(len(leaves)>0)
graphs = []
source = leaves
first = (firstWeight,firstFrequency,firstLeft,firstRight) = source[0]
while firstFrequency>1 or len(leaves)+len(graphs)>1:
assert(len(graphs)<5)
if firstFrequency>1:
if firstFrequency %2 == 1:
source[0] = (firstWeight, 1, firstLeft, firstRight)
else:
source.remove(first)
graphs.append((2*firstWeight,firstFrequency // 2,first,first))
else: #firstFrequency == 1 but len(leaves)+len(graphs)>1
source.remove(first)
secondSource = sourceOfFirstOfTwo(leaves,graphs)
second = (secondWeight,secondFrequency,secondLeft,secondRight) = secondSource[0]
assert(secondFrequency>0)
if secondFrequency==1:
secondSource.remove(second)
else:
secondSource[0] = (secondWeight,secondFrequency-1,secondLeft,secondRight)
graphs.append((firstWeight+secondWeight,1,first,(secondWeight,1,secondLeft,secondRight)))
source = sourceOfFirstOfTwo(leaves,graphs)
first = (firstWeight,firstFrequency,firstLeft,firstRight) = source[0]
return(sourceOfFirstOfTwo(leaves,graphs)[0])
assertEqual(Meld([(1,1,0,0)]),(1, 1, 0, 0))
assertEqual(Meld([(1,2,0,0)]),(2,1,(1, 2, 0, 0),(1, 2, 0, 0)))
assertEqual(Meld([(1,4,0,0)]),(4,1,(2,2,(1, 4, 0, 0),(1, 4, 0, 0)),(2,2,(1, 4, 0, 0),(1, 4, 0, 0))))
assertEqual(Meld([(1,2,0,0),(3,1,0,0)]),(5,1,(2,1,(1,2,0,0),(1,2,0,0)),(3,1,0,0)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T21:06:30.780",
"Id": "40351",
"Score": "0",
"body": "Yes, this code is not ready for review. See the [FAQ](http://codereview.stackexchange.com/faq) item 5: \"To the best of my knowledge, does the code work?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T09:24:17.107",
"Id": "40386",
"Score": "0",
"body": "I apologize for my mistake. I will publish the code in the following days and review further the FAQ before asking any other question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T09:59:14.800",
"Id": "40704",
"Score": "0",
"body": "@JanneKarila: Code corrected and checked with pychecker, correct to the best of my knowledge. I took the liberty to \"undelete\" the question rather than ask a new one so that people can keep track."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T10:01:20.437",
"Id": "40706",
"Score": "0",
"body": "@GarethRees FAQ read and checked (I had read it only in diagonal at first, apologies renewed). Do people include their \"assert\" statement usually?"
}
] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>The Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>) recommends using 4 spaces for each indentation step, and <code>lowercase_words_with_underscores</code> for variable names and function names. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers if you do.</p></li>\n<li><p>In answer to your question in comments, <code>assert</code> statements are fine. It's usually a good sign when code includes them, because it shows that the programmer has thought about what needs to be true at each step of the algorithm.</p></li>\n<li><p>The <code>assertEqual</code> calls, on the other hand, are not quite in the right place. It's a good sign to see test cases. However, it's not a good idea to intermix the test suite with the code like this, because it means that every time your program gets run or your module gets loaded, the test suite gets run. That's harmless here because the test cases are so short, but if the test suite took a lot of time to run, you'd normally prefer not to run it every time.</p>\n\n<p>So I would suggest reorganizing the test code so that it uses the facilities in the <a href=\"http://docs.python.org/3/library/unittest.html\" rel=\"nofollow\"><code>unittest</code></a> module. Which includes its own <code>assertEqual</code> method, saving you the need to write your own. See below for how you might do this.</p></li>\n<li><p>The docstring of <code>sourceOfFirstOfTwo</code> seems confused. Python doesn't have \"pointers\" and it's best not to think in terms of pointers, but in terms of values. You should have written:</p>\n\n<pre><code>\"\"\"Given two lists of 4-tuples, return the one with the smallest first element.\"\"\"\n</code></pre>\n\n<p>but in fact this doesn't completely describe the behaviour of the function because it doesn't say what happens if one of the lists is empty.</p></li>\n<li><p>A confused or complicated docstring is often an indication that a function would profit from being simplified or generalized, and that's definitely the case here. The first thing to note is that sequences test true if they are non-empty, and false if they are empty, so the initial tests can be rewritten:</p>\n\n<pre><code>assert(leaves or graphs)\nif not leaves:\n return graphs\nelif not graphs:\n return leaves\n</code></pre>\n\n<p>Next, Python already compares tuples element-wise:</p>\n\n<pre><code>>>> sorted([(2,3), (1,4), (2,1)])\n[(1, 4), (2, 1), (2, 3)]\n</code></pre>\n\n<p>so there is no need to split up your 4-tuples into their components. Instead you can write:</p>\n\n<pre><code>if leaves[0] < graphs[0]:\n return leaves\nelse:\n return graphs\n</code></pre>\n\n<p>which can be simplified to:</p>\n\n<pre><code>return min(leaves, graphs)\n</code></pre>\n\n<p>since lists compare element-wise too. But now that we've made these simplifications, there's nothing in this function that needs to know about leaves and graphs. Really, it's a function that takes two sequences, discards empty ones, and returns the smaller among the remaining ones. But you can see that there's nothing special about the number two here. So I would generalize this function in order to further simplify it, like this (just one line!):</p>\n\n<pre><code>def min_non_empty(*sequences):\n \"\"\"Return the smallest of the non-empty sequences.\n Raise ValueError if all sequences are empty.\n\n >>> min_non_empty([1,2],[2,3],[])\n [1, 2]\n >>> min_non_empty([1,2],[1],[])\n [1]\n >>> min_non_empty([], [])\n Traceback (most recent call last):\n ...\n ValueError: min() arg is an empty sequence\n\n \"\"\"\n return min(s for s in sequences if s)\n</code></pre>\n\n<p>Notice how I've used the docstring to provide examples of how the function can be called. Python's <a href=\"http://docs.python.org/3/library/doctest.html\" rel=\"nofollow\"><code>doctest</code></a> module is capable of running these mini-tests and checking their output. (This feature doesn't substitute for a proper test suite, but it's a useful way to check examples in documentation.)</p>\n\n<p>Note also that there's no need for an assertion any more because <a href=\"http://docs.python.org/3/library/functions.html#min\" rel=\"nofollow\"><code>min</code></a> raises <code>ValueError</code> if you don't give it any arguments.</p>\n\n<p>But having done all that, I don't think we actually need this function at all. See below.</p></li>\n<li><p>A data structure with more than a couple of elements becomes unwieldy to manipulate if you represent it as a tuple. You have to refer to its elements by index (like <code>x[1]</code>) in which case it is not clear what that element means, or else you have to break it down into its components.</p>\n\n<p>It would be better to refer to the elements of your data structure by name. You could do this by creating a class, but the simplest thing to do here is to use a <a href=\"http://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow\">named tuple</a>:</p>\n\n<pre><code>Graph = namedtuple('Graph', 'weight frequency left right'.split())\n</code></pre></li>\n<li><p>Instead of using <code>0</code> as a placeholder meaning \"no left/right child\", it's conventional in Python to use <code>None</code>. That way there's no risk of confusing it for a weight or a frequency.</p></li>\n<li><p>Your <code>Meld</code> function lacks a docstring. What does it do and how to call it?</p></li>\n<li><p>Your <code>Meld</code> algorithm isn't the same as the <a href=\"http://lejyby.wordpress.com/2012/09/23/efficient-construction-of-minimum-redundancy-codes-for-large-alphabets-by-moffat-and-turpin-1998/\" rel=\"nofollow\">one in your blog</a>. (The original paper is hidden behind a paywall and IEEE want to charge me $31 just to read it, so I am basing this on your blog instead.) The differences are as follows: (i) you separate the graphs into two lists, <code>leaves</code> and <code>graphs</code>, whereas Moffat and Turpin just maintain a single list <code>A</code>; (ii) you set <code>first</code> to be the smaller of the initial elements of <code>leaves</code> and <code>graphs</code>, whereas Moffat and Turpin set <code>t</code> to be the first element of <code>A</code>; (iii) similarly for <code>second</code> and <code>u</code>.</p>\n\n<p>This causes some of the prefix trees to come out in a different order. For example, you have</p>\n\n<pre><code>>>> Meld([(1,2,0,0),(3,1,0,0)])\n(5, 1, (2, 1, (1, 2, 0, 0), (1, 2, 0, 0)), (3, 1, 0, 0))\n</code></pre>\n\n<p>but I believe that Moffat and Turpin's algorithm would go through these steps:</p>\n\n<ol>\n<li><code>A = [(1, 2), (3, 1)]</code></li>\n<li><code>A = [(3, 1), (2, 1, (1, 2), (1, 2))]</code></li>\n<li><code>A = [(5, 1, (3, 1), (2, 1, (1, 2), (1, 2)))]</code></li>\n</ol>\n\n<p>I don't know if this difference is significant, but I thought I ought to mention it.</p>\n\n<p><strong>Update:</strong> you noted in comments that the reason for this difference is that the description of Moffat and Turpin's algorithm in your blog was incomplete in that the list <code>A</code> needs to be maintained in sorted order (or rather, it needs to be possible to efficiently fetch the smallest element from the list).</p>\n\n<p>Maintaining a priority queue can be done efficiently in Python using the <a href=\"http://docs.python.org/3/library/heapq.html\" rel=\"nofollow\"><code>heapq</code></a> module. I've revised my code below to show how to do this.</p></li>\n<li><p>In the course of the algorithm you need to manipulate the list <code>graphs</code> by adding items at the right and removing items from the left. The latter operation is not efficient for ordinary Python lists: if you look at the <a href=\"http://wiki.python.org/moin/TimeComplexity\" rel=\"nofollow\">TimeComplexity</a> page on the Python Wiki you'll see that deleting an item from a list is O(<em>n</em>).</p>\n\n<p>In order to modify a sequence at both ends efficiently, you need to use some other data structure. In many cases you could use the double-ended queue class <a href=\"http://docs.python.org/3/library/collections.html#collections.deque\" rel=\"nofollow\"><code>collections.deque</code></a>, but here since you need to be able to efficiently fetch the smallest item in the sequence, the <a href=\"http://docs.python.org/3/library/heapq.html\" rel=\"nofollow\"><code>heapq</code></a> module is the one to use.</p></li>\n<li><p>The meld function is not very useful by itself. As you comment in your blog post, any actual user will need a function that converts the list of weights into the (weight, frequency) pairs (<a href=\"http://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow\"><code>collections.Counter</code></a> would be a convenient and efficient tool to do this in Python), and a function that processes the resulting prefix tree into the codes. You'd probably want to add these functions to your code.</p></li>\n</ol>\n\n<h3>2. Rewrite</h3>\n\n<p>Putting all this together, here's how I'd write this code:</p>\n\n<pre><code>from collections import namedtuple\nfrom heapq import heapify, heappush, heappop\nfrom unittest import TestCase\n\nGraph = namedtuple('Graph', 'weight frequency left right'.split())\n\ndef meld(graphs):\n \"\"\"Given a non-empty list 'graphs' of Graph objects, return a\n minimum-redundancy prefix tree constructed using the algorithm of\n Moffat and Turpin (1998).\n\n \"\"\"\n heapify(graphs)\n while True:\n t = graphs[0]\n if t.frequency > 1:\n if t.frequency % 2 == 0:\n heappop(graphs)\n else:\n graphs[0] = Graph(t.weight, 1, t.left, t.right)\n heappush(graphs, Graph(2 * t.weight, t.frequency // 2, t, t))\n elif len(graphs) > 1:\n assert(t.frequency == 1)\n heappop(graphs)\n u = graphs[0]\n if u.frequency == 1:\n heappop(graphs)\n else:\n graphs[0] = Graph(u.weight, u.frequency - 1, u.left, u.right)\n heappush(graphs, Graph(t.weight + u.weight, 1, t, u))\n else:\n assert(len(graphs) == 1 and t.frequency == 1)\n return t\n\nclass MeldTest(TestCase):\n def test(self):\n t = Graph(1, 1, None, None)\n self.assertEqual(meld([t]), t)\n\n u = Graph(1, 2, None, None)\n self.assertEqual(meld([u]), Graph(2, 1, u, u))\n\n v = Graph(1, 4, None, None)\n w = Graph(2, 2, v, v)\n self.assertEqual(meld([v]), Graph(4, 1, w, w))\n\n x = Graph(3, 1, None, None)\n self.assertEqual(meld([u, x]), Graph(5, 1, Graph(2, 1, u, u), x))\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li><p>There turned out to be no need for the <code>sourceOfFirstOfTwo</code> function.</p></li>\n<li><p>The unit tests have been moved to a <code>unittest.TestCase</code> class. You can run all the unit tests from the command line like this:</p>\n\n<pre><code>$ python -munittest mymodule.py\n.\n----------------------------------------------------------------------\nRan 1 test in 0.000s\n\nOK\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T15:22:31.520",
"Id": "40768",
"Score": "0",
"body": "9. Difference of Meld with blog version: Moffat and Turpin's algorithm does not make it clear that A must be maintained sorted for the produced prefix code to be optimal. They mention that \"Since A is initially sorted by increasing w, an since the weights of inserted nodes form a nondecreasing sequence, A can be maintained as two separate sorted lists, and each insertion operation requires O(1) time.\". (I long for Reproducible research) Your rewrite does not produce an optimal prefix code, but I will still use it to inspire me to write better looking code and post the result after I am done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T15:23:54.963",
"Id": "40769",
"Score": "0",
"body": "(I had a longer answer with many thanks for each of the ways your comments helped me, but had to cut it down to fit in the comment length limit, so here it is in a shorter form: MANY THANKS)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T16:57:27.780",
"Id": "40770",
"Score": "0",
"body": "Aha, that explains things! I've updated my answer to show how you can use the `heapq` module to simply and efficiently maintain a priority queue. (The insertions and deletions are O(log *n*) rather than O(1) but that doesn't make much difference in practice—the simplicity of the heap is more important than the slight asymptotic inefficiency.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T17:30:07.647",
"Id": "40772",
"Score": "0",
"body": "Thanks: adding the priority queue corrects your solution. (I will still implement it with one list and one deque though.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T07:33:15.673",
"Id": "40783",
"Score": "0",
"body": "Newbie question: are \"unittest\" (and $PYTHONPATH) supposed to be a mess to configure on a standard Ubuntu box?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T09:38:44.217",
"Id": "40791",
"Score": "0",
"body": "If you're having configuration difficulties, it's probably worth asking a question on [Stack Overflow](http://stackoverflow.com/)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T18:44:34.377",
"Id": "26309",
"ParentId": "26071",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "26309",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T15:44:50.907",
"Id": "26071",
"Score": "4",
"Tags": [
"python"
],
"Title": "Computation of Prefix Free Codes with many repeated weight values in reduced space"
}
|
26071
|
<p>I was writing a function (named <code>listenString</code>) in haskell to see if a string contains one of the strings in a list of strings, and to then return a value (of the type <code>m ()</code>) that corresponded with the string it found. The type of that function is <code>(Eq a, Monad m) => [a] -> [([a], m ())] -> m ()</code>.</p>
<p>The reason why I used a list to store the strings and their corresponding values (<code>[([a], m ())]</code>) instead of a Map was because I wanted to make sure that the function evaluated strings in the order that they were in the list, e.g. <code>listenString "hello there" [("lo",print True),("hello",print False)]</code> would printed <code>True</code>. If I used a map, the order might have been lost, and the function might have printed <code>False</code>.</p>
<p>Here's the code. I'm specifically wondering if there are any bugs, and if I'm using <code>ListT</code> correctly (of if I should be using something other than <code>ListT</code>), but any other feedback would be helpful and appreciated. </p>
<pre><code>import Data.Either
import Control.Monad.Trans.List
searchListMapMaybe f (Search a b c) = Search a (mapMaybe f b) c
data Search a b = Search a [a] b
type Searching a b = ListT (Either b) (Search a b)
listenString [] _ = return ()
listenString a l =
let list = filter (\(x,_) -> if (x == []) then False else True) l
noEmptyList [] = error "listenForString: You need to have at least one item in the list"
noEmptyList x = x
in listenStringSub a $ ListT $ Data.Either.Right $ fmap (\(x,y) -> Search x [] y) $ noEmptyList list
where
listenStringSub :: (Eq a) => [a] -> Searching [a] (m b) -> m b
listenStringSub _ (ListT (Data.Either.Left a)) = a
listenStringSub (c:cs) x = listenStringSub cs $ (listenStringMap c x) >>= searchFinal
where
listenStringMap char x = fmap ((searchReduce char) . (searchPop char)) x
searchPop :: (Eq a) => a -> Search [a] b -> Search [a] b
searchPop char (Search a@(x:_) l b)
| char == x = Search a (a:l) b
| otherwise = Search a l b
searchReduce :: (Eq a) => a -> Search [a] b -> Search [a] b
searchReduce char search = searchListMapMaybe (function char) search
where
function _ [] = Just []
function c l@(x:xs)
| c == x = Just xs
| otherwise = Nothing
searchFinal :: (Eq a) => Search [a] b -> Searching [a] b
searchFinal s@(Search a b c)
| [] `elem` b = ListT (Data.Either.Left c)
| otherwise = return s
</code></pre>
<p><strong>Edit:</strong> <code>listenString</code> should decide what values to return in the following order:</p>
<ol>
<li>Which list comes first: <code>listenString "hello there" [("lo",print True),("he",print False)]</code> would output <code>False</code>.</li>
<li>If two or more strings end in the exact same place, e.g. <code>listenString "hello there" [("lo",print True),("hello",print False)]</code>, I want the tuple closest to the beginning of the list to be displayed (the above expression would output <code>True</code>.</li>
</ol>
|
[] |
[
{
"body": "<p>Why do you need the element type to be a monad? The only point you require it is when you do <code>return ()</code> in order to signal failure. I'd propose implementing a more general function</p>\n\n<pre><code>lookupSublist :: Eq a => [a] -> [([a], b)] -> Maybe b\n</code></pre>\n\n<p>Which could be implemented as:</p>\n\n<pre><code>lookupSublist xs = fmap snd . listToMaybe . filter (flip isInfixOf xs . fst)\n</code></pre>\n\n<p>So we first filter out all alternatives where the first element doesn't have <code>xs</code> as infix. Then we return the second element of the first remaining element, if any.</p>\n\n<p>Some random notes on your code:</p>\n\n<ol>\n<li><p>Using <code>noEmptyList</code> as a guard mid-expression isn't a good idea. Using <code>error</code> is pretty \"evil\" in the first place, you don't want to bury it like that. Putting the <code>list</code> in the <code>where</code> would allow you to say <code>listenString a l | null list = error...</code></p></li>\n<li><p><code>(\\(x,_) -> if (x == []) then False else True)</code> is simply <code>not . null . fst</code>. I'm not quite sure why you filter for that, to be honest. Wouldn't having <code>[]</code> in the list be a pretty elegant way to implement a default fallback value?</p></li>\n<li><p>I am actually quit struggling to understand the rest of your code. I am pretty sure that your usage of <code>ListT</code> actually hurts more than it helps - generally when you start pattern-matching on the contents of a monad you are doing something wrong. Could you explain what you tried to do?</p></li>\n</ol>\n\n<hr>\n\n<p><strong>Edit:</strong> If the position of the match end should take priority, I would propose going over the prefixes of the string and suffix-test the options:</p>\n\n<pre><code>lookupFirstSublist str opts = listToMaybe $ mapMaybe f $ inits opts\n where f s = fmap snd $ listToMaybe $ filter (flip isSuffixOf s . fst) opts\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T01:47:48.813",
"Id": "40357",
"Score": "0",
"body": "I like this save one thing, I would instead of Maybe b have Maybe [a] -> b and use ap on it this way you could compose chains"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:47:49.943",
"Id": "40390",
"Score": "0",
"body": "`lookupSublist xs = fmap (\\x -> Just \\y -> (snd x) y) . filter (isInFixOf xs . fst)` for `lookupSublist :: Eq [a] => [a] -> [([a], [a] -> b)] -> [Maybe [a] -> b]`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T23:31:24.210",
"Id": "40520",
"Score": "0",
"body": "`lookupSublist` doesn't work at all: I'm assuming that you meant `listenList a xs = fmap snd $ listToMaybe (filter (\\x -> isInfixOf (fst x) a) xs)`. Even then, your implementation of `lookupSublist` has some problems: `listenList \"hello there\" [(\"lo\",True),(\"he\",False)]` returns `True` (It should return `False`, because `\"he\"` comes first in the `\"hello there\"`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T23:46:29.880",
"Id": "40521",
"Score": "0",
"body": "Thanks for your help though: I'll post an explanation of the code and I'll respond to your other points when I have time to edit it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T13:27:25.683",
"Id": "40548",
"Score": "0",
"body": "It works fine here... Your version just removes the currying. Are you sure you copied it right? I'll add my solution for the new problem in a bit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T13:48:58.353",
"Id": "40552",
"Score": "1",
"body": "Nevermind, there was actually a `flip` missing. Sorry about that :)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T16:19:27.437",
"Id": "26082",
"ParentId": "26072",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26082",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T18:01:40.860",
"Id": "26072",
"Score": "2",
"Tags": [
"haskell"
],
"Title": "Parsing a String to see if it contains another String, and then returning a monad if it does"
}
|
26072
|
<p>This piece of code basically just asks for a word and sees if it exists in a file. If not, the user is asked if it should be added to the file.</p>
<p>I am new to C programming and I want to know what you think about my code: things to change, things to remove, what not to do.</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
//Declarations
//**********************************************************
char wordContainer[20],wordFinder[20],ans[2];
int wordChecker=0;
FILE* filePtr=NULL;
//**********************************************************
filePtr=fopen("wordDic.dic","a+");//opening the file with the a+ option
printf("please enter the word you want to look for : ");
fgets(wordContainer,20,stdin);//entering the word we want to look for
if(filePtr==NULL)
{
printf("error while trying to open the dictionnary file");//allways good to check
}
/*while we haven't reach the end of the file see if the current word matchs the word we are looking for*/
while(fgets(wordFinder,20,filePtr)!=NULL)
{
if(strcmp(wordContainer,wordFinder)==0)
{
printf("this word was found in the dictionnary , would you like to perform another search ? y/n... ");
fgets(ans,2,stdin)
wordChecker++;//when the word is matched increase wordChecker and quit the while
break;
}
}
if(wordChecker==0)//if no match is found ask to enter this new word
{
printf("we couldn't find the word %s would you like to add it ? y/n ... ",wordContainer);
fgets(ans,2,stdin);
if(strcmp(ans,"y")==0 || strcmp(ans,"Y")==0)
{
fprintf(filePtr,"%s",wordContainer);
fflush(filePtr);//not exactly sure what it does exept that it clear the output buffer maybe ?
printf("this word has been added");
}
else
{
printf("thank you for using this program,bye");
exit(0);
}
}
fclose(filePtr);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Your code looks quite neat, although note that formatting, including spaces\naround operators etc, line lengths, defining multiple variable per line, should follow a conventional style. </p>\n\n<p>There are some issues, the main one being that compiling and running the code,\nit does not work. The problem is that</p>\n\n<pre><code>fopen(filename, \"a+\");\n</code></pre>\n\n<p>opens the file for reading and writing but leaves the stream pointer at the\nend of the file. So any subsequent <code>read</code> will fail. You need a <code>rewind();</code>\nor equivalent (<code>fseek</code> etc) after checking that the file opened successfully.</p>\n\n<p>After fixing the rewind, another issue is that <code>fgets</code> returns the input word\nwith a trailing newline, \\n. Your code ignores this and manages to work\nbecause the strings that are written to and read from the dictionary also have\na trailing \\n. But this fails when a user enters a string that fills your\nbuffers, 19 characters or more. In this case, the <code>fgets</code> call cannot read\nthe whole string and reads just the 1st 19 chars (and adds a terminating \\0),\nleaving the remaining chars in the input stream. In this case there is no\ntrailing \\n in the buffer. The next time you read from stdin the 20th and 21st chars are\nread and treated as the y/n answer. Even if these chars happen to be \"y\", the\n19-char word is written to the dictionary without a trailing \\n, corrupting\nthe dictionary (try looking up <code>abcdefghijklmnopqrsy</code> - notice the 'y' at the end)</p>\n\n<p>There are ways to fix these problems, for example you could try using\n<code>getline()</code> to get the input string instead of <code>fgets</code>, although getline is\nmore tricky to use correctly. Alternatively (as it is just an exercise)\njust check the input string to confirm that there is a trailing \\n (meaning\nthat the whole line was read) and reject the word and fflush the input if not. To do things\nproperly you really need to remove the trailing \\n from the user input string and\nfrom the string read from the dictionary before comparing, and add \\n back when writing to the\nfile.</p>\n\n<p>Another issue is poor comments. Comments must be useful; otherwise they are\njust noise (and hence make reading the code more difficult than it need be).\nAll of your comments are just noise.</p>\n\n<p>Note also that when opening the dictionary fails you should exit. There are numerous other issues, but I'll leave it at that for now...</p>\n\n<h2>EDIT</h2>\n\n<p>As no reviewers have commented on other issues, here are some other things I\nspotted:</p>\n\n<ul>\n<li><p>avoid use of constants such as 20. Instead, define the buffer size with a\ndefine and use sizeof where you need the buffer size. For example:</p>\n\n<pre><code>#define BUF_SIZE 20\n...\nchar buf[BUF_SIZE];\nfgets(buf, sizeof buf, stdin);\n</code></pre>\n\n<p>by using <code>sizeof</code> you guarantee that the size is correct - but note that\nif you use it on a pointer, then you get the wrong value:</p>\n\n<pre><code>char *buf = malloc(BUF_SIZE);\nfgets(buf, sizeof buf, stdin); // WRONG!!\n</code></pre>\n\n<p>in the latter case, <code>sizeof</code> returns the size of the pointer (typically 4\nor 8 bytes) - you need to pass BUF_SIZE to <code>fgets</code></p></li>\n<li><p>define the file name in a constant or a #define and use the file name in the\nerror message on failure to open. The message should be produced with\n<code>perror</code></p>\n\n<pre><code>const char *dict = \"wordDic.dic\";\n...\nFILE *file = fopen(dict,\"a+\");\nif (file == NULL) {\n perror(dict);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>notice that I exited immediately on failure (your code continues).\n<code>perror</code> will produce a short error message on stderr that says <strong>why</strong> the file\ncould not be opened, not just that it couldn't. Also note that I checked\nthe file pointer immediately, not after prompting the user, as you do.</p></li>\n<li><p>you ask the user whether she would like to perform another search\n(on success) but then ignore the answer.</p></li>\n<li><p>the call to <code>fflush</code> is strictly unnecessary. Buffered output like\n<code>fprintf</code> (and <code>printf</code>) writes to file when it sees a \\n in the buffer. In\nthis case, your strings have \\n embedded (from the <code>fgets</code> call) and so\n<code>fprintf</code> will flush the buffer; the buffer is empty when <code>fflush</code> is\ncalled. The normal thing would be for the word in <code>wordContainer</code> to have\nno \\n and for <code>fprintf</code> to use a format containing \\n - <code>fprintf(filePtr,\n\"%s\\n\", word);</code> - and again, no <code>fflush</code> is needed.</p></li>\n<li><p>your </p>\n\n<pre><code>else\n{\n printf(\"thank you for using this program,bye\");\n exit(0);\n}\n</code></pre>\n\n<p>exits before the final closing of the file and zero return. Closing the file is good practice, although it will happen when the\nprogram exits anyway.</p></li>\n<li><p>I don't really like your variable names - three variables starting with\n'word' is confusing. I'd go for something like <code>word</code> for the user-entered\nword, <code>entry</code> for the dictionary entry read from file and <code>found</code> to\nindicate that the word was found in the dictionary. That is a rather\npersonal preference though...</p></li>\n<li><p>remember to put a \\n on the end of lines that are printed, eg on exiting the\nprogram.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T16:10:21.017",
"Id": "40345",
"Score": "0",
"body": "thanks a lot for you very helpful answer ,about the rewind problem , it was there , realy ! But i think it was lost during the parsing as for the `\\n` problem I'll probably write a function that goes trough the entered word and the words retrieved from the file and replaces the `\\n` with a `\\0`, and thanks again for your answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T19:23:59.700",
"Id": "40743",
"Score": "0",
"body": "William Morris, I can never thank you enough for your edit , it's exactly the kind of answer I'd hoped to get , I'll try to apply everything you said on my future programs :D"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T14:12:24.617",
"Id": "26079",
"ParentId": "26074",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T01:50:37.180",
"Id": "26074",
"Score": "4",
"Tags": [
"beginner",
"c",
"search",
"file"
],
"Title": "Checking for an existing word in a file"
}
|
26074
|
<p>I'm trying to optimize a python string that works on big data sets, the way it works is by taking in a with a list of keywords and scores and taking in a file loaded with data from the twitter api. The program does a keyword match against tweet text. At the end of the program I want to produce an average for each term found in text object of the json file. e.g.</p>
<p><em>sad 3</em></p>
<p>With sad being the keyword and 3 being the average score.</p>
<p>It's running way too slow but I'm new to Python coming from a php background and I think I'm doing things the php way in python. </p>
<p>How can I get this code to run faster?</p>
<pre><code>import sys
import json
import re
def findRecord(key, records):
for r in records:
if r[0] == key:
return r
def average_records(records):
for r in records:
if r[1] > 0:
avg = r[1] / r[2]
print r[0] + ' ' + str(avg)
else:
avg = r[3] / r[4]
print r[0] + ' ' + str(avg)
def hw(sent_file, tweet_file):
scores = {}
sent_file = open(sent_file, 'r')
for line in sent_file:
term, score = line.split("\t")
scores[term] = int(score)
recored_affin = []
#print scores.items()
data = []
with open(tweet_file, 'r') as f:
for line in f:
data.append(json.loads(line))
#print data[4]['text']
for tweet in data:
total = 0
if 'text' in tweet:
for k, v in scores.iteritems():
#print tweet['text']
num_of_aff = len(re.findall(k, tweet['text']))
if num_of_aff > 0:
#print "Number is: " + str(num_of_aff)
#print "Word is: " + k
#print "Tweet is: " + tweet['text']
total += (v * num_of_aff)
#print "Score is: " + str(total)
#while count < len(recorded_affin):
foundRow = findRecord(k, recored_affin)
if foundRow != None:
index = recored_affin.index(foundRow)
quick_rec = recored_affin[index]
if v > 0:
new_value = quick_rec[1] + v
new_count = quick_rec[2] + 1
old_neg_value = 0
old_neg_count = 0
recored_affin.append([k, new_value, new_count, old_neg_value, old_neg_count])
recored_affin.remove(foundRow)
elif v < 0:
old_pos_value = 0
old_pos_count = 0
new_value = quick_rec[3] + v
new_count = quick_rec[4] + 1
recored_affin.append([k, old_pos_value, old_pos_count, new_value, new_count])
recored_affin.remove(foundRow)
else:
if v > 0:
recored_affin.append([k,v,1,0,0])
elif v < 0:
recored_affin.append([k,0,0,v,1])
#print recored_affin
##print foundRow
##print total
average_records(recored_affin)
def lines(fp):
print str(len(fp.readlines()))
def main():
sent_file = open(sys.argv[1])
tweet_file = open(sys.argv[2])
hw(sys.argv[1], sys.argv[2])
#lines(sent_file)
#lines(tweet_file)
if __name__ == '__main__':
main()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T21:10:08.077",
"Id": "40352",
"Score": "0",
"body": "Please provide some example data. Without being able to run your program, it's hard to tell whether we've made it any faster."
}
] |
[
{
"body": "<p>Your code contains a mix of tabs and spaces. This caused your code to display incorrectly before I edited it. The most common way in python is to use only spaces. You should be able to configure your editor to insert spaces instead of tabs when you push the tab key.</p>\n\n<pre><code>import sys\nimport json\nimport re\n\ndef findRecord(key, records):\n</code></pre>\n\n<p>Python convention is to name function lowercase_with_underscores</p>\n\n<pre><code> for r in records:\n if r[0] == key:\n return r\n</code></pre>\n\n<p>It is going to be inefficient to loop over records looking for things like this. Instead, you use a dictionary and look them up by key.</p>\n\n<pre><code>def average_records(records):\n for r in records:\n</code></pre>\n\n<p>Rather than indexing <code>r</code> all over the place, I suggest using:</p>\n\n<pre><code> for k, new_value, new_count, old_neg_value, old_neg_count in records:\n</code></pre>\n\n<p>Then you can access those names directly. It'll be easier to read and probably marginally faster.</p>\n\n<pre><code> if r[1] > 0:\n avg = r[1] / r[2]\n print r[0] + ' ' + str(avg)\n else:\n avg = r[3] / r[4]\n print r[0] + ' ' + str(avg)\n</code></pre>\n\n<p>In this case, you can do: <code>print r[0], avg</code> for the same result.</p>\n\n<pre><code>def hw(sent_file, tweet_file):\n</code></pre>\n\n<p>I have no idea what <code>hw</code> means</p>\n\n<pre><code> scores = {}\n\n sent_file = open(sent_file, 'r')\n\n for line in sent_file:\n term, score = line.split(\"\\t\")\n scores[term] = int(score)\n</code></pre>\n\n<p>This scores bit is a nicely self contained section. I suggest making it a separate function. </p>\n\n<pre><code> recored_affin = []\n\n #print scores.items()\n</code></pre>\n\n<p>Don't keep dead code, just remove it. If you think you might need it back look into version control.</p>\n\n<pre><code> data = []\n\n with open(tweet_file, 'r') as f:\n for line in f:\n data.append(json.loads(line))\n\n #print data[4]['text']\n</code></pre>\n\n<p>You're finished with the file now, you should really drop out of the with block.</p>\n\n<pre><code> for tweet in data:\n</code></pre>\n\n<p>There isn't really much point in storing the json objects in a list just to process them. Just process them as you get them.</p>\n\n<pre><code> total = 0\n if 'text' in tweet:\n for k, v in scores.iteritems():\n\n #print tweet['text']\n num_of_aff = len(re.findall(k, tweet['text']))\n if num_of_aff > 0:\n #print \"Number is: \" + str(num_of_aff)\n #print \"Word is: \" + k\n #print \"Tweet is: \" + tweet['text']\n total += (v * num_of_aff)\n #print \"Score is: \" + str(total)\n\n #while count < len(recorded_affin):\n</code></pre>\n\n<p>Don't leave commented code in there</p>\n\n<pre><code> foundRow = findRecord(k, recored_affin)\n\n if foundRow != None:\n</code></pre>\n\n<p>Use <code>is None</code> to check for foundRow</p>\n\n<pre><code> index = recored_affin.index(foundRow)\n</code></pre>\n\n<p>That's going to be expensive, it scans through the whole list again.</p>\n\n<pre><code> quick_rec = recored_affin[index]\n</code></pre>\n\n<p>Isn't this just foundRow again?</p>\n\n<pre><code> if v > 0:\n new_value = quick_rec[1] + v\n new_count = quick_rec[2] + 1\n old_neg_value = 0\n old_neg_count = 0\n recored_affin.append([k, new_value, new_count, old_neg_value, old_neg_count])\n recored_affin.remove(foundRow)\n</code></pre>\n\n<p>Expensive, has to scan through again.\n elif v < 0:</p>\n\n<pre><code> old_pos_value = 0\n old_pos_count = 0\n new_value = quick_rec[3] + v\n new_count = quick_rec[4] + 1\n recored_affin.append([k, old_pos_value, old_pos_count, new_value, new_count])\n recored_affin.remove(foundRow)\n</code></pre>\n\n<p>You've got some duplication here, you should move the common logic out of the if blocks.</p>\n\n<pre><code> else:\n if v > 0:\n recored_affin.append([k,v,1,0,0])\n elif v < 0:\n recored_affin.append([k,0,0,v,1])\n\n #print recored_affin\n\n ##print foundRow\n\n\n ##print total\n average_records(recored_affin)\n\n\n\ndef lines(fp):\n print str(len(fp.readlines()))\n\ndef main():\n sent_file = open(sys.argv[1])\n tweet_file = open(sys.argv[2])\n</code></pre>\n\n<p>Why do you open these file but never do anything with them?</p>\n\n<pre><code> hw(sys.argv[1], sys.argv[2])\n #lines(sent_file)\n #lines(tweet_file)\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>Your speed issues are probably the result of using a list and constantly searching over the whole list instead of using a dictionary. Make recorded_affin a dictionary, and your code should be simpler and faster.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T13:44:48.657",
"Id": "26078",
"ParentId": "26077",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T09:12:19.680",
"Id": "26077",
"Score": "4",
"Tags": [
"python",
"optimization",
"twitter"
],
"Title": "Optimizing python code for big data sets"
}
|
26077
|
<p>What are your thoughts on the fallowing immutable stack implementation? It is implemented having as a basis a C# immutable stack (where garbage collector assistance does not impose using a reference counted implementation like here).</p>
<pre><code>namespace immutable
{
template<typename T>
class stack: public std::enable_shared_from_this<stack<T>>
{
public:
typedef std::shared_ptr<T> headPtr;
typedef std::shared_ptr<stack<T>> StackPtr;
template <typename T> friend struct stackBuilder;
static StackPtr empty()
{
return std::make_shared<stackBuilder<T>>(nullptr, nullptr);
}
static StackPtr Create()
{
return empty();
}
StackPtr push(const T& head)
{
return std::make_shared<stackBuilder<T>>(std::make_shared<T>(head), shared_from_this());
}
StackPtr pop()
{
return this->tail;
}
headPtr peek()
{
return this->head;
}
bool isEmpty()
{
return (this->head == nullptr);
}
private:
stack(headPtr head, StackPtr tail): head(head), tail(tail)
{
}
stack<T>& operator= (const stack<T>& other);
private:
headPtr head;
StackPtr tail;
};
template <typename T>
struct stackBuilder: public stack<T>
{
stackBuilder(headPtr head, StackPtr tail): stack(head, tail){}
};
}
</code></pre>
<p>Usage:</p>
<pre><code>auto empty = stack<int>::empty();
auto newStack = empty->push(1);
auto stack = newStack;
while(!stack->isEmpty())
{
std::cout << *stack->peek() << "\n";
stack = stack->pop();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T14:46:46.110",
"Id": "40342",
"Score": "1",
"body": "Shouldn't `pop()` remove or un-scope the value at `tail`, or do you mean it to be a `top()` function instead?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T15:39:22.620",
"Id": "40343",
"Score": "0",
"body": "@JamalA pop() Every operation on imutable stack returns a new stack. pop() cannot mutate the original stack"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T15:53:17.977",
"Id": "40344",
"Score": "0",
"body": "Oh, right. I must've missed the keyword here: immutable. I've always assumed that `pop()` always modifies the stack in some way, unlike `top()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-13T12:45:17.533",
"Id": "52199",
"Score": "0",
"body": "Why would you want something like this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-14T07:20:19.050",
"Id": "52245",
"Score": "0",
"body": "@busy_wait I'd guess the key is in the `functional-programming` tag; in functional programming, everything is immutable."
}
] |
[
{
"body": "<ol>\n<li><p>Element mutability</p>\n\n<p>Your stack is not <em>entirely</em> immutable, because <code>peek</code> returns a pointer to a non-const <code>T</code>, which means it's possible to modify the elements of the stack. And given your use of <code>shared_ptr</code>, this may have severe consequences. Consider this code:</p>\n\n<pre><code>using immutable::stack;\n\nvoid doSomething(stack::StackPtr stack);\n\nint main() {\n auto stack1 = stack<int>::empty()->push(1);\n assert(*stack1->peek() == 1); // succeeds\n doSomething(stack1);\n assert(*stack1->peek() == 1); //FAILS!\n}\n\nvoid doSomething(stack<int>::StackPtr st) {\n *st->peek() = 42;\n}\n</code></pre>\n\n<p>If this is intended behaviour, it should definitely be heavily documented. To me, it looks much more like a bug, however.</p>\n\n<p>One option would be to change <code>headPtr</code> to be a pointer to <code>const</code>:</p>\n\n<pre><code>typedef std::shared_ptr<const T> headPtr;\n</code></pre>\n\n<p>However, perhaps a more user-friendly solution would be to change <code>peek()</code> to return a <code>const</code>-reference to <code>T</code> instead of a shared pointer. After all, if I put a <code>T</code> on the stack, I would expect to get a <code>T</code> back, not a <code>pointer to T</code>:</p>\n\n<pre><code>const T& peek()\n{\n return *this->head;\n}\n</code></pre>\n\n<p>Of course, this would require handling the case of <code>peek</code>-ing an empty stack, or at least documenting that it produces undefined results.</p></li>\n<li><p><code>stackBuilder</code></p>\n\n<p>I understand you're using the <code>stackBuilder</code> class template to be able to use <code>std::make_shared</code> internally, but it opens up a way to bypass your creation mechanism, which is a potential source of bugs. Nothing prevents a user from doing this:</p>\n\n<pre><code>immutable::stackBuilder<int> p(nullptr, nullptr);\np.push(7);\n</code></pre>\n\n<p>This will fail at runtime because no <code>std::shared_ptr</code> has ever referred to <code>p</code>, so <code>shared_from_this()</code> won't work.</p>\n\n<p>You should make <code>stackBuilder</code> a private member class of <code>stack</code> (it doesn't even have to be a template any more). That way, it's inaccessible from outside, but its constructor can still be <code>public</code>, so <code>std::make_shared</code> works. </p>\n\n<p>If your compiler implements C++11 member access rights correctly, <code>stackBuilder</code> will then no longer have to be declared as <code>friend</code>, because member classes have the same access rights as other members.</p></li>\n<li><p>Copy constructor</p>\n\n<p>Your class has an inaccessible assignment operator (which is good since it's supposed to be immutable), but the copy constructor is accessible normally. This is again a potential problem, since your class doesn't work if it's not owned by a <code>shared_ptr</code>. So this code will compile, but fail at runtime:</p>\n\n<pre><code>using immutable::stack;\n\nauto stack1 = stack<int>::empty();\nauto stack2(*stack1);\nstack2.push(7);\n</code></pre>\n\n<p>You should make the copy constructor inaccessible as well.</p></li>\n<li><p>Inconsistent capitalisation</p>\n\n<p><code>StackPtr</code> vs. <code>headPtr</code>, all <code>camelCase</code> member functions vs. <code>Create()</code> etc. You should pick one pattern and stick to it.</p>\n\n<p>Related to this is the fact that your class closely resembles one from the standard library (<code>std::stack</code>), so it might be worthwhile to modify your naming to match the <code>std</code> one. That would mean renaming <code>peek()</code> to <code>top()</code>, and <code>isEmpty()</code> to <code>empty()</code> (and of course renaming your current <code>empty()</code> to something else). But this depends on other parts of your project as well, of course.</p></li>\n<li><p>Storing non-copyable types</p>\n\n<p>I think <code>push()</code> should take its argument by value, and <code>std::move()</code> it into the new stack; that way, you can store non-copyable types in the stack as well:</p>\n\n<pre><code>StackPtr push(T newHead)\n{\n return std::make_shared<stackBuilder<T>>(std::make_shared<T>(std::move(newHead)), shared_from_this());\n}\n</code></pre>\n\n<p>Alternatively, provide two overloads, one taking <code>const T&</code> and one taking <code>T&&</code>. This would potentially be more efficient for types which are expensive to move.</p>\n\n<p>Note that I've renamed the parameter to <code>newHead</code> - when originally reading your code, I was actually confused and though you were pushing <code>this->head</code>. It's best to prevent such naming confusion.</p></li>\n<li><p>Storing non-movable types</p>\n\n<p>You might also provide an <code>emplace()</code>, which would even allow non-movable types to be stored (especially as the stack is immutable), and be more efficient with types expensive to copy/move:</p>\n\n<pre><code>template <class... Arg>\nStackPtr emplace(Arg&&... arg)\n{\n return std::make_shared<stackBuilder<T>>(std::make_shared<T>(std::forward<Arg>(arg)...), shared_from_this());\n}\n</code></pre></li>\n<li><p>Const-correctness</p>\n\n<p>It doesn't matter too much in your case, because access to its instances is stricty via <code>StackPtr</code>, but you might want to mark all the member functions as <code>const</code> to emphasize the fact that the class is immutable. <code>StackPtr</code> would then change like this:</p>\n\n<pre><code>typedef std::shared_ptr<const stack<T>> StackPtr;\n</code></pre>\n\n<p>This nicely documents that the class is immutable, and allows it to be more easily used inside other const-correct code, mainly const-correct templates.</p></li>\n<li><p>A note on performance</p>\n\n<p>I can't see any blatant performance issues there. Nevetheless, your users must be aware that the class uses mechanisms which could negatively affect performance-critical code. One is dynamic allocation. The other one are shared pointers, which must internally use atomic operations or synchronisation on their reference counts.</p>\n\n<p>For normal use, this is hardly a problem. If you expect the class to be used in performance-critical code, though, you might want to provide a custom allocator for it which would prevent constant deallocation and re-allocation. Still, I don't think this is worth doing until profiling tells you otherwise.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-13T12:12:34.553",
"Id": "32640",
"ParentId": "26080",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T13:19:06.067",
"Id": "26080",
"Score": "5",
"Tags": [
"c++",
"performance",
"functional-programming",
"stack",
"immutability"
],
"Title": "Immutable C++ stack - thoughts and performance"
}
|
26080
|
<p>I recently started learning Haskell and as my first project I decided to port a particle simulation I had written in C.</p>
<p>The simulation is pretty simple. We have a cubic box with particles (spheres) inside it. Then we choose to either move a particle or to change the volume of the box and check for any collisions between the particles. If there are any collisions we keep the old configuration.</p>
<p>To speed up collision detection I have also implemented a 'cell linked list' which is in principle a uniform grid with a minimum size of a cell equal to the particle diameter. In the C code I have implemented this using arrays while in the Haskell code I use a Vector of Lists.</p>
<p>You can find my full code <a href="https://github.com/Grieverheart/hPartSim" rel="nofollow noreferrer">here</a>, but here are some of the most important snippets,</p>
<p>The main Simulation Loop, where type <code>Eval a = ReaderT (Env a) (StateT (SimState a) IO)</code></p>
<pre>
<code>
runSimulation :: Int -> Eval Double ()
runSimulation steps = do
Env npart ps <- ask
forM_ [1..steps] (\i -> do
forM_ [1..npart+1] (\_ -> do
SimState config _ variables <- get
selection <- liftIO $ getRandomR (0, npart)
if selection < npart
then do
rdx <- liftIO $ getRandomRs (0.0, _dx variables) >>= \r -> return $ take 3 r
rn <- liftIO $ getRandomR (0, npart - 1)
lift $ moveParticle (vec3fromList rdx) rn
else do
let dv = _dv variables
rdv <- liftIO $ getRandomR (-dv, dv)
racc <- liftIO $ getRandomR (0.0, 1.0)
let vol = boxVolume $ _box config
acc = exp $ (-ps) * rdv + fromIntegral npart * log ((vol + rdv) / vol)
when (racc < acc) $ changeVolume rdv
)
when (i `mod` 100 == 0) $ do
state@(SimState _ _ variables) <- get
let accVol = fromIntegral (_nVol variables) / 100.0
accMov = fromIntegral (_nMov variables) / (fromIntegral npart * 100)
olddx = _dx variables
olddv = _dv variables
newdx = (*) olddx (if accMov > 0.3 && olddx < 0.45 then 1.04 else 0.94)
newdv = (*) olddv (if accVol > 0.15 then 1.04 else 0.94)
liftIO $ print i
liftIO $ printf "dx = %.6f, dv = %.6f, nMov = %d, nVol = %d\n" newdx newdv (_nMov variables) (_nVol variables)
put $! state{_vars = variables{_dx = newdx, _dv = newdv, _nMov = 0, _nVol = 0}}
printConfig $ "Data/test" ++ show i ++ ".dat"
</code>
</pre>
<p>Here I'm effectively randomly choosing to either displace a particle or change the volume and every 100 steps I print useful information.</p>
<p>These two moves <code>moveParticle</code>, <code>changeVolume</code> are listed below,</p>
<pre><code>
moveParticle :: (RealFrac a, Floating a) => Vec3 a -> Int -> StateIO a ()
moveParticle dx nPart = do
SimState config@(Configuration box particles) cll variables <- get
let particle = particles V.! nPart
particle' = Particle $ applyBC $ _position particle .+. dx
cllIdx = cellIndex (_nCells cll) (_position particle')
isCollision = any (checkCollision box) [(particle', particles V.! pId) | pId <- neighbours cll cllIdx, pId /= nPart]
unless isCollision $ do --Accept move if there is no collision
let cllIdxOld = cellIndex (_nCells cll) (_position particle)
cll' = if cllIdx == cllIdxOld then cll else cllInsertAt (cllRemoveAt cll cllIdxOld nPart) cllIdx nPart
particles' = modifyVectorElement nPart particle' particles
put $! SimState config{_particles = particles'} cll' variables{_nMov = _nMov variables + 1}
changeVolume :: (Floating a, RealFrac a) => a -> Eval a ()
changeVolume dv = do
SimState config@(Configuration box particles) cll variables <- get
Env npart _ <- ask
let v = boxVolume box
box' = let scalef = ((v + dv) / v)**(1.0 / 3.0) in scaleBox scalef box
isCollision = any (checkCollision box') combinations
{-- A list of all the particles pairs that need to be checked for collision.
For each particle, the particles in the neighbouring cells are used. --}
combinations = do
pId <- [0..(npart - 1)]
let particle = particles V.! pId
cllIdx = cellIndex (_nCells cll) (_position particle)
pId' <- neighbours cll cllIdx
guard (pId /= pId')
return (particle, particles V.! pId')
unless isCollision $ do --Accept move if there is no collision
let new_cell_size = zipWith ((/) . fromIntegral) (_nCells cll) box'
new_n = map truncate box'
config' = config{_box = box'}
recreate = any (< 1.0) new_cell_size || any (> 2.0) new_cell_size || any (> 2) (zipWith ((abs .) . (-)) new_n (_nCells cll))
cll' = if recreate then generateCellList config' else cll
put $! SimState config' cll' variables{_nVol = _nVol variables + 1}
</code></pre>
<p>I would really appreciate a code review, especially since I just started learning Haskell. The code right now feels a bit messy. As you may have also noticed, I have given the accessor functions an underscore in their name with the intention to use Lenses later on.</p>
<p>I'm especially interested in any performance improvements. My Haskell implementation is up to 10 times slower than the C code which is unacceptable for a simulation. I should also mention that I've tried converting the Cell type to a Data.Seq and the Box type to a Vector but didn't see any performance improvements.</p>
<p>You can find the profiling report <a href="http://pastebin.com/hh7fEXTR" rel="nofollow noreferrer">here</a> and below I have also posted the space profiling graphs. I don't quite understand from these what is making the Haskell implementation so slow.</p>
<p><img src="https://i.stack.imgur.com/Yfvc6.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/nkZCl.png" alt="enter image description here"></p>
<p><img src="https://i.stack.imgur.com/c6jYD.png" alt="enter image description here"></p>
|
[] |
[
{
"body": "<p>Heap profiling will not tell you much in this case - memory leaking is definitely not your problem. Using cost-centre profiling would probably be better suited for identification of the hot-spots.</p>\n<p>After looking at the profile a bit (using <a href=\"https://github.com/scpmw/ghc\" rel=\"noreferrer\">home-grown tools</a>), the worst offenders seem to be:</p>\n<ol>\n<li><p>Lots of calls to <code>stg_newArray</code>, undoubtedly due to the <code>CellList</code> vector getting copied by <code>modify</code>. The documentation says that <code>modify</code> can update destructively, but I am pretty sure that this only refers to situations where the source <code>Vector</code> can be derived to be a temporary value available for fusion.</p>\n<p>To really get destructive updates, you would probably have to explicitly use a <code>MVector</code> and the <code>ST</code> monad. As you already have a monad around, the amount of refactoring involved wouldn't be crushing, but you would obviously lose a bit of purity.</p>\n</li>\n<li><p>Additionally, the <code>neighbours</code>, <code>getCell</code> and <code>cellNeighbours</code> functions are getting <em>hammered</em> by your program. You are doing some pretty fancy list processing in there that GHC seems to not optimize very well - pretty much all these lists are actually generated and consumed. Helping GHC a bit by spelling out the loops might improve things.</p>\n</li>\n<li><p>Finally, the default random number generator is <em>slow</em> - any time you use it you get a flurry of <code>Integer</code> allocations behind the scenes. Try to find a better one on Hackage.</p>\n</li>\n</ol>\n<hr />\n<p>Actually, I might have mis-interpreted the profile for point number two a bit - the following is actually a <em>big</em> no-no:</p>\n<pre><code>type CellIndex = [Int] -- The index of a cell [i, j, k]\n</code></pre>\n<p>Haskell can do a lot of optimization, but only if it has enough information. As it stands, <code>getCell</code> will get a prefix like:</p>\n<pre><code> case y5 of wild18 {\n [] -> lvl9;\n : i1 ds8 -> case ds8 of wild19 {\n [] -> lvl9;\n : j1 ds9 -> case ds9 of wild20 {\n [] -> lvl9;\n : k1 ds10 -> case ds10 of wild21 {\n [] -> case i1 of wild22 { GHC.Types.I# y6 ->\n case j1 of wild23 { GHC.Types.I# y7 ->\n case k1 of wild24 { GHC.Types.I# y8 -> ... } } };\n : ipv1 ipv2 -> lvl9\n } } } }\n</code></pre>\n<p>Meaning that it traverse the list, checks that it contains exactly three elements, and then unpacks every <code>Int</code> separately. By passing <code>(Int, Int, Int)</code> or your own <code>Vec3</code> you would give Haskell enough information to derive that it can skip all the heap allocation.</p>\n<hr />\n<p>Concerning my original point:</p>\n<pre><code>cellNeighbours (CellList !nCells _) cell = do\n i <- [-1..1]\n j <- [-1..1]\n k <- [-1..1]\n let temp = zipWith3 (((+).).(+)) nCells cell [i, j, k]\n return $! zipWith mod temp nCells\n</code></pre>\n<p>Now this is arguably nice code - even though I personally don't like overly tricky <code>(.)</code> constructions or usage of the list monad in the first place (list comprehensions!). The performance problem here is that this becomes something like follows after desugaring:</p>\n<pre><code>concatMap (\\i -> concatMap (\\j -> concatMap (\\k -> [...]) [-1..1]) [-1..1]) [-1..1])\n</code></pre>\n<p>GHC will <em>not</em> unroll these, which means that you have constructed a multiple-level loop doing trivial list concatenations in a completely predictable manner.</p>\n<p>If you for example wrote it as:</p>\n<pre><code>cellNeighbours (CellList (d,e,f) _) (x,y,z) = map add offsets\n where add (a,b,c) = (x+a+d, y+b+e, z+c+f)\n offsets = [(a,b,c) | a <- [-1..1], b <- [-1..1], c <- [-1..1]]\n</code></pre>\n<p>That would make <code>offsets</code> a global constant that only gets evaluated once <em>and</em> would allow GHC to fuse the <code>map</code> with the <code>concatMap</code> in <code>neighbours</code>, eliminating the intermediate list completely.</p>\n<hr />\n<p>Some points on the structure:</p>\n<ol>\n<li><p>You should try to isolate your simulation code as much as possible. Right now it is in "main.hs", which should normally just handle initialization and configuration. Splitting out the actual maths bits would be a pretty straightforward improvement.</p>\n</li>\n<li><p>On a similar note, you already have a monad, but aren't using it as an encapsulation tool - your core simulation code still uses <code>put</code> directly. Try to find out what "verbs" you are really using, then define some simple wrappers for those (say <code>increaseParticleMoves</code>?). After you have eliminated all direct access, you can then export the monad and all actions to its own module, newtype-wrap it and stop exporting its definition. Having this sort of infrastructure would for example make the switch to <code>ST</code> much easier.</p>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T17:54:57.577",
"Id": "40405",
"Score": "0",
"body": "Hi Peter, thank you very much for taking the time to analyze my code and comment on it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T18:01:15.930",
"Id": "40406",
"Score": "0",
"body": "On point 2, I'm not sure what you're trying to say, could you be a bit more specific? I also depended on these functions being lazily evaluated, do you know if this is the case? On point 3, I did indeed notice `Integer` being used and later found out it is due to `Random` probably calling a `time` function. Maybe I'm asking too much, but could you perhaps give me any tips beyond performance e.g. style and structure of the code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T13:52:41.087",
"Id": "40476",
"Score": "0",
"body": "I have added some more comments. And no, the problem with `Random` isn't `time`, it's that it internally always first generates a large `Integer` random number and then cuts it down to what was actually requested."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T17:47:46.523",
"Id": "26118",
"ParentId": "26081",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "26118",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T15:51:15.420",
"Id": "26081",
"Score": "13",
"Tags": [
"performance",
"haskell",
"simulation",
"physics"
],
"Title": "Haskell Particle Simulation"
}
|
26081
|
<p>The requirement is to skip a line beginning from <code>#</code> sign. Basically, we need to treat it as a comment line. The input is given by the user from the keyboard. I will not be reading it from a file. I have a link to the code that i have written so far. In this code, I have used multiple lines to skip a commented line which is in red colored text.</p>
<p>I wanted to know if it could be improved. As in, just one line of code to skip comment line.</p>
<p>Please note: The comment line could be given anywhere from the keyboard.</p>
<pre><code>#include
#include
#include
#include
using namespace std;
unsigned long int m;
unsigned long int n;
int res;
unsigned long int i, j, k, ctr, maxIndex;
long int l,la,lb;
string command, key,comment;
string indexS;
long int index, lo=0, hi,mid;
char key1[500];
char keyd[500];
char keym[500];
char data1[10000][500], maskS[10000][500];
char maskey[10000];
char maskSt[10000][500];
char data[10000][500];
void *runner(void *numbers);
void *runnera(void *numbersa);
void *runnerStar(void *numbers);
void *runnerStara(void *numbersa);
int readKey(string s); /* A function that returns 1 when '*' is found and returns 0 if '*' not found in key*/
void checkKey(string str);
void checkIndex(string strInd);
char StoC(string input);
void mErr(string eKey, unsigned long int mCheck);
long int search(char dataS[10000][500], char keyS[500], unsigned long int mS, unsigned long int nS, unsigned long int initial, unsigned long int final);
long int searchStar(char dataSt[10000][500],char keySt[500], unsigned long int mSt, unsigned long int nSt, unsigned long int initialSt, unsigned long int finalSt);
long int searchA(char dataS[10000][500], char keyS[500], unsigned long int mS, unsigned long int nS, unsigned long int initial, unsigned long int final);
long int searchStarA(char dataSt[10000][500],char keySt[500], unsigned long int mSt, unsigned long int nSt, unsigned long int initialSt, unsigned long int finalSt);
/*---Structure for threads--*/
struct arg_struct {
char numData[5000][500];
char numKey[500];
unsigned long int numM;
unsigned long int numN;
unsigned long int numLo;
unsigned long int numMid;
};
struct arg_structa {
char numaData[5000][500];
char numaKey[500];
unsigned long int numaM;
unsigned long int numaN;
unsigned long int numaMid;
unsigned long int numaHi;
};
int main()
{
cout << "Enter the command:"<< endl;
cout << "Enter input of the form:\n";
cout << "(a) for insert(i) and replace(r) : i \n";
cout << "(b) for delete(d) : d \n";
cout << "(c) for searching(s) : s \n";
cin >> command;
const char *comnta = command.c_str();
if(*comnta =='#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>>command;
const char *comntb = command.c_str();
if(*comntb =='#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>>command;
}
const char *comntc = command.c_str();
if(*comntc =='#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>>command;
}
}
try {
if(command == "d") {
cin >> indexS;
const char *indexComm = indexS.c_str();
if(*indexComm == '#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
const char *indexComma = indexS.c_str();
if(*indexComma == '#') { /*Skipping comment line part*/
index = 0;
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
}
}
checkIndex(indexS);
index = atoi(indexS.c_str());
}
else if(command =="s") {
cin >> key;
const char *keyComm = key.c_str();
if(*keyComm == '#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>> key;
const char *keyComma = key.c_str();
if(*keyComma == '#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>> key;
}
}
checkKey(key);
}
else if(command == "i" || command == "r") {
cin >> indexS;
const char *indexCommc = indexS.c_str();
if(*indexCommc == '#') { /*Skipping comment line part*/
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
const char *indexCommd = indexS.c_str();
if(*indexCommd == '#') {
index = 0;
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
}
}
checkIndex(indexS);
index = atoi(indexS.c_str());
ctr = index;
if(maxIndex < ctr)
maxIndex = ctr;
cin >> key;
const char *keyCommb = key.c_str();
if(*keyCommb == '#') {
cin.clear();
getline(cin,comment);
cin>> key;
const char *keyCommc = key.c_str();
if(*keyCommc == '#') {
cin.clear();
getline(cin,comment);
cin>> key;
}
}
checkKey(key);
}
else
throw(command);
}
catch(string err) {
cout << "The input must be of the form:\n";
cout << "(a) for insert(i) and replace(r) : i \n";
cout << "(b) for delete(d) : d \n";
cout << "(c) for searching(s) : s \n";
exit(0);
}
m = key.size(); /* Bit size of each entry of TCAM*/
n = 10000; /*Number of entries in TCAM*/
/*--------------------------------------------------------------------------------------*/
int loop = 0;
for(;;) {
cout << "Enter input of the form:\n";
cout << "(a) for insert(i) and replace(r) : i \n";
cout << "(b) for delete(d) : d \n";
cout << "(c) for searching(s) : s \n";
if(loop == 1) {
cout << "Enter the command:\n";
if (!(cin >> command))
break;
const char *comntd = command.c_str();
if(*comntd =='#') {
cin.clear();
getline(cin,comment);
cin>>command;
const char *comntd = command.c_str();
if(*comntd =='#') {
cin.clear();
getline(cin,comment);
cin>>command;
}
const char *comnte = command.c_str();
if(*comnte =='#') {
cin.clear();
getline(cin,comment);
cin>>command;
}
}
try {
if(command == "d")
{
cin >> indexS;
const char *indexCommd = indexS.c_str();
if(*indexCommd == '#') {
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
const char *indexComme = indexS.c_str();
if(*indexComme == '#') {
index = 0;
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
}
}
checkIndex(indexS);
index = atoi(indexS.c_str());
}
else if(command =="s") {
cin >> key;
const char *keyCommd = key.c_str();
if(*keyCommd == '#') {
cin.clear();
getline(cin,comment);
cin>> key;
const char *keyComme = key.c_str();
if(*keyComme == '#') {
cin.clear();
getline(cin,comment);
cin>> key;
}
}
checkKey(key);
mErr(key, m);
}
else if(command == "i" || command == "r") {
cin >> indexS;
const char *indexCommf = indexS.c_str();
if(*indexCommf == '#') {
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
const char *indexCommg = indexS.c_str();
if(*indexCommg == '#') {
index = 0;
cin.clear();
getline(cin,comment);
cin>>indexS;
index = atoi(indexS.c_str());
}
}
checkIndex(indexS);
index = atoi(indexS.c_str());
ctr = index;
if(maxIndex < ctr)
maxIndex = ctr;
cin >> key;
const char *keyCommf = key.c_str();
if(*keyCommf == '#') {
cin.clear();
getline(cin,comment);
cin>> key;
const char *keyCommg = key.c_str();
if(*keyCommg == '#') {
cin.clear();
getline(cin,comment);
cin>> key;
}
}
checkKey(key);
mErr(key, m);
}
else
throw(command);
}
catch(string err) {
cout << "The input must be of the form:\n";
cout << "(a) for insert(i) and replace(r) : i \n";
cout << "(b) for delete(d) : d \n";
cout << "(c) for searching(s) : s \n";
exit(0);
}
}
loop =1;
/*-------------Without '*' bits in the search key i.e res=0-------------------------------*/
/*-------------------------------Begin searching part of the code------------------------*/
readKey(key);
if(command == "s" && res ==0)
{
StoC(key); /* returns key1 which is a char type*/
pthread_t tid, tida;
pthread_attr_t attr;
pthread_attr_init(&attr);
struct arg_struct args;
struct arg_structa argsa;
/*----Spliting up the indices of the TCAM for parallelism-----*/
lo =0;
hi = maxIndex;
mid = (lo+hi)/2;
/*-----Assigning values to the data structure-------*/
for(unsigned long int o=lo; o<=mid; o++)
for(unsigned long int r=0; r {
args.numData[o][r] = data[o][r];
args.numKey[r] = key1[r];
}
for(unsigned long int x=mid+1; x<=hi; x++)
for(unsigned long int u=0; u {
argsa.numaData[x][u] = data[x][u];
argsa.numaKey[u] = key1[u];
}
args.numM = m;
args.numN = n;
args.numLo = lo;
args.numMid = mid;
argsa.numaM = m;
argsa.numaN = n;
argsa.numaMid = mid;
argsa.numaHi = hi;
/*----Creating 2 threads to be executed------*/
pthread_create(&tid, &attr, runner, (void *)&args);
pthread_create(&tida, &attr, runnera, (void *)&argsa); /* thread for second half of data*/
/*-------Waiting for both the thrads to complete execution-------*/
pthread_join(tid, NULL);
pthread_join(tida, NULL);
/*------Printing ouput values based on lowest index match----------*/
if(la ==-1 && lb==-1)
cout<< la <
else if(la == -1 && lb >=0)
cout<< lb <
else if(la >= 0 && lb ==-1)
cout<< la <
else if(la>=0 && lb >=0)
cout<< la < }
/*-----------------Search with '*' bits in the search key---------------------------------------------*/
else if(command == "s" && res==1)
{
StoC(key);
pthread_t thid, thida;
pthread_attr_t attr;
pthread_attr_init(&attr);
struct arg_struct args;
struct arg_structa argsa;
lo =0;
hi = maxIndex;
mid = (lo+hi)/2;
for(unsigned long int o=lo; o<=mid; o++)
for(unsigned long int r=0; r {
args.numData[o][r] = data[o][r];
args.numKey[r] = key1[r];
}
for(unsigned long int x=mid+1; x<=hi; x++)
for(unsigned long int u=0; u {
argsa.numaData[x][u] = data[x][u];
argsa.numaKey[u] = key1[u];
}
args.numM = m;
args.numN = n;
args.numLo = lo;
args.numMid = mid;
argsa.numaM = m;
argsa.numaN = n;
argsa.numaMid = mid;
argsa.numaHi = hi;
/*--------creating thread for program-----------------*/
pthread_create(&thid, &attr, runnerStar, (void *)&args);
pthread_create(&thida, &attr, runnerStara, (void *)&argsa); /* thread for second half of data*/
/*------Wait for both the threads to complete execution--------*/
pthread_join(thid, NULL);
pthread_join(thida, NULL);
/*------Printing ouput values based on lowest index match----------*/
if(la ==-1 && lb==-1)
cout<< la <
else if(la == -1 && lb >=0)
cout<< lb <
else if(la >= 0 && lb ==-1)
cout<< la <
else if(la>=0 && lb >=0)
cout<< la <
}
/*-------------Inserting data at index-- i key 1011-----dataind[n+1][m]-------------------------*/
else if(command =="i")
{
StoC(key);
if((data[index][0] == '\0')) {
for(unsigned long int bit=0; bit data[index][bit] = key1[bit];
}
else {
unsigned long int g = 0;
for(g=(index+1);g if(data[g][0] =='\0')
break;
}
if(maxIndex < g)
maxIndex = g;
for( unsigned long int e=g; e>index; e--)
for(unsigned long int biti=0; biti data[e][biti] = data[e-1][biti];
for( unsigned long int bit=0; bit data[index][bit] = key1[bit];
}
}
/*------------- delete index---------------------------*/
else if(command =="d")
{
i=0;
for(i=index; i<=maxIndex;i++)
for(int bitd=0; bitd data[i][bitd]= data[i+1][bitd];
if(maxIndex >= index && maxIndex !=0)
maxIndex = maxIndex-1;
}
/*------------- replace index key---------------------------*/
else if(command == "r")
{
StoC(key);
for(unsigned long int bitr=0; bitr data[index][bitr] = key1[bitr];
}
cout<<"\n\n\n";
cout<<<"tcam table="" entries="" without="" star\n"; // line();
cout<<<"index"<<<"data"<<<"mask"<
//line();
for(unsigned long int k=0;k<=10;k++)
{
cout<<<<<
}
//line();
cout<<<
}
return 0;
}
/*----------------------Function definitions begin------------------*/
int readKey(string s)
{
const char *p = s.c_str();
while (*p != '\0') {
if (*p == '*') {
res = 1;
return(res);
}
else {
res = 0;
}
*p++;
}
return(res);
}
/*-------------------------------------------------*/
void checkKey(string str)
{
const char *p = str.c_str();
try {
while (*p != '\0') {
if(*p=='*' || *p=='0' || *p=='1')
*p++;
else
throw(*p);
}
}
catch( char error) {
cout <<"ERROR: The input key must be in '1', '0', or '*'" << endl;
exit(0);
}
}
/*-------------------------------------------------*/
void checkIndex(string strInd)
{
const char *ind = strInd.c_str();
try {
while (*ind != '\0') {
if(*ind=='0'|| *ind=='1'|| *ind=='2'|| *ind=='3'|| *ind =='4'|| *ind=='5'|| *ind=='6'|| *ind=='7'|| *ind=='8'|| *ind=='9')
*ind++;
else
throw(*ind);
}
}
catch( char error) {
cout <<"ERROR: The input index must be a number" << endl;
exit(0);
}
}
/*----------------------------------------------------*/
char StoC(string input)
{
i = 0;
const char *p = input.c_str();
while (*p != '\0')
{
key1[i] = *p;
i++;
*p++;
}
return(*key1);
}
/*-----------------ERROR in key length-------------------------*/
void mErr(string eKey, unsigned long int mCheck)
{
if(eKey.size() != mCheck) {
cout<< "ERROR: Key size must not vary"<
exit(0);
}
}
/*---------------------------Search without * key-----------------*/
long int search(char dataS[10000][500],char keyS[500], unsigned long int mS, unsigned long int nS, unsigned long int initial, unsigned long int final)
{
/*---------------------Generating mask of the TCAM entries----------------------------*/
for(unsigned long int i=initial; i<=final; i++)
for(unsigned long int j=0; j if(dataS[i][j] == '*')
maskS[i][j]='0';
else
{
data1[i][j] = dataS[i][j];
maskS[i][j] = '1';
}
bool flag = true;
for(la=initial; la<=final; la++) {
flag = true;
for(unsigned long int k=0;k if ( maskS[la][k]== '1') {
if (keyS[k] != data1[la][k])
{
flag = false;
}
}
}
if (flag)
{
return(la);
}
}
la = -1;
return(la);
}
/*---------------------------Search without * key2-----------------*/
long int searchA(char dataS[10000][500],char keyS[500], unsigned long int mS, unsigned long int nS, unsigned long int initial, unsigned long int final)
{
/*---------------------Generating mask of the TCAM entries----------------------------*/
for(unsigned long int u=initial+1; u<=final; u++)
for(unsigned long int j=0; j if(dataS[u][j] == '*')
maskS[u][j]='0';
else
{
data1[u][j] = dataS[u][j];
maskS[u][j] = '1';
}
bool flaga = true;
for(lb=initial+1; lb<=final; lb++) {
flaga = true;
for(unsigned long int k=0;k if ( maskS[lb][k]== '1') {
if (keyS[k] != data1[lb][k]) {
flaga = false;
}
}
}
if (flaga)
{
return(lb);
}
}
lb = -1;
return(lb);
}
/*------------------------------Search with * key-------------------------------------------------------*/
long int searchStar(char dataSt[10000][500],char keySt[500], unsigned long int mSt, unsigned long int nSt, unsigned long int initialSt, unsigned long int finalSt)
{
for(unsigned long int a=initialSt; a<=finalSt; a++)
for(unsigned long int b=0; b if(dataSt[a][b] == '*') maskSt[a][b]='0';
else
{
data1[a][b] = dataSt[a][b];
maskSt[a][b] = '1';
}
for(unsigned long int j=0;j
{
if(keySt[j] =='*')
keym[j] = '0';
else
{
keyd[j] = keySt[j];
keym[j] = '1';
}
}
bool flag = true;
for( la=initialSt; la<=finalSt; la++) {
flag = true;
for(unsigned long int k=0;k if ( maskSt[la][k]== '1' && keym[k]=='1') {
if (keyd[k] != data1[la][k] )
{
flag = false;
}
}
}
if (flag)
{
return(la);
}
}
la = -1;
return(la);
}
/*---------------------------------------------------------------------------------*/
/*------------------------------Search with * key-------------------------------------------------------*/
long int searchStarA(char dataSt[10000][500],char keySt[500], unsigned long int mSt, unsigned long int nSt, unsigned long int initialSt, unsigned long int finalSt)
{
for(unsigned long int a=initialSt+1; a<=finalSt; a++)
for(unsigned long int b=0; b if(dataSt[a][b] == '*') maskSt[a][b]='0';
else
{
data1[a][b] = dataSt[a][b];
maskSt[a][b] = '1';
}
for(unsigned long int j=0;j
{
if(keySt[j] =='*')
keym[j] = '0';
else
{
keyd[j] = keySt[j];
keym[j] = '1';
}
}
bool flaga = true;
for( lb=initialSt+1; lb<=finalSt; lb++) {
flaga = true;
for(unsigned long int k=0;k if ( maskSt[la][k]== '1' && keym[k]=='1') {
if (keyd[k] != data1[la][k] )
{
flaga = false;
}
}
}
if (flaga)
{
return(lb);
}
}
lb = -1;
return(lb);
}
/*-----------Thread1 function for searching without star key------------------*/
void *runner(void *numbers)
{
struct arg_struct *args = (struct arg_struct *)numbers;
search(args-> numData, args-> numKey, args-> numM, args-> numN, args-> numLo, args-> numMid);
pthread_exit(0);
}
/*-----------Thread2 function for searching without star key------------------*/
void *runnera(void *numbersa)
{
struct arg_structa *argsa = (struct arg_structa *)numbersa;
searchA(argsa-> numaData, argsa-> numaKey, argsa-> numaM, argsa-> numaN, argsa-> numaMid, argsa-> numaHi);
pthread_exit(0);
}
/*-----------Thread1 function for searching without star key------------------*/
void *runnerStar(void *numbers)
{
struct arg_struct *args = (struct arg_struct *)numbers;
searchStar(args-> numData, args-> numKey, args-> numM, args-> numN, args-> numLo, args-> numMid);
pthread_exit(0);
}
void *runnerStara(void *numbersa)
{
struct arg_structa *argsa = (struct arg_structa *)numbersa;
searchStarA(argsa-> numaData, argsa-> numaKey, argsa-> numaM, argsa-> numaN, argsa-> numaMid, argsa-> numaHi);
pthread_exit(0);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T00:20:56.347",
"Id": "40353",
"Score": "0",
"body": "This code is a simple tcam simulation"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T00:53:49.117",
"Id": "40354",
"Score": "0",
"body": "Please copy your code _here_ so we may review it... don't link to it. Edit your post question to include it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T01:23:30.647",
"Id": "40356",
"Score": "0",
"body": "Added the code.."
}
] |
[
{
"body": "<p>There is far too much code here for me to review all of it. However, this looks like pure <code>C</code> except for <code>std::string</code> and some <code>iostream</code> usage. I don't know how familiar you are with <code>C++</code> as opposed to <code>C</code>, but I would write many of these functions very, very differently. In just about every function relating to string manipulation, you first convert it to a C-style string, and then use a lot of old constructs. Much of this can be <strong>greatly</strong> simplified:</p>\n\n<pre><code>int readKey(string s) \n{\n //Lots of C string wrangling\n}\n</code></pre>\n\n<p>can be a one-liner:</p>\n\n<pre><code>bool readKey(const std::string& str)\n{\n return str.find('*') != std::string::npos;\n}\n</code></pre>\n\n<p>The function signature has changed a bit. Firstly, don't pass <code>string</code> by value, pass it by reference to const. Secondly, <code>string</code> has a lot of what you're trying to do inbuilt (and for examples later on, if it doesn't, <code><algorithm></code> probably does).</p>\n\n<hr>\n\n<p><code>checkKey</code> and <code>checkIndex</code> do almost the exact same thing - abstract this out into a single function:</p>\n\n<pre><code>bool checkValid(const std::string& s, const std::string& allowable, \n const std::string& error)\n{\n bool valid = std::all_of(s.begin(), s.end(), \n [&allowable](char c) \n { return allowable.find(c) != std::string::npos; }); \n if(!valid) {\n std::cerr << error << \"\\n\";\n }\n return valid;\n}\n</code></pre>\n\n<p>Then again <code>checkKey</code> and <code>checkIndex</code> become one liners:</p>\n\n<pre><code>bool checkKey(const std::string& s)\n{\n return checkValid(s, \"*01\", \"Error: The input key must be in '1', '0', or '*'\");\n}\n\nbool checkIndex(const std::string& strInd)\n{\n return checkValid(s, \"0123456789\", \"Error: The input key must a number\");\n}\n</code></pre>\n\n<p>Using <code>throw</code> and then <code>catch</code> straight after to signal an error looks horrific to me. I'd personally rather return a <code>bool</code>, but you could simply make the function <code>void</code> and call <code>exit</code> again if you really want it to stop.</p>\n\n<hr>\n\n<p><code>char StoC(string input)</code> simply copies <code>input</code> into <code>key1</code>. Firstly, this is a buffer overflow just waiting to happen - there is absolutely no checking whether the length of <code>input</code> will overflow <code>key1</code>. Again, more useless <code>C</code> string wrangling. Assigning to global variables (ugh). The function name also leaves a lot to be desired. The previous ones could be improved, but after reading the code, I suppose I can at least sort of understand the names. This function name still makes no sense to me.</p>\n\n<p>Further, this doesn't need to be a function. Why even declare <code>key1</code> as a <code>char[]</code>? Why not have it as a <code>string</code> and simply use copy assignment: <code>key1 = <some string></code>?</p>\n\n<hr>\n\n<p>I don't really want to dig into some of the longer functions. The function names need a <em>lot</em> of work, for example:</p>\n\n<pre><code>void *runner(void *numbers);\nvoid *runnera(void *numbersa);\nvoid *runnerStar(void *numbers);\nvoid *runnerStara(void *numbersa);\n</code></pre>\n\n<p>I can glean absolutely nothing from those function names. The same can be said with regards to the variable names.</p>\n\n<p>Your <code>main</code> function is far, far too long - it needs to be broken up into more functions. The formatting is haphazard - perhaps this is a consequence of pasting the code here, but the whitespace is all over the place, making it even harder to read (and it's pretty hard to read to start with!).</p>\n\n<p>I realize you're using <code>pthreads</code> which makes things slightly more complicated. However, you can still easily utilize <code>std::string</code> and <code>std::vector</code> properly. Don't use things like:</p>\n\n<pre><code>char data1[10000][500];\n</code></pre>\n\n<p>Use a <code>std::vector<std::string></code> instead. It'll be less wasteful, you won't have to preallocate huge arrays to make sure they're always big enough (and there's never, ever any guarantee of that anyway). Both <code>std::string</code> and <code>std::vector</code> have C compatible layouts (if you need to pass the underlying array for <code>std::vector</code>, it's as simple as passing <code>&v[0]</code>).</p>\n\n<p>Basically (and this might sound a bit harsh), if I were given this code and told to maintain it, I would try to figure out exactly what it did. I would then throw everything away and rewrite it all from scratch, because it would probably take me less time than trying to decipher it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T04:25:40.637",
"Id": "40358",
"Score": "0",
"body": "Yes. Ill b making changes as per your suggestions. Thank you."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T03:40:37.340",
"Id": "26090",
"ParentId": "26088",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T00:19:21.323",
"Id": "26088",
"Score": "2",
"Tags": [
"c++",
"stream"
],
"Title": "Skipping comment line from keyboard via stdin"
}
|
26088
|
<p>I wrote this simple function in CoffeeScript to see if elements are found in an array:</p>
<pre><code>isFoundIn = (searchTerm, arrayToSearch) ->
returnVal = false
for a in arrayToSearch
returnVal = true if searchTerm is a
returnVal
</code></pre>
<p>Usage:</p>
<pre><code>isFoundIn('james', ['robert', 'michael', 'james'])`
</code></pre>
<p>would return true.</p>
<p>I know in Ruby it is very concise and readable to do this:</p>
<pre><code>myArr = ['robert', 'michael', 'james']
myArr.include? 'james'
</code></pre>
<p>Are there some strategies to refactor this to make it more readable or more like CoffeeScript?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T05:04:09.523",
"Id": "40359",
"Score": "0",
"body": "It seems you've replicated the native JS array `indexOf` function. While there's no exact match for Ruby's `include?` in JavaScript, a simple `array.indexOf(term) isnt -1` will give you the same result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T06:28:19.337",
"Id": "40360",
"Score": "1",
"body": "Heh, just posted an answer with much the same stuff seconds after your update :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T08:05:15.560",
"Id": "40380",
"Score": "1",
"body": "That's a reasonable question, but can infer from it that you're not using underscore.js? (or any other functional library for JS/CS). http://underscorejs.org/#contains. `_(myArr).contains(\"james\") #=> true`. I imagine having to write JS without all those extensions and I get the chills..."
}
] |
[
{
"body": "<p>Expanding on my comment above:</p>\n\n<p>Your <code>isFoundIn</code> function can be rewritten as simply</p>\n\n<pre><code>isFoundIn = (term, array) -> array.indexOf(term) isnt -1\n</code></pre>\n\n<p><code>indexOf</code> uses the strict <code>===</code> comparison, which is what CoffeeScript also uses for <code>is</code> - i.e. it's equivalent to your code.</p>\n\n<p>One could extend the native JS Array prototype with a <code>include</code> function to more closely mimic Ruby. In CoffeeScript, it'd be written as</p>\n\n<pre><code>Array::include = (term) -> @indexOf(term) isnt -1\n</code></pre>\n\n<p>Then you can do <code>[1, 2, 3].include(3)</code> and such. But extending native prototypes is generally frowned upon, and I can't recommend it. Tempting though.</p>\n\n<p>As for your original function, you could just do an explicit return right away if the <code>searchTerm</code> is found - no need to loop through the rest of the array</p>\n\n<pre><code> isFoundIn = (searchTerm, arrayToSearch) ->\n for a in arrayToSearch\n return true if searchTerm is a\n false\n</code></pre>\n\n<p>The point is moot, though, as <code>indexOf</code> does it all for you</p>\n\n<hr>\n\n<p>Addendum: I do like the <code>?</code> hack you used to fully match Ruby's method name, but it is still just that: A hack. You're effectively adding <code>undefined</code> as a possible return value for what should be a straight boolean. It'll also absorb errors (as that's its purpose) where e.g. the object responds to <code>indexOf</code> just fine, but - for whatever reason - hasn't been extended with the <code>include</code> function. So it's easy to get false negatives (unless you explicitly start checking for <code>undefined</code> and branch if that's the case and... well, the code fogs up quick)</p>\n\n<p>So again, definite points for creativity - wish I'd thought of it - but I personally wouldn't go near it in production code</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T06:42:56.657",
"Id": "40361",
"Score": "0",
"body": "Why is extending prototypes generally frowned upon in JavaScript? Is it because you can create compatibility issues hypothetically with future releases of ECMASript and or other libraries?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T08:09:59.423",
"Id": "40381",
"Score": "1",
"body": "@JamesJamesJames: Check SO, there are lots and lots of questions regarding this known issue: http://stackoverflow.com/questions/8859828/javascript-what-dangers-are-in-extending-array-prototype/8859941#8859941. More orthodox is the \"objects-wrapper\" that many libraries take (jQuery being the most known example)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T06:27:50.087",
"Id": "26092",
"ParentId": "26091",
"Score": "6"
}
},
{
"body": "<p>Any reason to not use <code>item in ary</code> syntax? it compiles down to a slightly convoluted usage of <code>.indexOf >=0</code> but it is the coffeescript way.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T14:29:36.927",
"Id": "40555",
"Score": "0",
"body": "+1 for the coffeescript way. Don't know why I didn't think of that usage of `in`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:06:50.483",
"Id": "26173",
"ParentId": "26091",
"Score": "4"
}
},
{
"body": "<p>If you want to make it \"more like CoffeeScript\", use array comprehensions:</p>\n\n<pre><code>isFoundIn = (searchTerm, arrayToSearch) ->\n return true for item in arrayToSearch when item is searchTerm\n false\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T20:42:40.200",
"Id": "26492",
"ParentId": "26091",
"Score": "0"
}
},
{
"body": "<p>The <code>in</code> in CoffeScript is essentially the same as Ruby's <code>include?</code>. You may write following Ruby version</p>\n\n<pre><code>['robert', 'michael', 'james'].include? 'james'\n</code></pre>\n\n<p>in CoffeeScript as</p>\n\n<pre><code>'james' in ['robert', 'michael', 'james']\n</code></pre>\n\n<p>You can use following if you want to add <code>include</code> to Array prototype:</p>\n\n<pre><code>Array::include = (o) -> o in @\n\nmyArr = ['robert', 'michael', 'james']\nconsole.log 'present' if myArr.include? 'james'\n</code></pre>\n\n<p>Note: <code>?</code> in include has different meaning in Ruby and CoffeeScript. In Ruby its the part of function name (although we can use <code>?</code> for boolean attributes in Rails). While in CoffeeScript <code>?</code> is an operator to check if the operand value is not null. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-29T00:18:14.177",
"Id": "231356",
"Score": "0",
"body": "Nice answer! But, this is not written very well. Please explain your code, and what improvements you are making from the OP's code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-29T04:36:43.307",
"Id": "231365",
"Score": "0",
"body": "@SirPython, does it look any better now?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-29T20:12:32.680",
"Id": "231505",
"Score": "0",
"body": "Much better! Good job."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-03-28T23:52:44.770",
"Id": "124136",
"ParentId": "26091",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T04:29:14.973",
"Id": "26091",
"Score": "3",
"Tags": [
"strings",
"search",
"coffeescript"
],
"Title": "Determining if a target string is found in an array of strings"
}
|
26091
|
<p>I have recently had a whole load of help trying to roll my own <em>loosely-coupled</em> Observable/Observer paradigm, here: <a href="https://stackoverflow.com/questions/16498315/loosely-coupled-observer-pattern">https://stackoverflow.com/questions/16498315/loosely-coupled-observer-pattern</a></p>
<p>To keep things simple and to aid in my understanding of the basic concepts, I asked about a specific implementation of Dog (Observable) vs Owner (Observer).</p>
<p>I am now trying to change that implementation into something more generic, so that I can create different types of Observers/Observables/Events for an actual application I intend to write.</p>
<p>I have something working now but I get the feeling that what I've got is going to cause me problems further down the line as my application grows.</p>
<p>I'd very much appreciate comments and suggestions on the following code, if indeed it is bad in some way (I think the Source class looks particularly nasty!). I'd like to know if this code is improvable, and if it is, how?</p>
<pre><code>// --- An event has a type (what happened?)
public enum EventType {
CREATE,
UPDATE,
DELETE
}
// --- Event contains what happened and the Observable that notified
public class Event<SourceType> {
private SourceType source;
private EventType type;
public SourceType getSource() { return source; }
public EventType getType() { return type; }
public Event(SourceType _source, EventType _type) {
source = _source;
type = _type;
}
}
// --- Listener interface
public interface IListener<SourceType> {
public void onEvent(Event<SourceType> _event);
}
// --- Implementation of that interface - this is a custom listener that deals with Persons.
// --- It looks like I'll need a new *Something*Listener for each additional Observer I want to observe.
public class PersonListener implements IListener<Person> {
public void onEvent(Event<Person> _event) {
System.out.println("EVENT: " + _event.getSource().getName());
// Would probably have a switch/case statement here to check the Event type (what happened?)
}
}
// --- A generic Observable
public class Source<ListenerType extends IListener<SourceType>, SourceType> {
private Set<ListenerType> listeners = new CopyOnWriteArraySet<ListenerType>();
public void addListener(ListenerType _listener) { listeners.add(_listener); }
public void fireEvent(Event<SourceType> _event) {
for(ListenerType listener : listeners) {
listener.onEvent(_event);
}
}
}
// --- A person who is observable (ill be subclassing this later into i.e Driver, Client, Receptionist)
public class Person extends Source<PersonListener, Person> {
private String name;
public String getName() { return name; }
public void setName(String _name) {
name = _name;
fireEvent(new Event<Person>(this, EventType.UPDATE));
}
public Person(String _name) {
setName(_name);
}
}
// --- Entry point
public class Boot {
public static void main(String[] args) {
Person person = new Person("Unnamed");
PersonListener listener = new PersonListener();
person.addListener(listener);
person.setName("Dave");
}
}
</code></pre>
<p><strong>Edit</strong></p>
<p>I'd like to point out that one of my main aims here is to have a decoupled Observer/Observable pattern for use with a MVC-pattern.</p>
<p>I intend to subclass these 'generic' classes (or perhaps use them within other classes instead, composition style). At some point I will have a series of 'Views' that will observe 'Models', but the Models will not 'care' or 'know about' about the Views. Wikipedia shows a circular MVC diagram which I am aiming to follow:</p>
<p><a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller</a></p>
<p>As the Source class right now needs a ListenerType (i.e a View) generic to be passed to it on instantiation; I am not sure if I have achieved de-coupling yet. Having said that, it is a <em>generic</em> value so perhaps this is already as abstract as it can be.</p>
<p>I am also having to pass a SourceType generic to the Listener to it can send that to any Events it fires. At the moment its the best I can do but I have a suspicion it could be done a better, more abstract way.</p>
<p><strong>Edit #2</strong></p>
<p>Thanks Amir for your kind help; here is the code in its current state:</p>
<pre><code>public enum EventType {
CREATE,
UPDATE,
DELETE
}
public class Event<SourceType> {
private SourceType source;
private EventType type;
public SourceType getSource() { return source; }
public EventType getType() { return type; }
public Event(SourceType _source, EventType _type) {
source = _source;
type = _type;
}
}
public interface IListener {
public void onEvent(Event<? extends ISource> _event);
}
public interface ISource {
public void addListener(IListener _listener);
public void fireEvent(EventType _eventType);
}
public class Person implements ISource {
private Set<IListener> listeners = new CopyOnWriteArraySet<IListener>();
private String name;
public String getName() { return name; }
public void setName(String _name) {
name = _name;
fireEvent(EventType.UPDATE);
}
public void addListener(IListener _listener) {
listeners.add(_listener);
}
public void fireEvent(EventType _eventType) {
// This line ok now (I just saw your edits)
Event<? extends ISource> _event = new Event<Person>(this, _eventType);
for(IListener listener : listeners) {
listener.onEvent(_event);
}
}
}
// Problem here still - the type PersonListener must implement the inherited abstract method IListener.onEvent(Event<ISource>); I guess thats because of the following method...
public class PersonListener implements IListener {
// Name clash: The method onEvent(Event<Person>) of type PersonListener has the
// same erasure as onEvent(Event<? extends ISource>) of type IListener but does
// not override it
public void onEvent(Event<Person> _event) {
// Do stuff here
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I have several remarks:</p>\n\n<ul>\n<li>Why do you need <code>public class Source<ListenerType extends IListener<SourceType>, SourceType></code>? Why does <code>Source</code> need to implement <code>IListener</code>? This seems unecessary complex.</li>\n</ul>\n\n<p>I would do it in a slightly different way:</p>\n\n<pre><code> public interface IListener {\n\n public void onEvent(Event<? extends ISource> _event);\n }\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public interface ISource {\n public void addListener(IListener listener);\n public void fireEvent(EventType evenType)\n}\n</code></pre>\n\n<p>I would implement Person and PersonListener as follows:</p>\n\n<pre><code>public class Person implement ISource {\n\nprivate Collection<IListener> listeners;\n\nprivate String name;\n\npublic String getName() { return name; }\n\npublic void setName(String _name) {\n\n name = _name;\n fireEvent(new Event<Person>(this, EventType.UPDATE));\n}\n\npublic void addListener(IListener listener) {\n listeners.add(listener);\n}\n\npublic void fireEvent(EventType evenType) {\n Event<? extends ISource> _event = new Event<Person>(this, evenType);\n\n for(IListener listener : listeners) {\n\n listener.onEvent(_event);\n }\n}\n\npublic Person(String _name) {\n\n setName(_name);\n}\n</code></pre>\n\n<p>}</p>\n\n<p>and: </p>\n\n<pre><code>public class PersonListener implements IListener {\n\npublic void onEvent(Event<? extends ISource> _event) {\n\n System.out.println(\"EVENT: \" + _event.getSource().getName());\n // Would probably have a switch/case statement here to check the Event type (what happened?)\n}\n</code></pre>\n\n<p>}</p>\n\n<p>By not using Generics on Listener, you can decouple between the Observers and Observables.\nFor example, in your code, you can have PersonListener listen to other Sources as well. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:16:36.460",
"Id": "40362",
"Score": "0",
"body": "Thanks for your input Amir. The Source does not implement IListener (i think?). It is given ListenerType as a generic, and that ListenerType extends IListener so that the Source can call the 'onEvent' method of the listener. Thats how I understand it at least. Your code looks much cleaner and I shall try it out now. I noticed the 'addListener' method is missing in your implementation of Person - would you suggest I keep copy/pasting that function into the different 'Source' classes I need (i.e Person, Driver, Dog, Cat)? Surely I'd be better off using inheritance to avoid dupe code?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:17:01.837",
"Id": "40363",
"Score": "0",
"body": "I am thinking of a class called 'Source' again that implements ISource, that Person can subclass from (as can Driver, Dog, Cat etc). However that is probably going to introduce too much complexity again I guess?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:37:50.597",
"Id": "40364",
"Score": "0",
"body": "I missed out on the Source - it does not implement IListener. Nevertheless, it is quite cumbersome. I should've added addListener to Person class. You can create an AbstractSource that implements these methods and other classes can inherit from it, but on the other hand, your classes can inherit from any other class, and just implement these 2 methods. That's up to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:40:57.030",
"Id": "40365",
"Score": "0",
"body": "Ok I am in the midst of implementing your code and I see a problem - the IListener Interface appears to *need* a SourceType generic, else how does the argument in the onEvent method know what a SourceType is? You didnt specify it, but I dont see how that would work. Secondly I can see addListener in ISource is accepting an Interface as an argument? Now im more confused!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:41:55.503",
"Id": "40366",
"Score": "0",
"body": "For your 2nd comment - you can have Person, Drivcer etc. inherit from Source, it's not a bad idea. But if you need to inherit from another class, you have the option of implementing ISource."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:45:20.907",
"Id": "40367",
"Score": "0",
"body": "Thanks for your comments regarding the inheritance aspect using an Abstract class. That's what ill do - I think its a great idea."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:50:44.290",
"Id": "40368",
"Score": "0",
"body": "My bad - I just learned you can indeed pass Interfaces as arguments you did in addListener - I truly thought that wouldnt work - I guess it does work because its not inside an implementation! Awesome. Still have the issue regarding the SourceType generic in the onEvent method of IListener. Thanks very much for your patience with my Java noobness :D"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:54:07.610",
"Id": "40369",
"Score": "0",
"body": "I would change public void onEvent(Event<SourceType> _event) in ILister to public void onEvent(Event<ISource> _event). This way the Listener is free to listen to events from all ISources, and is not bound to a single ISource, and will probably help with the compilation problem you mentioned before."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:55:31.623",
"Id": "40370",
"Score": "0",
"body": "Genius :D Let me try that out now!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T12:23:55.883",
"Id": "40371",
"Score": "0",
"body": "I changed the onEvent in IListener to take ISource. However I've got a couple of errors - 1. in fireEvent of Person, I have the line: Event<ISource> _event = new Event<Person>(this, _eventType); Im getting a type mismatch (cannot convert Event<ISource> to Event<Person>. If I change it to Event<Person> = new...; I get an error on the looped listener.onEvent(_event) line - the method onEvent(Event<Isource>) is not applicable for the args Event<Person>. 2 - In PersonListener I have public void onEvent(Event<Person> _event) - it tells me name-clash, same erasure as IListener, not overridding it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T12:24:59.777",
"Id": "40372",
"Score": "0",
"body": "Would it be easier for both of us (and others) if I edit the question and add the new code as I now have it? All these comments are messy and hard to read :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T12:29:36.107",
"Id": "40373",
"Score": "0",
"body": "Instead of public void onEvent(Event<SourceType> _event) you should use: public void onEvent(Event<? extends SourceType> _event)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T12:42:57.547",
"Id": "40374",
"Score": "0",
"body": "Plz see my edits to my answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T12:53:14.880",
"Id": "40375",
"Score": "0",
"body": "Thanks Amir, I was also updating my code at the same time as you :). Ive amended it here and in Eclipse and am left with just the error in PersonListener (name clash)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T13:31:38.820",
"Id": "40376",
"Score": "0",
"body": "I am sorry, but I cannot fix this 'type erasure' problem I am having within PersonListener. \"Name clash: The method onEvent(Event<Person>) of type PersonListener has the same erasure as onEvent(Event<? extends ISource>) of type IListener but does not override it\". I _sort of_ understand that Java sees this as a kind of duplicate method once the types have been erased but I have no idea how to solve it!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T13:41:37.847",
"Id": "40377",
"Score": "0",
"body": "I can see your edit to the onEvent in PersonListener and this does seem like it would work. However, in doing that I am unable to determine the actual type 'Person' in that method. I.e I am unable to call _event.getSource().getName() (getName belongs to Person but not ISource). I have a horrible feeling casts are going to be needed, which is kinda what I hoped to avoid all along, else I'd just implement Java's own Observable/Observer classes :D"
}
],
"meta_data": {
"CommentCount": "16",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-12T11:02:30.727",
"Id": "26094",
"ParentId": "26093",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-11T22:44:00.870",
"Id": "26093",
"Score": "1",
"Tags": [
"java",
"mvc",
"generics"
],
"Title": "Java; Generic Observer/Observable - is this as messy as I think?"
}
|
26093
|
<p>I couldn't find a good example, so after some fighting with writing non-serializable object to file in Android, I decided to show you my solution. Could you tell me if it is OK or how could it be improved?</p>
<p>This class is used to store information in a file. <code>writeObject</code> and <code>readObject</code> methods were created, because <code>android.graphics.Point</code> is not serializable. This is the reason why <code>strokes</code> was declared as transient. To make sure that we are able to overwrite file, we need to create our own <code>ObjectOutputStream</code>, which overrides <code>writeStreamHeader</code>, so the second header will not be appended to our file. We check if the file size is greater that zero, and according to this we create our <code>OutputStream</code>.</p>
<p>In general, what I understand is that to write a non-serializable object to file we need to make it transient and define our <code>readObject</code>and <code>writeObject</code> methods. To overwrite a file we need to make our own <code>ObjectOutputStream</code>.</p>
<pre><code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
import android.graphics.Point;
import android.os.Environment;
public class LogInfo implements Serializable{
private static final long serialVersionUID = 710487907869630527L;
transient public ArrayList<Point[][]> strokes;
public LogInfo()
{
strokes = new ArrayList<Point[][]>();
}
private void writeObject(ObjectOutputStream stream) throws IOException
{
stream.defaultWriteObject();
stream.writeInt(strokes.size());
Point[][] pointsArray = null;
for (int i = 0; i < strokes.size(); i++)
{
pointsArray = ((Point[][])strokes.get(i));
stream.writeInt(pointsArray.length);
for (int j = 0; j < pointsArray.length; j++)
{
stream.writeInt(pointsArray[j].length);
for (int k = 0; k < pointsArray[j].length; k++)
{
stream.writeInt(pointsArray[j][k].x);
stream.writeInt(pointsArray[j][k].y);
}
}
}
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException, ClassCastException
{
stream.defaultReadObject();
strokes = new ArrayList<Point[][]>();
int strokesSize = stream.readInt();
for (int i = 0; i < strokesSize; i++)
{
int arrayXSize = stream.readInt();
Point[][] points = new Point[arrayXSize][];
for (int j = 0; j < arrayXSize; j++)
{
int arrayYSize = stream.readInt();
points[j] = new Point[arrayYSize];
for (int k = 0; k < arrayYSize; k++)
points[j][k] = new Point(stream.readInt(), stream.readInt());
}
strokes.add(points);
}
}
public void writeLog()
{
File file = new File (Environment.getExternalStorageDirectory().getAbsolutePath(), "data.log");
FileOutputStream fos;
try {
fos = new FileOutputStream(file, true);
ObjectOutputStream writer;
if(file.length() > 0)
{
writer = new MyObjectOutputStream(fos);
}
else
{
writer = new ObjectOutputStream(fos);
}
writer.writeObject(this);
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public ArrayList<LogInfo> readLog()
{
ArrayList<LogInfo> logInfoArray = new ArrayList<LogInfo>();
try{
File file = new File (Environment.getExternalStorageDirectory().getAbsolutePath(), "data.log");
FileInputStream fis = new FileInputStream(file);
ObjectInputStream reader = new ObjectInputStream(fis);
while (file.canRead())
{
logInfoArray.add((LogInfo) reader.readObject());
}
reader.close();
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
return logInfoArray;
}
}
class MyObjectOutputStream extends ObjectOutputStream {
public MyObjectOutputStream(OutputStream os) throws IOException {
super(os);
}
@Override
protected void writeStreamHeader() {}
}
</code></pre>
|
[] |
[
{
"body": "<p>Just a small detail: you don't need to make <code>strokes</code> transient. When you override <code>readObject</code>/<code>writeObject</code>, you completely override the usual serialization mechanism.</p>\n\n<p>Transient just means that the usual serialization mechanism should skip that member when marshalling/unmarshalling the whole object.</p>\n\n<p>Otherwise, it looks pretty good. I haven't checked explicitly that <code>readObject</code>/<code>writeObject</code> process everything in the same order, but hopefully you made some unit test that checks for that.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T03:42:19.683",
"Id": "40601",
"Score": "0",
"body": "If strokes are not transient, it tries to serialize them by default and it does not work. It only works when they are transient..."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T20:40:24.150",
"Id": "26179",
"ParentId": "26095",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T08:12:52.497",
"Id": "26095",
"Score": "1",
"Tags": [
"java",
"android",
"makefile",
"stream",
"serialization"
],
"Title": "Write and read non-serializable object to file android example"
}
|
26095
|
<p>I have the following code that allows easy creation, pulling, and deletion of Tickets in a CakePHP application.</p>
<pre><code>App::uses('Component', 'Controller');
App::uses('Ticket', 'Model');
App::import(array('Security'));
class TicketComponent extends Component
{
public $name = 'Ticket';
// Create a new ticket by providing the data to be stored in the ticket.
function set($info = null)
{
$this->garbage();
if ($info)
{
$ticketObj = new Ticket();
$data['Ticket']['hash'] = md5(time());
$data['Ticket']['data'] = $info;
if ($ticketObj->save($data))
{
return $data['Ticket']['hash'];
}
}
return false;
}
// Return the value stored or false if the ticket can not be found.
function get($ticket = null)
{
$this->garbage();
if ($ticket)
{
$ticketObj = new Ticket();
$data = $ticketObj->findByHash($ticket);
if (is_array($data) && is_array($data['Ticket']))
{
// optionally auto-delete the ticket -> this->del($ticket);
return $data['Ticket']['data'];
}
}
return false;
}
// Delete a used ticket
function del($ticket = null)
{
$this->garbage();
if ($ticket)
{
$ticketObj = new Ticket();
$data = $ticketObj->findByHash($ticket);
if ( is_array($data) && is_array($data['Ticket']) )
{
return $data = $ticketObj->delete($data['Ticket']['id']);
}
}
return false;
}
// Remove old tickets
function garbage()
{
$deadline = date('Y-m-d H:i:s', time() - (24 * 60 * 60)); // keep tickets for 24h.
$ticketObj = new Ticket();
$data = $ticketObj->query('DELETE from tickets WHERE created < \''.$deadline.'\'');
}
}
</code></pre>
<p>It feels a little old now (not sure how old the code is) but wondered if certain things could be improved and if there was any parts that were considered 'bad code'.</p>
<p>Some observations of my own:</p>
<ul>
<li>Do I need to keep creating the <code>$ticketObj</code>? And is using <code>new Ticket()</code> correct for CakePHP conventions?</li>
<li>The garbage function runs when anything ticket related is called, and makes sure that expired tickets cannot be used... But requires that it be called at the beginning of all other functions. Could this be better? Not necessarily a CRON job, but more code efficient.</li>
</ul>
|
[] |
[
{
"body": "<p>In order to call each time the garbage function just create a </p>\n\n<pre><code>public function beforeFilter() {\n parent::beforeFilter();\n $this->garbage();\n</code></pre>\n\n<p>About the new Ticket()\ni think it would be okay to change the</p>\n\n<pre><code>$ticketObj->..\n</code></pre>\n\n<p>to </p>\n\n<pre><code>$this->Ticket->..\n</code></pre>\n\n<p>Also i think setting your function name's as <strong>set</strong> is a bad idea because they are built in functions in cakephp</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-06T12:12:18.563",
"Id": "38687",
"ParentId": "26096",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T09:09:47.830",
"Id": "26096",
"Score": "2",
"Tags": [
"php",
"cakephp"
],
"Title": "CakePHP Ticket Component"
}
|
26096
|
<p>I have written the following Javascript class</p>
<pre><code>function InScroll( container, options ) {
"use strict";
var isRunning = false;
// utilities
var noop = function() {};
var inter = null;
if(!container) {
alert('container element not provided');
return;
}
if(!options.interval) options.interval = 500;
// save screen info
var page = {
contentHeight: $(container).getHeight(),
pageHeight: document.viewport.getHeight(),
scrollPosition : 0,
}
function scroll() {
var pos = $(container).select("div.kurz").length;
if(pos == 0) {
this.kill();
return;
}
// get scroll position y-axis.
page.scrollPosition = document.viewport.getScrollOffsets()[1];
if( !isRunning && (page.contentHeight - page.pageHeight - page.scrollPosition ) < 450) {
new Ajax.Request(options.url + "?pos=" + pos, {
onCreate: onCreate,
onSuccess: append,
onFailure: error,
onComplete: onComplete
});
}
}
function onCreate() {
isRunning = true;
}
function onComplete() {
isRunning = false;
page.contentHeight= $(container).getHeight();
}
function append( response ) {
var resp = response.responseText.strip();
if(resp == "") kill();
container.innerHTML += resp;
}
function error( response ) {
var resp = response.responseText.strip();
container.innerHTML += resp;
}
function start() {
if(!container) {
alert('container element not provided');
return;
}
if(!options || !options.url) {
alert('content loader script should be set as options.url');
return;
}
(function(that) {
inter = window.setInterval( function() { that.scroll()}, 50);
})(this)
}
function kill() {
clearInterval(inter);
$(options.loader).hide();
}
return {
start: start,
kill : kill,
scroll: scroll
}
}
</code></pre>
<p>Here I wanted to expose only the <code>start</code> and <code>kill</code> functions but due to the use of <code>windows.setInterval</code> i had to expose also the scroll function.</p>
<p>Can someone please have a look at the code, and give some suggestion how may I optiomize it?</p>
|
[] |
[
{
"body": "<p>It seems to me that you don't need the self invoking function and the anonymous function:</p>\n\n<pre><code>inter = window.setInterval( scroll, 50);\n</code></pre>\n\n<p>should do</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T11:34:20.097",
"Id": "26099",
"ParentId": "26097",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26099",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T10:04:58.893",
"Id": "26097",
"Score": "1",
"Tags": [
"javascript",
"ajax"
],
"Title": "Continuously scrolling content loader"
}
|
26097
|
<p>When I need to get maximum value of A, B, and C, then I would write like:</p>
<pre><code>val = A;
val = max(val, B);
val = max(val, C);
</code></pre>
<p>But, in this case, I need to write two "val" in the one line. And, it is cumbersome if the "val" is more complex like "val[0][1][2].element"... If it is adding value, I can write like "val += B" without writing "val" twice in the line.</p>
<p>I can make macro like:</p>
<pre><code>#define MAXEQ(A,B) (A) = max((A), (B))
</code></pre>
<p>But, it looks not very intuitive.</p>
<p>Is there any smarter way to write these things ?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:55:14.873",
"Id": "40392",
"Score": "1",
"body": "Would you like a version that allows `for( x : list ) val <= highest(x);`? But this is a better question for StackOverflow not CodeReview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T11:35:18.797",
"Id": "40542",
"Score": "1",
"body": "What about just doing `val = max(A, max(B, C))`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T17:54:51.513",
"Id": "40575",
"Score": "0",
"body": "@LokiAstari : effectiveness of chosen algorithm, is a form of code review. Though this might be a personal opinion =("
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-05T17:46:57.183",
"Id": "64459",
"Score": "0",
"body": "Seems largely on topic to me, though I'd have been happier with a complete code snippet...which he *almost* provided. He has working code and wants to make it cleaner; this seems a perfect CR question. I'd rather see this question on CR than on SO."
}
] |
[
{
"body": "<p>If you have access to C++11, I'd suggest using <code>std::max</code> with an <code>initializer_list<T></code>. A complete minimal example:</p>\n\n<pre><code>#include <algorithm>\n#include <initializer_list>\n#include <iostream>\n\nint main()\n{\n int a = 1;\n int b = 2;\n int c = 3;\n\n int m = std::max({a, b, c});\n\n std::cout << m << \"\\n\";\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:52:46.863",
"Id": "40391",
"Score": "0",
"body": "How would you make this work if the data is generated in a loop, or the number of data changes at runtime?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T01:01:22.480",
"Id": "40430",
"Score": "3",
"body": "@BenVoigt If the data changes at runtime, store it in a container and use `max_element`. That, to me, didn't seem the intent of the question; rather, \"I have a number of (already defined) variables - how do I find the max of them concisely\"."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T22:11:02.017",
"Id": "453982",
"Score": "0",
"body": "@Yuushi I don't follow - why does it matter if the data changes at runtime?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T12:51:13.280",
"Id": "26101",
"ParentId": "26100",
"Score": "27"
}
},
{
"body": "<p>Assuming you have an unknown set of data, you can always place it in an array / vector / list and run...</p>\n\n<pre><code>int res = *max_element( intList.begin(), intList.end() ); //where intList is the list\n</code></pre>\n\n<p>Which is as commented by @Yuushi : but expended on, since it can get quirky</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <list>\n#include <stdlib.h> \n#include <algorithm> // std::max\n\nusing namespace std;\n\nint main() {\n list<int> intList;\n int a, b;\n int maxItems = rand() % 40 + 10; //10 to 50 items\n\n cout << \"=== Testing a maximum of \" << maxItems << \" values ===\\n\"; \n cout << \"generating random value set: {\";\n\n for( a = 0; a < maxItems; ++a ) {\n b = rand() % 100;\n cout << b << \", \";\n intList.push_back(b);\n }\n cout << \"}\\n\";\n\n //Note max element inputs iterators, and outputs the max value iterator! \n //-> which is the pointer to the actual value (hence * to get value)\n a = *max_element( intList.begin(), intList.end() );\n cout << \"max value generated = \" << a << \"\\n\";\n\n return 0;\n}\n</code></pre>\n\n<p>Which can give a sample result as below</p>\n\n<pre><code>=== Testing a maximum of 33 values ===\ngenerating random value set: {86, 77, 15, 93, 35, 86, 92, 49, 21, 62, 27, 90, 59, 63, 26, 40, 26, 72, 36, 11, 68, 67, 29, 82, 30, 62, 23, 67, 35, 29, 2, 22, 58, }\nmax value generated = 93\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T22:24:11.890",
"Id": "453984",
"Score": "0",
"body": "Why do you need to do this? Why does it matter if the data is \"unknown\"? How will it fail, and why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-15T22:46:57.550",
"Id": "453986",
"Score": "1",
"body": "`std::vector<int>` will in almost every case be more efficient than `std::list<int>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-26T23:10:17.347",
"Id": "503626",
"Score": "0",
"body": "@TylerShellberg He is not saying it will fail if the data is known. However, it is somewhat bizarre to write code to find the maximum of data known before compilation. You could just pick the maximum and avoid the unnecessary code/confusion."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T17:51:21.953",
"Id": "26211",
"ParentId": "26100",
"Score": "0"
}
},
{
"body": "<p>A simpler way would be to use this overloaded function <code>std::max</code> that accepts an object of the type <code>std::initializer_list<int></code></p>\n<pre><code>#include<iostream>\n#include<algorithm>\nusing namespace std;\nint main()\n{\n int a = 2;\n int b = 3;\n int c = 4;\n cout << max({a,b,c}) << '\\n';\n\n cout << max({7,7,8}) << '\\n';\n\nreturn 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-09T15:55:21.607",
"Id": "501925",
"Score": "0",
"body": "What does this add that's missing from [Yuushi's answer](/a/26101/75307)? Apart from polluting the global namespace with the whole of `std`, I mean. Please just vote for the existing answer instead of duplicating it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-01-08T17:42:42.570",
"Id": "254455",
"ParentId": "26100",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T11:48:46.110",
"Id": "26100",
"Score": "15",
"Tags": [
"c++"
],
"Title": "Maximum of three values in C++"
}
|
26100
|
<p>Test version of my code for handling individual mouseenter / mouseleave events for objects created dynamically. The code emulates a seating cart for a bus, as you mouse over the objects it will display the students name and remove it when your mouse leaves the object. Current test only accounts for four students. If you decide to compile and run the code set the spinedit controls to one row and two seats per row. I hardcoded four "student records" so the actions only work for four of the seats. Thanks again for any help you can provide.</p>
<pre><code>unit SeatingChart;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, Spin;
Type
TPanelSeat = Array of TPanel;
TPanelRow = Array of TPanelSeat;
Type
TStudent = Class(Tobject)
Name: String;
End;
Type
TTemplate = Class(Tobject)
const
BufferVal = 20;
Pan_Height = 40;
Pan_Width = 125;
Var
Prev_Top : Integer;
Pass_Left : Integer; //Previous Left Value of Passenger side seat
Driv_Left : Integer; //Previous Left Value of Driver side seat
PanelRow : TPanelRow;
Private
StudentInfo: Array[0..3] of TStudent;
Procedure Initialize;
End;
type
TForm1 = class(TForm)
lblRow: TLabel;
lblSPR: TLabel;
seSPR: TSpinEdit;
seRow: TSpinEdit;
btnClearLayout: TButton;
ScrollBox1: TScrollBox;
Label1: TLabel;
Label2: TLabel;
procedure btnClearLayoutClick(Sender: TObject);
procedure seRowChange(Sender: TObject);
procedure seSPRChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
BusTemplate : TTemplate;
procedure CreateSeats;
procedure DestroySeats;
procedure UpdateSeats;
procedure ResetSpinValues;
Procedure CreatePanelDisplay(PR: TPanelRow);
Function LabelSeats(R,S: Integer): String;
Function BuildSeatArray(RowNum,SPR: Integer): TPanelRow; //Returns Row
public
{ Public declarations }
Procedure FindStudent(Sender: Tobject);
Class Procedure OnMouseEnter(Sender: Tobject);
Class Procedure OnMouseLeave(Sender: Tobject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.btnClearLayoutClick(Sender: TObject);
begin
DestroySeats;
ResetSpinValues;
end;
function TForm1.BuildSeatArray(RowNum, SPR: Integer): TPanelRow;
var
I,J: Integer;
begin
SetLength(BusTemplate.PanelRow, RowNum);
SetLength(Result, Length(BusTemplate.PanelRow));
for I := 0 to High(BusTemplate.PanelRow) do
begin
SetLength(BusTemplate.PanelRow[I], SPR * 2);
for J := 0 to High(BusTemplate.PanelRow[I]) do
begin
BusTemplate.PanelRow[I][J] := TPanel.Create(Self);
end;
Result[I] := BusTemplate.PanelRow[I] ;
end;
end;
procedure TForm1.CreatePanelDisplay(PR: TPanelRow);
Var
I,J : Integer;
SeatNumber : Integer;
begin
SeatNumber := 0;
BusTemplate.Initialize;
//Create Left/Right Lane Seats
for I := 0 to High(PR) do /// Row Loop
begin
if I > 0 then
BusTemplate.Prev_Top := BusTemplate.Pan_Height + BusTemplate.Prev_Top + BusTemplate.BufferVal;
for J := 0 to High(PR[I]) do /// Seats Per Row Loop
begin
PR[I][J].Height := BusTemplate.Pan_Height;
PR[I][J].Width := Round(BusTemplate.Pan_Width div (Length(PR[I]) Div 2));
PR[I][J].Visible := True;
PR[I][J].Top := BusTemplate.Prev_Top;
PR[I][J].Parent := ScrollBox1;
PR[I][J].OnMouseEnter := OnMouseEnter;
PR[I][J].OnMouseLeave := OnMouseLeave;
Inc(SeatNumber);
if Not (J >= (Length(PR[I]) Div 2)) then
begin
PR[I][J].left := BusTemplate.Pass_Left + BusTemplate.BufferVal;
PR[I][J].caption := LabelSeats(Length(PR) - I,SeatNumber);
BusTemplate.Pass_Left := BusTemplate.Pass_Left + PR[I][J].Width;
end
else
begin
PR[I][J].left := (ScrollBox1.Width - ((BusTemplate.Pan_Width + BusTemplate.BufferVal) - BusTemplate.Driv_Left));
PR[I][J].caption := LabelSeats(Length(PR) - I,SeatNumber);
BusTemplate.Driv_Left := BusTemplate.Driv_Left + PR[I][J].Width;
end;
end;/// End Seats Per Row Loop
BusTemplate.Pass_Left := 0;
BusTemplate.Driv_Left := 0 ;
SeatNumber := 0;
end;/// End Row Loop
end;
procedure TForm1.CreateSeats;
Var
X,Y: Integer;
begin
Y := seSPR.Value;
X := seRow.Value;
if (X <> 0) and (Y <> 0) then
CreatePanelDisplay(BuildSeatArray(X,Y));
end;
procedure TForm1.DestroySeats;
var
I,J:Integer;
begin
//Frees the seat controls
for I := 0 to Length(BusTemplate.PanelRow) - 1 do
begin
For J := 0 to Length(BusTemplate.PanelRow[I]) - 1 do
begin
BusTemplate.PanelRow[I][J].Free;
end;
SetLength(BusTemplate.PanelRow[I],0);
end;
SetLength(BusTemplate.PanelRow,0);
end;
procedure TForm1.FindStudent(Sender: TObject);
Var
I,J: Integer;
begin
for I := 0 to high(BusTemplate.PanelRow) do
begin
for J:= 0 to high(BusTemplate.PanelRow[I]) do
begin
if Sender = Bustemplate.PanelRow[I][J] then
label2.Caption := BusTemplate.StudentInfo[J].Name;
end;
end;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
I: Integer;
begin
for I := 0 to high(BusTemplate.StudentInfo) do
begin
BusTemplate.StudentInfo[I].Free;
end;
BusTemplate.Free;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
BusTemplate := TTemplate.Create;
end;
Function TForm1.LabelSeats(R, S: Integer): String;
begin
Result := 'R' + inttostr(R) + 'S' + inttostr(S);
end;
class procedure TForm1.OnMouseEnter(Sender: Tobject);
begin
Form1.FindStudent(Sender);
end;
class procedure TForm1.OnMouseLeave(Sender: Tobject);
begin
Form1.Label2.Caption := '';
end;
procedure TForm1.ResetSpinValues;
begin
seRow.Value := 0;
seSPR.Value := 0;
end;
procedure TForm1.seRowChange(Sender: TObject);
begin
UpdateSeats;
end;
procedure TForm1.seSPRChange(Sender: TObject);
begin
UpdateSeats;
end;
procedure TForm1.UpdateSeats;
begin
DestroySeats;
CreateSeats;
end;
{ TTemplate }
Procedure TTemplate.Initialize;
var
I:Integer;
begin
for I := 0 to High(StudentInfo)do
begin
StudentInfo[I] := TStudent.Create;
end;
StudentInfo[0].Name := 'Pablo Cruise';
StudentInfo[1].Name := 'Miguel Sanchez';
StudentInfo[2].Name := 'The Eradicator';
StudentInfo[3].Name := 'Fatty McGee';
Prev_Top := BufferVal;
Pass_Left := 0;
Driv_Left := 0;
end;
end.
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T13:16:55.327",
"Id": "26102",
"Score": "1",
"Tags": [
"delphi"
],
"Title": "Suggestions for Improvement, handling MouseEnter / MouseLeave Events for dynamically created objects."
}
|
26102
|
<p>I have the following mockup that I need some feedback on how I might improve the <code>url_decode</code> function to make it faster and use less memory. There are a couple of requirements. I have to use the <code>StringArg</code> and <code>StringReturn</code> structs. I also need to completely decode the string. I am aware of double encoded attacks, but this is for data mining and I need to get the string fully decoded, hence the while loop. </p>
<p>Please have a look at function <code>StringReturn* url_decode(char* line)</code> and suggest anything that I can do to improve the speed or reduce the memory used.</p>
<pre><code>#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <ctype.h>
struct StringArg
{
int length;
char* data;
StringArg(const char* inData)
{
length = strlen(inData);
data = new char[length+1];
strcpy(data, inData);
}
};
struct StringReturn
{
int size;
char* data;
StringReturn(int inSize)
{
size = inSize;
data = new char[size+1];
}
};
StringArg* stringArg(char* line)
{
return new StringArg(line);
}
StringReturn* stringReturnInfo(int size)
{
return new StringReturn(size);
}
StringReturn* url_decode(char* line)
{
StringArg *str;
str = stringArg(line);
int lengths = str->length;
char* urlData = new char[lengths+1];
char* fmt = new char[4];
memcpy(urlData, str->data, str->length);
urlData[lengths] = 0;
bool bFoundChar = false;
int j = 0;
do
{
j = 0;
bFoundChar = false;
for (int i = 0; i < lengths; i++)
{
char ch = urlData[i];
if (ch == '+')
{
urlData[j++] = ' ';
}
else if (ch == '%' && i+2 < lengths && isxdigit(urlData[i+1]) && isxdigit(urlData[i+2]))
{
bFoundChar = true;
fmt = new char[4];
fmt[0] = urlData[++i];
fmt[1] = urlData[++i];
fmt[2] = 0;
urlData[j++] = (char)strtol(fmt, NULL, 16);
}
else {
urlData[j++] = ch;
}
}
lengths = j;
}while (bFoundChar);
StringReturn *ret = stringReturnInfo(j);
ret->size = j;
memcpy(ret->data, urlData, j);
delete urlData;
delete fmt;
return ret;
}
void test_decode(char* line)
{
StringReturn *str = url_decode(line);
printf(str->data);
}
int main(int argc, const char * argv[])
{
test_decode("bob.com?url=http%3A%2F%2Fsteve.com%3Furl%3Dhttp%253A%252F%252Fjohn.com");
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>This is doomed to failure:</p>\n<pre><code>struct StringArg\n{\n int length;\n char* data;\n StringArg(const char* inData)\n {\n length = strlen(inData);\n data = new char[length+1];\n strcpy(data, inData);\n }\n};\n</code></pre>\n<p>This can only lead to disaster. It is unlikely it is more efficient than std::string and is much more likely to lead to memory leaks.</p>\n<p>Use std::string it will work is correct and has been optimized very heavily you can not beat it using your own hand written one. This is a premature optimization.</p>\n<p>Same Again:</p>\n<pre><code>struct StringReturn\n{\n int size;\n char* data;\n StringReturn(int inSize)\n {\n size = inSize;\n data = new char[size+1];\n }\n};\n</code></pre>\n<p>Don't pass pointers around:</p>\n<pre><code>StringArg* stringArg(char* line)\n{\n return new StringArg(line);\n}\n</code></pre>\n<p>Use std::unique_ptr to encapsulate the pointer object so that it does correct memory management. If you are doing things correctly the resulting code optimizes to a no-op and if you don't do things correctly it saves your ass. In fact I would just throw away your string classes and use std::string. The copy construction from a return is nearly always elided by NRVO and thus is much more efficient than you seem to think.</p>\n<p>Same Again</p>\n<pre><code>StringReturn* stringReturnInfo(int size)\n{\n return new StringReturn(size);\n}\n</code></pre>\n<p>Manually copying a C-string is very painful. Use std::string</p>\n<pre><code> int lengths = str->length;\n char* urlData = new char[lengths+1];\n char* fmt = new char[4];\n memcpy(urlData, str->data, str->length);\n urlData[lengths] = 0;\n\n // Or you can do:\n\n std::string urlData = line;\n</code></pre>\n<p>Also your code is not exception safe.<br />\nPlease use RIAA to make sure that there are no leaks (or use std::string that does this already).</p>\n<p>The definition of a URL can be found here: <a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc3986</a><br />\nPretending the '+' is a space is only valid in the path section of a URI and not valid in the query or fragment parts of the URI thus scanning the whole string for '+' is not correct.</p>\n<blockquote>\n<p>I also need to completely decode the string. I am aware of double encoded attacks</p>\n</blockquote>\n<p>The specification does not allow for double (or nested) encoding. If it decodes to another '%' then that is the value. You don't try and re-interpret that value.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T18:42:03.610",
"Id": "26120",
"ParentId": "26103",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26120",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:08:05.643",
"Id": "26103",
"Score": "3",
"Tags": [
"c++",
"strings",
"url"
],
"Title": "URL decode function optimization"
}
|
26103
|
<p>I am using this code for my responsive layout mobile sidebar hide/show. I am not an expert in jQuery and just wonder if I can optimize this code with the same functionality.</p>
<pre><code>$(function() {
var a = $("#sidepanelpull");
var l = $("#sidepanelclose");
side = $(".qa-sidepanel");
sideHeight = side.height();
$(l).hide();
$(a).on("click", function(b) {
b.preventDefault();
side.slideToggle("fast");
l.fadeToggle("fast");
$(this).text($(this).text() == 'Hide Sidebar' ? 'Show Sidebar' : 'Hide Sidebar');
$(this).toggleClass('sidebar-state');
});
$(l).on("click", function(b) {
b.preventDefault();
side.slideToggle("fast");
$(this).fadeOut("fast");
$(a).text($(a).text() == 'Hide Sidebar' ? 'Show Sidebar' : 'Hide Sidebar');
$(a).toggleClass('sidebar-state');
});
$(window).resize(function() {
var b = $(window).width();
if (b > 320 && side.is(":hidden")) {
side.removeAttr("style")
}
})
});
</code></pre>
<p>Little details about the code:</p>
<ol>
<li><code>.qa-sidepanel</code> is a main sidebar div</li>
<li><code>#sidepanelpull</code> is a handler when user click it will slide open the <code>.qa-sidepanel</code> and also <code>fadeToggle</code> <code>#sidepanelclose</code> handler ( which is located at the top )</li>
<li><code>#sidepanelclose</code> is a text link which will be visible at the top when sidebar is open so user on mobile can close from the top if it is too long.</li>
</ol>
|
[] |
[
{
"body": "<p>style-wise I did some changes, have a look</p>\n\n<pre><code>$(function() {\n\nvar $window = $(window),\n $a = $(\"#sidepanelpull\"),\n $l = $(\"#sidepanelclose\"),\n $side = $(\".qa-sidepanel\"),\n sideHeight = $side.height(); // Declared but never used??\n\n$a.on(\"click\", function() {\n $side.slideToggle(\"fast\");\n $l.fadeToggle(\"fast\");\n $a.text( $a.text() == 'Hide Sidebar' ? 'Show Sidebar' : 'Hide Sidebar' );\n $a.toggleClass('sidebar-state');\n return false;\n});\n\n$l.hide().on(\"click\", function() {\n $side.slideToggle(\"fast\");\n $l.fadeOut(\"fast\");\n $a.text( $a.text() == 'Hide Sidebar' ? 'Show Sidebar' : 'Hide Sidebar' );\n $a.toggleClass('sidebar-state');\n return false\n});\n\n$window.resize(function() {\n var b = $window.width();\n if (b > 320 && $side.is(\":hidden\")) {\n $side.removeAttr(\"style\")\n }\n});\n\n});\n</code></pre>\n\n<p>most notably, you are calling jQuery on object that are already jQuery objects (<code>$(l)</code> and so on). every call to <code>$()</code> will have its performance overhead. Inmy code the jQuery DOM querying engine is only triggered in the inital variables declaration statement (notice how I grouped <code>var</code> declarations with commas).\nEven calling <code>$(this)</code> has its overhead so it's best to use the cached variable.</p>\n\n<p>Also, it's good practice to start variables names that contain jQuery objects with the dollar sign <code>$</code>.</p>\n\n<p>And the <code>sideHeight</code> variable is declared but never used?</p>\n\n<p>Since every jQuery method returns the objects it's been called on, you can chain method calls, so I've chained <code>$l.hide().on()</code> since <code>hide()</code> returns <code>$l</code> itself.</p>\n\n<p>Also <code>removeAttr(\"style\")</code> should be left as a last resort just in case you don't have better methods to change the element's style.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T15:51:46.717",
"Id": "26109",
"ParentId": "26105",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26109",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:51:47.520",
"Id": "26105",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"mobile"
],
"Title": "Hide/show sidebar"
}
|
26105
|
<p>I have this small Haskell script that I wrote some time ago to parse a set of financial CSV files to produce other CSV files. I've recently had a problem with large input files (around 300Mb) that I solved with RTS options. </p>
<p>Still, I'd like to make it more lazy and efficient. For example, I noted that it loads the whole input file in memory before starting writing results despite the left fold that was intended to be lazy. What's wrong here?</p>
<p>Moreover, I'd like to know how to make it more readable (since a smart colleague used to other functional languages stated it's unreadable) and idiomatic to Haskell.</p>
<p><strong>Main.hs</strong></p>
<pre><code>{-# LANGUAGE CPP, TemplateHaskell #-}
module Main (
main
) where
import System.Exit (exitFailure)
import System.Environment(getArgs)
import System.IO (withFile, IOMode(..), hGetContents)
import Data.Maybe (catMaybes)
import Data.Time.LocalTime (TimeOfDay(..))
import Data.Time.Format (formatTime)
import System.Locale (defaultTimeLocale)
import TickWrite
import EarlyTrade
main = do
args <- getArgs
switchArgs args
putStrLn "Done"
switchArgs ("importTrades":"help":xs) = importTradesHelp
switchArgs ("importTrades":outDir:filenames) = mapM_ (importTrades outDir) filenames
switchArgs ["importTrades"] = importTradesHelp
switchArgs [] = print $ "You must specify a tool"
transformFile :: FilePath -> ([String] -> a) -> (a -> IO r) -> IO r
transformFile file operation continuation = withFile file ReadMode (\h -> hGetContents h >>= (continuation.operation.lines))
importTradesHelp = print "importTrades outDir fileNames"
importTrades :: FilePath -> FilePath -> IO ()
importTrades outDir csvFile = transformFile csvFile (foldTradingSample.getTickWriteTrades) (saveTradingSamples outDir)
where getTickWriteTrades = filter (isBetween (9, 0) (18, 0)).(catMaybes.(map fromCSVLine))
foldTradingSample = foldl toTradingSample []
saveTradingSamples :: String -> [TradingSample] -> IO ()
saveTradingSamples folder samples = mapM_ (saveTradingSample folder) samples
saveTradingSample :: String -> TradingSample -> IO ()
saveTradingSample folder sample = writeFile fileName contents
where fileName = folder ++ "\\" ++ (equity sample) ++ "_" ++ (formatTime defaultTimeLocale "%F" $ day sample) ++ ".CSV"
contents = tradingSampleToCSV sample
</code></pre>
<p><strong>EarlyTrade.hs</strong></p>
<pre><code>module EarlyTrade (
Trade,
TradingSample (..),
toTradingSample,
tradingSampleToCSV
) where
import qualified TickWrite as Tw
import Data.Time.Calendar (Day)
import Data.Time.LocalTime (timeOfDayToDayFraction)
import Data.List (intersperse)
type Simbol = String
data Trade = Trade { tPrice :: Double
, tTime :: Double
, tVolume :: Integer
} deriving (Show, Read, Eq)
data TradingSample = TradingSample { equity :: Simbol
, day :: Day
, trades :: [Trade]
} deriving (Show, Read, Eq)
tradingSampleToCSV :: TradingSample -> String
tradingSampleToCSV (TradingSample _ _ t) = unlines $ map tradeToCSVRow t
tradeToCSVRow :: Trade -> String
tradeToCSVRow (Trade p t v) = show t ++ "," ++ show p ++ "," ++ show v
fromTickWrite :: Tw.Trade -> Trade
fromTickWrite tt = Trade {tPrice = Tw.tPrice tt
,tTime = fromRational $ timeOfDayToDayFraction $ Tw.tTime tt
,tVolume = Tw.tVolume tt
}
toTradingSample :: [TradingSample] -> Tw.Trade -> [TradingSample]
toTradingSample (current:others) twTrade
| newEqt == equity current && newDay == day current = (current { trades = newTrades }):others
| otherwise = current : toTradingSample others twTrade
where newEqt = Tw.tSimbol twTrade
newDay = Tw.tDate twTrade
newTrade = fromTickWrite twTrade
newTrades = trades current ++ [newTrade]
toTradingSample [] twTrade = [TradingSample { equity = Tw.tSimbol twTrade
, day = Tw.tDate twTrade
, trades = [fromTickWrite twTrade]
}]
</code></pre>
<p><strong>TickWrite.hs</strong></p>
<pre><code>module TickWrite (
Trade(..),
fromCSVLine,
isBetween
) where
import Data.Time.Calendar (Day, fromGregorian)
import Data.Time.LocalTime (TimeOfDay(..))
import Data.Time.Format (parseTime)
import Data.List.Split (splitOn)
import System.Locale (defaultTimeLocale)
data Trade = Trade {tSimbol :: String
,tDate :: Day
,tTime :: TimeOfDay
,tPrice :: Double
,tVolume :: Integer
,tTradeNumber :: String
,tExcludeRecordFlag :: String
,tFilteredPrice :: String
,tCompanyID :: String
} deriving (Show, Read, Eq)
isBetween :: (Int, Int) -> (Int, Int) -> Trade -> Bool
isBetween (sH, sM) (eH, eM) trade = tradeTime >= start && tradeTime <= end
where tradeTime = tTime trade
start = TimeOfDay sH sM 0
end = TimeOfDay eH eM 0
fromCSVLine = fromCSVRecord . (splitOn ",")
parseValue :: Read a => String -> Maybe a
parseValue s =
case reads s of
[] -> Nothing
((i,_):_) -> Just i
fromCSVRecord (s:d:t:p:v:n:e:f:c:xs) = do
dateV <- parseTime defaultTimeLocale "%Y/%m/%d" d
timeV <- parseTime defaultTimeLocale "%T%Q" t
volumeV <- parseValue v
priceV <- parseValue p
return Trade {tSimbol = s
,tDate = dateV
,tTime = timeV
,tPrice = priceV
,tVolume = volumeV
,tTradeNumber = n
,tExcludeRecordFlag = e
,tFilteredPrice = f
,tCompanyID = c
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T05:22:58.580",
"Id": "40528",
"Score": "0",
"body": "I don't have time at the moment to give a full write up, but you can fix the memory issues by using `pipes` or `conduit`. Both libraries will allow you to avoid the large intermediate list and stream results to the output file immediately as they are generated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T07:39:21.820",
"Id": "40534",
"Score": "0",
"body": "@GabrielGonzalez a few month ago I did looked at those libraries, but I was unable to understand what was the most supported. In other languages I'm used to choose libraries that have good community support. In the Haskell ecosystem this is really hard to see. What's their state now? Is there a \"winner\" library for such approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:09:28.433",
"Id": "40559",
"Score": "0",
"body": "`conduit` currently has the best community support, but `pipes` support is growing rapidly. Right now your best choice is `conduit`. Besides, both libraries are very similar, so you can very easily switch from one to the other."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T21:51:46.680",
"Id": "40588",
"Score": "0",
"body": "@GiacomoTesio Have a stop at #haskell on freenode whenever you're uncertain about what's best supported; they're quite a good representation of 'the community' so what they prefer is what you will find the best community support for."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T15:13:03.763",
"Id": "26107",
"Score": "3",
"Tags": [
"haskell",
"functional-programming",
"memory-management",
"csv",
"finance"
],
"Title": "Parsing and producing sets of financial CSV files"
}
|
26107
|
<p>I want to make a container which manages <strong>big objects</strong>. which performs <strong>deep copies</strong> on copy construction and copy assignment. I also like the interface of the <strong>std containers</strong>, so I wanted to implement it using public inheritance:</p>
<pre><code>template <class TBigObject>
class Container : public std::vector< std::shared_ptr<TBigObject> >
{
public:
Container(int nToAllocate){ /* fill with default constructed TBigObjects */}
Container(const Container& other){ /* deep copy */ }
Container(Container&&) = default;
Container& operator = (const Container& population){ /* deep copy */ }
Container& operator = (Container&&) = default;
};
</code></pre>
<p>I heard of the <strong>"Thou shalt not inherit from std containers"</strong> maxim and the reasons behind it. So I decided to make an alternative:</p>
<pre><code>template <class T>
using Container = std::vector< std::shared_ptr<T> >;
template <class T>
Container<T> defaultAllocate(int nItems);
template <class T>
Container<T> deepCopy(const Container<T>& other);
</code></pre>
<p>This looks more expressive, but using the code feels strange and verbose:</p>
<pre><code>class Big;
Container<Big> someContainer = defaultAllocate(12);
Container<Big> copy = deepCopy(someContainer);
</code></pre>
<p>instead of:</p>
<pre><code>class Big;
Container<Big> someContainer(12);
Container<Big> copy = someContainer;
</code></pre>
<p>I am a beginner programmer and I don't want to make errors early on. I would like to ask your advice on which choice to make. Or even better, if there is a third option.</p>
|
[] |
[
{
"body": "<p>I think you are going about it the wrong way.</p>\n\n<p>Containers already perform copy on copy construction/assignment because they are designed for value objects not pointers. What you really want is a wrapper object for pointers that performs a deep copy when that object is copied.</p>\n\n<p>This has the added advantage of working with all containers.</p>\n\n<p>If you define the move operators then it also works well with re-size operations as the move semantics will be applied to the wrapper when the the container is re-sized.</p>\n\n<p>The other advantage here is you can make the wrapper behave like the underlying type. So you get easy access to all the algorithms.</p>\n\n<pre><code>template<typename T>\nclass Deep\n{\n T* value;\n public:\n Deep(): value(NULL) {}\n // Take ownership in this case.\n Deep(T const* value): value(value) {}\n Deep(T const& value): value(new T(value)) {}\n ~Deep() {delete value;}\n Deep(Deep&& move) {std::swap(value, move.value);}\n Deep(Deep const& copy) {T* tmp = new T(*(copy.value));swap(tmp,value);delete tmp;}\n // Note this does do a deep copy via copy and swap\n Deep& operator=(Deep copy) {std::swap(value, copy.value);return *this;}\n Deep& operator=(Deep&& move) {std::swap(value, move.value);return *this;}\n\n // Note: undefined behavior if used when value is NULL.\n // You may want to add logic here depending on use case.\n operator T&() {return *value;}\n operator T const&() const {return *value;}\n\n T* release() {T* tmp = value;value = NULL;return tmp;}\n};\nint main()\n{\n std::vector<Deep<int>> deep(5,7);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:51:20.923",
"Id": "40635",
"Score": "0",
"body": "Thank you! I am going to have to read this many times to fully understand. It looks like a really great concept. So this template is like an automatically dereferenced smart pointer? Is this a popularly known idiom?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:11:34.323",
"Id": "40643",
"Score": "1",
"body": "@MartinDrozdik: Its more like a copying smart pointer (in terms of resource management). There is not one in the standard as in general you don't want to deep copy pointer (that is why you are using pointers to avoid the copy)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:13:17.017",
"Id": "40644",
"Score": "1",
"body": "@MartinDrozdik: The auto de-referencing part is really useful technique unto itself. In this context it makes algorithms really easy to use (as you can use the underlying object with manually de-referencing it (this plays nicely with algorithms that expect values not pointers)). Note: This is why you need a constructor that works by value so the algorithms can put stuff back into the container, and it automatically gets wrapped."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:19:38.903",
"Id": "26241",
"ParentId": "26111",
"Score": "2"
}
},
{
"body": "<p>For starters, you talk about deepcopy then make collection of shared pointers. It's more than confusing. </p>\n\n<p>If you mean DC, that is what you shall do. You can start by creating a proper smart pointer. Most of it is quite easy to do -- The one UI use have the same interface as auto_ptr without the templated ctors. The tricky part is the copy itself, that the pointer must do on its copy, but really must use some external force. Here you can either fix some strategy, like using the copy ctor of the object, or make it configurable. Mine uses a simple static policy class that is template parameter, but you can also make it a template function that the clients can specialize, or think up something else.</p>\n\n<p>Once you have your dc_ptr, you can just use vestor or any collection of it as it fits all the requirements. And the semantics make sense too: copy of the collection will be completely separate from the original. </p>\n\n<p>The fly in the ointment is you can have pointers in NULL state, for good or ill. If that is not desireable, you have to write your own interface for the collection that prevents this situation, and say replaces nulls with default-constructed objects or something. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-29T21:40:40.917",
"Id": "26774",
"ParentId": "26111",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26241",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T16:33:22.463",
"Id": "26111",
"Score": "3",
"Tags": [
"c++",
"c++11"
],
"Title": "How to design interface of deep-copy behaving pointer containers?"
}
|
26111
|
<p><em>ETC = "Estimated Time of Completion"</em></p>
<p>I'm counting the time it takes to run through a loop and showing the user some numbers that tells him/her how much time, approximately, the full process will take. I feel like this is a common thing that everyone does on occasion and I would like to know if you have any guidelines that you follow.</p>
<p>Here's an example I'm using at the moment:</p>
<pre><code>int itemsLeft; //This holds the number of items to run through.
double timeLeft;
TimeSpan TsTimeLeft;
list<double> avrage;
double milliseconds; //This holds the time each loop takes to complete, reset every loop.
//The background worker calls this event once for each item. The total number
//of items are in the hundreds for this particular application and every loop takes
//roughly one second.
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//An item has been completed!
itemsLeft--;
avrage.Add(milliseconds);
//Get an avgrage time per item and multiply it with items left.
timeLeft = avrage.Sum() / avrage.Count * itemsLeft;
TsTimeLeft = TimeSpan.FromSeconds(timeLeft);
this.Text = String.Format("ETC: {0}:{1:D2}:{2:D2} ({3:N2}s/file)",
TsTimeLeft.Hours,
TsTimeLeft.Minutes,
TsTimeLeft.Seconds,
avrage.Sum() / avrage.Count);
//Only using the last 20-30 logs in the calculation to prevent an unnecessarily long List<>.
if (avrage.Count > 30)
avrage.RemoveRange(0, 10);
milliseconds = 0;
}
//this.profiler.Interval = 10;
private void profiler_Tick(object sender, EventArgs e)
{
milliseconds += 0.01;
}
</code></pre>
<p>As I am a programmer at the very start of my career I'm curious to see what you would do in this situation. My main concern is the fact that I calculate and update the UI for every loop, is this bad practice? </p>
<p>Are there any do's/don't's when it comes to estimations like this? Are there any preferred ways of doing it, e.g. update every second, update every ten logs, calculate and update UI separately? Also when would an ETA/ETC be a good/bad idea.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T13:19:32.190",
"Id": "40395",
"Score": "0",
"body": "I'm sure you've seen timers like this that switch over to \"less than a minute\" and \"less than 30 seconds\" when nearing the end of the processing. If you see the last few estimates jumping around a lot you may wish to consider this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T13:25:55.897",
"Id": "40396",
"Score": "0",
"body": "That's a great idea, @DanPichelman. Absolutely something to consider."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T14:01:04.583",
"Id": "40397",
"Score": "1",
"body": "If you're interested in the conceptual / design aspects of timers, then this question is on-topic for P.SE. If you're asking about _that_ specific example of timer code then Codereview would be a better site."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T16:50:10.987",
"Id": "40401",
"Score": "0",
"body": "The code is just an example. I first asked the question on SO and questions with code is usually preferred and since I had the code I added it as a reference. I admit that the text just below the code might be confusing but if you read even further down it should make sense. I'm slightly upset that this was migrated but I guess I just wasn't clear enough."
}
] |
[
{
"body": "<p>Your approach looks reasonable if one makes the assumption that the average time for item processing is roughly the same for each item. </p>\n\n<p>Updating the UI once a second is ok, updating it more often does not make much sense since the typically user cannot follow that visually either. If this really becomes a bottleneck, you might consider to add some code like</p>\n\n<pre><code>if(timeWhenUIWasUpdated < currentTime-1.0)\n{\n this.Text = String.Format(/*...*/);\n timeWhenUIWasUpdated = currentTime; // unit: seconds\n}\n</code></pre>\n\n<p>(you will have to introduce those two variables <code>timeWhenUIWasUpdated</code> and <code>currentTime</code> into your code).</p>\n\n<p>Of course, when your progress event gets called more often (for example, several 10,000s a second), you will have to think about further optimizations, since even without the UI you will have to do some time value management or calculations. But as long as this is not the case, keep things simple.</p>\n\n<p>This one here</p>\n\n<pre><code>if (avrage.Count > 30) \n avrage.RemoveRange(0, 10);\n</code></pre>\n\n<p>looks like premature optimization, I guess</p>\n\n<pre><code> avrage.RemoveRange(0, 1);\n</code></pre>\n\n<p>will give you a more smooth behaviour (and I guess you won't notice the difference in running time in most real-world cases). </p>\n\n<p>Furthermore, for testing purposes, you may consider to refactor the average-time calculation into a <code>SlidingAverageCalculator</code> class, separating the logic fully from the background worker and the UI display. This will make it really easy to write unit tests for that part of the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T13:02:58.480",
"Id": "40398",
"Score": "0",
"body": "Yes, the time for each item is roughly the same in this particular process. I assume an estimated time would be hard to get right if that wasn't the case? Your suggestion on `.RemoveRange` is a good example of what I want to learn, things that would or would not effect the execution time. The last thing I want is for this piece of added functionality to noticeably slow down the process."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T16:06:51.123",
"Id": "40399",
"Score": "0",
"body": "@HjalmarZ: I would not take too many thoughts here on what slows down the process as long as you don't really notice performance losses. At least not when talking about 1 event per second and 30 samples."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T12:31:24.087",
"Id": "26113",
"ParentId": "26112",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26113",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T11:46:12.037",
"Id": "26112",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Norms, rules or guidelines for calculating and showing ETA/ETC for a process"
}
|
26112
|
<p>Can I do something better with this code? It's just a snippet of a library I wrote.</p>
<pre><code><?php
/*
* Variable.class.php
* (c) 2013 sinan eker`enter code here`
* */
class Variable extends Config {
protected static $vars = array();
final public static function variables(){
return static::$vars;
}
final public static function clear(String $name){
unset(static::$vars[$name->getString()]);
}
final public static function destruct(){
unset(static::$vars);
static::$vars = array();
}
final public static function override(String $name, $value){
static::clear($name);
static::register($name, $value);
}
final public static function get(String $name){
$name = $name->getString();
return (isset(static::$vars[$name]) ? static::$vars[$name] : null);
}
final public static function register(String $name, $value){
return (!is_null(static::get($name)) ? false : static::$vars[$name->getString()] = $value);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all, method and variable docblocks are recommended. Provide a description of each method, its parameters and their return values.</p>\n\n<p>I would give your getter function <code>Variable::variables()</code> an active name like <code>getVariables()</code> and rename your <code>Variable::get()</code> method to <code>getVariable()</code>. Consistency is important and you want to avoid confusion with the magic getter <a href=\"http://php.net/manual/en/language.oop5.magic.php\" rel=\"nofollow\"><code>__get()</code></a>.</p>\n\n<p>Are you intentionally using the non-magic method <code>Variable::destruct</code> instead of the PHP magic method <a href=\"http://php.net/manual/en/language.oop5.decon.php\" rel=\"nofollow\"><code>__destruct()</code></a>?</p>\n\n<p>This is more of a syntax preference, but I would use <code>array_key_exists()</code> instead of <code>isset()</code> when referring to the property <code>static::$vars</code> since I find the verbage more aligned with what you are testing.</p>\n\n<p>The docblocks are the only important thing. Good work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T21:03:51.797",
"Id": "40423",
"Score": "0",
"body": "First of all, thank you! I would not use array_key_exists, isset is faster!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T21:11:55.097",
"Id": "40426",
"Score": "0",
"body": "also this is a class, for using without an object instance. so the static is entitled!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T19:55:15.020",
"Id": "26123",
"ParentId": "26114",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T16:51:44.980",
"Id": "26114",
"Score": "2",
"Tags": [
"php",
"object-oriented",
"php5"
],
"Title": "Variable class from library"
}
|
26114
|
<p>In the ZF2 model mapper, mappings are quite often duplicated in the original mapping class & other mapping classes.</p>
<p>I am using a static mapping methods (<code>mapToInternal</code>, <code>mapToExternal</code>) to remove this duplication. Could this be done any better?</p>
<pre><code><?php
//...
/**
* Class ItemTable
*
* @package Job\Model\Mapper\Item
*/
class ItemTable extends Table implements ItemInterface
{
/**
* @param \ArrayObject $external
* @return ItemEntity
*/
static public function mapToInternal(\ArrayObject $external)
{
$item = new ItemEntity();
empty($external->id) ? : $item->setId($external->id);
empty($external->account_id) ? : $item->setAccountId($external->account_id);
empty($external->title) ? : $item->setTitle($external->title);
empty($external->description) ? : $item->setDescription($external->description);
empty($external->created_on) ? : $item->setCreatedOn($external->created_on);
empty($external->updated_on) ? : $item->setUpdatedOn($external->updated_on);
return $item;
}
/**
* @param ItemEntity $item
* @return array
*/
static public function mapToExternal(ItemEntity $item)
{
$data = array(
'id' => $item->getId(),
// @todo complete once login is done
'account_id' => 1, //$item->getAccountId(),
'title' => $item->getTitle(),
'description' => $item->getDescription(),
'updated_on' => $item->getUpdatedOn(),
'created_on' => $item->getCreatedOn(),
);
return $data;
}
/**
* return array
*/
public function findAll()
{
$response = $this->getDao()->findAll();
$items = array();
foreach ($response as $item) {
$itemEntity = self::mapToInternal($item);
$statisticEntity = ItemStatisticTable::mapToInternal($item);
$itemEntity->setStatistic($statisticEntity);
$items[] = $itemEntity;
}
return $items;
}
// ...
</code></pre>
|
[] |
[
{
"body": "<p>Two minor notes:</p>\n\n<ol>\n<li><p>This function uses only data of <code>ItemEntity</code>:</p>\n\n<blockquote>\n<pre><code>static public function mapToExternal(ItemEntity $item)\n{\n $data = array(\n 'id' => $item->getId(),\n // @todo complete once login is done\n 'account_id' => 1, //$item->getAccountId(),\n 'title' => $item->getTitle(),\n 'description' => $item->getDescription(),\n 'updated_on' => $item->getUpdatedOn(),\n 'created_on' => $item->getCreatedOn(),\n );\n\n return $data;\n}\n</code></pre>\n</blockquote>\n\n<p>I would consider putting this function into the <code>ItemEntity</code> class. It seems <a href=\"http://c2.com/cgi/wiki?DataEnvy\" rel=\"nofollow\">data envy</a>.</p></li>\n<li><p>It's confusing here that <code>$items</code> does not contain any <code>$item</code>:</p>\n\n<blockquote>\n<pre><code>$items = array();\nforeach ($response as $item) {\n $itemEntity = self::mapToInternal($item);\n $statisticEntity = ItemStatisticTable::mapToInternal($item);\n $itemEntity->setStatistic($statisticEntity);\n\n $items[] = $itemEntity;\n}\n\nreturn $items;\n</code></pre>\n</blockquote>\n\n<p>I'd rename it to <code>$result</code> to describe its purpose.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-24T00:01:12.767",
"Id": "45169",
"ParentId": "26116",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T17:20:17.610",
"Id": "26116",
"Score": "4",
"Tags": [
"php",
"zend-framework"
],
"Title": "ZF2 Model Mapper"
}
|
26116
|
<p>I try to intercept some OpenGL calls for testing my rendering classes. Reflection is used for replacing the OpenGL backend.</p>
<p>I feel this class is badly written and I need advices for refactoring it.</p>
<pre><code>package fr.meuns.opengl;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.FloatBuffer;
public class GL
{
private static class MethodSignature
{
String name;
Class< ? >[] parameters;
public MethodSignature( String name, Class< ? >... parameters )
{
this.name = name;
this.parameters = parameters;
}
}
private final static MethodSignature[] METHOD_SIGNATURES = new MethodSignature[] {
new MethodSignature( "glGenBuffers" ),
new MethodSignature( "glDeleteBuffers", int.class ),
new MethodSignature( "glBindBuffer", int.class, int.class ),
new MethodSignature( "glBufferData", int.class, FloatBuffer.class, int.class ),
new MethodSignature( "glGetBufferSubData", int.class, long.class, FloatBuffer.class )
...
};
private final static String[] CONSTANT_NAMES = new String[] {
"GL_ARRAY_BUFFER",
"GL_ELEMENT_ARRAY_BUFFER",
"GL_STATIC_DRAW"
...
};
public static int GL_ARRAY_BUFFER;
public static int GL_ELEMENT_ARRAY_BUFFER;
public static int GL_STATIC_DRAW;
...
public static Method _glGenBuffers;
public static Method _glDeleteBuffers;
public static Method _glBindBuffer;
public static Method _glBufferData;
public static Method _glGetBufferSubData;
...
public static int glGenBuffers()
{
try
{
return (int)_glGenBuffers.invoke( null );
}
catch( IllegalAccessException | IllegalArgumentException | InvocationTargetException e )
{
e.printStackTrace();
return 0;
}
}
public static void glDeleteBuffers( int buffer )
{
try
{
_glDeleteBuffers.invoke( null, buffer );
}
catch( IllegalAccessException | IllegalArgumentException | InvocationTargetException e )
{
e.printStackTrace();
}
}
public static void glBindBuffer( int target, int buffer )
{
try
{
_glBindBuffer.invoke( null, target, buffer );
}
catch( IllegalAccessException | IllegalArgumentException | InvocationTargetException e )
{
e.printStackTrace();
}
}
public static void glBufferData( int target, FloatBuffer data, int usage )
{
try
{
_glBufferData.invoke( null, target, data, usage );
}
catch( IllegalAccessException | IllegalArgumentException | InvocationTargetException e )
{
e.printStackTrace();
}
}
public static void glGetBufferSubData( int target, long offset, FloatBuffer data )
{
try
{
_glGetBufferSubData.invoke( null, target, offset, data );
}
catch( IllegalAccessException | IllegalArgumentException | InvocationTargetException e )
{
e.printStackTrace();
}
}
public ...
public static void useClass( Class< ? > glClass )
{
for( String name : CONSTANT_NAMES )
try
{
GL.class
.getField( name )
.set( null, glClass.getField( name ).get( null ) );
}
catch( IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e1 )
{
e1.printStackTrace();
}
for( MethodSignature signature : METHOD_SIGNATURES )
try
{
GL.class
.getField( "_" + signature.name )
.set( null, glClass.getDeclaredMethod( signature.name, signature.parameters ) );
}
catch( IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException | NoSuchMethodException e )
{
e.printStackTrace();
}
}
}
</code></pre>
<p>Initialization for rendering using LWJGL :</p>
<pre><code>import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
...
GL.useClass( GL11.class );
GL.useClass( GL15.class );
GL.useClass( GL20.class );
...
</code></pre>
<p>Initialization for testing :</p>
<pre><code>import fr.meuns.opengl.GLMock;
...
GL.useClass( GLMock.class );
...
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T21:05:36.353",
"Id": "40518",
"Score": "0",
"body": "I can elaborate if necessary."
}
] |
[
{
"body": "<pre><code>public class GL\n</code></pre>\n\n<p>Your class name should really be a more descriptive noun.</p>\n\n<pre><code>private static class MethodSignature\n</code></pre>\n\n<p>You actually have no need for this <code>private static class</code> since Reflection gives you direct access to methods and method signatures, as you'll see in my modified version of your code below.</p>\n\n<pre><code>String name;\nClass<?>[] parameters;\n</code></pre>\n\n<p>When you create a class, you should always explicitly declare whether a field is <code>public</code>, <code>protected</code>, or <code>private</code>.</p>\n\n<pre><code>private final static MethodSignature[] METHOD_SIGNATURES = new MethodSignature[] { //...\nprivate final static String[] CONSTANT_NAMES = new String[] { //...\n</code></pre>\n\n<p>Again, you don't need either of these since you have Reflection, which gives you access to methods and fields.</p>\n\n<pre><code>public static int GL_ARRAY_BUFFER;\npublic static int GL_ELEMENT_ARRAY_BUFFER;\npublic static int GL_STATIC_DRAW;\n\npublic static Method _glGenBuffers;\npublic static Method _glDeleteBuffers;\npublic static Method _glBindBuffer;\npublic static Method _glBufferData;\npublic static Method _glGetBufferSubData;\n</code></pre>\n\n<p>These are all very odd variable names. In general, <code>NAMES_IN_CAPS</code> are constants (<code>private static final</code>). The beginning underscore is also a paradigm that isn't really Java-esque (and to my knowledge in other languages it is generally used for <code>private</code>-like fields).</p>\n\n<p>public static int glGenBuffers() {</p>\n\n<p>Your method names are also oddly named for Java. In general, Java method names should be actions and verb phrases. (For example, <code>getGLGenBuffers()</code>)</p>\n\n<pre><code>catch(IllegalAccessException | IllegalArgumentException | InvocationTargetException e)\n</code></pre>\n\n<p>No need for these lengthy <code>catch</code> declarations since they all do the same thing and all you're doing is printing the stack trace. <code>catch(Exception e)</code> will do and make your code more sensible.</p>\n\n<pre><code>public static void useClass(Class<?> glClass)\n</code></pre>\n\n<p>This entire method will be refactored below. But basically you don't need two <code>for()</code> loops, since you're just looping through the class's fields. This also eliminates the need for the overarching constants for the field names and the method signatures, as you'll see.</p>\n\n<p>I cut your code length by about half by doing all of the above, and I think it's generally more readable and understandable this way as well.</p>\n\n<pre><code>import java.lang.reflect.Field;\nimport java.lang.reflect.Method;\nimport java.nio.FloatBuffer;\n\npublic class OpenGLInterceptor { \n\n public static int GL_ARRAY_BUFFER;\n public static int GL_ELEMENT_ARRAY_BUFFER;\n public static int GL_STATIC_DRAW;\n //...\n\n public static Method _glGenBuffers;\n public static Method _glDeleteBuffers;\n public static Method _glBindBuffer;\n public static Method _glBufferData;\n public static Method _glGetBufferSubData;\n //...\n\n public static int invokeGenBuffers() {\n try {\n return (Integer)_glGenBuffers.invoke(null);\n }\n catch(Exception e) {\n e.printStackTrace();\n return 0;\n }\n }\n\n public static void invokeDeleteBuffers(int buffer) {\n try {\n _glDeleteBuffers.invoke(null, buffer);\n }\n catch(Exception e){\n e.printStackTrace();\n }\n }\n\n public static void invokeBindBuffer(int target, int buffer) {\n try {\n _glBindBuffer.invoke( null, target, buffer );\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void invokeBufferData(int target, FloatBuffer data, int usage) {\n try {\n _glBufferData.invoke(null, target, data, usage);\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void invokeGetBufferSubData(int target, long offset, FloatBuffer data) {\n try {\n _glGetBufferSubData.invoke( null, target, offset, data );\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n\n public static void useClass(Class<?> glClass) {\n for(Field field : GL.class.getDeclaredFields()) {\n try {\n if(field.getName().contains(\"_\")) {\n field.set(null, glClass.getDeclaredMethod(field.getName(), ((Method)field.get(null)).getParameterTypes()));\n }\n else {\n field.set(null, glClass.getField(field.getName()).get(null));\n }\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T23:17:22.977",
"Id": "51371",
"Score": "0",
"body": "A lot of good ideas, thank you. Tomorrow I will take more times to think about you post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T21:18:06.370",
"Id": "51547",
"Score": "0",
"body": "Renaming gl* to invoke* implies a lot of renaming in the existing engine code and also reduce readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T21:31:59.620",
"Id": "51548",
"Score": "0",
"body": "@sylvain Why would you have to rename the existing engine code? From what you said, your code is just to intercept what that code is doing, so it should be entirely separate. I also completely disagree with you about the readability bit, but of course that's subjective."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-05T13:55:25.403",
"Id": "51576",
"Score": "0",
"body": "Because I want to instrument the whole engine. Rendering classes use the OpenGLInterceptor (or GL in case). For running application I just use classes provided by LWJGL but for testing I can use a mock or log class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T21:44:03.723",
"Id": "53943",
"Score": "0",
"body": "*When you create a class, you should always explicitly declare whether a field is public, protected, or private.* - But not declaring it any of the three results in a fourth choice, package-protected, for which there is no explicit declaration. If the OP actually wants package-protected fields, not adding any explicit declaration was his only choice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T15:21:42.443",
"Id": "57944",
"Score": "0",
"body": "I agree with this answer **except using \"catch(Exception e)\"**. Catching the `Exception` class **is not recommended as that will catch IllegalStateException, NullPointerException and **all runtime exceptions**. **You should not swallow a NullPointerException or similar!** (By swallow I mean \"only print the stack trace\")"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T19:21:49.847",
"Id": "57990",
"Score": "0",
"body": "@SimonAndréForsberg I only put that because all he was doing was printing the stack trace anyway, which is the default behavior when not catching the exception regardless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T19:26:39.760",
"Id": "57991",
"Score": "0",
"body": "@JeffGohlke Not totally correct. If you don't catch a RuntimeException, the thread will stop (unless it's catched higher up in the calling hierarchy). By catching it, you allow the thread to continue running without any guarantee that previous statements has been successful with their job - which is doomed to cause more errors down the line."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-02T17:24:17.067",
"Id": "32152",
"ParentId": "26119",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T18:02:58.450",
"Id": "26119",
"Score": "2",
"Tags": [
"java",
"reflection",
"static",
"opengl"
],
"Title": "Java reflection and static classes"
}
|
26119
|
<p>I am looking for a starting point to code plugins, primarily for Zepto.js (with fall back for jQuery). These will provide reusable functions for Tumblr theming.</p>
<p>However, I can't seem to find anything in depth about writing a plugin (with Zepto) as the example, apart from a small snippet on the Zepto site: <a href="http://zeptojs.com/" rel="nofollow">http://zeptojs.com/</a></p>
<p>The code below is pieced together from reading various 'jQuery' plugin tutorials, but I am not 100% sure how solid it is.</p>
<pre><code>;(function($){
$.extend($.fn, {
pluginName: function(el, options) {
// Set defaults
this.defaults = {
option: 'option',
onComplete: function() {}
};
// Combine defaults / options
var settings = $.extend({}, this.defaults, options);
// Do stuff
$.each(this, function() {
});
// Call back if needed
settings.onComplete.call(this);
// Return `this` for chain ability
return this;
}
});
}(window.Zepto || window.jQuery));
</code></pre>
<p>According to the Zepto documentation, my plugins method will be added to the Zepto object. Is this acceptable? </p>
<p>I would also like the option to use private / public functions contained in the plugin for flexibility. </p>
<p>I apologise if my questions come across as confusing or novice, but any help / improvements would be greatly appreciated.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:56:05.117",
"Id": "40420",
"Score": "1",
"body": "You could check the [jQuery Boilerplate](http://jqueryboilerplate.com/) for a better understanding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:53:02.710",
"Id": "40457",
"Score": "0",
"body": "Thanks @JosephtheDreamer that's where I got bits for the code above."
}
] |
[
{
"body": "<p>This looks fine to me, but then again it's sample (boilerplate) code ;)</p>\n\n<ul>\n<li>Consider <code>\"use strict\"</code>; </li>\n<li>If it was not for the <code>onComplete</code>, you could simply <code>return</code> the result of <code>$.each</code></li>\n</ul>\n\n<p>I like your options handling, graceful fallback to jQuery, style, it's all good.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T20:46:44.643",
"Id": "46963",
"ParentId": "26121",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "46963",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T19:07:01.773",
"Id": "26121",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"plugin"
],
"Title": "Zepto / jQuery plugin base"
}
|
26121
|
<p>I need to get the numbers in a string like "1,2,5-9", the function should return a list with these values [1,2,5,6,7,8,9]</p>
<p>Here's what I did. Is this the best way or there's something simpler/better?</p>
<pre><code>function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function getNumbers(stringNumbers) {
var nums = [];
var list1 = stringNumbers.split(",");
var length = list1.length;
for(var i = 0; i < length; i++) {
var number = list1[i];
if(number.indexOf("-") != -1) {
range = number.split("-");
if(isNumber(range[0]) && isNumber(range[1])) {
var min = parseInt(range[0]);
var max = parseInt(range[1]);
//edit to accept range like 9-5
if(min > max){
var min_ref = min;
min = max;
max = min_ref;
}
while(min <= max) {
nums.push(min);
min++
};
}
} else {
if(isNumber(number)) {
nums.push(parseInt(number));
}
}
}
//edit to sort list at the end
return nums.sort(function(a,b){return a - b});
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:37:07.040",
"Id": "40414",
"Score": "1",
"body": "`str.match(/(\\d+)/g).slice(1)` or something similar should probably be enough though :-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:37:53.790",
"Id": "40415",
"Score": "0",
"body": "Unless I misunderstood something, that is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:39:05.903",
"Id": "40416",
"Score": "0",
"body": "@FlorianMargaine For simple numbers, that would work. But they also have ranges. For example: `5-9` should end up including 5, 6, 7, 8 and 9"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:51:29.300",
"Id": "40418",
"Score": "0",
"body": "@Ian Exactly, sometimes I'll receive a String with that kind of range, and I need to get all numbers between."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:54:27.067",
"Id": "40419",
"Score": "1",
"body": "@FlorianMargaine using that on a String \"1,2,5-9\" returned [2,5,9], I need the 1 too... slice should be from index 0 right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:59:23.650",
"Id": "40421",
"Score": "0",
"body": "What happens if there was a space or some other character in some place in the string? Or is it safe to assume they will only be separated by `,` and `-`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:59:34.630",
"Id": "40422",
"Score": "0",
"body": "This isn't as strict as what you have, but maybe something like: http://jsfiddle.net/P3XUx/1/ . I'm not sure if it's better or more efficient (sometimes I do weird things with regex), but it's something that seems to work for me. It also depends on what kind of input there can be"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T21:11:54.627",
"Id": "40425",
"Score": "0",
"body": "@Ian lol, I understand absolutely nothing about regex, but that did the job too. I won't use this code so often, so efficiency it's not realy the question here. I just did that function, and started wondering if there was something easier to read/extend later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T21:25:45.287",
"Id": "40427",
"Score": "0",
"body": "@JosephtheDreamer Yes, we can assume that will be only `,` and `-` on the string"
}
] |
[
{
"body": "<p>Well, <a href=\"http://jsfiddle.net/mkhC3/\" rel=\"nofollow\">here's my version</a> that's <a href=\"http://jsperf.com/getting-numbers-and-ranges-from-string/5\" rel=\"nofollow\">benchmarked across different browsers</a>. Might need some improvement (currently finding shortcuts for the isNumber), but works as marketed:</p>\n\n<pre><code>function getNumbers(stringNumbers) {\n\n //personal preference, but I got this handy tip from the internet that\n\n //if you had assignments, better if they are individually var'ed\n var nums = [];\n var entries = stringNumbers.split(',');\n var length = entries.length;\n\n //for variabes that don't, comma separated\n var i, entry, low, high, range;\n\n for (i = 0; i < length; i++) {\n entry = entries[i];\n\n //shortcut for testing a -1\n if (!~entry.indexOf('-')) {\n //absence of dash, must be a number\n //force to a number using +\n nums.push(+entry);\n } else {\n //presence of dash, must be range\n range = entry.split('-');\n\n //force to numbers\n low = +range[0];\n high = +range[1];\n\n //XOR swap, no need for an additional variable. still 3 steps though\n //http://en.wikipedia.org/wiki/XOR_swap_algorithm\n if(high < low){\n low = low ^ high;\n high = low ^ high;\n low = low ^ high;\n }\n\n //push for every number starting from low\n while (low <= high) {\n nums.push(low++);\n }\n }\n }\n\n //edit to sort list at the end\n return nums.sort(function (a, b) {\n return a - b;\n });\n}\n</code></pre>\n\n<p>Here's <a href=\"http://jsfiddle.net/mkhC3/1/\" rel=\"nofollow\">another version</a>, which is <a href=\"http://jsperf.com/getting-numbers-and-ranges-from-string/5\" rel=\"nofollow\">slightly slower (the V2)</a> since I added the additional number checks which the one above didn't but more conformant to the specification of the question.</p>\n\n<pre><code>var getNumbers = (function () {\n\n //we create a closure so as not to expose some of our utility functions\n\n function isNumber(n) {\n //we check isFinite first since it will weed out most of the non-numbers\n //like mixed numbers and strings, which parseFloat happily accepts\n return isFinite(n) && !isNaN(parseFloat(n));\n }\n\n //let's get this one out as well\n //the simple sort() wouldn't work so instead we provide a sorter\n function sorterFunction(a, b) {\n return a - b;\n }\n\n //getNumbers should be this function\n return function (stringNumbers) {\n\n //variable declaration format is personal preference\n //but I prefer having declarations with assignments have individual vars\n //while those that have no assignments as comma separated\n var i, range, low, high, entry;\n\n //an added bonus, \" and ' are the same in JS, but order still applies\n //I prefer to use ' since it's cleaner\n var entries = stringNumbers.split(','); \n var length = entries.length;\n var nums = [];\n\n for (i = 0; i < length; ++i) {\n entry = entries[i];\n\n if (isNumber(entry)) {\n //we check if the entry itself is a number. If it is, then we push it directly.\n //an additinal advantage is that negative numbers are valid\n nums.push(+entry);\n } else {\n\n //if not a number, probably it had the - and not being a negative number\n //only here do we split after we determined that the entry isn't a number\n range = entry.split('-');\n\n //check if what we split are both numbers, else skip\n if (!isNumber(range[0]) || !isNumber(range[1])) continue;\n\n //force both to be numbers\n low = +range[0];\n high = +range[1];\n\n //since we are dealing with numbers, we could do an XOR swap\n //which is a swap that doesn't need a third variable\n //http://en.wikipedia.org/wiki/XOR_swap_algorithm\n if (high < low) {\n low = low ^ high;\n high = low ^ high;\n low = low ^ high;\n }\n\n //from low, we push up to high\n while (low <= high) {\n nums.push(low++);\n }\n }\n }\n return nums.sort(sorterFunction);\n }\n}());\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:20:28.753",
"Id": "40481",
"Score": "0",
"body": "Nice work! I'll use the V2, personal preference and more readable to me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:23:35.420",
"Id": "40482",
"Score": "0",
"body": "By the way, the XOR swap works in IE7/8?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:31:16.803",
"Id": "40484",
"Score": "0",
"body": "@JonatasGusmão The v2 is the same as v1, just added checks and encapsulation. Must be the way I wrote the comments :D As for the XOR swap, I don't have IE at the moment, but [MSDN says it does](http://msdn.microsoft.com/en-us/library/ie/ece515h6(v=vs.94).aspx)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T12:27:55.227",
"Id": "41090",
"Score": "0",
"body": "@JosephtheDreamer could u add my solution to benchmark"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-10-18T23:35:41.657",
"Id": "271282",
"Score": "0",
"body": "The `!~` shortcut should not appear in code intended for human readers. It is the job of a JavaScript minifier to create such code."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:09:20.533",
"Id": "26138",
"ParentId": "26125",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "26138",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T20:25:16.047",
"Id": "26125",
"Score": "7",
"Tags": [
"javascript"
],
"Title": "Getting all number from a String like this \"1,2,5-9\""
}
|
26125
|
<p>I wrote a class with this function. Can I improve my code performance in the bottom of the function? I don't like the <code>while</code> loops!</p>
<pre><code>public function loadFields(array $fields, $as_object = Config::FIELDS_AS_OBJECT) {
$connection = $this->connection;
$sql = "SELECT ".implode(",", $fields)." FROM ".$this->table." WHERE lang = ?";
if (!($stmt = $connection->prepare($sql))){
throw new MysqliPrepareException($connection);
}
if(!($stmt->bind_param('s',$this->lang))){
throw new MysqliBindParamException($connection);
}
if(!$stmt->execute()){
throw new MysqliExecuteException($connection);
}
$stmt->store_result();
$variables = array();
$data = array();
$meta = $stmt->result_metadata();
while ($field = $meta->fetch_field()) {
$variables[] = &$data[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $variables);
$i = 0;
while ($stmt->fetch()) {
$array[$i] = array();
foreach ($data as $k => $v) {
$array[$i][$k] = $v;
}
$i++;
}
$array = (!isset($array[1]) ? $array[0] : $array);
return ($as_object == true ? (object) $array : $array);
}
</code></pre>
|
[] |
[
{
"body": "<p>I'd imagine a <a href=\"http://php.net/manual/en/pdostatement.fetchall.php\" rel=\"nofollow\"><code>$stmt->fetchAll()</code></a> would be more performant than the while-loop and <code>$stmt->fetch()</code>. Rather than paging over an entire set of records one at a time, try returning the results from the database in-bulk. Your code is making a trip to the database with each iteration of your while loop. Your code will still look virtually identical:</p>\n\n<pre><code>$i = 0;\n$r = $stmt->fetchAll();\nforeach ($r as $data) {\n $array[$i] = array();\n foreach ($data as $k => $v) {\n $array[$i][$k] = $v;\n }\n $i++;\n} \n</code></pre>\n\n<p>If you're using mysqli (native driver only), and not PDO's MySQL, you could do this:</p>\n\n<pre><code>$i = 0;\n$r = $stmt->get_result();\n$r = $r->fetchAll();\nforeach ($r as $data) {\n $array[$i] = array();\n foreach ($data as $k => $v) {\n $array[$i][$k] = $v;\n }\n $i++;\n} \n</code></pre>\n\n<p>You shouldn't worry about loops per se, but performance hits that you see, whether they come from loops or not. This is only possible if you're profiling your code. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T18:38:28.843",
"Id": "40581",
"Score": "0",
"body": "Yep, thanks, but this doesn't work for be because I use mysqli and the mysqli_stmt object doesn't have a method fetchAll."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:19:50.597",
"Id": "40675",
"Score": "0",
"body": "Sorry user1232375, I didn't realize you're using mysqli. I added some code that should work as long as you're using a native mysqli driver. It uses the mysqli_stmt::get_result() method: http://www.php.net/manual/en/mysqli-stmt.get-result.php"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T09:31:19.337",
"Id": "40883",
"Score": "0",
"body": "Yep, tested it with mysql and it worked! Thank you for your work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T17:48:44.040",
"Id": "41019",
"Score": "0",
"body": "Awesome, glad I could help! Would you mind accepting my answer?"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T03:04:48.743",
"Id": "26188",
"ParentId": "26126",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T21:35:04.913",
"Id": "26126",
"Score": "3",
"Tags": [
"php",
"performance",
"object-oriented",
"php5"
],
"Title": "Performance of loading fields"
}
|
26126
|
<p>I'm working on a web application using Bottle, and it is, at this point, functional. </p>
<p>The gist of it is that I have a database of drinks, with associated IDs, and associated sets of ingredients. the name and ID of the drink are passed to the client, which displays them.</p>
<p>Currently, when the program loads up, all drinks and their associated ingredient amounts are loaded into a list of dictionaries, like so:</p>
<pre><code>SampleDrinkDict = {'name': 'Screwdriver', 'id': 4, 'vodka':2, 'orange juice':6}
DrinkDictList = []
DrinkDictList.append(SampleDrinkDict)
</code></pre>
<p>Once the <code>DrinkDictList</code> is fully populated, I pass the names and IDs of every one to the client, which populates those in a list. When a drink is selected, it makes a callback to scan the <code>DrinkDictList</code> and find the matching 'id' field. Once it finds it in the list, the ingredient amounts and details are populated on the page.</p>
<p>Would it be faster/better/more proper for me to only query ingredients from the DB once a drink is selected? </p>
<p>For example, would it be faster/more pythonic/better to do this?</p>
<pre><code>SampleDrinkDict = {'name': 'Screwdriver', 'id': 4,}
DrinkDictList = []
DrinkDictList.append(SampleDrinkDict)
@bottle.route('/drinkSelected/:id'):
def getIng(id,db):
sqlString = '''SELECT ingredients WHERE Drink_id = ?'''
argString = (id,)
ingredientList = db.execute(SqlString, argString).fetchall()
</code></pre>
<p>This is all running on a Raspberry Pi, and I'm worried about taxing the RAM once the drink list becomes huge. Is there any reason to go with one approach over the other?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:57:53.827",
"Id": "40445",
"Score": "0",
"body": "You should use `lower_case_with_underscores` for variable names like `SampleDrinkDict` - see the [style guide](http://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables)."
}
] |
[
{
"body": "<p>Whether you need to store data in the DB is really gonna depend on your testing, but here are a few thoughts about how to reduce memory usage while still building the entire drink table at startup:</p>\n\n<ul>\n<li>While they're convenient, you don't necessarily need to use dictionaries for this. You could replace each dictionary with a tuple where the first item is the drink name, the second item is the drink id, and the rest of the items are tuples of size 2 with the ingredient name and the ratio for that ingredient. This would change your example to <code>('Screwdriver', '4', ('vodka', 2), ('orange juice', 6))</code>. <code>sys.getsizeof</code> gives 280 for the dictionary and only 88 for the tuple, a significant reduction.</li>\n<li>If you're still pressed for space, you can take advantage of the fact that you probably have a lot of overlap in terms of your ingredients. Build a list with a string for each ingredient that one of your drinks uses. Then each tuple can simply have an <code>int</code> referring to the index of the ingredient in your ingredient list. This prevents you from storing a string like 'vodka' 20 different times. Once again using <code>sys.getsizeof</code> gives a value of 42 for the string 'vodka' and a value of 24 for the number 100. This will of course only work if you have enough overlap in your ingredients.</li>\n</ul>\n\n<p>If those ideas aren't enough to reduce your memory usage to an acceptable amount, you're probably going to need to go with your second solution(unless some other folks have some better ideas!). I don't really see one of your solutions as more pythonic than the other, so I wouldn't worry about that.</p>\n\n<p>And enjoy the raspberry pi!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T06:25:45.470",
"Id": "40434",
"Score": "3",
"body": "One can [`intern`](http://docs.python.org/2/library/functions.html#intern) strings instead of your second bullet point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T06:34:28.023",
"Id": "40435",
"Score": "1",
"body": "@JanneKarila good point, that's a much nicer way of solving the problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:59:38.820",
"Id": "40446",
"Score": "2",
"body": "Don't forget that changing from a dictionary (~O(1) lookups) to a list of tuples (O(n) lookups) will slow searches down considerably."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:27:51.730",
"Id": "40468",
"Score": "1",
"body": "@AlexL but he isn't really using a dictionary, he's using a list of dictionaries. Searching through that list is still O(n)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T13:42:04.087",
"Id": "40474",
"Score": "0",
"body": "I don't think I'll be swapping to tuples, as currently all of my logic and the bottle templates operate based on them. And i've already got a list of ingredients, but i havent yet used their indices to access the information, thats a good idea. I'll try out the string intern() too. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T17:54:53.787",
"Id": "40499",
"Score": "1",
"body": "@Nolen Good point, perhaps he could improve performance by using drink ID as the key to his drinks dict? `drinks = {1: {name: screwdriver, ...}, 2: {...}, ...}`"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T04:52:40.233",
"Id": "26132",
"ParentId": "26127",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26132",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-13T21:47:14.203",
"Id": "26127",
"Score": "6",
"Tags": [
"python",
"performance",
"sql",
"hash-map",
"bottle"
],
"Title": "Load drinks and their ingredients into dictionaries"
}
|
26127
|
<p>I want to play around with the Powerball lotto drawing history. What other probability theories could I try or what other probability class libraries exist. The code parses the file very quickly but is there a better way to go about it?</p>
<p>I am working on a multiple regression analysis with the first <code>white_ball</code> as a dependent variable.</p>
<pre><code>#include <iostream>
#include <algorithm>
#include <sstream>
#include <fstream>
#include "linear.h" // http://www.codecogs.com/code/maths/approximation/regression/linear.php
#include <string>
using namespace std;
// Powerball rules.
// (http://en.wikipedia.org/wiki/Powerball)
const int POWERBALL_WHITE = 59; // White balls number 1-59
const int WHITE_DRAWS = 5; // Only 5 balls are drawn.
const int POWERBALL_RED = 35; // Red balls number 1-35
const int REB_DRAWS = 1; // Only 1 ball is drawn.
// Parse rules.
const int MAX_LINE = 37;
const char* DELIMITER_DATE = "/"; // Draw date format is separated by forward slash.
typedef struct {
int month;
int day;
int year;
int white_ball_1;
int white_ball_2;
int white_ball_3;
int white_ball_4;
int white_ball_5;
int reb_ball;
} Powerball;
int main (int argc, char** argv) {
// Open the historical data file.
// (http://www.powerball.com/powerball/pb_nbr_history.asp)
ifstream lotto;
lotto.open("lotto.txt");
if (!lotto.good())
return 1;
// How many weekly drawing have taken place?
int number_Drawings = (int)count(istreambuf_iterator<char>(lotto), istreambuf_iterator<char>(), '\n') - 1;
lotto.seekg(0);
// Create Powerball drawing array.
Powerball *drawings;
drawings = (Powerball*) malloc(number_Drawings * sizeof(Powerball));
// Parse loto results to Powerball array.
lotto.ignore(50, '\n'); // Skip first line with category references.
while (!lotto.eof()) {
Powerball draw;
// Line objects to parse.
static int n;
int month, day, year;
char DELIMITER; // Date delimiter like variable.
int white_1,white_2, white_3, white_4, white_5, red;
lotto >> month >> DELIMITER >> day >> DELIMITER >> year >> white_1 >> white_2 >> white_3 >> white_4 >> white_5 >> red;
draw.month = month;
draw.day = day;
draw.year = year;
draw.white_ball_1 = white_1;
draw.white_ball_2 = white_2;
draw.white_ball_3 = white_3;
draw.white_ball_4 = white_4;
draw.white_ball_5 = white_5;
draw.reb_ball = red;
drawings[n++] = draw;
if (lotto.peek() != '\n') // For entries with Plus Ball or extra characters
lotto.ignore(10, '\n');
}
lotto.close();
// Create linear regression arrays variables.
double lin_reg_1[number_Drawings];
double lin_reg_2[number_Drawings];
double lin_reg_3[number_Drawings];
double lin_reg_4[number_Drawings];
double lin_reg_5[number_Drawings];
for (int i = 0; i < number_Drawings; i++) {
lin_reg_1[i] = drawings[i].white_ball_1;
lin_reg_2[i] = drawings[i].white_ball_2;
lin_reg_3[i] = drawings[i].white_ball_3;
lin_reg_4[i] = drawings[i].white_ball_4;
lin_reg_5[i] = drawings[i].white_ball_5;
}
cout << "There are " << number_Drawings << " drawings that have taken place since " <<
drawings[number_Drawings].month << "/" << drawings[number_Drawings].day << "/" << drawings[number_Drawings].year
<< endl << endl;
cout << "------------------------------------------------------------------------" << endl;
cout << "Linear regression test 1. White_1 dependent, White_2 independent" << endl;
cout << "------------------------------------------------------------------------" << endl;
Maths::Regression::Linear reg_a(number_Drawings,lin_reg_1,lin_reg_2);
cout << "Slope = " << reg_a.getSlope() << endl;
cout << "Intercept = " << reg_a.getIntercept() << endl;
cout << "Regression coefficient = " << reg_a.getCoefficient() << endl << endl;
cout << "------------------------------------------------------------------------" << endl;
cout << "Linear regression test 2. White_2 dependent, White_3 independent" << endl;
cout << "------------------------------------------------------------------------" << endl;
Maths::Regression::Linear reg_b(number_Drawings,lin_reg_2,lin_reg_3);
cout << "Slope = " << reg_b.getSlope() << endl;
cout << "Intercept = " << reg_b.getIntercept() << endl;
cout << "Regression coefficient = " << reg_b.getCoefficient() << endl << endl;
cout << "------------------------------------------------------------------------" << endl;
cout << "Linear regression test 3. White_3 dependent, White_4 independent" << endl;
cout << "------------------------------------------------------------------------" << endl;
Maths::Regression::Linear reg_c(number_Drawings,lin_reg_3,lin_reg_4);
cout << "Slope = " << reg_c.getSlope() << endl;
cout << "Intercept = " << reg_c.getIntercept() << endl;
cout << "Regression coefficient = " << reg_c.getCoefficient() << endl << endl;
cout << "------------------------------------------------------------------------" << endl;
cout << "Linear regression test 4. White_4 dependent, White_5 independent" << endl;
cout << "------------------------------------------------------------------------" << endl;
Maths::Regression::Linear reg_d(number_Drawings,lin_reg_4,lin_reg_5);
cout << "Slope = " << reg_d.getSlope() << endl;
cout << "Intercept = " << reg_d.getIntercept() << endl;
cout << "Regression coefficient = " << reg_d.getCoefficient() << endl << endl;
cout << "------------------------------------------------------------------------" << endl;
cout << "Linear regression test 5. White_5 dependent, White_1 independent" << endl;
cout << "------------------------------------------------------------------------" << endl;
Maths::Regression::Linear reg_e(number_Drawings,lin_reg_5,lin_reg_1);
cout << "Slope = " << reg_e.getSlope() << endl;
cout << "Intercept = " << reg_e.getIntercept() << endl;
cout << "Regression coefficient = " << reg_e.getCoefficient() << endl << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T17:50:21.890",
"Id": "40498",
"Score": "1",
"body": "For inspiration, take a look at the following:\nhttp://isocpp.org/blog/2013/03/n3551-random-number-generation ;\n[PDF] http://isocpp.org/files/papers/n3551.pdf ;\nhttp://en.cppreference.com/w/cpp/numeric/random ; \nhttp://www.boost.org/doc/libs/release/libs/math/doc/sf_and_dist/html/math_toolkit/dist.html"
}
] |
[
{
"body": "<p>My suggestions won't make your code faster, I focused on idiomatic and clear code. It's already quite nice as it is. :)</p>\n\n<pre><code>// Powerball rules.\n// (http://en.wikipedia.org/wiki/Powerball)\nconst int POWERBALL_WHITE = 59; // White balls number 1-59\nconst int WHITE_DRAWS = 5; // Only 5 balls are drawn.\nconst int POWERBALL_RED = 35; // Red balls number 1-35\nconst int REB_DRAWS = 1; // Only 1 ball is drawn.\n</code></pre>\n\n<p>Did you mean <code>RED_DRAWS</code>? You're not using any of those constants. Interestingly, it does make the code clearer for someone who doesn't know the rules.</p>\n\n<pre><code>// Parse rules.\nconst int MAX_LINE = 37;\nconst char* DELIMITER_DATE = \"/\"; // Draw date format is separated by forward slash.\n\ntypedef struct {\n int month;\n int day;\n int year;\n int white_ball_1;\n int white_ball_2;\n int white_ball_3;\n int white_ball_4;\n int white_ball_5;\n</code></pre>\n\n<p>A static array would be easier here: <code>int whiteballes[WHITE_DRAWS]</code>.</p>\n\n<pre><code> int reb_ball;\n</code></pre>\n\n<p>Did you mean <code>red_ball</code>?</p>\n\n<pre><code>} Powerball;\n</code></pre>\n\n<p>This is a C-style struct, but a C++-style struct would have been more idiomatic.</p>\n\n<pre><code>int main (int argc, char** argv) {\n // Open the historical data file.\n // (http://www.powerball.com/powerball/pb_nbr_history.asp)\n ifstream lotto;\n lotto.open(\"lotto.txt\");\n</code></pre>\n\n<p>Isn't it simpler to use the constructor of <code>std::ifstream</code>?</p>\n\n<pre><code> if (!lotto.good())\n return 1;\n</code></pre>\n\n<p>This can be very surprising if nothing is printed on <code>std::cerr</code>.</p>\n\n<pre><code> // How many weekly drawing have taken place?\n int number_Drawings = (int)count(istreambuf_iterator<char>(lotto), istreambuf_iterator<char>(), '\\n') - 1;\n lotto.seekg(0);\n // Create Powerball drawing array.\n Powerball *drawings;\n drawings = (Powerball*) malloc(number_Drawings * sizeof(Powerball));\n</code></pre>\n\n<p>C-style allocation, when you could have used a C++03 vector or a C++11 fixed-size array. You're not even freeing this memory.</p>\n\n<pre><code> // Parse loto results to Powerball array.\n lotto.ignore(50, '\\n'); // Skip first line with category references.\n</code></pre>\n\n<p>Avoid magic numbers, this a good fit for a constant.</p>\n\n<pre><code> while (!lotto.eof()) {\n Powerball draw;\n\n // Line objects to parse.\n static int n;\n int month, day, year;\n char DELIMITER; // Date delimiter like variable.\n int white_1,white_2, white_3, white_4, white_5, red;\n\n lotto >> month >> DELIMITER >> day >> DELIMITER >> year >> white_1 >> white_2 >> white_3 >> white_4 >> white_5 >> red;\n</code></pre>\n\n<p>Why don't you read directly in <code>draw</code>? This would make the following lines unnecessary.</p>\n\n<pre><code> draw.month = month;\n draw.day = day;\n draw.year = year;\n draw.white_ball_1 = white_1;\n draw.white_ball_2 = white_2;\n draw.white_ball_3 = white_3;\n draw.white_ball_4 = white_4;\n draw.white_ball_5 = white_5;\n draw.reb_ball = red;\n\n drawings[n++] = draw;\n if (lotto.peek() != '\\n') // For entries with Plus Ball or extra characters\n lotto.ignore(10, '\\n'); \n</code></pre>\n\n<p>General formatting advice: avoid long lines and spaces after instructions.</p>\n\n<pre><code> }\n lotto.close();\n\n // Create linear regression arrays variables.\n double lin_reg_1[number_Drawings];\n double lin_reg_2[number_Drawings];\n double lin_reg_3[number_Drawings];\n double lin_reg_4[number_Drawings];\n double lin_reg_5[number_Drawings];\n</code></pre>\n\n<p>What about a matrix?</p>\n\n<pre><code> for (int i = 0; i < number_Drawings; i++) {\n lin_reg_1[i] = drawings[i].white_ball_1;\n lin_reg_2[i] = drawings[i].white_ball_2;\n lin_reg_3[i] = drawings[i].white_ball_3;\n lin_reg_4[i] = drawings[i].white_ball_4;\n lin_reg_5[i] = drawings[i].white_ball_5;\n }\n</code></pre>\n\n<p>If white_ball was an array, you could have only one affectation in your loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:04:30.710",
"Id": "40480",
"Score": "1",
"body": "@BrandonClark (A1) I do mean a C++ struct, eg. `struct Powerball { ... }`, since everything is visible. (A9) somethings like `a = 2; `. (A10) To be clear, matrix here means vector of vector or array of array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T15:32:16.007",
"Id": "40489",
"Score": "2",
"body": "Don't loop on `.eof()`, it doesn't do what you want. Loop on the stream state itself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T05:34:01.397",
"Id": "40530",
"Score": "1",
"body": "@BrandonClark http://stackoverflow.com/questions/14615671/whats-the-real-reason-to-not-use-the-eof-bit-as-our-stream-extraction-condition"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:51:26.753",
"Id": "26136",
"ParentId": "26130",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "26136",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T03:21:02.207",
"Id": "26130",
"Score": "5",
"Tags": [
"c++",
"c++11",
"statistics"
],
"Title": "Fun with probability theory"
}
|
26130
|
<p>I am validating two IP addresses. I simply wrote a peice of code like </p>
<pre><code>if(string.IsNullOrEmpty(ip1) && string.IsNullOrEmpty(ip2)
return true;
</code></pre>
<p>But is this logically correct? What should we done with empty strings? If both are empty strings, is it okay to return true?</p>
<p>May be a complete code snipet can give better insight.</p>
<pre><code>public static bool IsIPAddressMatching(string ipAddressA, string ipAddressB)
{
try
{
if(string.IsNullOrEmpty(ipAddressA) || string.IsNullOrEmpty(ipAddressB))
return true;
var address1 = IPAddress.Parse(ipAddressA);
var address2 = IPAddress.Parse(ipAddressB);
if (address1.AddressFamily == address2.AddressFamily)
return (address1.Equals(address2));
// some code here to check mapped IP addresses
}
catch (Exception)
{
return false;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:43:47.277",
"Id": "40442",
"Score": "2",
"body": "What do you want to achieve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:50:49.830",
"Id": "40444",
"Score": "0",
"body": "It seems not clear enough to give an answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T11:29:13.160",
"Id": "40463",
"Score": "1",
"body": "You don't need to check `AddressFamily` yourself, `IPAddress.Equals()` already does that."
}
] |
[
{
"body": "<p>Personally i would check the strings on NullOrWhitespace, but knowing you want to validate IP addresses, i recommend to use the IPAddress object for them which has an Parse and TryParse method. When that's done it's quite easy to create an static method for it which provides easy access.</p>\n\n<p>Below i have written an example:</p>\n\n<p><em><strong>References:</em></strong></p>\n\n<pre><code>using System;\nusing System.Linq;\nusing System.Net;\n</code></pre>\n\n<p><em><strong>Code:</em></strong></p>\n\n<pre><code>public static class IPAddressValidation\n{\n public static bool Validate(string self)\n {\n IPAddress result;\n IPAddress.TryParse(self, out result);\n\n return result != null;\n }\n\n public static bool Validate(string[] self)\n {\n return self.All(Validate);\n }\n}\n</code></pre>\n\n<p>Also, in some cases it might be sufficient to just throw an exception, when you are expecting it to be always valid for example, instead of user input. Validation methods don't always have to return true or false, sometimes it's such an essential value, that stopping the whole process by throwing the exception might be desired behavior.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:07:29.170",
"Id": "40447",
"Score": "1",
"body": "I agree entirely with using the inbuilt type `IPAddress` to attempt to parse the string but this is a horrible implementation. `TryParse` returns a bool indicating its success so you shouldn't be checking for null. I also don't think you should have this as an extension method - especially one called 'IsValid': `string a = \"123\"; bool result = a.IsValid()` - Is a valid *what*?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:14:12.513",
"Id": "40449",
"Score": "0",
"body": "Yes i agree on the implementation, updating it in a second, still i would check on null though, but that's my personal preference i guess."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T21:14:49.317",
"Id": "40585",
"Score": "0",
"body": "Point being your return statement in Validate could be : return IPAddress.TryParse(self, out Result);"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T10:10:32.630",
"Id": "40611",
"Score": "0",
"body": "Yes i know what he was saying, but then, what would be the use of 'Result', i think this is better for the readability as every programmer now knows what's happening, to some it would make no sense to fill 'Result', while returning on the same line for example."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:01:48.917",
"Id": "26137",
"ParentId": "26135",
"Score": "1"
}
},
{
"body": "<p>From the IP validation point of view null or empty IP addresses are exceptional actions so you can not say that two null or empty strings are the same IP addresses becouse they aren't IP addresses and sometimes not even strings.</p>\n\n<p>And you don't have to sorrund the logic with try-catch block becouse it will eat usefull information when things will get ugly. If you don't want to deal with parsing exception then use IPAddress.TryParse it will be faster becouse throwing an exception is always a heavy weight stuff (check it with profiler).</p>\n\n<pre><code>public static bool IsIPAddressMatching(string ipAddressA, string ipAddressB)\n{\n if (ipAddressA == null)\n {\n throw new ArgumentNullException(\"ipAddressA\");\n }\n if (ipAddressB == null)\n {\n throw new ArgumentNullException(\"ipAddressB\");\n }\n\n if (string.IsNullOrEmpty(ipAddressA))\n {\n throw new ArgumentException(\"ipAddressA cannot be an empty string\", \"ipAddressA\");\n }\n if (string.IsNullOrEmpty(ipAddressB))\n {\n throw new ArgumentException(\"ipAddressB cannot be an empty string\", \"ipAddressB\");\n }\n\n var address1 = IPAddress.Parse(ipAddressA);\n var address2 = IPAddress.Parse(ipAddressB);\n\n if (address1.AddressFamily == address2.AddressFamily)\n {\n return (address1.Equals(address2));\n }\n\n // some code here to check mapped IP addresses\n\n return ...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:49:05.707",
"Id": "40485",
"Score": "0",
"body": "What's the point in the first 4 `if (...) throw...`s? The `IPAddress.Parse` method will throw an `ArgumentNullException` if either `ipAddressA` or `ipAddressB` are `null`. It will also throw a `FormatException` if the string is not a valid IP address. I don't think all the checks first add anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:56:20.490",
"Id": "40486",
"Score": "0",
"body": "+1 for the ArgumentNullException part. Mostly C/C++ programmers tends to forget about this :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T10:58:19.240",
"Id": "26145",
"ParentId": "26135",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T07:41:31.283",
"Id": "26135",
"Score": "0",
"Tags": [
"c#"
],
"Title": "Should I return true or false if both of the IP address strings are empty?"
}
|
26135
|
<p>I was curious about trying to write my own simple Database Connection Pool, where all the responsibility for freeing resources belongs to objects which use those connections.</p>
<p>There are:<br/>
<strong>3 classes</strong> - ConnectionPool, RecoverableConnection and ConnectionFactory<br/>
<strong>1 interface</strong> - IrresponsibleConnectionManager</p>
<p><strong>Is my code (my thoughts) acceptable ?</strong> <em>Or is it a complete junk ?</em> It took me an hour and half to write and I know there are several better algorithms to implement. But this could server well for my pourpose. I also found this solution faster to some libraries I had downloaded, even faster than DataSource.</p>
<p>I'm glad to hear <strong>any comments</strong> about my code !</p>
<pre><code>import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* @author XY
*/
public class ConnectionFactory {
private static ConnectionPool connectionPool;
public static void initializeConnectionPool(String url, Properties connectionProperties, int connectionPoolSize) throws SQLException {
if (connectionPool == null) {
connectionPool = new ConnectionPool(url, connectionProperties, connectionPoolSize);
}
}
/**
* Returns a connection from connection pool.
*
* @param waitTime Time to wait for a connection.
* @return Connection to the database.
* @throws java.sql.SQLException When connection is not available within given wait time.
*/
public static Connection getConnection(ConnectionPool.WaitTime waitTime) throws SQLException {
return connectionPool.getConnection(waitTime);
}
}
</code></pre>
<hr>
<pre><code>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.*;
/**
* Offers unified way to handle database connections. Provides connection pooling functionality.
*
* @author XY
* Date: 13.5.13
*/
public class ConnectionPool implements IrresponsibleConnectionPoolManager {
private int pool_size = 0;
private Queue<Connection> availableConnections;
/**
* @param url Database URL
* @param connectionProperties Properties of the connection to establish.
* @param poolSize Number of connections to establish.
* @throws SQLException When creating of the connection pool fails.
*/
public ConnectionPool(String url, Properties connectionProperties, int poolSize) throws SQLException {
initializeConnections(url, connectionProperties);
pool_size = poolSize;
}
/**
* Creates the pool of available connections according to currently set number of pool size.
* Note that connection pool must be initialized to it's full capacity, or it is emptied and objects
* are free to be garbage collected.
*
* @param url Database connection URL
* @param properties Properties required for connection.
* @throws SQLException If case of not finishing creating connection pool, this exception is thrown.
*/
private void initializeConnections(String url, Properties properties) throws SQLException {
availableConnections = new ArrayDeque<>();
try {
//Fills list of available connections
for (int i = 0; i < pool_size; i++) {
Connection createdConnection = new RecoverableConnection(DriverManager.getConnection(url, properties), this);
availableConnections.add(createdConnection);
}
} catch (SQLException e) {
//Free involved objects for garbage collection
availableConnections.removeAll(availableConnections);
availableConnections = null;
throw new SQLException("Could not establish connection.");
}
}
/**
* Returns a connection from connection pool.
*
* @param waitTime Time to wait for a connection.
* @return Connection to the database.
* @throws SQLException When connection is not available within given wait time.
*/
public Connection getConnection(WaitTime waitTime) throws SQLException {
Connection returnedConnection;
//Operations with connection pool should be synchronized
synchronized (ConnectionPool.class) {
returnedConnection = availableConnections.poll();
}
if (returnedConnection == null && waitTime == WaitTime.IMMEDIATELY) {
//If request method doesn't want to wait, throw an exception.
throw new SQLException("No connection available at the moment.");
} else if (returnedConnection == null) {
//If connection is not required immediately, wait for specified time and recursively
//call this method again
try {
Thread.sleep(waitTime.getWaitTime());
} catch (InterruptedException e) {
e.printStackTrace();
}
//Try to get connection object one more time
returnedConnection = getConnection(WaitTime.IMMEDIATELY);
return returnedConnection;
} else {
//Connection object is available
return returnedConnection;
}
}
public void recycleConnection(Connection c) {
availableConnections.offer(c);
}
/**
* Represents time to wait for a connection. Ensures unified waiting intervals.
*/
public enum WaitTime {
IMMEDIATELY(0),
HALF_A_SECOND(500),
ONE_SECOND(1000),
THREE_SECONDS(3000),
FIVE_SECONDS(5000);
private int waitTime;
private WaitTime(int i) {
this.waitTime = i;
}
public int getWaitTime() {
return waitTime;
}
}
</code></pre>
<p>}</p>
<hr>
<pre><code>/**
* Connection pool manager recycling allocated connections when
* @author XY
*/
interface IrresponsibleConnectionPoolManager {
/**
* Returns connection back to connection pool.
*
* @param recycledConnection Connection to return back to connection pool.
*/
void recycleConnection(Connection recycledConnection);
}
</code></pre>
<hr>
<pre><code>import java.sql.*;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
/**
* Wraps any object implementing Connection interface and makes it manageable by any implementation of ConnectionPoolmanager
* @author XY
* @see IrresponsibleConnectionPoolManager
* @see Connection
*/
public class RecoverableConnection implements Connection {
private Connection connection;
private IrresponsibleConnectionPoolManager manager;
public RecoverableConnection(Connection connection, IrresponsibleConnectionPoolManager manager) {
this.connection = connection;
this.manager = manager;
}
@Override
public Statement createStatement() throws SQLException {
return connection.createStatement();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return connection.prepareStatement(sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return connection.prepareCall(sql);
}
@Override
public String nativeSQL(String sql) throws SQLException {
return connection.nativeSQL(sql);
}
@Override
public boolean getAutoCommit() throws SQLException {
return connection.getAutoCommit();
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
connection.setAutoCommit(autoCommit);
}
@Override
public void commit() throws SQLException {
connection.commit();
}
@Override
public void rollback() throws SQLException {
connection.rollback();
}
@Override
/**
* Return connection to the connection pool
*/
public void close() throws SQLException {
connection = null;
manager.recycleConnection(this);
}
@Override
public boolean isClosed() throws SQLException {
return connection == null;
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return connection.getMetaData();
}
@Override
public boolean isReadOnly() throws SQLException {
return connection.isReadOnly();
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
connection.setReadOnly(readOnly);
}
@Override
public String getCatalog() throws SQLException {
return connection.getCatalog();
}
@Override
public void setCatalog(String catalog) throws SQLException {
connection.setCatalog(catalog);
}
@Override
public int getTransactionIsolation() throws SQLException {
return connection.getTransactionIsolation();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
connection.setTransactionIsolation(level);
}
@Override
public SQLWarning getWarnings() throws SQLException {
return connection.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
connection.clearWarnings();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return connection.createStatement(resultSetType, resultSetConcurrency);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return connection.prepareStatement(sql, resultSetType, resultSetConcurrency);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return connection.prepareCall(sql, resultSetType, resultSetConcurrency);
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return connection.getTypeMap();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
connection.setTypeMap(map);
}
@Override
public int getHoldability() throws SQLException {
return connection.getHoldability();
}
@Override
public void setHoldability(int holdability) throws SQLException {
connection.setHoldability(holdability);
}
@Override
public Savepoint setSavepoint() throws SQLException {
return connection.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return connection.setSavepoint(name);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
connection.rollback();
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
connection.releaseSavepoint(savepoint);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return connection.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return connection.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return connection.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return connection.prepareStatement(sql, autoGeneratedKeys);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return connection.prepareStatement(sql, columnIndexes);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return connection.prepareStatement(sql, columnNames);
}
@Override
public Clob createClob() throws SQLException {
return connection.createClob();
}
@Override
public Blob createBlob() throws SQLException {
return connection.createBlob();
}
@Override
public NClob createNClob() throws SQLException {
return connection.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
return connection.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException {
return connection.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
connection.setClientInfo(name, value);
}
@Override
public String getClientInfo(String name) throws SQLException {
return connection.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException {
return connection.getClientInfo();
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
connection.setClientInfo(properties);
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return connection.createArrayOf(typeName, elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return connection.createStruct(typeName, attributes);
}
@Override
public String getSchema() throws SQLException {
return connection.getSchema();
}
@Override
public void setSchema(String schema) throws SQLException {
connection.setSchema(schema);
}
@Override
public void abort(Executor executor) throws SQLException {
connection.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
connection.setNetworkTimeout(executor, milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException {
return connection.getNetworkTimeout();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return connection.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return connection.isWrapperFor(iface);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
RecoverableConnection that = (RecoverableConnection) o;
if (connection != null ? !connection.equals(that.connection) : that.connection != null) return false;
if (manager != null ? !manager.equals(that.manager) : that.manager != null) return false;
return true;
}
@Override
public int hashCode() {
int result = connection != null ? connection.hashCode() : 0;
result = 31 * result + (manager != null ? manager.hashCode() : 0);
return result;
}
}
</code></pre>
|
[] |
[
{
"body": "<p>ConnectionFactory looks like a singleton and I think could probably be rewritten and would be safer as a singleton. Unsynchronized concurrent calls to initializeConnectionPool() would have unintended side-effects. Take a look at <a href=\"http://en.wikipedia.org/wiki/Singleton_pattern\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Singleton_pattern</a> to see which Java singleton pattern works best for you.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:10:05.473",
"Id": "26205",
"ParentId": "26139",
"Score": "1"
}
},
{
"body": "<p>1) ConnectionFactory.initializeConnectionPool() is not thread-safe since two threads could see the connectionPool as null and set it at the same time. The first one will be \"lost\" and garbage collected, so it is not catastrophic, but it should probably be thread-safe. I did not check other classes for threadsafety, but they might also have issues.</p>\n\n<p>2) ConnectionFactory.getConnection() should probably return some useful error message if initializeConnectionPool() had not been called before. It would actually make more sense to replace initializeConnectionPool() by the constructor. In such a case you would not use the singleton pattern, since you might have many instances of ConnectionFactory (hopefully to different databases).</p>\n\n<p>3) The constructor ConnectionPool() calls initializeConnections() <em>before</em> setting <code>pool_size</code>, but it should be the other way around</p>\n\n<p>4) Instead of using a <code>Queue<Connection></code> in ConnectionPool, you should use a BlockingQueue. They have poll and offer methods that take a time out. You somewhat recreated that behavior with thread.sleep. However thread.sleep can sometimes wake up before its intended time and it is in general preferable to use existing classes that provide some functionality since you know they are bulletproof. </p>\n\n<p>5) It does not smell quite right that RecoverableConnection contains a connection manager as a member. That class is very long but just seems to redefine all Connection methods. It is probably better to get rid of RecoverableConnection and just use normal Connections.</p>\n\n<p>I have not read all your classes, but I hope those comments will be useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T19:23:11.933",
"Id": "26214",
"ParentId": "26139",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T08:16:13.660",
"Id": "26139",
"Score": "4",
"Tags": [
"java"
],
"Title": "Connection Pooling"
}
|
26139
|
<p>I have this repetitive block of code and I'm looking for ways to make it reusable and as flat as possible.</p>
<p>Here it is:</p>
<pre><code>Controller.showKeyboardRegion = function() {
logger.info('Controller.showKeyboardRegion => CreateAccountLayoutController');
var view = new CreateAccountKeyboardView();
Controller.layout.createAccountKeyboardRegion.show(view);
view.startCreateAccountKeyboard();
}
Controller.showPhoneNumberRegion = function() {
logger.info('Controller.showPhoneNumberRegion => CreateAccountLayoutController');
var view = new CreateAccountPhoneNumberView();
Controller.layout.createAccountPhoneNumberRegion.show(view);
view.startCreateAccountPhoneNumber();
}
Controller.showNameRegion = function() {
logger.info('Controller.showNameRegion => CreateAccountLayoutController');
var view = new CreateAccountNameView();
Controller.layout.createAccountNameRegion.show(view);
view.startCreateAccountName();
}
</code></pre>
<p>I have nine of those in my real code. Is there a way to make this simpler and better?</p>
|
[] |
[
{
"body": "<pre><code>var key;\n\n//Here you store the necessary information for each of the 9 functions\n\n//the key of the map will be the function name\n//builder will be the reference to the constructor\n//layoutObj is the name of the property from Controller.layout from which we call show()\n//viewStarter will be the name of the method we call from the view\nvar fn = {\n showKeyboardRegion : {\n builder : CreateAccountKeyboardView,\n layoutObj : 'createAccountKeyboardRegion',\n viewStarter : 'startCreateAccountKeyboard'\n },\n showPhoneNumberRegion : {\n builder : CreateAccountPhoneNumberView,\n layoutObj : 'createAccountPhoneNumberRegion',\n viewStarter : 'startCreateAccountPhoneNumber'\n },\n showNameRegion : {\n builder : CreateAccountNameView,\n layoutObj : 'createAccountNameRegion',\n viewStarter : 'startCreateAccountName'\n }\n}\n\n/* EVERYTHING BEYOND HERE IS WHAT ATTACHES THE ABOVE DATA TO Controler */\n\n//for each entry in the map\nfor(key in fn){\n //a quick property check to see if property is on the map\n if(!fn.hasOwnProperty(key)) continue;\n\n //attach to controller per key\n Controller[key] = (function(key){\n\n //we use a closure and passed in key, so that the function will use the\n //value of key at that iteration, since key will be changed over the course\n //of the loop.\n\n //so we extract the data from the map for a bit of readability\n var entry = fn[key];\n var builder = entry.builder;\n var layoutObj = entry.layoutObj;\n var viewStarter = entry.viewStarter;\n\n //return our handler\n return function(){\n var view = new builder();\n logger.info('Controller.'+key+' => CreateAccountLayoutController');\n Controller.layout[layoutObj].show(view);\n view[viewStarter]();\n }\n }(key));\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T10:54:52.213",
"Id": "26144",
"ParentId": "26142",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26144",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T10:18:47.200",
"Id": "26142",
"Score": "-1",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "Backbone Marionette code improvement"
}
|
26142
|
<p>I have written a small batch job which will collect data from db and send mail to user. Can you please do a review of the code with design prinicples in mind and also with best practices for Db and file writer. I am writing to file in this code and sending it in mail.</p>
<p>The user will call the class with report type to be generated along with startdate and enddate.</p>
<p>There could be 3-4 type of report generation types so user can give comma separated list of report types to be generated. I take the report type and generate the class related to it.</p>
<p>I want to write an extensible code or maintable code.In these set of classes CSVwriter and Report Dao do play major part . I want to keep a single procedure from where differnt reports get data , hence report dao method getDataForRepot is used for all different reports similarly CSV writer is used to write data to csv file for all report.</p>
<p>Please do close review of Reprot Dao and CSVwriter class.Is there need of VO or DTO ?</p>
<p>Below is the main class which calls report generator class basically </p>
<pre><code>import java.util.ResourceBundle;
public class ReportsManager {
public static void main(String[] args) {
try {
if (args.length > 0) {
String[] reportsList = null;
if (args[0] != null && args[0].trim().length() != 0) {
reportsList = args[0].split(",");
}
String startDate = null;
if (args[1] != null && args[1].trim().length() != 0) {
startDate = args[1];
}
String endDate = null;
if (args[2] != null && args[2].trim().length() != 0) {
startDate = args[2];
}
final ResourceBundle BUNDLE = ResourceBundle
.getBundle(AppConstants.CONFIG_PATH);
for (int i = 0; i < reportsList.length; i++) {
final String clazzName = BUNDLE.getString(reportsList[i]);
BatchJLogger.logMessage(" Report Generation Started for "
+ reportsList[i]);
String fileDetails[] = null;
ReportsInterface reports = (ReportsInterface) Class
.forName(clazzName).newInstance();
fileDetails = reports.execute(startDate, endDate,
reportsList[i]);
String strBody = reports.getMailContent();
MailSender mailSender = new MailSender(reportsList[i]);
mailSender.sendMail(strBody, fileDetails[0],
fileDetails[1], true);
}
} else {
System.err
.println(" Please enter the report type to be generated");
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
</code></pre>
<p>Below is the interface which all report types should implement</p>
<pre><code>public interface ReportsInterface {
public String[] execute(String startDate,String endDate,String reportType) throws IOException,SQLException,Exception;
/**
* called after execute.
*/
public String getMailContent();
}
</code></pre>
<p>Below is one of the report class which creates file and then calls Db to get data using Stored procedure then writes content to File and send mail</p>
<pre><code>import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Vector;
public class UserDetailsReport implements ReportsInterface {
private Map<Integer, TreeMap<String,String>> userDetialsData =null;
String dateTimeStamp;
@Override
public String[] execute(String startDate, String endDate,String reportType) throws IOException,SQLException,Exception{
String[] fileName=null;
ReportDao reportDao = new ReportDao();
userDetialsData = reportDao.getDataForRepot(startDate,
endDate,reportType);
CsvWriter csvWriter = new CsvWriter();
fileName=csvWriter.writeDetailsToFile(reportType, callMeReportData,startDate,endDate);
dateTimeStamp=fileName[2];
return fileName;
}
public String getMailContent(){
StringBuilder body = new StringBuilder();
body.append("\n");
body.append("\n");
body.append("Please find attached report.");
body.append("\n");
body.append("\n");
body.append("\n");
body.append("\n");
body.append("Thanks,");
return body.toString();
}
}
</code></pre>
<p>Below is the class with creates and writes data to csv files</p>
<pre><code> import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
public class CsvWriter {
// this will hold the list of header for each reprot so that i dont have to write any specific method for a particular report
private static Map<String,ArrayList<String>> headers = new HashMap<String, ArrayList<String>>();
static{
ArrayList<String> callMe = new ArrayList<String>();
callMe.add("Mobile Phone");
callMe.add("Call Time");
callMe.add("Submitted On");
callMe.add("First Name");
callMe.add("Last Name");
callMe.add("Email");
ArrayList<String> leadGen = new ArrayList<String>();
leadGen.add("First Name");
leadGen.add("Last Name");
leadGen.add("Mobile Phone");
leadGen.add("Product Interested");
leadGen.add("Submitted On");
headers.put("USERDETAILS_REPORT", callMe);
headers.put("SOMEOTHER_REPORT", leadGen);
}
private FileWriter fileWriter = null;
private String folderName = null;
public enum ReportType{USERDETAILS_REPORT,SOMEOTHER_REPORT};
public FileWriter getFileWriter() {
return fileWriter;
}
public void setFileWriter(FileWriter fileWriter) {
this.fileWriter = fileWriter;
}
final ResourceBundle BUNDLE = ResourceBundle
.getBundle(AppConstants.CONFIG_PATH);
public CsvWriter() {
folderName = BUNDLE.getString("FOLDER_PATH");
}
// this method will be used by all the reprots
public String[] writeDetailsToFile(String reportType,Map<Integer, TreeMap<String,String>> values,String startDate,String endDate) throws IOException,Exception {
String filePath=null;
String fileName =null;
String[] details=null;
try{
//BatchJLogger.logMessage(" Started Execution of method writeDetailsToFile " );
BatchJLogger.logMessage(" Started Execution of method openXls " );
details = createFileName(reportType, startDate, endDate);
fileName=details[0];
filePath = folderName + File.separator + fileName;
fileWriter = new FileWriter(filePath);
File f = new File(filePath);
BatchJLogger.logMessage(" file created "+f.exists() );
fileWriter.write("Report Name");
fileWriter.write(",");
switch (ReportType.valueOf(reportType)) {
case USERDETAILS_REPORT:
fileWriter.write("USER DETILS");
break;
case SOMEOTHER_REPORT:
fileWriter.write("SOME");
break;
default:
break;
}
fileWriter.write(",");
fileWriter.write("Date ");
fileWriter.write(",");
fileWriter.write(CsvWriter.getCurrentDate());
fileWriter.write("\n");
fileWriter.write("\n");
ArrayList<String> cloumnNames = headers.get(reportType);
int fileHeader = 0;
for (String columnName : cloumnNames) {
fileWriter.write(columnName);
if(fileHeader < cloumnNames.size()){
fileWriter.write(",");
}
fileHeader++;
}
fileWriter.write("\n");
Set<Integer> recordSet = values.keySet();
for (Integer record : recordSet) {
TreeMap<String, String> data = values.get(record);
int columnCount = 0;
for (String columnName : cloumnNames) {
String columnData=data.get(columnName);
if((columnName.equalsIgnoreCase("Mobile Phone")||columnName.equalsIgnoreCase("Submitted On")) && columnData!=null ){
fileWriter.write("'");
}
fileWriter.write(BatchJUtil.checknull(columnData));
if(columnCount < cloumnNames.size()){
fileWriter.write(",");
}
columnCount++;
}
fileWriter.write("\n");
}
}
finally{
fileWriter.flush();
fileWriter.close();
return new String[]{filePath,fileName,details[1]};
}
//BatchJLogger.logMessage(" end of Execution of method writeDetailsToFile " );
}
public String[] createFileName(String reportType,String startDate,String endDate) throws ParseException{
String[] data =null;
String fileName=null;
String toDaysDate=null;
if(startDate!=null && startDate.length()!=0){
startDate=BatchJUtil.convertformat(startDate);
endDate=BatchJUtil.convertformat(endDate);
toDaysDate=startDate+"_To_"+endDate;
}else{
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
String date = dateFormat.format(cal.getTime());
String[] parsedDate = date.split("-");
int numDay = Integer.parseInt(parsedDate[0]);
String month = parsedDate[1];
int numYear = Integer.parseInt(parsedDate[2]);
toDaysDate = BatchJUtil.checkNumber(numDay) + "-"+month+ "-" + BatchJUtil.checkNumber(numYear);
}
switch (ReportType.valueOf(reportType)) {
case USERDETAILS_REPORT:
fileName="UserDetails_"+toDaysDate+".csv";
break;
case SOMEOTHER_REPORT:
fileName="SomeOther_"+toDaysDate+".csv";
break;
default:
break;
}
data=new String[]{fileName,toDaysDate};
return data;
}
public static String getCurrentDate(){
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Calendar cal = Calendar.getInstance();
return dateFormat.format(cal.getTime());
}
}
</code></pre>
<p>This is the class which gets connection from Db</p>
<pre><code>import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.sql.DataSource;
public class RConnection {
private Connection mConnection;
private Statement mStatement;
private static Object lockObject = new Object();
private static int openCount = 0;
private static int closeCount = 0;
private static String dataSourceName = "somedb";
private static DataSource dataSource = null;
private Vector statementVector= new Vector();
private Vector resultSetVector= new Vector();
public CallableStatement createCallableStatement(String sql) throws SQLException
{
CallableStatement cstmt = null;
try
{
cstmt = this.getDBConnection().prepareCall(sql);
statementVector.add(cstmt);
}
catch(SQLException e)
{
e.printStackTrace();
throw new SQLException("Can not create CallableStatement for sql "+e.getMessage());
}
return cstmt;
}
public ResultSet getResultSet(CallableStatement cstmt, int paramNo) throws SQLException
{
ResultSet rs=null;
try
{
rs=(ResultSet) cstmt.getObject(paramNo);
resultSetVector.add(rs);
}
catch(SQLException e)
{
e.printStackTrace();
throw new SQLException("Can not retrieve ResultSet for this CallableStatement "+e.getMessage());
}
return rs;
}
public static int getOpenConnections()
{
return openCount;
}
public static int getCloseConnections()
{
return closeCount;
}
/**
/**
* Constructor being made Private, Singleton implementation
*/
public RConnection()
{
this.connect();
}
/**
* This is the function that is used to connect to the
* database using jdbc
*/
public void connect()
{
try
{
String errorString = "Error obtaining database connection.";
final ResourceBundle BUNDLE = ResourceBundle.getBundle(AppConstants.CONFIG_PATH);
try {
String DB_USERNAME = BUNDLE.getString(AppConstants.DB_USERNAME);
String DB_PASSWORD = BUNDLE.getString(AppConstants.DB_PASSWORD)
String DB_URL = BUNDLE.getString(AppConstants.DB_URL);
Class.forName(AppConstants.DRIVER_CLASS_NAME);
mConnection = DriverManager.getConnection(DB_URL, DB_USERNAME,
DB_PASSWORD);
mConnection.setAutoCommit(false);
}catch (NullPointerException e) {
throw new Exception(errorString+":"+e.getMessage());
}
catch(SQLException sqle) {
throw new SQLException(errorString+":"+sqle.toString());
}
if (mConnection == null) {
throw new SQLException(errorString);
} else {
synchronized (lockObject) {
openCount++;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
throw new SQLException(e.getMessage());
}
}
/** Return Connection **/
public Connection getDBConnection()
{
return mConnection;
}
/**
* Execute any plain SQL query and returns the ResultSet
*/
public ResultSet executeSQL(String query) throws SQLException
{
ResultSet lRSet = null;
try
{
// close the statement if already open
if(mStatement != null) mStatement.close();
mStatement = mConnection.createStatement();
lRSet = mStatement.executeQuery(query);
}
catch(SQLException ex)
{
System.err.println("Error Query : " + query);
ex.printStackTrace();
throw new SQLException(ex.getMessage());
}
return lRSet;
}
public void commit()
{
try
{
if(mStatement != null) mStatement.close();
if(mConnection != null && !mConnection.getAutoCommit()) mConnection.commit();
}
catch(Exception ex)
{
ex.printStackTrace();
throw new Exception(ex.getMessage());
}
}
public void close()
{
try
{
if ((mConnection != null) && !mConnection.isClosed()) {
if(!resultSetVector.isEmpty())
{
//ok close all result sets once more
int rsSize = resultSetVector.size();
for(int i=0;i<rsSize;i++)
{
ResultSet rset=(ResultSet)resultSetVector.get(i);
try
{
rset.close();
}
catch(SQLException e)
{
throw new SQLException(e.getMessage());
}
}
}
if(!statementVector.isEmpty())
{
//ok close all statements once more
int stmtSize = statementVector.size();
for(int i=0;i<stmtSize;i++)
{
CallableStatement cstmt=(CallableStatement)statementVector.get(i);
try
{
cstmt.close();
}
catch(SQLException e)
{
//ignore this
}
}
}
mConnection.close();
synchronized (lockObject) {
closeCount++;
}
}
}
catch(Exception ex)
{
ex.printStackTrace();
throw new Exception(ex.getMessage());
}
}
} //end of Rconnection
</code></pre>
<p>Below is the dao class</p>
<pre><code> import java.lang.reflect.Field;
import java.sql.CallableStatement;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class ReportDao {
public RConnection connection = new RConnection();
public enum ReportType{USERDETAILS_REPORT,SOMEOTHER_REPORT};
public final static int NO_OF_RECORDS=6;
public Map<Integer, TreeMap<String,String>> getDataForRepot(String startDate, String endDate,String reportType) throws Exception {
BatchJLogger.logMessage(" Started Execution of method getDataForRepot " );
ResultSet rs = null;
Statement stmt = null;
CallableStatement cstmt = null;
try {
stmt = connection.getDBConnection().createStatement();
rs = getReportRecords(cstmt,startDate,endDate,reportType);
Map<Integer, TreeMap<String,String>> values= getFormattedData(rs);
BatchJLogger.logMessage(" No of records fetched "+values.size() );
BatchJLogger.logMessage(" End Execution of method getDataForRepot " );
return values;
} finally {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
/*if(cstmt!=null){
cstmt.close();
}*/
connection.close();
BatchJLogger.logMessage(" End Execution of method getDataForRepot " );
}
}
public ResultSet getReportRecords(CallableStatement cstmt,String startDate, String endDate,String reportType)
throws SQLException,Exception {
ResultSet rs = null;
try{
BatchJLogger.logMessage(" Started Execution of method getReportRecords ");
String procedure = "{call SOME_PROC (?,?,?,?)}";
cstmt = connection.createCallableStatement(procedure);
int procId=7;
switch (ReportType.valueOf(reportType)) {
case USERDETAILS_REPORT:
cstmt.setInt(1, 7);
break;
case SOMEOTHER_REPORT:
cstmt.setInt(1, 8);
break;
default:
break;
}
if(startDate!=null){
cstmt.setTimestamp(2, BatchJUtil.convertToTimeStamp(startDate,true));
cstmt.setTimestamp(3, BatchJUtil.convertToTimeStamp(endDate,false));
}else{
cstmt.setTimestamp(2, null);
cstmt.setTimestamp(3, null);
}
cstmt.registerOutParameter(4,
getOracleParamReturnType("CURSOR"));
cstmt.execute();
rs = connection.getResultSet(cstmt, 4);
BatchJLogger.logMessage(" End Execution of method getReportRecords ");
}catch (Exception e) {
e.printStackTrace();
connection.close();
}finally{
return rs;
}
}
public static int getOracleParamReturnType(String paramName) {
if (paramName == null)
return -1;
Field cursorField;
try {
Class c = Class.forName("oracle.jdbc.driver.OracleTypes");
cursorField = c.getField(paramName);
return cursorField.getInt(c);
} catch (Throwable th) {
th.printStackTrace();
return -1;
}
}
public Map<Integer, TreeMap<String,String>> getFormattedData(ResultSet rs ) throws SQLException, ParseException{
Map<Integer, TreeMap<String,String>> data = new TreeMap<Integer, TreeMap<String,String>>();
List<String> coulmnNames = new ArrayList<String>();
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for (int i = 1; i < columnCount + 1; i++ ) {
coulmnNames.add(rsmd.getColumnName(i)) ;
}
int noOfRecords =0 ;
while (rs.next()) {
TreeMap<String,String> values = new TreeMap<String, String>();
for (String name : coulmnNames) {
if(name.equalsIgnoreCase("Submitted On")){
if(rs.getString(name)!=null){
String submittedOn =rs.getString(name);
values.put(name, submittedOn);
}else{
values.put(name, null);
}
}else{
values.put(name, rs.getString(name));
}
}
data.put(++noOfRecords, values);
}
return data;
}
public void deleteBatchJobRecord(String reportName) throws SQLException{
try {
String deleteRecord = "delete from BATCH where SOME_ID=? and RUN_ID=(Select MAX(RUN_ID) "
+ "from BATCH where SOME_ID=?)";
PreparedStatement pstmt = connection.getDBConnection()
.prepareStatement(deleteRecord);
switch (ReportType.valueOf(reportName)) {
case USERDETAILS_REPORT:
pstmt.setInt(1, 7);
pstmt.setInt(2, 7);
break;
case SOMEOTHER_REPORT:
pstmt.setInt(1, 8);
pstmt.setInt(2, 8);
break;
default:
break;
}
int result = pstmt.executeUpdate();
System.out.println(" record deleted " + result);
} finally {
connection.close();
}
}
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Eating up exceptions</p>\n\n<pre><code>} catch (Exception e) {\n e.printStackTrace();\n} \n</code></pre>\n\n<p>Since your application cannot recover from most of the exceptions it should not catch and ignore (eat) exceptions but rather catch it, print the stack trace and pass it along.</p></li>\n<li><p><code>NullPointerException</code></p>\n\n<pre><code>String[] reportsList = args[0].split(\",\");\n</code></pre>\n\n<p>When you do not provide any arguments to your application (args.length == 0 -> args[0] == NULL) it will throw a <code>NullPointerException</code></p></li>\n<li><p><code>finally</code> block is not needed</p>\n\n<pre><code>} finally {\n System.exit(0);\n}\n</code></pre>\n\n<p>By default once the end of the <code>main</code> is reached a <code>0</code> return code is returned from the application, so this code is not needed.</p></li>\n<li><p>Not passing the exception cause</p>\n\n<pre><code>throw new SQLException(\"Can not create CallableStatement for sql \");\n</code></pre>\n\n<p>When you wrap a caught exception with a new exception like in this case you should pass the caught exception into the new exception's constructor, otherwise you are loosing the actual cause of the exception.</p></li>\n<li><p>Closing of JDBC objects not inside a <code>finally</code> block</p>\n\n<pre><code>rs = getReportRecords(cstmt,reportType);\nwhile (rs.next()) {\n str = new String[6];\n for (int i = 0; i < 6; i++) {\n str[i] = rs.getString(i + 1);\n }\n vecDetails.addElement(str);\n}\nif (rs != null)\n rs.close();\nif (stmt != null)\n stmt.close();\n</code></pre>\n\n<p>Your code does not guarantee that the ResultSet and the Statement objects will be always closed. <code>close</code> methods should be called from <code>finally</code> blocks.</p></li>\n<li><p><code>Vector</code> instead of <code>ArrayList</code></p>\n\n<p><code>ArrayList</code> should be preferred over <code>Vector</code> in non-multithreaded code.</p></li>\n<li><p>Generics are not used</p></li>\n<li><p>Unnecessary casting</p>\n\n<pre><code>String str[] = (String[]) null;\n</code></pre></li>\n<li><p>Magic numbers</p>\n\n<pre><code>str = new String[6];\n</code></pre>\n\n<p>Usage of hardcoded magic numbers should be reduced as much as possible, in cases when it is not possible they should be defined as <code>final static</code> and given a meaningful name.</p></li>\n<li><p>Catching of <code>NullPointerException</code></p>\n\n<pre><code>}catch (NullPointerException e) { \n throw new SQLException(errorString+\":\"+e.getMessage());\n}\n</code></pre>\n\n<p>Your code should not be catching an unchecked <code>NullPointerException</code> (indicating a programming error) and throw a check <code>SQLException</code> (indicating a database problem).</p></li>\n</ol>\n\n<hr>\n\n<p>This is not a complete list, I think only when these few problems are fixed we can start working on the design of this application.</p>\n\n<p>You can use one of the tools such as:</p>\n\n<ul>\n<li>findbugs</li>\n<li>PMD</li>\n<li>checkstyle</li>\n</ul>\n\n<p>to further improve the quality of your code</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:42:13.300",
"Id": "40471",
"Score": "0",
"body": "Could you please explian me what do you mean by eating up exception i am printing stacktrace of it do you mean that i am throwing it to higher level"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T13:07:14.123",
"Id": "40472",
"Score": "0",
"body": "Yes, sometimes it is allowed, when your application is prepared to get an exception and recover from it, but in case of this application, I think if there is an exception you should not continue exception but throw it up and fail."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T13:37:32.940",
"Id": "40473",
"Score": "0",
"body": "HI Adam, I have made most of changes could you please look into this from desgin perspective"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:30:11.960",
"Id": "26150",
"ParentId": "26143",
"Score": "3"
}
},
{
"body": "<p>Adam already did a pretty good job, but here are some other comments:</p>\n\n<p>1) the <code>ResultSet</code>s are cached in <code>resultSetVector</code>. That could lead to a very serious memory leak. I must admit I have not read and understood everything, but it seems very strange to cache <code>ResultSet</code>s.</p>\n\n<p>2) Not using generics and using Vector's does look antiquated. However, this code might have been intended to be threadsafe and some of the Vector's might not be replaceable by List's. If RConnection was meant to be threasafe, it needs a look more work because it far from threadsafe, despite the Vector's and <code>lockObject</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T07:04:22.610",
"Id": "40532",
"Score": "0",
"body": "Could you please explain me more on \"the ResultSets are cached in resultSetVector. That could lead to a very serious memory leak\" i am not caching it please explain. I have one more question here if i have to add one more report type and lets procedure and csv writing would be different for that how could this be handled"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T13:47:41.660",
"Id": "40551",
"Score": "0",
"body": "Could you please explain"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:03:03.360",
"Id": "40616",
"Score": "0",
"body": "Everytime RConnection.getResultSet() is called, the ResultSet is returned, but it is also cached in RConnection.resultSetVector. The cached ResultSet's are only closed when RConnection.close() is called. It might be better to let the users close the ResultSet themselves. Also, I'm not sure what happens if the user closes the ResultSet and it is closed again in RConnection.close()."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:14:11.903",
"Id": "40620",
"Score": "0",
"body": "I'm not completely sure I understood your last question, but it seems different sub-classes of ReportsInterface are handled correctly with `clazzName`, as long as your resource file (BUNDLE) is configured properly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:16:12.687",
"Id": "40633",
"Score": "0",
"body": "Tow things toto 1) as you set results are cachedin RConnection.resultSetVector then how can use this cache 2) your right its all about different sublasses of reportinterface but i want to design CSVwriter to be more generic could you help on this"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:43:41.553",
"Id": "26175",
"ParentId": "26143",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T10:28:35.197",
"Id": "26143",
"Score": "1",
"Tags": [
"java",
"optimization",
"performance",
"design-patterns"
],
"Title": "Email report generation from database"
}
|
26143
|
<p>I have made this function that should take a set of price data and calculate a set of monthly returns. The idea is that is should be able to cope with irregular time intervals.
For example I have daily data for the S&P 500 but many hedge funds only release price data monthly.</p>
<p>Here is what I have come up with:</p>
<pre><code>//Turns a price series into an array of monthly returns.
function monthlyReturns($dates, $prices, $startDate = "", $endDate = ""){
if ($endDate == "") $endDate = time();
if (count($dates) != count($prices)){
die("The dates array must be the same length as the prices array");
}
$i = 0; $firstPass = false;
foreach ($dates as $date){
$d = strtotime($date);
if ($startDate == "" || ($d >= $startDate && $d <= $endDate )) :
$p = $prices[$i];
$month = date('M',$d);
$year = date('Y',$d);
if ($i == 0 || $firstPass == false){
$startPrice = $p;
$lastMonth = $month;
}
if ($month != $lastMonth && $i != 0){
$returnTable['date'][] = $dates[$i-1];
$returnTable['return'][] = $p / $startPrice - 1;
$startPrice = $p;
}
$lastMonth = $month;
$firstPass = true;
endif;
$i++;
}
return $returnTable;
}
</code></pre>
<p>I noticed that for a fund with only monthly data the returns are off by a month. Can anyone see any major flaws with this function that could explain this or a solution to solve it.</p>
<p>For info, the monthly returns for hedge funds often come near the end of the month. E.g.</p>
<pre><code>date | Price
-----------------
2013-01-29 | 25.69
2013-02-28 | 27.62
2013-03-30 | 26.53
2013-04-29 | 28.45
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:25:09.317",
"Id": "40467",
"Score": "0",
"body": "So `$dates` is sorted and you are actually only interested in the price at the last date of a month to calculate the return?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:28:36.127",
"Id": "40469",
"Score": "0",
"body": "yes, exactly. The `$dates` and `$prices` arrays are in ascending chronological order."
}
] |
[
{
"body": "<p>If there are now performance constraint I always prefere a readable solution over a compact one. So I would go with the following: (assuming <code>$prices</code> is sorted and there are no gaps in the months)</p>\n\n<pre><code><?\ndate_default_timezone_set('Europe/Berlin');\n\n//Put the data into a assoc array. If necessary I would maybe create a separate\n//method to create this input or put it also to extractMonthlyFinalPrice()\n$prices=array(); \n$prices['2013-01-29']='25.69';\n$prices['2013-02-28']='27.62';\n$prices['2013-03-02']='13.53';\n$prices['2013-03-07']='16.53';\n$prices['2013-03-30']='26.53';\n$prices['2013-03-30']='26.53';\n$prices['2013-04-29']='28.45';\n\n$monthlyFinalPrice=extractMonthlyFinalPrice($prices);\n/*\narray(4) {\n [\"2013-01\"]=> string(5) \"25.69\"\n [\"2013-02\"]=> string(5) \"27.62\"\n [\"2013-03\"]=> string(5) \"26.53\"\n [\"2013-04\"]=> string(5) \"28.45\"\n}\n*/\n\n$monthlyReturns=calculateMonthlyReturn($monthlyFinalPrice,new DateTime(\"2013-02\"));\n/*\narray(3) {\n [\"2013-02\"]=> float(1.93) //with '2013-01' as start\n [\"2013-03\"]=> float(-1.09)\n [\"2013-04\"]=> float(1.92)\n*/\n\nfunction extractMonthlyFinalPrice($prices)\n{\n $monthlyPrice=array();\n foreach ($prices as $date=>$price)\n {\n $month=substr($date,0,7);\n $monthlyPrice[$month]=$price; // just overwrite existing value and use the last\n }\n return $monthlyPrice;\n}\n\n//Be careful with timestamps. Think about using DateTime.\nfunction calculateMonthlyReturn($monthlyFinalPrice, DateTime $startDate=null, DateTime $endDate=null)\n{\n if ($endDate==null) $endDate=new DateTime();\n $monthlyReturns=array();\n $lastMonthPrice=null;\n foreach ($monthlyFinalPrice as $month=>$price)\n {\n $date=new DateTime($month);\n $inRange = $date>=$startDate && $date <=$endDate;\n if ($lastMonthPrice!=null && $inRange)\n {\n $monthlyReturns[$month]=$price-$lastMonthPrice;\n }\n //assuming that there are no gaps in the list. \n //Otherwise some date magic is required.\n $lastMonthPrice=$price; \n }\n return $monthlyReturns;\n}\n</code></pre>\n\n<p>As you see, there is no much \"logic\" left. I get rid of a bunch of ifs and could split the bigger problem in two smaller own. Now you could write tests independently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T16:05:32.617",
"Id": "40492",
"Score": "0",
"body": "Brilliant answer. Took me a bit of time to integrate into my code but it seems to work well. Many thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:27:50.003",
"Id": "40504",
"Score": "0",
"body": "This was just a starting point for discussion... :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:31:02.610",
"Id": "40505",
"Score": "0",
"body": "e.g. you could add a break in the foreach if you are beyond the end date, to skip the remaining months."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T21:11:59.783",
"Id": "40519",
"Score": "0",
"body": "Yes I made my own additions/changes. One thing that had confused me for a minute was your calculation for return: `$price-$lastMonthPrice` should be `$price / $lastMonthPrice - 1`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T13:14:30.553",
"Id": "26152",
"ParentId": "26146",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26152",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T11:05:49.337",
"Id": "26146",
"Score": "1",
"Tags": [
"php"
],
"Title": "improvements to this php function to calculate monthly returns from a set of price data"
}
|
26146
|
<p>In my project I am using 10-15 SQL queries, for that I have a common <code>class</code> for <strong>database connectivity</strong> and using that I have executed the queries by passing the <code>connection</code>, <code>command</code> and <code>dataReader</code>. </p>
<p>With some reference in SO, I learned that my code is not properly structured. I would like to learn and write high performance code.</p>
<p><strong>DBConnectivity.cs</strong>:</p>
<pre><code>class DBConnectivity
{
public SqlConnection connection = null;
public SqlCommand command = null;
public SqlDataReader dataReader = null;
public string connectionString = null;
public List<MasterTableAttributes> masterTableList;
public DBConnectivity()
{
connectionString = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
connection = new SqlConnection(connectionString.ToString());
//-----Master table results
connection.Open();
string masterSelectQuery = "SELECT * FROM MASTER_TABLE";
command = new SqlCommand(masterSelectQuery, connection);
dataReader = command.ExecuteReader();
masterTableList = new List<MasterTableAttributes>();
while (dataReader.Read())
{
MasterTableAttributes masterTableAttribute = new MasterTableAttributes()
{
fileId = Convert.ToInt32(dataReader["Id"]),
fileName = Convert.ToString(dataReader["FileName"]),
frequency = Convert.ToString(dataReader["Frequency"]),
scheduledTime = Convert.ToString(dataReader["Scheduled_Time"])
};
masterTableList.Add(masterTableAttribute);
}
dataReader.Close();
connection.Close();
}
}
</code></pre>
<p><strong>Program.cs</strong>:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
DBConnectivity dbConnectivity = new DBConnectivity();
Transaction txnObj = new Transaction(dbConnectivity); //Query1
Sales saleObj = new Sales (dbConnectivity);//Query2
}
}
</code></pre>
<p><strong>Transaction.cs</strong>:</p>
<pre><code>class Transaction
{
public Transaction(DBConnectivity dbConnectivity)
{
dbConnectivity.connection.Open();
string txnQuery = "SELECT ...";
dbConnectivity.command = new SqlCommand(txnQuery, dbConnectivity.connection);
dbConnectivity.dataReader = dbConnectivity.command.ExecuteReader();
while (dbConnectivity.dataReader.Read())
{
...
}
dbConnectivity.dataReder.close();
dbConnectivity.connection.Close();
}
}
</code></pre>
<p><strong>Sales.cs</strong>:</p>
<pre><code>class Sales
{
public Sales(DBConnectivity dbConnectivity)
{
dbConnectivity.connection.Open();
string salesQuery = "SELECT ...";
dbConnectivity.command = new SqlCommand(salesQuery, dbConnectivity.connection);
dbConnectivity.dataReader = dbConnectivity.command.ExecuteReader();
while (dbConnectivity.dataReader.Read())
{
...
}
dbConnectivity.dataReder.close();
dbConnectivity.connection.Close();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>The reader/command/connection fields of <code>DBConnectivity</code> are not really being used to represent state of <code>DBConnectivity</code>. This is obvious because of usage like:</p>\n\n<pre><code>dbConnectivity.command = new SqlCommand(salesQuery, dbConnectivity.connection);\ndbConnectivity.dataReader = dbConnectivity.command.ExecuteReader();\nwhile (dbConnectivity.dataReader.Read()) {...}\n</code></pre>\n\n<p>frankly, they should just be local variables:</p>\n\n<pre><code>var command = new SqlCommand(salesQuery, connection);\nvar dataReader = dbConnectivity.command.ExecuteReader();\nwhile (dataReader.Read()) {...}\n</code></pre>\n\n<hr>\n\n<p>Additionally, in all uses, you are not correctly disposing your resources. The <code>IDisposable</code> contract is important: if something is <code>IDisposable</code>, then it is <strong>your job</strong> to make sure it gets disposed when done. So with the above example:</p>\n\n<pre><code>using(var command = new SqlCommand(salesQuery, connection))\nusing(var dataReader = dbConnectivity.command.ExecuteReader())\n{\n while (dataReader.Read()) {...}\n}\n</code></pre>\n\n<p>This <code>using</code> makes a <strong>huge</strong> difference, and ensures you don't drop connections etc on the floor when exceptions happen.</p>\n\n<hr>\n\n<p>Personally, I would not advocate doing this type of work <em>in a constructor</em> - that is not intuitive. A <code>static</code> method that returns a populated instance, sure - or an instance method that populates an existing instance. But a constructor? not so clear.</p>\n\n<hr>\n\n<p>I also suspect that you could benefit from the use of tooling to avoid boiler-plate code that is error-prone and not important to your actual work. For example, tools like dapper allow much simpler object population. For example:</p>\n\n<pre><code>public class DBConnectivity\n{\n private readonly string connectionString;\n public DBConnectivity(string connectionString = null)\n {\n if(string.IsNullOrEmpty(connectionString))\n {\n connectionString = ConfigurationManager.ConnectionStrings[\"Master\"].ConnectionString;\n }\n this.connectionString = connectionString;\n }\n public SqlConnection OpenConnection() {\n var conn = new SqlConnection(connectionString);\n conn.Open();\n return conn;\n }\n public List<MasterTableAttributes> GetMasterTableList()\n {\n using(var connection = OpenConnection())\n {\n const string sql = \"SELECT Id as [FileId], FileName, Frequency, Scheduled_Time as [ScheduledTime] FROM MASTER_TABLE\";\n return connection.Query<MasterTableAttributes>(sql).ToList();\n }\n }\n}\n</code></pre>\n\n<p>Here the only useful state is the connection string, with a method that creates new connections. Note how this is used with <code>using</code> to create <strong>and dispose</strong> the connection, with \"dapper\" then taking the load for handling the data.</p>\n\n<p>If you really wanted to pass this around, you can:</p>\n\n<pre><code> public List<SomethingSalesEsque> SomeMethodOnSales(DBConnectivity dbConnectivity)\n { \n using(var conn = dbConnectivity.OpenConnection())\n {\n return conn.Query<SomethingSalesEsque>(someQuery).ToList();\n }\n }\n</code></pre>\n\n<hr>\n\n<p>From your code, I'm <em>guessing</em> you have:</p>\n\n<pre><code>class MasterTableAttributes\n{\n public int fileId;\n public string fileName;\n public string frequency;\n public string scheduledTime;\n}\n</code></pre>\n\n<p>this would preferably be:</p>\n\n<pre><code>class MasterTableAttributes\n{\n public int FileId {get;set;}\n public string FileName {get;set;}\n public string Frequency {get;set;} // maybe an enum?\n public string ScheduledTime {get;set;} // datetime? timespan?\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T09:11:15.410",
"Id": "40540",
"Score": "0",
"body": "I tried using **Dapper.net** tool from **NuGet** package, while debugging I was redirected to a new tab `\"No Source Available\"`. Is there anything I am missing and will this cause any problem further?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T11:32:19.690",
"Id": "40541",
"Score": "0",
"body": "@user1671639 presumably there was an exception: if so - what was the exception message? it is *probably* trying hard to tell you what the problem is. You can see the exception when debugging in the IDE, or by using `catch`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T12:19:38.267",
"Id": "40544",
"Score": "0",
"body": "there is no exception. But when I tried to debug it took to a new tab saying **\"No Source Available\"** where the `stacktrace` message of `SqlMapper.cs` took place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T12:33:46.000",
"Id": "40545",
"Score": "0",
"body": "@user1671639 for it to do that, either there *is* an exception, or you are hitting \"step into\". If the latter: well, don't \"step into\" if there is nothing to step into. If the former: try just hitting the \"play\" button (F5) to see what it says next. Can you clarify what you mean by \"the `stacktrace` message\" ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T14:43:15.727",
"Id": "40557",
"Score": "0",
"body": "Yeah this happens only when I hit \"stepInto\". Sorry that is not `stacktrace` it is **\"Call stack location\"**. Would be helpful If there are tutorials in `dapper.net`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:16:59.057",
"Id": "40561",
"Score": "0",
"body": "@user1671639 there really isn't much more to it than on the homepage: https://code.google.com/p/dapper-dot-net/"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:38:26.530",
"Id": "26151",
"ParentId": "26149",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "26151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T12:16:07.480",
"Id": "26149",
"Score": "4",
"Tags": [
"c#"
],
"Title": "Handling multiple queries in C#"
}
|
26149
|
<p>Just a little thing I made to load 20 random images from imgur. I looked at the way that imgur references images on its site, and I felt like I could probably generate a random string of letters and numbers that would, on occasion, produce a valid image URL. So I threw this together in PHP, because I am trying to learn PHP. It takes a while to get the 20 that it does, way longer for more. I would like to speed it up, and my current project in PHP is to learn more about classes etc, but I really have no idea where to start.</p>
<p>I would love some feedback! I know this looks real amateur hour, but I am a real amateur, so go easy on me!</p>
<p>BEWARE: not everything on imgur is worksafe, so if you decide to try this code out on your own server, the images returned are truly random with no filter, so no telling what you might see.</p>
<pre><code><html>
<head>
<title>Random imgur Loader</title>
<style type='text/css'>
#bg {
position:fixed;
top:-50%;
left:-50%;
width:200%;
height:200%;
z-index: -10;
}
#bg img {
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
margin:auto;
min-width:50%;
min-height:50%;
z-index: -10;
opacity: 0.4;
}
#container {
width: 760px;
margin: 0 auto;
}
.imgcell {
border: 1px solid black;
}
</style>
</head>
<body>
<div id='container' style='text-align: center;'>
<?php
$gcode1=generateCode(5);
$url3="http://i.imgur.com/".$gcode1.".jpg";
?>
<div id="bg">
<img src="<?=$url3?>" alt="">
</div>
<?php
$pagepath=$_SERVER["PHP_SELF"];
if ($_GET['numimg']=='') {
$numimg=20;
} else {
$numimg=$_GET['numimg'];
}
?>
<h1 style='font-family: verdana;'><?=$numimg?> random imgur images</h1>
<table border=0><tr>
<?php
function generateCode($length=6) {
$source='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$code='';
for ($i=0; $i<$length; $i++) {
$code .= $source[(rand() % strlen($source))];
}
return $code;
}
$ii=1;
while ($ii<=$numimg):
$gcode=generateCode(5);
$url="http://i.imgur.com/".$gcode.".jpg";
$url2="http://www.imgur.com/".$gcode;
$headerfile=get_headers($url2, 1);
$http_code=$headerfile[1];
$imgheader=get_headers($url, 1);
$imgcode=$imgheader["Content-Type"];
#echo $imgcode;
if ($imgcode == 'image/gif') {
$bcode='red';
} else {
$bcode='gray';
}
if($http_code!="HTTP/1.1 404 Not Found") {
print("<td style='border: 2px solid $bcode' ><a target='_blank' href='$url2'><img title='$imgcode' width='160px' height='160px' src='$url'></a><td>");
echo(str_repeat(' ',4096));
if ($ii % 5 == 0) {
print("</tr><tr>");
}
flush();
$ii++;
}
endwhile;
?>
</tr></table>
<?php print("<p><a href='$pagepath'>Get $numimg more!</a></p>");?>
</div>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T16:07:43.513",
"Id": "40493",
"Score": "0",
"body": "First of all I'd separate my php from the HTML. Create class of functions and call them on the HTML like `myclass::myfunction(arguments)` or similar. See [Model-View-Controller](http://c2.com/cgi/wiki?ModelViewController)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:01:05.973",
"Id": "40507",
"Score": "0",
"body": "There's no way to _really_ speed this up, since it's essentially random. It might be really fast the next time you run it or it might run forever (unlikely, but possible). You _could_ spawn off several processes and check multiple urls in parallel, but since it's still random, there's no guarantee it'll actually find _n_ images faster. By all means try refactoring it, see what other here say, and learn what you can (I'm all for that), but \"using classes\" is not a silver bullet in this case - the general approach is just slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T20:57:47.280",
"Id": "40517",
"Score": "0",
"body": "@Flambino Yeah it averages about 1.2 failures for every image it does find. That average goes up exponentially the longer I make the generated string length, some have 5, 6, 7 or more. I guess it takes longer on the longer strings because there might be fewer of those, plus a longer string means another power more possibilities. Pretty cool little proof of concept I guess, just looks ugly to me. I'm going to work on trimming it up a bit. Thanks for the input!"
}
] |
[
{
"body": "<p>Definitely separate your PHP from HTML as Alex suggested. You probably don't need to go the full <a href=\"http://phpmaster.com/the-mvc-pattern-and-php-1/\" rel=\"nofollow\">MVC route</a> for something so simple, but simply generating your PHP variables <em>then</em> outputing your HTML would make your code a lot more readable/manageable. </p>\n\n<p>I like your idea of generating a random string and checking it, but Flambino's right, it will never be reliable (by design) - also, imgur probably hates you ;) A simpler approach would be to consume imgur's RSS feed: <a href=\"http://feeds.feedburner.com/ImgurGallery?format=rss\" rel=\"nofollow\">http://feeds.feedburner.com/ImgurGallery?format=rss</a></p>\n\n<p>I was bored one morning, so I added something similar to the login page of one of my projects. It pulls one random image from lolcats' RSS feed and inserts it into the page. Here's the code that pulls the image:</p>\n\n<pre><code>$feed = $this->get('feed_parser'); // This is just a SimplePie object\n$feed->set_feed_url('http://feeds.feedburner.com/lolcats/rss');\n$feed->init();\n$items = $feed->get_items();\n$item = $items[array_rand($items)]; // Gets one random image, but can modify for more\n$item = $item->get_content();\n</code></pre>\n\n<p>$this->get('feed_parser') is just a fancy way of getting a <a href=\"http://simplepie.org/\" rel=\"nofollow\">SimplePie</a> object from the <a href=\"http://pimple.sensiolabs.org\" rel=\"nofollow\">PIMPLE</a> container - you could just instantiate a SimplePie object yourself (<a href=\"http://misko.hevery.com/2008/07/30/top-10-things-which-make-your-code-hard-to-test/\" rel=\"nofollow\">if you want code you can't test</a>). After running this code, $item would be a PHP array (or some collection class) containing the details of one image. In my case, I then exposed this as JSON and a REST API endpoint for use by JavaScript, but you could just as easily have PHP output the appropriate HTML.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T08:39:49.387",
"Id": "40538",
"Score": "1",
"body": "Apparently, imgur has [a proper API](http://api.imgur.com/), which might be easier than parsing the rss feed. It even has [\"random images\" endpoint](http://api.imgur.com/endpoints/gallery#gallery-random)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T17:26:09.410",
"Id": "40651",
"Score": "0",
"body": "Ah I didn't even think about the fact that I was not being a very good netizen by hammering imgur :( Yeah their RSS feed might be more apporpriate. Also, their API has a random images endpoint?! wtf, well at least I learned some PHP in the process haha"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:22:40.903",
"Id": "40677",
"Score": "0",
"body": "Good find Flambino! I'd definitely use their API."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T02:51:45.390",
"Id": "26185",
"ParentId": "26153",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26185",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:01:30.850",
"Id": "26153",
"Score": "2",
"Tags": [
"php",
"beginner",
"html",
"random",
"image"
],
"Title": "Random imgur image loader"
}
|
26153
|
<p>I know that this is a complete mess and does not even come close to fitting PEP8. That's why I'm posting it here. I need help making it better.</p>
<pre><code>bookName = None
authorName = None
bookStartLine = None
bookEndLine = None
def New_book(object):
def __init__(self, currentBookName, currentAuthorName, currentBookStartLine, currentBookEndLine):
self.currentBookName = currentBookName
self.currentAuthorName = currentAuthorName
self.currentBookStartLine = currentBookStartLine
self.currentBookEndLine = currentBookEndLine
import urllib.request
def parser(currentUrl): #parses texts to extract their title, author, begginning line and end line
global bookName
global authorName
global bookStartLine
global bookEndLine
global url
url = 'http://www.gutenberg.org/cache/epub/1232/pg1232.txt' #machiaveli
url = currentUrl
book = urllib.request.urlopen(url)
lines = book.readlines()
book.close()
finalLines = [line.decode()[:-2] for line in lines]
for line in finalLines:
if "Title" in line:
currentBookName = line[7:len(line)]
break
for line in finalLines:
if "Author" in line:
currentAuthorName = line[8:len(line)]
break
currentBookStartLine,currentBookEndLine = False,False
for index,line in enumerate(line,start=1):
if "*** START OF THE PROJECT" in line:
currentBookStartLine = index
if "*** END OF THE PROJECT" in line:
currentBookEndLine = index
url = currentUrl
bookName = currentBookName
authorName = currentAuthorName
bookStartLine = currentBookStartLine
bookEndLine = currentBookEndLine
parser('http://www.gutenberg.org/cache/epub/768/pg768.txt') #wuthering heights
print(url)
print(bookName)
print(authorName)
print(bookStartLine)
print(bookEndLine)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T16:02:09.083",
"Id": "40490",
"Score": "0",
"body": "`I know that this is a complete mess`. If you know something is a complete mess I'm sure you have a reason to think so. Focus on the why and try to change it."
}
] |
[
{
"body": "<ul>\n<li>No need for a New_Book class with something so simple – I recommend a <a href=\"http://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow\">named tuple</a> instead.</li>\n<li>HTTPResponse objects don't seem to have a readlines() method (in Python 3) – this forces you to explicitly split the response data with '\\r\\n'.</li>\n<li>It's best to use the with-statement for file/resource operations. This is a CYA in case you forget to include resource.close() in your code.</li>\n</ul>\n\n<p>Here's my refactor:</p>\n\n<pre><code>from urllib.request import urlopen\nimport collections\n\ndef parser(url): \n '''parses texts to extract their title, author, begginning line and end line'''\n\n with urlopen(url) as res:\n lines = res.read().decode('utf-8').split('\\r\\n')\n\n title = next(line[7:] for line in lines if line.startswith(\"Title: \"))\n author = next(line[8:] for line in lines if line.startswith(\"Author: \"))\n start,end = False,False\n\n for index,line in enumerate(lines,start=1):\n if line.startswith(\"*** START OF THIS PROJECT\"):\n start = index\n\n if line.startswith(\"*** END OF THIS PROJECT\"):\n end = index - 1\n\n content = \"\".join(lines[start:end])\n\n return collections.namedtuple('Book', ['title', 'author', 'content', 'start', 'end'])(title, author, content, start, end)\n\nbook = parser('http://www.gutenberg.org/cache/epub/1232/pg1232.txt' ) #machiaveli <3\nprint(\"{} by {}. {} lines\".format(book.title,book.author,book.end-book.start))\n#print(book.content)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T07:10:25.377",
"Id": "26197",
"ParentId": "26155",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T14:27:03.410",
"Id": "26155",
"Score": "2",
"Tags": [
"python",
"beginner",
"parsing"
],
"Title": "New book parser"
}
|
26155
|
<p>I just posted a small open source CFML project <a href="https://github.com/jetendo/db-dot-cfc" rel="nofollow noreferrer">here</a>
db.cfc is a standalone CFC with <strike>472</strike> lines of code.</p>
<p>Here is the execute function in db.cfc. This is just a partial example pulled from the 400+ lines of the code in db.cfc. If you have any suggestions for the rest of the CFC, feel free to post them.</p>
<p>This code is currently optimized for speed so that it is not much slower than a regular <code><cfquery></code>. The project doesn't have any unit tests yet.</p>
<pre><code><cffunction name="execute" returntype="any" output="no">
<cfargument name="name" type="variablename" required="yes" hint="A variable name for the resulting query object. Helps to identify query when debugging.">
<cfscript>
var queryStruct={
lazy=this.lazy,
datasource=this.datasource
};
var pos=0;
var processedSQL="";
var startIndex=1;
var curArg=1;
var running=true;
var db=structnew();
var cfquery=0;
var k=0;
var i=0;
var s=0;
var paramCount=arraylen(variables.arrParam);
if(this.dbtype NEQ "" and this.dbtype NEQ "datasource"){
queryStruct.dbtype=this.dbtype;
structdelete(queryStruct, 'datasource');
}else if(isBoolean(queryStruct.datasource)){
this.throwError("db.datasource must be set before running db.execute() by either using db.table() or db.datasource=""myDatasource"";");
}
if(not isBoolean(this.cachedWithin)){
queryStruct.cachedWithin=this.cachedWithin;
}
queryStruct.name="db."&arguments.name;
if(len(this.sql) EQ 0){
this.throwError("The sql statement must be set before running db.execute();");
}
if(this.verifyQueriesEnabled){
if(compare(this.sql, variables.lastSQL) NEQ 0){
variables.lastSQL=this.sql;
variables.verifySQLParamsAreSecure(this.sql);
processedSQL=replacenocase(this.sql,variables.trustSQLString,"","all");
processedSQL=variables.parseSQL(processedSQL, this.datasource);
}else{
processedSQL=replacenocase(replacenocase(this.sql,variables.trustSQLString,"","all"), variables.tableSQLString, "","all");
}
}else{
processedSQL=this.sql;
}
if(this.disableQueryLog EQ false){
ArrayAppend(this.arrQueryLog, processedSQL);
}
</cfscript>
<cftry>
<cfif paramCount>
<cfquery attributeCollection="#queryStruct#"><cfloop condition="#running#"><cfscript>
pos=find("?", processedSQL, startIndex);
</cfscript><cfif pos EQ 0><cfset running=false><cfelse><cfset s=mid(processedSQL, startIndex, pos-startIndex)>#preserveSingleQuotes(s)#<cfqueryparam attributeCollection="#variables.arrParam[curArg]#"><cfscript>
startIndex=pos+1;
curArg++;
</cfscript></cfif></cfloop><cfscript>
if(paramCount GT curArg-1){
this.throwError("db.execute failed: There were more parameters then question marks in the current sql statement. You must run db.execute() before building any additional sql statements with the same db object. If you need to build multiple queries before running execute, you must use a copy of db, such as db2=duplicate(db);<br /><br />SQL Statement:<br />"&processedSQL);
}
s=mid(processedSQL, startIndex, len(processedSQL)-(startIndex-1));
</cfscript>#preserveSingleQuotes(s)#</cfquery>
<cfelse>
<cfquery attributeCollection="#queryStruct#">#preserveSingleQuotes(processedSQL)#</cfquery>
</cfif>
<cfcatch type="database">
<cfscript>
if(this.autoReset){
structappend(this, this.config, true);
}
variables.arrParam=[]; // has to be created separately to ensure it is a separate object
</cfscript>
<cfif left(trim(processedSQL), 7) NEQ "INSERT "><cfrethrow></cfif>
<cfscript>
if(this.disableQueryLog EQ false){
ArrayAppend(this.arrQueryLog, "Query ##"& ArrayLen(this.arrQueryLog)&" failed to execute for datasource, "&this.datasource&".<br />CFcatch.message: "&CFcatch.message&"<br />cfcatch.detail: "&cfcatch.detail);
}
</cfscript>
<!--- return false when INSERT fails, because we assume this is a duplicate key error. --->
<cfreturn false>
</cfcatch>
<cfcatch type="any"><cfscript>
if(paramCount and curArg GT paramCount){
this.throwError("db.execute failed: There were more question marks then parameters in the current sql statement. You must use db.param() to specify parameters. A literal question mark is not allowed.<br /><br />SQL Statement:<br />"&processedSQL);
}
</cfscript><cfrethrow></cfcatch>
</cftry>
<cfscript>
if(this.autoReset){
structappend(this, this.config, true);
}
variables.arrParam=[]; // has to be created separately to ensure it is a separate object
</cfscript>
<cfif structkeyexists(db, arguments.name)>
<cfreturn db[arguments.name]>
<cfelse>
<cfreturn true>
</cfif>
</cffunction>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T17:00:39.417",
"Id": "40494",
"Score": "0",
"body": "I prefer `NOT len(trim(this.dbtype))` over `this.dbtype NEQ \"\"`, but looks good other than that imo"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T15:16:07.537",
"Id": "40641",
"Score": "0",
"body": "Bruce, what I would say is this function is way too long. If you look at breaking that down into smaller private functions that will be way more readable and testable."
}
] |
[
{
"body": "<p>Points:</p>\n\n<ul>\n<li>I agree with @baynezy. The function is doing too much. What are your\nunit tests like for this they must be a nightmare? (I just noticed you said you don't have any unit tests yet. Write the tests FIRST. You are doing yourself and your clients a disservice by writing code like this without tests. It's professionally irresponsible for you to release untested code).</li>\n<li>I've seen the CFC this comes out of, and you seem to be overusing/misusing the <code>this</code> scope. I'm fairly certain you generally should be using the <code>variables</code> scope for a lot of this?</li>\n<li>why have you written a UDF for <code>throwError()</code>? CFML already has this function built in</li>\n<li>when throwing an exception, you should be specifying an exception type, so calling code and then deal with said exception. Thrown exceptions are not for the human reader (ie: as indicated by your overly-long error messages), they're intended for the calling code.</li>\n<li>why do you switch to <code><cfscript></code> for a simple <code>if</code> & <code>throw</code> statement? You have a lot of very small <code>CFScript</code> blocks for seemingly no reason. It makes the code harder to read & bloated to be switching back and forth between tags and script.</li>\n<li>your <code>k</code>, <code>i</code> and <code>s</code> variables could probably stand having more descriptive names.</li>\n<li>returning a mix of boolean or result value is a bit grim.</li>\n<li>have you checked the thread safety of this method, given you're writing back to the CFC's <code>this</code> and <code>variables</code> scopes (I've seen the CFC, but have not <em>studied</em> it ;-)</li>\n<li>returning <code>FALSE</code> when an <code>INSERT</code> fails is bad. Either bubble the error back, or raise your own one (I'd do the former).</li>\n</ul>\n\n<p>I haven't checked your actual logic yet, but those were my initial observations from just glancing over the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T02:41:14.160",
"Id": "40970",
"Score": "0",
"body": "throwError appends message which says the error is outside of db.execute, not inside. I try to help myself and others avoid having to read my framework code by explaining the error with how they are using it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T02:44:23.343",
"Id": "40971",
"Score": "0",
"body": "thread safety: Only 1 query can be created and executed at a time with a single instance of this cfc. If you need to build 2 queries before executing, you'd need a duplicate of the cfc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T03:04:32.287",
"Id": "40972",
"Score": "0",
"body": "Maybe I should use db.select, db.insert, etc instead of db.execute to make the return type consistent. Obviously you can't get a query result from an insert statement. I forgot to document the return type. \"this\" usage is to make those values easy to set from the outside. The example code tests the features, it's just not mxunit style yet. Thanks Adam. Hope you feel better soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T03:46:40.820",
"Id": "41062",
"Score": "0",
"body": "I spent many hours rewriting the project based on advice and other ideas. There are 2 cfcs now, so that one is threadsafe/cacheable (a global factory) and the other is smaller and used to build/execute queries for individual requests. The way you write queries is mostly the same aside from changing it to have more functions and variables scope instead of this scope. I also used access=\"package\" to reduce the amount of public methods. Try running example.cfc?method=index to understand how clean the public interface is. Super time consuming to refactor and still keep it fast."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T14:19:03.963",
"Id": "42213",
"Score": "0",
"body": "I'd say you're doing something wrong if you need to worry about code-execution overhead in functions which hit external resources like DBs. Especially for the logic requirements here, which are inconsequential. I have a suspicion you try to overcomplicate things which in turn leading to you needing to try to speed things up, rather than just KISS in the first place.\n\nIf I were you I'd focus on writing clean maintainable (and testable) code - none of which you are doing at the moment, based on the above - rather than whether it runs in 5ms or 4ms."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T01:33:49.600",
"Id": "26398",
"ParentId": "26156",
"Score": "3"
}
},
{
"body": "<p>Some more feedback:</p>\n\n<ul>\n<li>I'm not a fan of having variables called things like 'name' or 'cfquery', too generic and also you run the risk of using reserved words with this approach.</li>\n<li>You have exactly 2 comments for nearly 100 lines of code... I prefer more comments, especially for something slightly complex</li>\n<li><p>You define this struct, but you don't add anything to it:</p>\n\n<pre><code>var db=structnew();\n</code></pre>\n\n<p>then at the end you check if it has anything in it... but this IF statement is completely redundant, you'll always return true</p>\n\n<pre><code><cfif structkeyexists(db, arguments.name)>\n <cfreturn db[arguments.name]>\n <cfelse>\n <cfreturn true>\n </cfif>\n</code></pre></li>\n<li><p>You jump in and out of <code>cfscript</code>, it's messy and unnecessary. You don't really gain anything from stuff like this:</p>\n\n<pre><code><cfloop condition=\"#running#\"><cfscript>\n pos=find(\"?\", processedSQL, startIndex);\n </cfscript>\n</code></pre></li>\n<li><p>You don't use these variables: </p>\n\n<pre><code>var cfquery=0;\nvar k=0;\nvar i=0;\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:24:12.283",
"Id": "43518",
"Score": "0",
"body": "cfquery is defined by <cfquery> when result attribute is not defined - it contains info about the query. I am trying to avoid all unscoped variables because these cause issues with railo debugger & performance. Only queries that return data are defined as the name attribute, so structkeyexists IS required. The db struct was so that the query name can be anything without conflicting with other local variables. The query having a provided name makes debugging easier. coldfusion doesn't support <cfqueryparam> in cfscript. new query() is CFC-based and it is inferior performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:24:53.520",
"Id": "43519",
"Score": "0",
"body": "If I wrote comment about every decision I make in the code, it would be so verbose and confusing if they become inaccurate. Many of my old comments are inaccurate, so I just remove them now, and focus on things like renaming variables or something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:47:49.827",
"Id": "43521",
"Score": "0",
"body": "I understand why you define cfquery, however you then don't use it as a variable... just delete it. If however you DID want to use the query info, you just specify the `result` attribute, so you can use a var-scoped variable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:53:19.270",
"Id": "43522",
"Score": "0",
"body": "In CFScript you can use query.addParam instead of cfqueryparam"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-28T18:54:56.013",
"Id": "43523",
"Score": "0",
"body": "If old comments become inaccurate when you update the comments, update the comments, don't delete them!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-30T04:20:10.477",
"Id": "43590",
"Score": "0",
"body": "while that is true, the whole point of my db.cfc component is to replace new query() & cfquery with a superior custom API, faster performance and security that is enforced through SQL parsing & analysis. I have over 1500 unique queries that are using this component now. It has helped to protect against sql injection vulnerabilities across the entire app because it throws an exception if the sql isn't secure prior to running the query. There are only a handful of cfquery tags in my entire app because all of them were replaced with this component. The code for using this component is simpler."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-27T17:41:01.210",
"Id": "27855",
"ParentId": "26156",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26398",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T15:44:57.697",
"Id": "26156",
"Score": "2",
"Tags": [
"performance",
"coldfusion",
"cfml"
],
"Title": "Open source CFML database project"
}
|
26156
|
<p>I have just written an API framework which I am hoping to implement into one of my large sites very soon. However, before I do so, I want to be sure that the script is well written and there are no obvious mistakes that I have missed.</p>
<p>As with most projects, the key here is automation and speed... I have tried to automate as much as possible whilst also keeping expensive code to a minimum.</p>
<p>These are a few sample requests that one could fire at this API:</p>
<pre><code>// Return the logged in users details
http://api.example.net/user/
// Return the registered companies for the logged in user
http://api.example.net/user/companies/
</code></pre>
<p>Where user is the <code>$object</code> on both and 'default' is the <code>$request</code> on the first and 'companies' is the <code>$request</code> on the second...</p>
<p>The data is then retrieved based on the <code>$request</code> on the <code>$object</code>... Make sense? :-) I hope so, here is my code:</p>
<pre><code><?php
// +------------------------------------------------------------------------+
// | api.php |
// +------------------------------------------------------------------------+
// | Copyright (c) Example Ltd 2012. All rights reserved. |
// | Version 1.0 |
// | Last modified 14/05/2013 |
// | Email dev@example.net |
// | Web https://api.example.net |
// +------------------------------------------------------------------------+
/*
* Example API
*
* @version 1.0
* @author Ben Carey <ben.carey@example.net>
* @copyright Example Ltd
*
*/
// Guidelines for creating and adding a working method
// 1. All functions must have $parameters=array() as their only parameter
// 2. All must return some sort of data
// 3. Set the $example->json_constants if you need to specify anything about the JSON output
// 4. Any errors place into $example->error (string) and return
// Once the method has been created, you can proceed to adding it to the API
// 1. Work out what address you want e.g. api.example.net/user/companies
// -> This example will translate to the domain api.example.net/api.php?object=user&request=companies
// 2. If the object has a corresponding class and the class does not already exist in the defined list then add it
// 3. If the object does not have a corresponding class, it is an alias so add it (if not already there), to the alias array
// and map it to the correct class
// 4. Now you need to map the request to the method. If there is no request set (e.g. /user instead of /user/companies) then the request
// is treated as 'default'. You can then specify in the $api_methods array $object -> $request -> $method
// Define the allowed domains,
// this will prevent other sites from being able to
// access the API via AJAX
$allowed_domains = array('http://beta.example.net','https://beta.example.net');
// Test if the domain is allowed to connect
if(isset($_SERVER['HTTP_ORIGIN'])&&in_array($_SERVER['HTTP_ORIGIN'],$allowed_domains)){
// Allow access to the current domain
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
}
// Include the site configuration
include('C:\Inetpub\vhosts\example.net\subdomains\beta\httpdocs\_snippets\_system\config.php');
// Define the Example Classes
// All of these paths link to the class initiation file,
// in other words, by including them it will include all
// necessary files and create an instance of the class
$classes = array(
'authorized' => $_PATHS['EXAMPLE'].'\_snippets\_classes\class.authorized.php',
'documents' => $_PATHS['EXAMPLE'].'\_snippets\_classes\class.documents.php',
'reports' => $_PATHS['EXAMPLE'].'\_snippets\_classes\class.reports.php',
'settings' => $_PATHS['EXAMPLE'].'\_snippets\_classes\class.settings.php',
);
// Create a map of aliases to classes
// This will allow objects that do not have a matching class but
// but do have a corresponding method in another class
// specified here
$class_aliases = array(
'user' => 'authorized',
'company' => 'authorized'
);
// Gather the relevant methods for the supplied
// request method
switch($_SERVER['REQUEST_METHOD']){
case 'GET':
// Create an array that maps the objects to the
// relevant request and method within the class
$api_methods = array(
'authorized' => array(
'default' => 'get_authorized'
),
'documents' => array(
'sessions' => 'get_active_sessions'
),
'masterfiles' => array(
'items' => 'get_master_file_items',
'properties' => 'get_master_file_properties',
'reference' => 'get_master_file_reference'
),
'user' => array(
'companies' => 'get_registered_companies_for_user'
)
);
// Set the parameters to be passed to the corresponding
// method, this is set depending on the page request method
$parameters = $_GET;
break;
case 'POST':
// Create an array that maps the objects to the
// relevant request and method within the class
$api_methods = array(
'settings' => array(
'user' => 'update_user'
)
);
// Set the parameters to be passed to the corresponding
// method, this is set depending on the page request method
$parameters = $_POST;
break;
}
// The object and request are always supplied via GET
$object = strtolower($_GET['object']);
$request = strtolower($_GET['request']);
// Set the class to include based on the object supplied
if(isset($classes[$object])){
$class = $classes[$object];
}elseif(isset($class_aliases[$object])){
$class = $classes[$class_aliases[$object]];
}else{
$data = array('error' => 'Specified object does not exist');
}
// Set the method to execute based on the request supplied
if(!empty($request)&&isset($api_methods[$object][$request])){
$method = $api_methods[$object][$request];
}elseif(isset($api_methods[$object]['default'])){
$method = $api_methods[$object]['default'];
}else{
$data = array('error' => 'Specified request does not exist');
}
// Only proceed if there are no errors
if(empty($data)){
// If the request is via AJAX then prevent all redirects
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest'){
$prevent_redirect = true;
}
// Include the relevant class
include($class);
// Remove the request and method values from the parameters
unset($parameters['object'],$parameters['request']);
// Execute the relevant method
$data = call_user_func(array($example,$method));
// If there was an error then replace the data variable
$data = !empty($example->error) ? array('error' => $example->error) : $data;
}
echo json_encode($data,$example->json_constants);
?>
</code></pre>
|
[] |
[
{
"body": "<p>Ignoring your code for a second, here's some feedback on the design of your API.</p>\n\n<p>It may be better to simply include the user's companies in the response for the /user endpoint. This would make your code more complex, but API consumers' lives easier.</p>\n\n<p>Obviously removing the /user/companies endpoint eliminates the ability to request ONLY company data for a specific user. If you feel it's important to be able to request this information on its own, then here's two options.</p>\n\n<ol>\n<li>Allow partial responses via GET parameters (i.e. GET /user?fields=companies) or something similar with JSON in the request body.</li>\n<li>Decouple the companies endpoint from the /user endpoint and create a top-level /companies endpoint. Provide a way to query by user ID, and you could get the same data as /user/company</li>\n</ol>\n\n<p>As a final note, if you ever plan on allowing queries for information on users <em>other than</em> the current user, you may want to use a \"me\" placeholder in the endpoint like so: /user/me. If you were to use a modern routing library like <a href=\"http://www.slimframework.com/\" rel=\"nofollow\">Slim</a>, you can easily support queries for the current user <em>and</em> arbitrary users simply by parsing everything after the slash (/) like so:</p>\n\n<pre><code>$app->get('/user/:user_id', function ($user_id) {\n if ('me' == $user_id) {\n // Get the current user\n } else {\n // Get user with ID $user_id\n }\n ...\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T17:42:11.890",
"Id": "40497",
"Score": "0",
"body": "Thank you for your answer. The user and companies are just there for illustrative purposes. This API is for a very large web application so splitting up the requests is absolutely essential as it minimises the number of queries executed by one script, thus improves efficiency of the whole site. As for the user and 'me' placeholder, that is a handy idea that I will definitely implement into some of my other applications but for this it is not really relevant. +1 for your contribution :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T17:12:27.653",
"Id": "26160",
"ParentId": "26157",
"Score": "2"
}
},
{
"body": "<p><strong>tl;dr</strong> . No seriously, your code is really hard to read. I'm not sure if you added some comments only for this question or if it is the a exact copy of your file, but it is to much. Every time you have the feeling that you need a comment do explain your code, think about extracting a variable or a method with a suitable name. Write a method <code>setAccessControlHeader()</code>, <code>loadConfig()</code>, <code>loadMapping()</code>,<code>getClassFromRequest()</code>, <code>getMethodFromRequest()</code>, etc . All this will help you and any other reader of your code to get a first overview of your code without digging into the details how e.g. you mapping is implemented. Anybody who is interested in the details can easily look in the method anyway. The main benefit, beside a more obvious structure, is the easier testability, as you can test every method at it's own.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T06:10:29.970",
"Id": "26195",
"ParentId": "26157",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26160",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T15:50:19.937",
"Id": "26157",
"Score": "0",
"Tags": [
"php",
"api"
],
"Title": "How is this for an API structure"
}
|
26157
|
<p>Please help me restructure this Java code to allow for sometime have 4 items in packagePriceList.</p>
<pre><code>public static HTMLSelectOptionsElement listPremiumPackageTermsWithPrice(String[] packagePriceList, int cyberSourceBillingMode) {
HTMLSelectOptionsElement optionsElement = new HTMLSelectOptionsElement();
// Testing only. Allows for a shorter recurring term for QA testing.
if (cyberSourceBillingMode == DiceUtilConstants.CYBERSOURCE_BILLING_MODE_ICS_WEEKLY_OVERRIDE) {
optionsElement.addOption("1 Week", String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_7_DAYS));
}
optionsElement.addOption("1 Month - " + packagePriceList[0], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_30_DAYS));
optionsElement.addOption("3 Months - " + packagePriceList[1], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_90_DAYS));
optionsElement.addOption("6 Months - " + packagePriceList[2], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_180_DAYS));
optionsElement.addOption("12 Months - " + packagePriceList[3], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_365_DAYS));
return optionsElement;
}
</code></pre>
<p>I thought about just catching the IndexOutOfBoundsException but would that be a bit of a hack?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:16:55.193",
"Id": "40511",
"Score": "0",
"body": "The question is not clear: you'll always get `packagePriceList` of length 4, or sometimes less, sometimes more?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:26:47.260",
"Id": "40512",
"Score": "0",
"body": "Also thought about adding a completely new method or adding a check in the method on the size of packagePriceList."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:28:05.453",
"Id": "40513",
"Score": "0",
"body": "Yes toto2 the packagePriceList sometimes has 3 and sometimes 4. I apologize for the question not being clear."
}
] |
[
{
"body": "<p>First, a simple solution:</p>\n\n<pre><code>optionsElement.addOption(\"1 Month - \" + packagePriceList[0], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_30_DAYS));\noptionsElement.addOption(\"3 Months - \" + packagePriceList[1], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_90_DAYS));\noptionsElement.addOption(\"6 Months - \" + packagePriceList[2], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_180_DAYS));\nif (packagePriceList.length == 4)\n optionsElement.addOption(\"12 Months - \" + packagePriceList[3], String.valueOf(UserPackage.PREMIUM_PACKAGE_TERM_365_DAYS));\n</code></pre>\n\n<p>But I don't like the signature of <code>listPremiumPackageTermsWithPrice(String[] packagePriceList,...)</code>. The problem is that you must implicitly know that the the first element corresponds to 1 month, etc. It would be better to have an argument which is of type <code>Map<PackageTerm, String></code>, where the key of the map is one of <code>UserPackage.PREMIUM_PACKAGE_TERM_XX_DAYS</code> and the value of the map is the same string as before. If your <code>UserPackage.PREMIUM_PACKAGE_TERM_XX_DAYS</code> where actually <code>enum</code>'s, you could use an <code>EnumMap</code>. </p>\n\n<p>Here is the enum I would define:</p>\n\n<pre><code>public enum PackageTerm {\n PREMIUM_PACKAGE_TERM_30_DAYS(\"1 month\"), \n PREMIUM_PACKAGE_TERM_90_DAYS(\"3 months\"), \n PREMIUM_PACKAGE_TERM_180_DAYS(\"6 months\"), \n PREMIUM_PACKAGE_TERM_365_DAYS(\"12 months\");\n\n private String timePeriodString;\n\n private PackageTerm(String timePeriodString) {\n this.timePeriodString = timePeriodString);\n }\n\n public String printedString(String price) {\n return timePeriodString + \" - \" + price;\n }\n}\n</code></pre>\n\n<p>and the method is changed to:</p>\n\n<pre><code>HTMLSelectOptionsElement listPremiumPackageTermsWithPrice(Map<PackageTerm, String> packagesWithPrice, ...) {\n for (PackageTerm packageTerm : PackageTerm.values()) { // in the order 1/3/6/12 months\n String priceIfAny = packagesWithPrice.get(packageTerm); // null if not present\n if (priceIfAny != null)\n optionsElement.addOptions(packageTerm.printedString(priceIfAny), packageTerm.toString());\n // You would need to override PackageTerm.toString(). By default it is the name of the enum.\n }\n}\n</code></pre>\n\n<p>Note that you could put other relevant data and methods within the enum PackageTerm.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T07:53:25.977",
"Id": "40536",
"Score": "0",
"body": "Not coherent number of days PREMIUM_PACKAGE_TERM_30_DAYS(\"6 months\"), PREMIUM_PACKAGE_TERM_30_DAYS(\"12 months\");"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:51:35.743",
"Id": "26176",
"ParentId": "26159",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T16:31:11.987",
"Id": "26159",
"Score": "-1",
"Tags": [
"java"
],
"Title": "Restructure this Java code to allow for sometime have 4 items in packagePriceList"
}
|
26159
|
<p>I'm sort of at a loss for what to do with webapps and whether what I'm doing is actually allowed or not. Here is a sample of the type of thing I'm doing at the moment. I need a list that is accessible by essentially everything.</p>
<pre><code>global_list = []
@bottle.route('/')
def index():
global_list.append(4)
@bottle.route('/test')
def test():
return len(global_list)
@bottle.run(port='8080')
</code></pre>
<p>The problem (or what I think is a problem) is that it feels wrong and I've been told it is unsafe to use a global variable. This code works perfectly fine, but is there a better or safer way to handle this? Even with multiple clients at the same time, the data in the list currently does not get corrupted. What kind of issues am I going to run into if I keep using this?</p>
|
[] |
[
{
"body": "<p>Ah, the age old pragmatism vs. purism. While it sounds like you have a healthy amount of skepticism, I think this is actually one of the few instances where it's OK to use a global variable. The core of your problem is you need to share data (state) between two routes. A global variable is the simplest way of doing this if all you're doing is appending the number 4 each time.</p>\n\n<p>Here's some things to consider:</p>\n\n<ul>\n<li>Security: You mentioned security. Will any sensitive information be stored in global_list? If so, you should consider putting safegards in place (authentication and authorization) to make sure only the right people see the appropriate information. Also, if you store user input to the variable, be very careful how you use the data (SQL injection).</li>\n<li>Persistence: Will state need to be maintained across webserver restarts? If everything is in a Python variable, it will be lost when you shut down the process. You may want to persist the data to a filesystem or database.</li>\n<li>Resources: Are you going to be storing <em>lots</em> of information in this global variable? If so, the process may run out of memory, because the global variable is never garbage collected. The solution here is to store the data somewhere and generate aggregate data to use in the app instead (or do pagination).</li>\n<li>Shared-state side effects: Anytime you share data, you have to be conscious of side effects caused by altering this data. If two routes are reading/writing from the same variable, one route could do something that breaks the other route.</li>\n</ul>\n\n<p>More on resources:</p>\n\n<p>For instance, if you store 1KB every time the / route is loaded and get 1M visitors a month, you'd be up to 1GB of memory just for global_list in around 1 month. 1KB is a lot of data, and you probably don't need all of this information to do your calculation in /test. Instead, you could aggregate the data by using global_list as a running total for the full set of data stored elsewhere (a database or filesystem).</p>\n\n<p>If you're doing more than simply presenting a count of records in /test, and you need whole (or partial) records, then you can do pagination. Let's say you're presenting a list of the records in global_list. In this case, /test could simply return the first 10 records by default, but allow the user to see more pages by providing a <em>page</em> parameter. So if the user wants to see records 31-40, they could request /test?page=4</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T13:53:42.473",
"Id": "40553",
"Score": "0",
"body": "Security: No sensitive Data. Persistence: no need to maintain state. A restart rebuilds the variable from DB. Resources: A valid concern. Could you explain more about pagination/aggregate data? Shared-state: There is only one route that modifies the variable, all others are just consumers. Thanks a lot!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:00:32.630",
"Id": "40558",
"Score": "0",
"body": "Makes sense. This is a pesonal web app for distributed personal use that will have at most 2-3 connections at once, and the data resets on shutdown, so this won't be an issue. Thanks for the feedback"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T05:10:09.110",
"Id": "26193",
"ParentId": "26165",
"Score": "2"
}
},
{
"body": "<p>What about threading? You run just one thread of the server? Anyway, you should take a look at memcached for bottle (<a href=\"https://pypi.python.org/pypi/bottle-memcache/\" rel=\"nofollow\">https://pypi.python.org/pypi/bottle-memcache/</a>). Maybe not for this particular case but it can come in handy for bigger projects.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T10:15:51.297",
"Id": "40886",
"Score": "0",
"body": "Threading shouldnt be an issue here, as the application is for a single user, maybe two at a time. It won't be hitting the web. If you are curious, it's a drink-mixing machine that is for single-person use: http://i.imgur.com/1ge8vq5.png . Memcached looks pretty awesome though. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T23:21:35.130",
"Id": "26392",
"ParentId": "26165",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26193",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:02:28.427",
"Id": "26165",
"Score": "3",
"Tags": [
"python",
"design-patterns",
"scope",
"bottle"
],
"Title": "Accessing a global list"
}
|
26165
|
<p>The rules for this program are to:</p>
<ul>
<li>Generate n X n grid.</li>
<li>Arbitrarily pick a point and grow a 'shape' based off that initial point.</li>
<li>Must have at least 3 points.</li>
<li>Strongly biased to not completely fill grid.</li>
</ul>
<hr>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
namespace ShapeTestInConsole
{
class Program
{
static void Main(string[] args)
{
Shape.Initialize(4, 4);
Shape shape = new Shape();
Draw(shape);
Console.ReadLine();
}
private static void Draw(Shape shape)
{
for (var x = 0; x < Shape.Width; x++)
{
for (var y = 0; y < Shape.Height; y++)
{
Console.Write("|");
Console.Write(" " + shape.ShapeDefinition[x, y].ToString() + " ");
Console.Write("|");
}
Console.Write("\n");
for (var i = 0; i < Shape.Width * 5; i++)
Console.Write("_");
Console.Write("\n");
}
}
}
public class Shape
{
private static readonly Random _random;
private static readonly Tuple<int, int>[] _adjacent = new[]
{
Tuple.Create(0,-1),
Tuple.Create(1,0),
Tuple.Create(0,1),
Tuple.Create(-1,0)
};
public byte[,] ShapeDefinition { get; private set; }
public static int Width { get; private set; }
public static int Height { get; private set; }
static Shape()
{
_random = new Random();
}
public Shape()
{
ShapeDefinition = new byte[Width, Height];
//Place seed point
ShapeDefinition[_random.Next(0, Width), _random.Next(0, Height)] = 1;
var activePoints = 1;
var starts = new List<Point>();
var neighbors = new List<Point>();
var neighborsToActivate = new List<Point>();
Build(starts, neighbors, neighborsToActivate, activePoints, 0, 1);
}
public static void Initialize(int width, int height)
{
Width = width;
Height = height;
}
private void Build(List<Point> starts, List<Point> neighbors, List<Point> neighborsToActivate,
int activePoints, int runCount, int currentLevel)
{
// Ditch if... Has bias for 4 X 4 grid
if (activePoints >= (Width * Height) || runCount > 5 || currentLevel >= 5)
return;
// minimum 3 points desired
if (activePoints >= 3 && activePoints < 6)
{
if (_random.Next(0, 9) == 2)
return;
}
else if (activePoints >= 6 && activePoints < 8)
{
if (_random.Next(0, 6) == 2)
return;
}
else if (activePoints >= 8)
{
if (_random.Next(0, 5) == 2)
return;
}
starts.Clear();
// Gather points
for (var x = 0; x < ShapeDefinition.GetLength(0); x++)
for (var y = 0; y < ShapeDefinition.GetLength(1); y++)
{
if (ShapeDefinition[x,y] == currentLevel)
starts.Add(new Point(x,y));
}
neighbors.Clear();
// with each start get adjacent usable point
foreach (var currentStartPoint in starts)
{
for (var i = 0; i < _adjacent.Length; i++)
{
var neighborX = currentStartPoint.X + _adjacent[i].Item1;
var neighborY = currentStartPoint.Y + _adjacent[i].Item2;
if (InBounds(neighborX, neighborY))
{
if (ShapeDefinition[neighborX, neighborY] == 0)
neighbors.Add(new Point(neighborX, neighborY));
}
}
neighborsToActivate.Clear();
// randomly pick which usable point(s) will be include with shape
neighborsToActivate = neighbors.OrderBy(n => _random.Next())
.Take(_random.Next(1, neighbors.Count + 1))
.ToList();
for (var j = 0; j < neighborsToActivate.Count; j++)
{
ShapeDefinition[neighborsToActivate[j].X, neighborsToActivate[j].Y] = (byte)(currentLevel + 1);
activePoints++;
}
}
runCount++;
currentLevel++;
Build(starts, neighbors, neighborsToActivate, activePoints, runCount, currentLevel);
}
private static bool InBounds(int x, int y)
{
return x >= 0 && x < Width &&
y >= 0 && y < Height;
}
}
}
</code></pre>
<p>This is a good facsimile of what I trying to accomplish now. My own thoughts on improvements would be that Shape, for how I would like to use it, should not have methods to create itself and should instead be created by a ShapeFactory or ShapeBuilder class. A Shape's only job is to be a shape.</p>
|
[] |
[
{
"body": "<ol>\n<li><p><code>runCount</code> and <code>CurrentLevel</code> seem redundant.</p></li>\n<li><p>I don't see why you pass <code>start</code>, <code>neighbors</code> and <code>neighborsToActivate</code> as parameters to the recursive function since you just clear them without using the data.</p></li>\n<li><p><code>activePoint</code> might be better off being a member of Shape since that information might useful elsewhere too.</p></li>\n<li><p>I would have made <code>Draw</code> a method of <code>Shape</code> since it is so closely associated with <code>Shape</code>.</p></li>\n</ol>\n\n<p>You are now storing the shape as \"active\" points in a grid. It would be possible also to store the shape as a list of points, e.g. {(2,3), (3,3), (3,4)}. I'm not saying it is better here, but it might be a better option for some applications, especially if you have a very large grid with very few active points.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:43:40.093",
"Id": "26239",
"ParentId": "26166",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26239",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:06:58.407",
"Id": "26166",
"Score": "1",
"Tags": [
"c#",
".net",
"recursion"
],
"Title": "Implement recursion"
}
|
26166
|
<p>I am developing a script that will act as a surrogate of sorts for a web portal and an email blast program. The web portal is used to create web-to-print files and is very good at creating print-ready PDF files, but currently lacks any email blast or HTML output options for the end user. In order to circumvent this limitation, my script will parse data that is in an email that is automatically sent after each order is placed. In this email are variables from the site that user has submitted as well as images that the user has uploaded. </p>
<p>My code still needs to archive the emails after they have been zipped (to eliminate duplicate files) and send the zip file to the person who ordered the HTML. Despite not being 100%, I was hoping to get some good feedback/criticism on what I have so far. I am not brand new to Python, but I am self taught and figured this is the best place to learn how to refine my code.</p>
<p>Here is my current (expected) workflow:</p>
<ol>
<li>User logs into web portal to order.</li>
<li>User uploads images, enters text into fields, and receives a proof of their "HTML".</li>
<li>User completes order, checks out. Process is now out of user's hands.</li>
<li>An email is generated and sent to me. This email includes all information necessary to create HTML markup.</li>
<li>Script reads email, downloads attachments, assigns values to variables based on their "markup" in the email. Specific characters are used to identify text strings to be used.</li>
<li>Script creates HTML markup using assigned variables, then adds <code>.html</code> file and all included images to a <code>.zip</code> file fit for distribution.</li>
<li>Script archives email to prevent duplicate zip files being created on next run.</li>
<li>An email is sent to the user with the zip file attached.</li>
<li>User uploads zip file to their own specific email blast program.</li>
</ol>
<p>Links to my code and supporting files are here:</p>
<ul>
<li><a href="http://snipplr.com/view/71177/email-to-html-script/" rel="nofollow">Script</a></li>
<li><a href="http://www.filedropper.com/orderh98fq2byusername" rel="nofollow">Email files</a></li>
</ul>
<p></p>
<pre><code>import email, getpass, imaplib, os, re, csv, zipfile, glob, threading
detach_dir = 'directory' # directory where to save attachments
user = ("username")
pwd = ("password")
# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap server")
m.login(user,pwd)
m.select("INBOX") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes
resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id
for emailid in items:
resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
email_body = data[0][1] # getting the mail content
mail = email.message_from_string(email_body) # parsing the mail content to get a mail object
#Check if any attachments at all
if mail.get_content_maintype() != 'multipart':
continue
# we use walk to create a generator so we can iterate on the parts and forget about the recursive headache
for part in mail.walk():
# each part is a either non-multipart, or another multipart message
# that contains further parts... Message is organized like a tree
if part.get_content_type() == 'text/plain':
content = part.get_payload()
message = re.compile(r'\%(.+?)\%', re.DOTALL).findall(content)
message = re.sub(r'=\\r\\', '', str(message))
message = re.sub(r'\[\'', '', str(message))
message = re.sub(r'\'\]', '', str(message))
token = re.compile(r'\$(.+?)\$', re.DOTALL).findall(content)
token = re.sub(r'\[\'', '', str(token))
token = re.sub(r'\'\]', '', str(token))
tag = re.compile(r'\^(.+?)\^', re.DOTALL).findall(content)
tag = re.sub(r'\[\'', '', str(tag))
tag = re.sub(r'\'\]', '', str(tag))
print message
print token
print tag
#print part.get_payload() # prints the raw text
# multipart are just containers, so we skip them
if part.get_content_maintype() == 'multipart':
continue
# is this part an attachment ?
if part.get('Content-Disposition') is None:
continue
filename = part.get_filename()
counter = 1
# if there is no filename, we create one with a counter to avoid duplicates
if not filename:
filename = 'part-%03d%s' % (counter, 'bin')
counter += 1
att_path = os.path.join(detach_dir, filename)
#Check if its already there
if not os.path.isfile(att_path) :
# finally write the stuff
fp = open(att_path, 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
path = detach_dir
os.chdir(path)
image1 = str(glob.glob('upload-photo1*'))
image2 = str(glob.glob('upload-photo2*'))
image3 = str(glob.glob('upload-photo3*'))
image1 = re.sub(r'\[\'', '', image1)
image1 = re.sub(r'\'\]', '', image1)
image2 = re.sub(r'\[\'', '', image2)
image2 = re.sub(r'\'\]', '', image2)
image3 = re.sub(r'\[\'', '', image3)
image3 = re.sub(r'\'\]', '', image3)
htmlFile = str(token)+'.html'
#if tag == 'email_blast_demo':
htmlCode = ('''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title></head><body>
<table width="554" border="0" cellspacing="0" cellpadding="0" align="center"><tr><td>
<img src="'''+image1+'''" width="554" height="186" /></td></tr><tr><td>
<p style="font-family:Arial, Helvetica, sans-serif; font-size:11pt; line-height:14pt;">
<br />Dear [Fld:FirstName],<br /><br />'''+str(message)+'''<br /><br /><a href="PLACEHOLDER">
<img src="'''+image2+'''" width="248" height="38" alt="Opt-in for men\'s health tips now" /></a>
<br /><br /><br /><img src="'''+image3+'''" width="167" height="62" align="right" /><br />
<p style="font-family:Arial, Helvetica, sans-serif; font-size:10pt;"></td></tr></table>
</body></html>''')
htmlData = open(os.path.join('directory', htmlFile), 'w+')
htmlData.write(htmlCode)
print htmlFile+' Complete'
htmlData.close()
allFiles = [f for f in os.listdir(path) if not f.endswith('.zip')]
for file in allFiles:
archive = zipfile.ZipFile(token+'.zip', mode='a')
archive.write(file)
archive.close()
os.unlink(file)
# This script will access a set email account, parse the text and attachments of each email, create HTML markup
# and zip the files together. This script assumes a set template for the HTML. I will most likely have to change
# this in order to incorporate multiple templates. The HTML markup for each template will be sent in the email
# and be parsed in the ame fashion as the `token` and `tag` variables above.
#
# What still needs to be done:
# 1) Archive email after being zipped so that duplicates are not created
# 2) Email .zip file to requestor (person who ordered)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T04:31:53.667",
"Id": "40526",
"Score": "0",
"body": "Just curious, is there a (possibly business) reason everything has to be done through email? It sounds like you're generating email templates for something like MailChimp or Campaign Monitor, in which case, why don't you just store the files on your server (or a third-party storage SaaS) rather than sending through email? This just seems like a roundabout way of doing something fairly simple."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T16:29:55.707",
"Id": "40572",
"Score": "0",
"body": "@JohnSyrinek It's definitely business and I do not know the specific email blast program the client is using. It's my understanding that there may be multiple programs in use and so the client wants something \"universal.\" Also, the client specified that the files be sent via email to the end-user. One of the big selling points for the client was the automation process that the web portal provides, and I am trying to maintain that by having the files be sent directly to the end-user."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T16:32:11.747",
"Id": "40573",
"Score": "0",
"body": "@JohnSyrinek (cont.) You couldn't be more right about this being a roundabout way of doing things, but in order to circumvent the web portal's limitations while still incorporating with the portal's functionality, it may be necessary."
}
] |
[
{
"body": "<h3>PEP8</h3>\n\n<p>You're not following <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">PEP8</a>, Python's official coding style guide, for example:</p>\n\n<ul>\n<li>Don't put multiple imports on the same line</li>\n<li>Put a space after commas in parameter lists, so <code>m.login(user, pwd)</code> instead of <code>m.login(user,pwd)</code></li>\n<li>There shouldn't be whitespace after <code>:</code></li>\n<li>Use at least 2 spaces before inline comments (before each <code># comment</code>)</li>\n<li>Put a space after <code>#</code> when starting comments, so <code># comment</code> instead of <code>#comment</code></li>\n<li>Some lines are too long (longer than 79 characters)</li>\n</ul>\n\n<h3>Bad practices</h3>\n\n<ul>\n<li>Remove unused imports: getpass, csv, threading</li>\n<li>No need for the parens in <code>user = (\"username\")</code>, and it may get confused as a tuple (which it isn't)</li>\n<li>The variable <code>m</code> is poorly named: judging by the name I might guess it's a \"message\", when it's actually a mailbox</li>\n<li>At the point where you do <code>str(message)</code>, <code>message</code> might not have been assigned yet</li>\n<li>At the point where you do <code>os.listdir(path)</code>, <code>path</code> might not have been assigned yet</li>\n</ul>\n\n<hr>\n\n<p>In this code:</p>\n\n<blockquote>\n<pre><code>resp, items = m.search(None, \"ALL\")\nitems = items[0].split() # getting the mails id\n\nfor emailid in items:\n resp, data = m.fetch(emailid, \"(RFC822)\")\n</code></pre>\n</blockquote>\n\n<p>The initialization of <code>resp</code> is pointless, because it will be reassigned anyway in the loop. Effectively you throw away the first assignment of <code>resp</code>. In such cases a common practice is to use <code>_</code> as the variable name, like this:</p>\n\n<pre><code>_, items = m.search(None, \"ALL\")\n</code></pre>\n\n<p>On closer look, I see that after the 2nd assignment too,\n<code>resp</code> is not used again. So it could be replaced with <code>_</code> there too.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>message = re.compile(r'\\%(.+?)\\%', re.DOTALL).findall(content)\n</code></pre>\n</blockquote>\n\n<p>This is the same as the above but simpler:</p>\n\n<pre><code>message = re.findall(r'\\%(.+?)\\%', content, re.DOTALL)\n</code></pre>\n\n<p>But since you have this code inside a for loop,\nit would be best to compile the pattern once before the loop,\nand reuse it inside, like this:</p>\n\n<pre><code>re_between_percent = re.compile(r'\\%(.+?)\\%', re.DOTALL)\nfor part in mail.walk():\n # ...\n message = re_between_percent.findall(content)\n</code></pre>\n\n<p>Do the same for the other statements too where you do <code>re.compile(...).findall(...)</code>.</p>\n\n<hr>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code> htmlData = open(os.path.join('directory', htmlFile), 'w+')\n htmlData.write(htmlCode)\n print(htmlFile + ' Complete')\n htmlData.close()\n</code></pre>\n</blockquote>\n\n<p>The Pythonic way to work with files:</p>\n\n<pre><code> with open(os.path.join('directory', htmlFile), 'w+') as htmlData:\n htmlData.write(htmlCode)\n print(htmlFile + ' Complete')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-22T10:15:20.633",
"Id": "74470",
"ParentId": "26167",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "74470",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:07:17.047",
"Id": "26167",
"Score": "6",
"Tags": [
"python",
"parsing",
"email"
],
"Title": "Parse emails and create HTML markup from attachments"
}
|
26167
|
<p>I have an image which is a black ring:</p>
<p><a href="http://imageshack.us/a/img51/2029/blackcb.png" rel="nofollow noreferrer">black ring http://imageshack.us/a/img51/2029/blackcb.png</a></p>
<p>In my view, I need to display it as a white ring. So, to tint the image, I have written the below method:</p>
<pre><code>- (UIImage *)getRingImage
{
UIImage *ringImage = [UIImage imageNamed:@"ring"];
CGFloat scale = [[UIScreen mainScreen] scale];
UIGraphicsBeginImageContext(CGSizeMake(ringImage.size.width * scale, ringImage.size.height * scale));
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect rect = CGRectMake(0, 0, ringImage.size.width * scale, ringImage.size.height * scale);
// Converting a UIImage to a CGImage flips the image,
// so apply a upside-down translation
CGContextScaleCTM(ctx, 1, -1);
CGContextTranslateCTM(ctx, 0, -rect.size.height);
// Set the fill color space
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGContextSetFillColorSpace(ctx, colorSpace);
// Set the mask to only tint non-transparent pixels
CGContextClipToMask(ctx, rect, ringImage.CGImage);
// Set the fill color
CGContextSetFillColorWithColor(ctx, [UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:1].CGColor);
UIRectFillUsingBlendMode(rect, kCGBlendModeColor);
ringImage = UIGraphicsGetImageFromCurrentImageContext();
CGColorSpaceRelease(colorSpace);
UIGraphicsEndImageContext();
return ringImage;
}
</code></pre>
<p>This code works fine. I want to know if there is a better way to do this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:05:13.950",
"Id": "40500",
"Score": "0",
"body": "What do you mean by \"better?\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:14:10.237",
"Id": "40501",
"Score": "0",
"body": "By \"better\" I mean, use of a different API which could achieve the same result but in less number of steps which in turn could lead to reduced execution time and CPU cycles."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T19:53:01.243",
"Id": "40515",
"Score": "1",
"body": "I doubt it. Even when it took you 20 steps, the code is simple. If you are interested in other blend modes see http://robots.thoughtbot.com/post/46668544473/designing-for-ios-blending-modes"
}
] |
[
{
"body": "<p>Try this function that I adapted. It creates a mono-color \"mask\" from an input image. If you use white, it turns every non-transparent pixel to white:</p>\n\n<pre><code>- (UIImage*)convertToMask: (UIImage *) image\n{\n UIGraphicsBeginImageContextWithOptions(image.size, NO, image.scale);\n CGRect imageRect = CGRectMake(0.0f, 0.0f, image.size.width, image.size.height);\n\n CGContextRef ctx = UIGraphicsGetCurrentContext();\n\n // Draw a white background (for white mask)\n CGContextSetRGBFillColor(ctx, 1.0f, 1.0f, 1.0f, 1.0f);\n CGContextFillRect(ctx, imageRect);\n\n // Apply the source image's alpha\n [image drawInRect:imageRect blendMode:kCGBlendModeDestinationIn alpha:1.0f];\n\n UIImage* outImage = UIGraphicsGetImageFromCurrentImageContext();\n\n UIGraphicsEndImageContext();\n\n return outImage;\n}\n</code></pre>\n\n<p>Used like this:</p>\n\n<pre><code>self.imageView.image = [self convertToMask:self.imageView.image];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:39:33.333",
"Id": "26171",
"ParentId": "26168",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T18:04:24.233",
"Id": "26168",
"Score": "2",
"Tags": [
"objective-c",
"ios",
"image"
],
"Title": "Tinting an image"
}
|
26168
|
<p>I created a library/npm module to handle the signaling process for <code>RTCPeerConnection</code>. There is still a good bit of work that needs done (error handling, dealing with users disconnecting during the signaling process, etc.), but at the moment I am mostly looking for suggestions/ideas about the overall architecture.</p>
<p>Here is the <a href="https://github.com/traviswimer/SignalFire.js" rel="nofollow">Github repo</a>.</p>
<p>Below I have included the module for the server-side and the script for the client-side.</p>
<p><strong>Server-Side:</strong></p>
<pre><code>var io = require('socket.io');
module.exports = function () {
// Is used to give each peer a unique ID
var peerIdCounter = 0;
// create next ID and return it
var incrementPeerIdCounter = function () {
peerIdCounter++;
return peerIdCounter;
};
// // // // /
/////////////////
// Peer Object //
/*****************************************************************************/
var createPeer = function (socket) {
/////////////////////////////////////
// Peer Object's Private Variables //
//////////////////////////////////////////////////
// //
var self;
var id;
// holds the peerConnect offer for this peer
var offer;
// list of peers that can connect
var connectingPeers = {};
// The Peer class
function Peer(socket) {
this.socket = socket;
id = incrementPeerIdCounter();
self = this;
// listen for client sending offer
self.socket.on('clientSendingOffer', receiveOfferFromClient);
// detect receiving an answer from clietn
self.socket.on('clientSendingAnswer', receiveAnswerFromClient);
// listen for ice candidates
self.socket.on('clientSendingIce', receiveIceCandidate);
}
// //
//////////////////////////////////////////////////
//////////////////////////////////
// Peer Object's Public Methods //
//////////////////////////////////////////////////
// //
// Initiates signaling process
Peer.prototype.connectToPeer = function (peer, successCallback, failCallback) {
// answering peer starts waiting for an offer
peer.acceptOfferFrom(self);
// This peer will make an offer
this.makeOfferRequest(peer);
};
// Request a peerConnection offer from the current peer
Peer.prototype.makeOfferRequest = function (peer) {
// add peer to list of accepted requests
connectingPeers[peer.getPeerId()] = peer;
// ask client for an offer
self.socket.emit('serverRequestingOffer', {
peerId: peer.getPeerId()
});
};
// Accept peerConnection offers from the specified peer
Peer.prototype.acceptOfferFrom = function (peer) {
// add peer to list of accepted requests
connectingPeers[peer.getPeerId()] = peer;
};
// getter for the peer ID
Peer.prototype.getPeerId = function () {
return id;
};
// //
//////////////////////////////////////////////////
///////////////////////////////////
// Peer Object's Private Methods //
//////////////////////////////////////////////////
// //
// Handle an offer sent from the client
var receiveOfferFromClient = function (data) {
offer = data.offer;
sendOfferToClient(data.peerId);
};
// Send offer to the other peer
var sendOfferToClient = function (peerId) {
connectingPeers[peerId].socket.emit(
'serverSendingOffer', {
peerId: self.getPeerId(),
offer: offer
});
};
// Send answer to initiating peer
var receiveAnswerFromClient = function (data) {
var peerId = data.peerId;
data.peerId = self.getPeerId();
connectingPeers[peerId].socket.emit('serverSendingAnswer', data);
};
//Handle ICE candidates received
var receiveIceCandidate = function (data) {
var iceInfo = {
peerId: self.getPeerId(),
candidate: data.candidate
};
connectingPeers[data.peerId].socket.emit('serverSendingIce', iceInfo);
};
// //
//////////////////////////////////////////////////
// Return an instance of the Peer class
return new Peer(socket);
};
/*____________________________________________________________________________*/
// // // // // // // /
/////////////////////////////
// Module's Public Methods //
/*****************************************************************************/
// Initiates listening for signaling requests
///////////////////////////////////////////////
var listen = function (port, successCallback, failCallback) {
if(typeof port != 'number') {
return false;
}
// Handle socket requests
/////////////////////////////
var server = io.listen(port);
server.sockets.on('connection', function (socket) {
var peer;
try {
peer = createPeer(socket);
} catch(e) {
failCallback(e);
} finally {
successCallback(peer);
}
});
return server;
};
// Return the public methods
return {
listen: listen
};
/*____________________________________________________________________________*/
}();
</code></pre>
<p><strong>Client-side</strong></p>
<pre><code>(function () {
var signalfire = function () {
// // // // /
/////////////////
// Peer Object //
/*****************************************************************************/
var createPeer = function (socket, options) {
/////////////////////////////////////
// Peer Object's Private Variables //
//////////////////////////////////////////////////
// //
var self;
//holds the ids of the peers that are connecting
var connectingPeers = {};
// holds function to call when server requests a connection offer
// or provides a connection offer
var makeRTCPeer = options.connector || function () {};
// holds function to call when signaling process is complete
var signalingComplete = options.onSignalingComplete || function () {};
// The Peer class
function Peer(socket) {
this.socket = socket;
self = this;
// listen for server requesting offer
self.socket.on('serverRequestingOffer', sendOfferToServer);
// detect receiving an offer from server
self.socket.on('serverSendingOffer', sendAnswerToServer);
// listen for ice candidates
self.socket.on('serverSendingAnswer', receiveAnswerFromServer);
// listen for ice candidates
self.socket.on('serverSendingIce', receiveIceCandidate);
}
// //
//////////////////////////////////////////////////
///////////////////////////////////
// Peer Object's Private Methods //
//////////////////////////////////////////////////
// //
// Receive offer request and return an offer
var sendOfferToServer = function (data) {
// create RTCPeerConnection
var rtcPeerConnection = makeRTCPeer();
// initialize ice candidate listeners
iceSetup(rtcPeerConnection, data);
// Add connection to list of peers
connectingPeers[data.peerId] = rtcPeerConnection;
// create offer and send to server
rtcPeerConnection.createOffer(function (offerResponse) {
data.offer = offerResponse;
rtcPeerConnection.setLocalDescription(offerResponse, function () {
socket.emit('clientSendingOffer', data);
});
});
};
// Receive peer offer from server. Return an answer.
var sendAnswerToServer = function (data) {
// create RTCPeerConnection
var rtcPeerConnection = makeRTCPeer();
// initialize ice candidate listeners
iceSetup(rtcPeerConnection, data);
// Add connection to list of peers
connectingPeers[data.peerId] = rtcPeerConnection;
// Create description from offer received
var offer = new RTCSessionDescription(data.offer);
// Set Description, create answer, send answer to server
rtcPeerConnection.setRemoteDescription(offer, function () {
rtcPeerConnection.createAnswer(function (answer) {
rtcPeerConnection.setLocalDescription(answer);
var answerData = {
peerId: data.peerId,
answer: answer
};
socket.emit('clientSendingAnswer', answerData);
});
});
};
// Receive peer answer from server
var receiveAnswerFromServer = function (data) {
var peerConn = connectingPeers[data.peerId];
var answer = new RTCSessionDescription(data.answer);
peerConn.setRemoteDescription(answer, function () {});
};
// receive ice candidates from server
var receiveIceCandidate = function (data) {
if(data.candidate !== null) {
connectingPeers[data.peerId].addIceCandidate(new RTCIceCandidate(data.candidate));
}
};
// setup ice candidate handling
var iceSetup = function (rtcPeerConnection, data) {
// check if connection has been created
rtcPeerConnection.onicechange = function (evt) {
if(rtcPeerConnection.iceConnectionState === 'connected') {
signalingComplete(rtcPeerConnection);
}
};
// listen for ice candidates and send to server
rtcPeerConnection.onicecandidate = function (iceData) {
var sendingIceInfo = {
peerId: data.peerId,
candidate: iceData.candidate
};
socket.emit('clientSendingIce', sendingIceInfo);
};
};
// //
//////////////////////////////////////////////////
// Return an instance of the Peer class
return new Peer(socket);
};
/*____________________________________________________________________________*/
// // // // //
////////////////////
// Public Methods //
/*****************************************************************************/
var connect = function (options, successCallback, failCallback) {
/*
Options:
"server" - The url + port of the server to connect to
"connector" - A function that is called when the server requests
an RTC offer. Must return an RTCPeerConnction object.
*/
if(typeof options != 'object') {
return false;
}
var socket = io.connect(options.server, {
'force new connection': true
});
socket.on('connect', function () {
var peer;
try {
peer = createPeer(socket, options);
} catch(e) {
failCallback(e);
} finally {
successCallback(peer);
}
});
socket.on('connect_error', function (e) {
failCallback(e);
});
return socket;
};
return {
connect: connect
};
/*____________________________________________________________________________*/
};
// set the signalfire global variable
window.signalfire = signalfire();
}());
</code></pre>
|
[] |
[
{
"body": "<p>Interesting code,</p>\n\n<p>I am somewhat surprised that you assign <code>connectToPeer</code> to <code>Peer.prototype</code>. A distinct <code>Peer</code> function object will be created with each call of <code>createPeer</code>, which makes it pointless to assign anything to the <code>prototype</code>. This means also from a memory perspective, that each connected peer has it's own closure with all the code in <code>createPeer</code>. I think you are doing this because you want the private functions, I am not convinced that it is worth it.</p>\n\n<p>Furthermore I am surprised that you call <code>successCallback</code> in <code>finally</code>, which means it also gets called in case of failure, which is not intuitive.</p>\n\n<p>There is clearly common code between the client and the server, you should extract that common code.</p>\n\n<p>Other than that, your code is well commented and fairly easy to follow, and JsHint has nothing to complain about.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-21T20:47:51.587",
"Id": "47832",
"ParentId": "26178",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T20:13:54.550",
"Id": "26178",
"Score": "2",
"Tags": [
"javascript",
"node.js",
"library-design",
"socket"
],
"Title": "RTCPeerConnection signaling library"
}
|
26178
|
<p>I couldn't quickly find Java code with googling to make serialized Json easier to read (this is a <strong>debugging library</strong>, obviously implementation code wouldn't use this as it's just more characters). This is <strong>not</strong> intended to be viewed in a web browser, this is intended for console output mostly. I'm fairly new to Json (that's probably why I don't know where to look for this), is there a use case that my code is missing?</p>
<pre><code>public class JsonWhitespace {
public static String toWhiteSpace(String noWhite) {
StringBuilder sb = new StringBuilder();
int tabCount = 0;
boolean inArray = false;
for(char c : noWhite.toCharArray()) {
if (c == '{') {
sb.append(c);
sb.append(System.lineSeparator());
tabCount++;
printTabs(sb, tabCount);
} else if(c == '}') {
sb.append(System.lineSeparator());
tabCount--;
printTabs(sb, tabCount);
sb.append(c);
} else if(c == ',') {
sb.append(c);
if (!inArray) {
sb.append(System.lineSeparator());
printTabs(sb, tabCount);
}
} else if (c == '[') {
sb.append(c);
inArray = true;
} else if (c == ']') {
sb.append(c);
inArray = false;
} else {
sb.append(c);
}
}
return sb.toString();
}
private static void printTabs(StringBuilder sb, int tabCount) {
for(int i = 0; i < tabCount; i++) {
sb.append('\t');
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T00:58:48.180",
"Id": "40522",
"Score": "0",
"body": "This will be thrown off by any of the characters tested for occurring in a value string."
}
] |
[
{
"body": "<p>I think you need to ignore the contents of quoted values.</p>\n\n<p>Add the flag:</p>\n\n<pre><code> boolean inQuotes=false;\n</code></pre>\n\n<p>then, at the top of your <code>if</code> statement:</p>\n\n<pre><code> if (c == '\"') {\n inQuotes=!inQuotes;\n }\n if (!inQuotes) {\n if (c == '{') {\n sb.append(c);\n sb.append(System.lineSeparator());\n tabCount++;\n printTabs(sb, tabCount);\n } else if(c == '}') {\n ... // Your code\n } else {\n sb.append(c);\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T03:54:17.937",
"Id": "40523",
"Score": "0",
"body": "Aha, I knew I must've missed something."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T01:01:37.770",
"Id": "26183",
"ParentId": "26181",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26183",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-14T21:25:02.623",
"Id": "26181",
"Score": "2",
"Tags": [
"java",
"json",
"formatting"
],
"Title": "Json whitespace formatter"
}
|
26181
|
<p>For my models for a certain section I thought it would be better to have a base class model for both "view" and "edit" models, like so:</p>
<pre><code>public abstract class Setting
{
[Required]
public int SettingId { get; set; }
public string Name { get; set; }
[Required]
[MaxLength(255)]
public string Value { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDt { get; set; }
}
public class ViewSetting : Setting
{
}
public class EditSetting : Setting
{
}
</code></pre>
<p>So in my <code>Service</code> or <code>Views</code> I use the appropriate <code>ViewSetting</code> or <code>EditSetting</code>. Right now I don't have anything that would be different - but should I follow a pattern like this to maintain a separation of concerns here? Or should I just stick to using one <code>Setting</code> class? (as an aside, I'm using Entity Frameworks but in my Service layer is where I convert to/from the models for the ORM)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T07:05:27.393",
"Id": "40533",
"Score": "0",
"body": "I might consider composition over inheritance in this case. Of course that's probably a preference thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T00:17:00.460",
"Id": "40593",
"Score": "0",
"body": "Meaning you would include `Setting` as an object in both `ViewSetting` and `EditSetting`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T01:18:10.263",
"Id": "40597",
"Score": "0",
"body": "Yes that would be one alternative to using the inheritance model"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T08:36:19.013",
"Id": "40606",
"Score": "1",
"body": "You mentioned \"Right now I don't have anything that would be different\". So you don't need it. If you need it, you can always add it later. Try to go with the simplest solution that possibly work. I would simply use a one Setting class as you mentioned."
}
] |
[
{
"body": "<p>The Model wouldn't change regardless of whether you were viewing it or editing the records in the given model. </p>\n\n<hr>\n\n<p>Let's go ahead and create a view and edit model from the information you have given us, it will look like this</p>\n\n<p><strong>Note:</strong> this doesn't work, it is here to make a point.</p>\n\n<pre><code>public abstract class Setting\n{\n [Required]\n public int SettingId { get; set; }\n\n public string Name { get; set; }\n\n [Required]\n [MaxLength(255)]\n public string Value { get; set; }\n public string ModifiedBy { get; set; }\n public DateTime ModifiedDt { get; set; }\n}\n\npublic class ViewSetting : Setting\n{\n public int SettingId { get; }\n public string Name { get; }\n public string Value { get; }\n public string ModifiedBy { get; }\n public DateTime ModifiedDt { get; }\n}\n\npublic class EditSetting : Setting\n{\n [Required]\n public int SettingId { set; }\n\n public string Name { set; }\n\n [Required]\n [MaxLength(255)]\n public string Value { set; }\n public string ModifiedBy { set; }\n public DateTime ModifiedDt { set; }\n}\n</code></pre>\n\n<p>and then you don't want to go setting the ID Field because that would change more than the properties of the data, it would be changing indexing in your database, so we would take that out too. And if you were going to edit the Record you should also make the <code>ModifiedBy</code> and <code>ModifiedDt</code> required.</p>\n\n<p>Also, because if you implement the Abstract class you implement everything anyway, it really doesn't make sense to create an abstract class, so I make them all regular classes and you can see what is really going on here.</p>\n\n<pre><code>public class Setting\n{\n [Required]\n public int SettingId { get; set; }\n\n public string Name { get; set; }\n\n [Required]\n [MaxLength(255)]\n public string Value { get; set; }\n public string ModifiedBy { get; set; }\n public DateTime ModifiedDt { get; set; }\n}\n\npublic class ViewSetting \n{\n public int SettingId { get; }\n public string Name { get; }\n public string Value { get; }\n public string ModifiedBy { get; }\n public DateTime ModifiedDt { get; }\n}\n\npublic class EditSetting \n{\n public string Name { set; }\n\n [Required]\n [MaxLength(255)]\n public string Value { set; }\n [Required]\n public string ModifiedBy { set; }\n [Required]\n public DateTime ModifiedDt { set; }\n}\n</code></pre>\n\n<p>you wouldn't really make separate models for editing and viewing. it isn't needed.</p>\n\n<p>The properties do the getting (get = view) and setting (set = edit). so there isn't really a reason to make two separate models, one for getting and one for setting, when one class/model can do it all</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-19T15:36:11.873",
"Id": "94092",
"ParentId": "26184",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T02:25:54.470",
"Id": "26184",
"Score": "2",
"Tags": [
"c#",
".net",
"asp.net",
"entity-framework"
],
"Title": "Models in .NET: separate settings"
}
|
26184
|
<p>I have this <code>Board</code> class:</p>
<pre><code>import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
Timer timer = new Timer(500, this);
private static boolean[][] emptyBoard = {{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false},
{false, false, false, false, false, false, false, false, false, false}};
private boolean[][] board;
private boolean isActive = false;
private int height;
private int width;
private int multiplier = 55;
private JButton button1;
private JButton button2;
private JButton button3;
public Board() {
this(emptyBoard);
}
public Board(final boolean[][] board) {
this.board = board;
height = board.length;
width = board[0].length;
setBackground(Color.black);
button1 = new JButton("Run");
add(button1);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
isActive = !isActive;
button1.setText(isActive ? "Pause" : "Run");
}
});
button2 = new JButton("Random");
add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setBoard(randomBoard());
}
});
button3 = new JButton("Clear");
add(button3);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setBoard(clearBoard());
}
});
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
getBoard()[e.getY() / multiplier][e.getX() / multiplier] = !getBoard()[e.getY() / multiplier][e.getX() / multiplier];
}
@Override
public void mouseReleased(MouseEvent e) {
}
});
timer.start();
}
public int getMultiplier() {
return multiplier;
}
public boolean[][] getBoard() {
return board;
}
public void setBoard(boolean[][] boardToSet) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
board[i][j] = boardToSet[i][j];
}
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
g.setColor(board[i][j] ? Color.green : Color.gray);
g.fillRect(j * multiplier, i * multiplier, multiplier - 1, multiplier - 1);
}
}
if (isActive) {
timer.start();
}
else {
timer.stop();
repaint();
}
}
public void actionPerformed(ActionEvent e) {
board = nextGeneration();
repaint();
}
public boolean[][] randomBoard() {
Random rand = new Random();
boolean[][] randBoard = new boolean[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
randBoard[i][j] = rand.nextBoolean();
}
}
return randBoard;
}
public boolean[][] clearBoard() {
boolean[][] emptyBoard = new boolean[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
emptyBoard[i][j] = false;
}
}
return emptyBoard;
}
public int countSurrounding(int a, int b) {
int count = 0;
int[][] surrounding = {{a - 1, b - 1},
{a - 1, b },
{a - 1, b + 1},
{a , b - 1},
{a , b + 1},
{a + 1, b - 1},
{a + 1, b },
{a + 1, b + 1}};
for (int[] i: surrounding) {
try {
if (board[i[0]][i[1]]) {
count++;
}
}
catch (ArrayIndexOutOfBoundsException e) {}
}
return count;
}
public boolean[][] nextGeneration() {
boolean[][] nextBoard = new boolean[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
nextBoard[i][j] = board[i][j];
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
if (board[i][j] && !(countSurrounding(i, j) == 2 || countSurrounding(i, j) == 3)) {
nextBoard[i][j] = false;
}
else if (!board[i][j] && countSurrounding(i, j) == 3) {
nextBoard[i][j] = true;
}
}
}
return nextBoard;
}
}
</code></pre>
<p>and this <code>GameOfLife</code> class:</p>
<pre><code>import javax.swing.JFrame;
class GameOfLife {
public static void main(String[] args) {
Board boardPanel = new Board();
JFrame frame1 = new JFrame();
frame1.setTitle("The Game of Life");
frame1.setSize(boardPanel.getBoard()[0].length * boardPanel.getMultiplier() + 5, boardPanel.getBoard().length * boardPanel.getMultiplier() + 27);
frame1.setResizable(false);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.add(boardPanel);
}
}
</code></pre>
<p>As you can tell, it's meant to represent John Conway's Game of Life on a JFrame. It's my first project using animation and graphics, so I expect there to be a few bad practices. Could anyone provide an honest, critical code review?</p>
<p>Thanks</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T09:06:56.587",
"Id": "40539",
"Score": "0",
"body": "Give better names for button1, frame1, etc."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T13:22:18.923",
"Id": "40547",
"Score": "0",
"body": "Since the following suggestions are too obvious to deserve an answer, I'll tell them in this comment:\n\nreplace `boolean[][] emptyBoard = {{....` with `boolean[][] emptyBoard = new boolean[10][10]`\n\nreplace `new MouseListener` with `new MouseAdapter` and remove empty methods.\n\nA just as obvious but not as trivial suggestion is to separate the logic from the swing dependent code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:17:29.150",
"Id": "40634",
"Score": "0",
"body": "Some suggestions on how to separate view and model:\nMove things elsewhere until you do not `import` anything from `java.awt` or `javax.swing`. If you were following single responsibility principle closely the following should be easy tasks:\n- start two instances of the game in two frames in the same process (from the same main() method)\n- add a freeze button to enable the grid to evolve but do not update the display and an unfreeze to restart the updates to the display"
}
] |
[
{
"body": "<ol>\n<li>As was suggested in the comments, initialize your matrix as <code>boolean[][] emptyBoard = new boolean[10][10]</code>, as in Java booleans will default to <code>false</code>.</li>\n<li>Document your code: all IDEs will have some support for JavaDoc, use it.</li>\n<li>Also suggested in the comments, variables should have better names; especially GUI elements (you might not realize the importance of this because in your case you have few elements, but doing this in larger applications will slowly become a royal PITA).</li>\n<li>Separate logic from presentation. Don't do GUI operations and the game calculations in the same class (i.e. <code>Board</code>).</li>\n<li><p>You shouldn't do this:</p>\n\n<pre><code>for (int[] i: surrounding) {\n try {\n if (board[i[0]][i[1]]) {\n count++;\n }\n }\n catch (ArrayIndexOutOfBoundsException e) {}\n}\n</code></pre>\n\n<p>Properly defining <code>surrounding</code> should avoid any <code>ArrayIndexOutOfBoundsException</code>.</p></li>\n<li>This is mainly a personal preference, but what you have in <code>main()</code> (the GUI parts) I would put in one (or more) separate methods.</li>\n<li>Another personal preference is using <code>ArratList</code> instead of arrays.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:34:19.467",
"Id": "26232",
"ParentId": "26196",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26232",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T06:57:10.647",
"Id": "26196",
"Score": "4",
"Tags": [
"java",
"swing",
"game-of-life"
],
"Title": "Game of Life Animation Java"
}
|
26196
|
<p>Can someone please review my code:</p>
<pre><code># dup/ish -> //github.com/rails/rails/issues/5449
class Form
include Mongoid::Document
attr_accessor :source
def self.ish(prefix, suffix, &block)
klass_name = prefix.classify + suffix
dup.tap do |klass|
klass.class_eval do
define_singleton_method(:name) do
prefix.classify
end
end
klass.class_eval(&block)
Object.const_set(klass_name, klass)
end
end
def self.compose(klass_name, id, source)
mongoid_translate = {:models => {}, :attributes => {}}
form = ish(klass_name, id) do
translate = {}
source.flatten.each do |widget|
if widget.include?('validate')
validates *widget.values_at('name', 'validate')
translate.store *widget.values_at('name', 'translate')
end
if widget.include?('name')
if 'upload' == widget['type']
has_many(:attachments)
accepts_nested_attributes_for(:attachments)
elsif 'repeat' == widget['type']
part_klass = Form.compose(widget['name'], id, widget['parts'])
embeds_many(widget['name'].pluralize, :class_name => part_klass.class.to_s)
accepts_nested_attributes_for(widget['name'].pluralize)
end
end
end
mongoid_translate[:attributes][self.name.downcase.to_sym] = translate
end
I18n.backend.store_translations(:pt_BR, {:mongoid => mongoid_translate})
form.new.tap do |form|
form.source = source
end
end
def prepare
self.source.flatten.each do |widget|
if widget.include?('name')
if 'repeat' == widget['type']
parts = send("#{widget['name'].pluralize}")
if parts.empty?
parts.build
widget['parts'].each do |part|
parts[0].write_attribute(part['name'], nil)
end
end
elsif 'upload' == widget['type']
attachments.build if attachments.empty?
else
begin
send(widget['name'].to_sym)
rescue NoMethodError
write_attribute(widget['name'], nil)
end
end
end
end
end
end
</code></pre>
|
[] |
[
{
"body": "<p>Few things I have noted in your design are listed below. Beware all of this is purely from a design perspective rather than application.</p>\n\n<ol>\n<li><strong>Source</strong> is defined as <code>attr_accessor</code> which essentially violates encapsulation. Inject it from outside in constructor call.(I am not able to understand why you have not gone for <code>attr_reader</code> instead of <code>accessor</code>.</li>\n<li>Ideally <code>self.compose</code> can be split into different method calls. It is violating <strong>SRP</strong> by doing too many things at one place. That is same for other methods as well.</li>\n<li>Speaking from a puritan view, the branched if condition is also a smell.</li>\n</ol>\n\n<p>In general, metaprogramming is considered to be something which must be avoided unless you have enough justification to keep it. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-07T17:44:08.640",
"Id": "215573",
"Score": "0",
"body": "Whoa I totally forgot I put this here. :P And yes I see very well all your points. It's actually something I knew had smells all over the place but wanted to check with other people (which I couldn't because I was the only programmer working on the project). Thanks for your time and effort! Have a great day."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-14T09:59:09.643",
"Id": "234531",
"Score": "0",
"body": "my pleasure! there might be more smells."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-21T10:36:09.340",
"Id": "108258",
"ParentId": "26202",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "108258",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T14:10:17.557",
"Id": "26202",
"Score": "2",
"Tags": [
"object-oriented",
"ruby",
"ruby-on-rails",
"form",
"meta-programming"
],
"Title": "Duplicating Rails model for a form with meta-programming"
}
|
26202
|
<pre><code> SELECT BR.IDObject AS IDObject,
B.imgName AS imgName,
BK.imgPath AS imgPath,
BR.imgType AS imgType
FROM ImageReferences BR
INNER JOIN BDB_WebImages B ON BR.IDWebImage = B.ID
INNER JOIN BDB_WebImageCategory BK ON BR.IDImageCategory = BK.ID
LEFT OUTER JOIN DB_IMAGES BDB ON BDB.IDImage = b.IDOriginalBild
LEFT OUTER JOIN Multilingual_Translation MLSignature1 ON MLSignature1.IDObject = BR.ID
AND MLSignature1.IDObjectType = 36
AND MLSignature1.IDMultilingualAttribute = (SELECT TOP 1 ID FROM Multilingual_Attribute WHERE Tablename = 'BDB_WebImageReference' AND Columnname = 'titel')
AND MLSignature1.IDLanguage = 1
LEFT OUTER JOIN Multilingual_Translation MLSignature2
ON MLSignature2.IDObject = BR.ID
AND MLSignature2.IDObjectType = 36
AND MLSignature2.IDMultilingualAttribute = (SELECT TOP 1 ID FROM Multilingual_Attribute WHERE Tablename = 'BDB_WebImageReference' AND Columnname = 'Description')
AND MLSignature2.IDLanguage = 1
LEFT OUTER JOIN Multilingual_Translation MLSignature3
ON MLSignature3.IDObject = BR.ID
AND MLSignature3.IDObjectType = 36
AND MLSignature3.IDMultilingualAttribute = (SELECT TOP 1 ID FROM Multilingual_Attribute WHERE Tablename = 'BDB_WebImageReference' AND Columnname = 'Signature3')
AND MLSignature3.IDLanguage = 1
LEFT OUTER JOIN SEO_Permalink SEODataWebImage
ON SEODataWebImage.IDObjekt = BR.ID
AND SEODataWebImage.IDType = 36
AND SEODataWebImage.IDLanguage = 1
LEFT OUTER JOIN SEO_Permalink SEODataBild
ON SEODataBild.IDObjekt = BDB.IDImage
AND SEODataBild.IDType = 33
AND SEODataBild.IDLanguage = 1
WHERE BR.IDObjekt IN (25,26,38,40,45)
AND BR.IDObjectType = 36
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T21:53:50.443",
"Id": "58196",
"Score": "0",
"body": "what SQL database are you using?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T21:54:46.230",
"Id": "58197",
"Score": "0",
"body": "also please give a little bit more about what you are asking about and what you think is bogging down the query"
}
] |
[
{
"body": "<p>Queries involving a large amount of data blobs on a SQL Server version that does not support streams will be pretty slow.</p>\n\n<p>Try using a common table expression to build up your reference query before hitting the actual image data (I'm assuming you're using data blobs to store your image data - which should be as far down the query as possible).</p>\n\n<p>Also use variables, or more CTE's, to hit your <code>Multilingual_Attribute</code> table.</p>\n\n<p>If you're using an environment where CTEs are not available, you can use temp tables and index on <code>IDWebImage</code>, <code>IDImageCategory</code>, and <code>IDImage</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:24:50.807",
"Id": "26208",
"ParentId": "26203",
"Score": "3"
}
},
{
"body": "<p>The part of your query where you have several <code>AND</code> conditions on your joins is a bit messy, I would put those into your where statement, as it would be cleaner. </p>\n\n<p>You should only join tables <strong><code>ON</code></strong> their Key columns and not <strong><code>ON</code></strong> other columns, it slows down your query because these other columns aren't indexed like a Primary or Foreign key.</p>\n\n<p>You should also use Temp Tables, so that you don't have to call a <code>SELECT</code> inside of the table joining on the main query. This will also make the query faster because you can add indexes and keys where you need to in the temp table.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T21:54:05.290",
"Id": "35781",
"ParentId": "26203",
"Score": "1"
}
},
{
"body": "<p>This query is horribly over-working. I can only believe that the query has been 'simplified' to put here on CR. Otherwise, as far as I can tell, the query can be rewritten as:</p>\n\n<pre><code> SELECT BR.IDObject AS IDObject,\n B.imgName AS imgName, \n BK.imgPath AS imgPath,\n BR.imgType AS imgType\n\n FROM ImageReferences BR\n INNER JOIN BDB_WebImages B ON BR.IDWebImage = B.ID\n INNER JOIN BDB_WebImageCategory BK ON BR.IDImageCategory = BK.ID\n WHERE BR.IDObjekt IN (25,26,38,40,45)\n AND BR.IDObjectType = 36\n</code></pre>\n\n<p>This is because all the other tables were <code>OUTER</code> joins, and their values are never 'selected' or used for 'projection'. Thus, they were just redundant ....</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T15:40:06.743",
"Id": "58360",
"Score": "0",
"body": "what about the `IDMultilingualAttribute`? that is different in each of those joins. you gotta scroll all the way over"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T15:49:18.897",
"Id": "58361",
"Score": "0",
"body": "Yeah, so? what if it is different. If it matches a record, where is that record **used** (it's not selected anywhere). If it does not match a record, then it's an outer join, so no problem."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T15:52:36.627",
"Id": "58362",
"Score": "1",
"body": "@Malachi - put a different way, where are the table aliases `MLSignature[123]` actually used? **nowhere** !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T15:56:08.013",
"Id": "58363",
"Score": "1",
"body": "I get what you are saying, I see it now. Forest, trees, running, look at grass, hit tree"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T09:23:04.067",
"Id": "63943",
"Score": "0",
"body": "The original query would likely have returned the result set that this simpler query yields, but with each row possibly repeated. Therefore, this query is not identical to the original — it's probably better, assuming you only want distinct rows."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T15:34:59.657",
"Id": "35848",
"ParentId": "26203",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T14:47:27.010",
"Id": "26203",
"Score": "-2",
"Tags": [
"optimization",
"sql"
],
"Title": "Optimizing this seemingly slow Query"
}
|
26203
|
<p>I'm trying to come up with a simple router class. I considered using a <code>Request</code> class, but I think that will turn something simple into something overly complex. That is why I did not consider creating one for my framework.</p>
<pre><code>class Router {
private $uri;
private $controller;
private $action;
private $params;
public function __construct($uri) {
$this->uri = $uri;
$this->action = 'index';
$this->params = array();
}
public function map() {
$uri = explode('/', $this->uri);
if (empty($uri[0])) {
$c = new Config('app');
$this->controller = $c->default_controller;
} else {
$this->controller = array_shift($uri);
if (!empty($uri[1]))
$this->action = array_shift($uri);
if(!empty($uri[2]))
$this->params = $uri;
}
}
public function getController() {
return $this->controller;
}
public function getAction() {
return $this->action;
}
public function getParams() {
return $this->params;
}
}
</code></pre>
<p>In the bootstrap, I did this to map the url:</p>
<pre><code>$uri = filter_var(rtrim(isset($_GET['url']) ? $_GET['url'] : null, '/'), FILTER_SANITIZE_URL);
$router = new Router($uri);
$router->map();
</code></pre>
<p>What can I do to improve this? </p>
|
[] |
[
{
"body": "<h2>What is a router used for?</h2>\n\n<p>Translate one address to another one connection two different <em>network</em> to eahc other depending on rules. It will never instantita a browser to display for example a HTTP request.</p>\n\n<h2>Your class doing to much and much lesser than it should</h2>\n\n<p>Your router should only deal with the input address and not instantiating a controller and other stuff. How should it work?</p>\n\n<ol>\n<li>need a collection of rules, call RouteTable (will store Route instances)</li>\n<li>rule: how to translate an url to a usefull address in the framwork (how to get named parameters like controller or action and so on)</li>\n<li>the Router it self which is containing the logic</li>\n</ol>\n\n<h2>Rules, Routes</h2>\n\n<p>A rule should contain the following stuffs:</p>\n\n<ul>\n<li>a pattern, say: \"{controller}/{action}/{id}\"</li>\n</ul>\n\n<p>This will mean that if we have an url like book/details/5 then the framework somewhere will instantiate the book controller and call it's details method with parameter 5.</p>\n\n<ul>\n<li>set up default values are always good practise becouse a route can work without having all parts set</li>\n</ul>\n\n<p>For example an id is not always mandatory it can be optional or we could define a pattern like \"veryimportanturl\" but the framwork can handle like: controller => lottery, action => getthisweekwinningnumbers, id => 5</p>\n\n<ul>\n<li>a good to have feature is to attach a unique name to our routes so they could be used for generating urls or form action parameters</li>\n<li>a powerfull weapon could be if we can say to a route: \"hey you have a handler, so if you are used to handle one request then you should tell how can we do that\"</li>\n</ul>\n\n<p>We can create different handlers for different routes: can have one for handling an MVC task, another one so serve special images (so we do not need to go through a complete MVC cycle can be create a thinner logic).</p>\n\n<p>These rule should be mapped into our RouteTable which will be the responsible to store these and for example keep the unique route names.</p>\n\n<h2>Router</h2>\n\n<p>A router will need two things:</p>\n\n<ul>\n<li>the current request data (rewritten url and maybe query string)</li>\n<li>the RouteTable</li>\n</ul>\n\n<p>The router is responsible to pick the correct one from the collection can be done different ways but here is my solution:</p>\n\n<ol>\n<li>ordering the available routes: by the static parts (fix parameters not pattern elements ({})) and by the constraints (in a route i can set up constraint like the id onyle can be in the range of 0-5) [static length descending, constraints' numbers descending]</li>\n<li>iterating through the ordered rules collection and trying to find out which one will be the first mach by using regular expression (the Route contains it's pattern translated into regular expression), if a match found i try to fill the pattern with data; if everything is in place i've founded otherwise continuing the search.</li>\n</ol>\n\n<p>If the correct route has been found my routing engine returns it to the other parts of the framework but not just the pure route but mapped all the values came from the request. If nothing has found i face with an exception.</p>\n\n<p>The way i see the router above does nearly nothing compared to a real router but do things what should not be done by it. Beside this it's unflexible (fixed array indexes, has a hard dependency on a Config class and a default controller (why?)).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T03:16:44.503",
"Id": "40600",
"Score": "0",
"body": "You see that I am relatively new to this thing and trying to figure things out, giving an example would make your answer better, but I will try to learn from what you have just said. thank you!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T08:05:04.520",
"Id": "40605",
"Score": "0",
"body": "Isee but first you have to plan what do you want to achieve with your rouing mechanism. The above is just a heads up for what can be done in a router and in the surrounding objects. But your question is not simple becouse a lots of stuff depends on the other parts of your framework."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:32:48.697",
"Id": "40621",
"Score": "0",
"body": "I will consider all the things written above and I will return and ask for another review. Thank you!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T20:47:55.100",
"Id": "26216",
"ParentId": "26204",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T14:48:02.323",
"Id": "26204",
"Score": "2",
"Tags": [
"php",
"mvc",
"controller",
"url-routing"
],
"Title": "Router Class In a Lightweight MVC Boilerplate"
}
|
26204
|
<p>How can I eliminate repetition from this code?</p>
<pre><code>std::vector<std::wstring> vec;
bool descending;
if (descending)
{
std::sort(vec.begin(),
vec.end(),
std::greater<std::wstring>());
}
else
{
std::sort(vec.begin(),
vec.end(),
std::less<std::wstring>());
}
</code></pre>
<p>I tried </p>
<pre><code>std::sort(vec.begin(),
vec.end(),
descending
? std::greater<std::wstring>()
: std::less<std::wstring>());
</code></pre>
<p>but it fails because <code>greater</code> and <code>less</code> do not evaluate to the same type.</p>
<p>Another question: is it possible to automatically retrieve the required type, <code>std::wstring</code>, from the object <code>vec</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T18:21:58.147",
"Id": "40578",
"Score": "0",
"body": "All containers have an internal type indicating the type they contain: `vec::value_type`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T18:30:52.417",
"Id": "40579",
"Score": "0",
"body": "@LokiAstari: MSVC++10 complains \"A name followed by :: must be a class or namespace name.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T18:35:21.390",
"Id": "40580",
"Score": "0",
"body": "See below: For value_type"
}
] |
[
{
"body": "<p>not an answer but extended comment that needs space:</p>\n\n<pre><code> typedef std::vector<std::wstring> Vec;\n Vec vec;\n\n std::sort(vec.begin(), vec.end(), std::greater<Vec::value_type>());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T18:36:28.583",
"Id": "26213",
"ParentId": "26209",
"Score": "3"
}
},
{
"body": "<p>There are a few ways of going about this. One is creating an aggregate type that can forward to the call to the correct comparator. </p>\n\n<pre><code>template <typename T>\nstruct comp\n{\nprivate:\n bool desc;\n std::greater<T> great;\n std::less<T> less;\n\npublic:\n explicit comp(bool descending = false)\n : desc(descending)\n { }\n\n bool operator()(const T& f, const T& g) const\n {\n return (desc) ? great(f, g) : less(f, g);\n }\n};\n</code></pre>\n\n<p>The downside of this is that a <code>comp</code> object will be at least <code>sizeof(greater + less + bool)</code>. This may or may not be a problem. Your call to sort would then look something like:</p>\n\n<pre><code>typedef std::wstring str_t;\nbool descending = true;\nstd::sort(vec.begin(), vec.end(), comp<str_t>(descending));\n</code></pre>\n\n<p>If the decision is always known at compile time, you can play some template tricks:</p>\n\n<pre><code>template <typename T, bool desc>\nstruct comp;\n\ntemplate <typename T>\nstruct comp<T, true>\n{\nprivate:\n std::greater<T> great;\n\npublic:\n bool operator()(const T& f, const T& g) const\n {\n return great(f, g);\n }\n};\n\ntemplate <typename T>\nstruct comp<T, false>\n{\nprivate:\n std::less<T> less;\n\npublic:\n bool operator()(const T& f, const T& g) const\n {\n return less(f, g);\n }\n};\n</code></pre>\n\n<p>This requires <code>descending</code> to be <code>const</code> or <code>constexpr</code>:</p>\n\n<pre><code>constexpr bool descending = false;\nstd::sort(v.begin(), v.end(), comp<str_t, descending>());\n</code></pre>\n\n<p>This might be a one step forward, two step back kind of solution. It's quite a bit of code to avoid an <code>if/else</code> - you'll need to decide if this is worth it at all.</p>\n\n<p>Edit: As @LokiAstari pointed out, you can simplify the above with inheritance:</p>\n\n<pre><code>template <typename T> \nstruct comp<T, true>\n : std::greater<T>\n{ }\n\ntemplate <typename T> \nstruct comp<T, false>\n : std::less<T> \n{ }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T11:50:25.763",
"Id": "40613",
"Score": "2",
"body": "Last example can be simplified to: `template <typename T> struct comp<T, true>: std::greater<T> {}` and `template <typename T> struct comp<T, false>: std::less<T> {}`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:05:25.367",
"Id": "40617",
"Score": "0",
"body": "@LokiAstari Good point. Added."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T02:12:48.847",
"Id": "26221",
"ParentId": "26209",
"Score": "5"
}
},
{
"body": "<p>Just create a simple helper function template:</p>\n\n<pre><code>template<typename Iter>\nvoid sort_with_order(Iter i0, Iter i1, bool descending)\n{\n typedef typename std::iterator_traits<Iter>::value_type value_type;\n\n if (descending)\n {\n std::sort(i0, i1, std::greater<value_type>());\n }\n else \n {\n std::sort(i0, i1, std::less<value_type>());\n }\n}\n</code></pre>\n\n<p>Then call it like this:</p>\n\n<pre><code>std::vector<std::wstring> vec;\nbool descending;\n\n// ...\n\nsort_with_order(vec.begin(), vec.end(), descending);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T13:06:53.563",
"Id": "40714",
"Score": "0",
"body": "Of course, this is how I did it, still not optimal."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T04:13:08.343",
"Id": "26279",
"ParentId": "26209",
"Score": "1"
}
},
{
"body": "<p>Using <a href=\"http://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow\"><code>std::function</code></a> seems to work here with g++ 4.5.2 and <code>-std=c++0x</code>:</p>\n\n<pre><code>#include <algorithm>\n#include <functional>\n#include <iostream>\n#include <string>\n#include <vector>\n\nint main(int argc, char* argv[]) {\n std::function<bool(std::string,std::string)> cmp; \n if (false)\n cmp = std::greater<std::string>();\n else\n cmp = std::less<std::string>();\n\n std::vector<std::string> vec = { \"2\", \"1\", \"3\" };\n std::sort(vec.begin(), vec.end(), cmp);\n\n for (int i = 0; i < vec.size(); ++i) {\n std::cout << vec[i] << std::endl;\n }\n}\n</code></pre>\n\n<p>You can also use the ternary operator if you cast your compare objects to the same type:</p>\n\n<pre><code> typedef std::function<bool(std::string,std::string)> cmp_t;\n const auto cmp =\n true ? static_cast<cmp_t>(std::greater<std::string>()) :\n static_cast<cmp_t>(std::less<std::string>());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T07:39:41.113",
"Id": "26285",
"ParentId": "26209",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26221",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T15:46:35.703",
"Id": "26209",
"Score": "8",
"Tags": [
"c++",
"sorting",
"vectors"
],
"Title": "C++ vectors sort ascending/descending"
}
|
26209
|
<p>I'm pretty excited to have coded my first JavaScript file which now works, and I've spent my evening trying to improve it.</p>
<p>It takes a location in the <code>#loc</code> input box and geocodes it (gets coordinates from a location) when the search button is pressed, or when the autosuggestion is clicked, then submits the form.</p>
<p>I've worked hard on this but I am really interested to see if any JavaScript gurus can spot any mistakes, because I love beautiful code.</p>
<p><a href="http://jsfiddle.net/E8sNt/" rel="nofollow">jsFiddle</a></p>
<pre><code>var coded = false;
geocode();
$.cookie("country", "uk");
// GEOCODE FUNCTION
function geocode() {
var input = $('#loc')[0];
var options = {types: ['geocode']};
var country_code = $.cookie('country');
if (country_code) {
options.componentRestrictions = {
'country': country_code
};
}
var autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
processLocation();
});
$('#searchform').on('submit', function(e) {
if (coded === false) {
processLocation();
}
return true;
});
$("#loc").bind("change paste keyup", function() {
coded = false;
});
}
function processLocation() {
var geocoder = new google.maps.Geocoder();
var address = $('#loc').val();
geocoder.geocode({
'address': address
},
function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
coded = true;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
} else {
coded = false;
alert("Sorry - We couldn't find this location. Please try an alternative");
}
});
coded = true;
}
</code></pre>
|
[] |
[
{
"body": "<p>Looking at your code, the first thing that stands out is the <code>coded</code> variable. You're checking or setting its value in many different places, which is the sort of thing you want to avoid, as it can quickly lead to errors. You're manually keeping track of the state.</p>\n\n<p>A simpler, more robust solution would be to store the last searched-for location in the <code>processLocation</code> function, and if it's asked twice or more for that same location, give the same result as the first time. That way, the logic is all in one place.</p>\n\n<p>The second thing I notice is that there's some duplication going on. For instance, getting <code>$(\"#loc\")</code> several times, and in different functions. Another thing you'll want to avoid. It's the DRY principle: Don't repeat yourself. </p>\n\n<p>Lastly, I'm afraid there's an outright bug. You use <code>$.cookie</code> to set the country to \"uk\", and that'll happen every time the page loads. Cookies exist to store data <em>between</em> pageviews; by overwriting any existing value with \"uk\" every time the page loads, what you're doing is no different from just writing <code>var country = \"uk\";</code> and not using cookies at all. Moreover, unless there's a way for the user to choose another country, there's not even a reason to use a <code>var</code> much less a cookie. You could simply set <code>componentRestrictions.country</code> to \"uk\" directly.</p>\n\n<p>Here's a rewrite</p>\n\n<pre><code>$(function () { // this will be called when the page has loaded - and keep things contained\n var input = $(\"#loc\"), // find the elements once and for all\n lat = $(\"#lat\"),\n lng = $(\"#lng\"),\n lastQuery = null,\n autocomplete;\n\n function processLocation(query) {\n var query = $.trim(input.val()),\n geocoder;\n\n if( !query || query == lastQuery ) {\n return; // stop here if query is empty or the same as last time\n }\n\n lastQuery = query; // store for next time\n\n geocoder = new google.maps.Geocoder();\n geocoder.geocode({ address: query }, function(results, status) {\n if( status === google.maps.GeocoderStatus.OK ) {\n lat.val(results[0].geometry.location.lat());\n lng.val(results[0].geometry.location.lng());\n } else {\n alert(\"Sorry - We couldn't find this location. Please try an alternative\");\n }\n });\n }\n\n // set up\n\n autocomplete = new google.maps.places.Autocomplete(input[0], {\n types: [\"geocode\"],\n componentRestrictions: {\n country: \"uk\"\n }\n });\n\n google.maps.event.addListener(autocomplete, 'place_changed', processLocation);\n\n $('#searchform').on('submit', function (event) {\n processLocation();\n event.preventDefault();\n });\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T09:44:56.593",
"Id": "40607",
"Score": "0",
"body": "Flambino, thank you so much, this is a really clean rewrite. I've been playing with this all morning but there is one little problem with it that I can't fix. After the search button is clicked it should geocode (if it hasn't already) and then submit the form. Your code does everything right except submit the form, can you tell me how I do that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:08:42.677",
"Id": "40642",
"Score": "1",
"body": "@JamesWillson Ah - missed that, sorry. I'd recommend that you should post the question on StackOverflow (since it's a \"how do I...\"-question) - or maybe there's something similar there already. I'd answer here, but the structure/flow of things will need some tweaking (you have to wait for the geocoding to succeed/fail before the form submission can procede. Otherwise, the form might well get submitted before the geocoder gets results back). Your code didn't make such checks, so neither does mine, and I'd rather keep my answer as close to 1:1 with the original question. I hope that makes sense"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T23:31:11.050",
"Id": "26220",
"ParentId": "26215",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26220",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-15T20:15:45.463",
"Id": "26215",
"Score": "3",
"Tags": [
"javascript",
"performance",
"jquery",
"formatting",
"geospatial"
],
"Title": "JavaScript geocoder"
}
|
26215
|
<p>With the inclusion of <code><random></code> into C++11, we can finally chuck out <code>std::rand</code> and start using generator with much better properties. Still, it's easy to get things wrong (uniform sampling where 0 occurs more than it should due to usage of <code>% size</code> comes to mind). To that end, I've written some wrapper libraries to ease usage of the library for some basic tasks, namely:</p>
<ul>
<li>Selection of values from a sequence with equal probability</li>
<li>Selection of values from a sequence according to a weighted distribution</li>
<li>Random "choice" - <code>k</code> out of <code>n</code> selection. </li>
</ul>
<p>The style is very similar to that of most of the algorithms in <code><algorithm></code>. Any comments or suggestions (or bug-finding) is welcome:</p>
<p><code>initialized_generator.hpp</code>:</p>
<pre><code>/*! \file intialized_generator.hpp
* \brief Helper struct to initialize and "warm up" a random number generator.
*
*/
#ifndef INITIALIZED_GENERATOR_SGL_HPP__
#define INITIALIZED_GENERATOR_SGL_HPP__
#include <random>
#include <array>
#include <algorithm>
#include <type_traits>
#include <ctime>
namespace simplegl
{
namespace detail
{
template <typename GeneratorType>
struct initialized_generator
{
public:
typedef GeneratorType generator_type;
typedef typename generator_type::result_type result_type;
private:
generator_type generator_;
//! \brief Seeds the given generator with a given source of randomness.
/*!
* Some random number generators generate "poor" random numbers until their
* internal states are sufficiently "mixed up". This should seed the given
* generator with enough randomness to overcome the initial bad statistical
* properties that are seen in some of these generators.
*
* The code below was nabbed from
* http://stackoverflow.com/questions/15509270/does-stdmt19937-require-warmup
*
* \param rd A std::random_device, utilized to generate random seed data.
*/
void warmup(std::random_device& rd)
{
std::array<int, std::mt19937::state_size> seed_data;
std::generate_n(seed_data.data(), seed_data.size(), std::ref(rd));
std::seed_seq seq(std::begin(seed_data), std::end(seed_data));
generator_.seed(seq);
}
//! \brief Seeds the given generator utilizing the current time.
/*!
* Seeds the given generator utilizing the current time as a seed.
* If the generator is std::mt19937, then also attempts to initialize
* it and warm it up with some additional (not really random) seed
* parameters.
*/
void warmup()
{
std::time_t initial = time(nullptr);
//This branch will be optimized out at compile time
if(std::is_same<GeneratorType, std::mt19937>::value) {
//Even relatively close "non-random" numbers for a sequence should
//be ok for seeding a mersenne twister.
std::seed_seq seq{initial, initial + 1, initial + 2, initial + 3,
initial + 4, initial + 5};
generator_.seed(seq);
} else {
//For an LCG, time should suffice as a seed. For a subtract with carry,
//it may not - apparently they are actually quite difficult to seed
//and are incredibly sensitive to initial state. This should perhaps
//be changed to deal with that, but I don't really have the expertise
//to know exactly how.
generator_.seed(initial);
}
}
public:
initialized_generator()
{
warmup();
}
initialized_generator(std::random_device& rd)
{
warmup(rd);
}
//! \brief Returns the minimum possible value the underlying generator
/*! can generate.
*
* Simple wrapper function forwarding to GeneratorType::min().
*/
static constexpr result_type min()
{
return generator_type::min();
}
//! \brief Returns the maximum possible value the underlying generator
/*! can generate.
*
* Simple wrapper function forwarding to GeneratorType::max().
*/
static constexpr result_type max()
{
return generator_type::max();
}
//! \brief Returns the next random number from the underlying generator.
/*!
* Simple wrapper function forwarding to operator()().
* \return The next random number, of type GeneratorType::result_type.
*/
result_type operator()()
{
return generator_();
}
//! \brief Allows implicit conversion back to the underlying GeneratorType.
/*!
*/
operator generator_type()
{
return generator_;
}
}; //end struct initialized_generator
} //end namespace detail
} //end namespace simplegl
#endif //INITIALIZED_GENERATOR_SGL_HPP__
</code></pre>
<hr>
<p><code>weighted_selection.hpp</code>:</p>
<pre><code>/*! \file weighted_selection.hpp
* \brief Selects values from a sequence based on a linear weighting.
*
*/
#ifndef WEIGHTED_SELECTION_SGL_HPP__
#define WEIGHTED_SELECTION_SGL_HPP__
#include <iterator>
#include <random>
#include <initializer_list>
#include <utility>
#include "initialized_generator.hpp"
namespace simplegl
{
template <typename GeneratorType = std::mt19937, typename UIntType = std::size_t>
struct weighted_selection
{
private:
typedef UIntType uint_type;
std::discrete_distribution<UIntType> distribution_;
detail::initialized_generator<GeneratorType> generator_;
uint_type prob_length_;
public:
weighted_selection(std::initializer_list<double> init, std::random_device& rd)
: distribution_(init),
generator_(rd),
prob_length_(init.size())
{ }
weighted_selection(std::initializer_list<double> init)
: distribution_(init),
prob_length_(init.size())
{ }
template <typename Iterator>
weighted_selection(Iterator begin, Iterator end, std::random_device& rd)
: distribution_(begin, end),
generator_(rd),
prob_length_(std::distance(begin, end))
{ }
template <typename Iterator>
weighted_selection(Iterator begin, Iterator end)
: distribution_(begin, end),
prob_length_(std::distance(begin, end))
{ }
//! \brief Selects a random value from the sequence [begin, end) based
//* on the weights given on initialization.
/*!
* Overload that performs error checking based on the distance
* between begin and end.
*
* \param begin A parameter supporting the RandomAccessIterator concept,
* which dereferences to the start of the given sequenece.
* \param end A parameter supporting the RandomAccessIterator concept,
* which is one past the end of the sequence.
* \return The next random value, with probability given by the
* supplied weights.
* \throw std::length_error when the distance between end and
* begin is not equal to the length of the weights initially supplied
* on object construction.
*/
template <typename RandomAccessIter>
typename std::iterator_traits<RandomAccessIter>::value_type
operator()(RandomAccessIter begin, RandomAccessIter end)
{
auto distance = end - begin;
uint_type unsigned_distance =
(distance > 0) ? static_cast<uint_type>(distance) : 0;
if(unsigned_distance != prob_length_) {
throw std::length_error("Iterator distance does not equal probability \
weight distances");
}
auto next = distribution_(generator_);
return *(begin + next);
}
//! \brief Selects a random value from the sequence [begin, ...) based
//* on the weights given on initialization.
/*!
* Overloaded version that performs no error checking. It is assumed that
* (begin + weights.size() - 1) is dereferencable.
*
* \param begin A parameter supporting the RandomAccessIterator concept,
* which dereferences to the start of the given sequenece.
* \return The next random value, with probability given by the
* supplied weights.
*/
template <typename RandomAccessIter>
typename std::iterator_traits<RandomAccessIter>::value_type
operator()(RandomAccessIter begin)
{
auto next = distribution_(generator_);
return *(begin + next);
}
//! \brief The number of weights this was initialized with.
uint_type num_weights() const
{
return prob_length_;
}
}; //end struct weighted_selection
} //end namespace simplegl
#endif //WEIGHTED_SELECTION_SGL_HPP__
</code></pre>
<hr>
<p><code>uniform_selection.hpp</code>:</p>
<pre><code>/*! \file uniform_selection.hpp
* \brief Selects values from a sequence with equal probability.
*
*/
#ifndef UNIFORM_SELECTION_SGL_HPP__
#define UNIFORM_SELECTION_SGL_HPP__
#include <iterator>
#include <random>
#include <stdexcept>
#include "initialized_generator.hpp"
namespace simplegl
{
template <typename GeneratorType = std::mt19937, typename UIntType = std::size_t>
struct uniform_selection
{
public:
typedef UIntType uint_type;
private:
std::uniform_int_distribution<UIntType> distribution_;
detail::initialized_generator<GeneratorType> generator_;
public:
uniform_selection()
{ }
uniform_selection(std::random_device& rd)
: generator_(rd)
{ }
//! \brief Selects a random value from the sequence [begin, end) with
//* equal probability.
/*!
* \param begin A parameter supporting the RandomAccessIterator concept,
* which dereferences to the start of the given sequenece.
* \param end A parameter suporting the RandomAccessIterator concept,
* which points to one past the end of the sequence.
* \return The next random value from [begin, end) with each value
* having probability of 1 / distance(begin, end) of being
* chosen.
* \throw std::length_error if begin and end are equal, or if
* the distance between them is negative.
*/
template <typename RandomAccessIter>
typename std::iterator_traits<RandomAccessIter>::value_type
operator()(RandomAccessIter begin, RandomAccessIter end)
{
typedef typename std::uniform_int_distribution<UIntType> distribution_type;
typedef typename distribution_type::param_type param_type;
auto distance = end - begin;
uint_type unsigned_distance =
(distance > 0) ? static_cast<uint_type>(distance) : 0;
uint_type zero = 0;
if(distance <= 0) {
throw std::length_error("Iterator distance is negative or zero.");
}
auto next = distribution_(generator_, param_type(zero, unsigned_distance - 1));
return *(begin + next);
}
}; //end struct uniform_selection
} //end namespace simplegl
#endif //UNIFORM_SELECTION_SGL_HPP__
</code></pre>
<hr>
<p><code>intrusive_random_choice.hpp</code>:</p>
<pre><code>/*! \file intrusive_random_choice.hpp
* \brief Selects k random values from a sequence of length n, k <= n.
*
*/
#ifndef INTRUSIVE_RANDOM_CHOICE_SGL_HPP__
#define INTRUSIVE_RANDOM_CHOICE_SGL_HPP__
#include <algorithm>
#include <random>
#include <limits>
#include "initialized_generator.hpp"
namespace simplegl
{
template <typename GeneratorType = std::mt19937, typename UIntType = std::size_t>
struct intrusive_random_choice
{
public:
typedef UIntType uint_type;
private:
detail::initialized_generator<GeneratorType> generator_;
public:
intrusive_random_choice()
{ }
intrusive_random_choice(std::random_device& rd)
: generator_(rd)
{ }
//! \brief Selects k random values from a sequence, where each value is
//* chosen with equal probability. This will modify the order in the
//* underlying sequence [begin, end).
/*!
* k must be less than or equal to the length of the sequence. No checking
* is done to enforce this. If k is greater than the sequence length, this
* will result in undefined behaviour. Inserts the k values into a sequence
* starting at insert. There must be space allocated for at least k elements,
* otherwise, undefined behaviour will result.
*
* This will generate a correct uniform distribution for k when the sequence
* length is less than (roughly) 2500. Any size larger requires more
* sophisticated techniques.
*
* \param begin A parameter supporting the RandomAccessIterator concept,
* which dereferences to the start of the given sequenece to select
* values from.
* \param end A parameter suporting the RandomAccessIterator concept,
* which points to one past the end of the sequence to select
* values from.
* \param insert The start of the sequence where the k random values will
* be inserted.
*/
template <typename RandomAccessIter, typename RandomAccessIter2>
void operator()(RandomAccessIter begin, RandomAccessIter end,
RandomAccessIter2 insert, uint_type k)
{
std::shuffle(begin, end, generator_);
for(uint_type i = 0; i < k; ++i) {
*insert++ = *begin++;
}
}
}; //end struct intrusive_random_choice
} //end namespace simplegl
#endif //INTRUSIVE_RANDOM_CHOICE_SGL_HPP__
</code></pre>
<hr>
<p><code>example_usage.cpp</code>:</p>
<pre><code>#include <initializer_list>
#include <vector>
#include <string>
#include <iostream>
#include <unordered_map>
#include <deque>
#include "weighted_selection.hpp"
#include "uniform_selection.hpp"
#include "intrusive_random_choice.hpp"
using namespace simplegl;
int main()
{
//Weighted Selection example
weighted_selection<> rs {10, 15, 20, 12, 18};
std::vector<std::string> s {"The", "Cake", "Is", "A", "Lie"};
std::unordered_map<std::string, std::size_t> strcount;
//Select 15 random elements:
for(int i = 0; i < 15; ++i) {
std::cout << rs(s.begin(), s.end()) << "\n";
}
std::cout << "\n--------------------------------------------------\n";
//Uniform Selection Example
uniform_selection<> us;
std::deque<int> d{10, 15, 20, 25, 30};
std::unordered_map<int, std::size_t> counts;
for(unsigned i = 0; i < 100000; ++i) {
++counts[us(d.begin(), d.end())];
}
for(const auto& it : counts) {
std::cout << it.first << " seen: " << it.second << " times\n";
}
std::cout << "\n";
//The same uniform_selection object can be used with sequences with
//different lengths
std::vector<int> ex {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(int i = 0; i < 5; ++i) {
std::cout << "Random element from ex: " << us(ex.begin(), ex.end()) << "\n";
}
std::cout << "\n--------------------------------------------------\n";
//Intrusive random choice example
intrusive_random_choice<> irc;
//Make a copy of d so we leave it in order
std::deque<int> dcopy(d.begin(), d.end());
//We'll select 3 elements from the 5 in dcopy
std::vector<int> v(3);
counts.clear();
for(int j = 0; j < 100000; ++ j) {
irc(dcopy.begin(), dcopy.end(), v.begin(), 3);
for(int i : v) {
++counts[i];
}
}
for(const auto& it : counts) {
std::cout << it.first << " seen: " << it.second << " times\n";
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:01:53.043",
"Id": "40615",
"Score": "3",
"body": "Double underscore in identifiers `__` is reserved."
}
] |
[
{
"body": "<p>Overall, your code is clean, well written and seems very consistent (and the comments also seem relevant). There is not much to say, so I will focus on some details since I don't see anything else to review:</p>\n\n<ul>\n<li>First of all, Loki is right in his comment: your header guards names (<code>UNIFORM_SELECTION_SGL_HPP__</code>, <code>INTRUSIVE_RANDOM_CHOICE_SGL_HPP__</code>...) are actually <a href=\"https://stackoverflow.com/a/228797/1364752\">reserved to the implementation</a> since they contain double underscores. You should remove the last underscore so that they are well-formed.</li>\n<li>It is mainly a matter of taste, but I would use the new <a href=\"http://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow noreferrer\">type alias</a> syntax (with <code>using</code>) instead of the old <code>typedef</code>. Contrary to <code>typedef</code>, <code>using</code> can be templated, therefore it allows you to always be consistent, whether you have templates or not. Also, I find the <code>X = Y</code> syntax clearer and closer to variable assignment.</li>\n<li><p>A tidbit:</p>\n\n<pre><code>std::is_same<GeneratorType, std::mt19937>::value\n</code></pre>\n\n<p>I would replace <code>GeneratorType</code> by <code>generator_type</code>. It won't change the generated code but since you use the <code>typedef</code>s instead of the template parameters names in the rest of your code, it will be more consistent.</p></li>\n<li><p><code>//This branch will be optimized out at compile time</code></p>\n\n<p>I would replace <code>will</code> by <code>should</code>. While any decent compiler should optimize it, there is no such garantee that it will be the case for <em>any</em> compiler. Since you don't know which compiler your code will be compiled with, you shouldn't make the assumption (<em>Ok, that's really a detail</em>).</p></li>\n<li>You could use curly braces instead of parenthesis in the initialization list of your constructors to prevent implicit type conversions.</li>\n</ul>\n\n<p>As you can see, there is almost nothing to say about your current code. You even used <code>std::shuffle</code> and that's great (even greater since <code>std::random_shuffle</code> will be deprecated in C++14). That's some really good code, kudos! :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-11T13:20:39.870",
"Id": "46909",
"ParentId": "26222",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "46909",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T03:48:29.343",
"Id": "26222",
"Score": "11",
"Tags": [
"c++",
"c++11",
"random"
],
"Title": "Random Generation From Sequences"
}
|
26222
|
<p>The goal is to have fields in a class which are optional and can be determined if they are set in order to be able to leave them out of serialization. </p>
<pre><code>template<typename T>
class Nullable
{
public:
Nullable() : m_value(), m_isSet(false) {}
Nullable(T value) : m_value(value), m_isSet(true) {}
Nullable(const Nullable& other) : m_value(other.m_value), m_isSet(other.m_isSet) {}
friend void swap(Nullable& a, Nullable& b)
{
using std::swap;
swap(a.m_isSet, b.m_isSet);
swap(a.m_value, b.m_value);
}
Nullable& operator=(Nullable other)
{
swap(*this, other);
return *this;
}
T operator=(T value) { set(value); return m_value; }
bool operator==(T value) { return m_isSet && value == m_value; }
operator T() const { return get(); }
T get() const
{
if (m_isSet) return m_value;
else throw std::logic_error("Value of Nullable is not set.");
}
bool is_set() const { return m_isSet; }
void reset() { m_isSet = false; m_value = T(); }
private:
void set(T value) { m_value = value; m_isSet = true; }
private:
T m_value;
bool m_isSet;
};
</code></pre>
<p>Any comments are welcome.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-11-05T14:55:15.557",
"Id": "125908",
"Score": "0",
"body": "Use `const T&` and `T&&` for construct and assignment operators. Also use `const T&` where you don't modify the values. Use variadic templates with perfect forwarding for versatile in place constructors."
}
] |
[
{
"body": "<p><strike>Don't see the point in:</p>\n<pre><code>using std::swap;\n</code></pre>\n<p>It adds a line. It is also longer to type than just prefix each swap with <code>std::</code></strike></p>\n<p>As pointed out by @Matt below. There is a good reason to do this.<br />\nRead his links below for a more detailed description.</p>\n<p>No point in doing copy-swap idiom for a class that is not managing resources.<br />\nSo really there is no need for the copy constructor or the assignment operator: the compiler-generated versions will work perfectly well.</p>\n<p>If you can compare against a value:</p>\n<pre><code>bool operator==(T value) { return m_isSet && value == m_value; }\n</code></pre>\n<p>Why can't you compare against <code>Nullable<T></code>? The cast operator does not help you here - <code>operator T() const { return get(); }</code> - as it potentially throws. Yet it is still logical to be able to compare or it should throw if either side has <code>m_isSet</code> as <code>false</code>.</p>\n<pre><code>Nullable<int> x(5);\nNullable<int> y;\n\nif (y == x){} // works as expected (always false as y is not set).\nif (x == y){} // throws an exception.\n</code></pre>\n<p>Also <code>operator==</code> should be const.</p>\n<p>Cast and get methods should be returning a reference (big <code>T</code> objects are expensive to copy). You will also want const versions of these functions.</p>\n<p>On a reset:</p>\n<pre><code>void reset() { m_isSet = false; m_value = T(); }\n</code></pre>\n<p>Why reset the <code>m_value</code> when it can not be accessed anyway when <code>m_isSet</code> is false. Also the cost of setting <code>T</code> here may be expensive for some classes.</p>\n<p>As a general comment.<br />\nI don't see the point. Each class should have its own serialization operators (<code>>></code> and <code><<</code>) and you will need to serialize the whole state for this to work symmetrically. Anything that is not needed for serialization is already marked as mutable (i.e. it is not part of the logical state of the object). Everything else is part of the logical state of the object. Anything that is optional has its own serialize operator and understands when not to serialize its own state.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:59:30.460",
"Id": "40631",
"Score": "0",
"body": "Good comments, thank you. As for your general comment, I agree in general, however, this is something I need to fit into an ancient (pre-standard) codebase. Nothing has a serialization operator, they have external classes to serialize, with the pointless opaque getters and setters to get the state of the object. The idea is that these objects are serialized into ini files (yeah, I know, not my idea either) which are edited by humans later, and they want as few clutter as possible in it. I have some int fields which should work like this and I think this is the cleanest possible way to do this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T18:04:32.410",
"Id": "40654",
"Score": "3",
"body": "Actually, there's a point in `using std::swap;`--in fact it's a well-known idiom used to enable ADL: http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom ;\nSee also:\nhttps://en.wikipedia.org/wiki/Argument-dependent_name_lookup and Section\n3.II. in http://www.boostpro.com/writing/n1691.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T07:31:26.470",
"Id": "40702",
"Score": "0",
"body": "@Matt: yes. I keep forgetting that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-05-16T12:05:41.103",
"Id": "26226",
"ParentId": "26224",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "26226",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T07:46:57.090",
"Id": "26224",
"Score": "12",
"Tags": [
"c++",
"template"
],
"Title": "Simple \"nullable\" template class. Are there weaknesses in the implementation?"
}
|
26224
|
<p>I'm learning to work in GAE. I'm so used to SQL, but transform my way of think the last 20 years to NoSQL is a little hard for me.</p>
<p>I have the next simple structure:</p>
<ul>
<li><code>BOOKS</code> than can have <code>CHAPTERS</code></li>
<li><code>CHAPTERS</code> that can have <code>VOTES</code></li>
</ul>
<p>In a traditional SQL I just make foreign keys from <code>VOTES</code> to <code>CHAPTERS</code>, and from it to <code>BOOKS</code>.</p>
<p>I do this for my models in Datastore:</p>
<pre><code>class Book(db.Model):
title = db.StringProperty(required=True)
author = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
# Get all the Chapters for a book
def getChapters(self):
key = self.chapterMemkey()
chapters = memcache.get(key)
if chapters is None:
logging.info('DB access for key %s.', key)
chapters = Chapter.all().ancestor(self).order("number").fetch(100)
if not memcache.set(key, chapters, 300):
logging.error('Memcache set failed for Chapters.')
else:
logging.info('Memcache for key %s.', key)
return chapters
class Chapter(db.Model):
""" All chapters that a book have """
title = db.StringProperty(required=True)
number = db.IntegerProperty(default=1)
created = db.DateTimeProperty(auto_now_add=True)
book = db.ReferenceProperty(Book,
required=True,
collection_name='chapters')
# Search by Book (parent)
@classmethod
def byBook(cls, book, limit=100):
chapter = book.getChapters()
return chapter
# Search by id
@classmethod
def byId(cls, id, book):
return Chapter.get_by_id(long(id), parent=book)
class Vote(db.Model):
""" All votes that a book-chapter have """
chapterNumber = db.IntegerProperty(required=True)
option = db.IntegerProperty(default=1)
value = db.IntegerProperty(default=1)
book = db.ReferenceProperty(Book,
required=True,
collection_name='book_votes')
chapter = db.ReferenceProperty(Chapter,
required=True,
collection_name='chapter_votes')
# --------------------------
# ClassMethods for the class
# --------------------------
# Search by Book (parent)
@classmethod
def byBook(cls, book, limit=100):
vote = book.getVotes()
return vote
# Search by id
@classmethod
def byId(cls, id, book):
return Vote.get_by_id(long(id), parent=book)
</code></pre>
<p>Well, my doubts are:</p>
<ol>
<li>Is this approach correct?</li>
<li>Must I define in the <code>Vote</code> class a reference for a book and for a chapter, as it was a foreign keys (just like I think I've done)?</li>
<li>Is well defined the way to retrieve the chapters from a book? I mean, in the <code>Chapter</code> class the function <code>byBook</code> uses a function from the <code>Book</code> class.</li>
<li><p>In the Vote class, I also define the <code>byBook</code> function but, must I define another <code>byChapter</code> function with similar behaviour than the <code>myBook</code> function? I mean something like that:</p>
<pre><code>@classmethod
def byChapter(cls, chapter, limit=100):
vote = chapter.getVotes()
return vote
</code></pre></li>
<li><p>Are the parents well-defined for <code>Votes</code> (book) or must <code>Chapter</code> instead be a <code>Book</code>? The votes are for the chapters, but a chapter belongs to book.</p></li>
<li><p>Which are the right ways to get the sum of all the votes for a specific chapter and for specific book?</p></li>
</ol>
|
[] |
[
{
"body": "<ol>\n<li><p>This depends on a few things (keep reading).</p></li>\n<li><p>Not necessarily. This is a question of optimization. You could fetch a vote's book by using Chapter as an intermediary (<code>vote.getChapter().getBook()</code>), but this would obviously require sequential trips to the database - one to get the vote, followed by one to get the chapter, and finally one to get the book. Do you plan on fetching a book for a vote frequently? If so, save some resources and stick with what you've got.</p></li>\n<li><p>From a dependency standpoint, this seems counterintuitive, but since a chapter cannot exist without a book (can it?), I would say this is fine and simply a matter of preference. This always seems awkward to me as well, so maybe someone else can provide more info.</p></li>\n<li><p>You can, again, this is a question of optimization and convenience. When you have questions like this, ask yourself, \"will I really need this?\". If the answer is no, or you're unsure, leave it out; you can always add it later if your needs change (the relations are setup correctly to do the joins, right?).</p></li>\n<li><p>See above.</p></li>\n<li><p>I would provide a Chapter.getVotesSum() and/or Book.getVotesSum(). These methods would include GQL queries to aggregate the appropriate rows from the votes table into a sum.</p></li>\n</ol>\n\n<p>(Sorry if I'm missing something, I don't use GAE)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T14:46:36.707",
"Id": "40836",
"Score": "0",
"body": "Thanks, @JohnSyrinek. I preffer optimization vs comfort, so in point 2 I will use then the optimized code.In point 3, right, a chapter has no sense without a book. Finally, in point 6, I was thinking in mantain a variable to accumulate every vote, to avoid the aggregate sum every time I need this data. This is more work for me, but is a better performance (and a lot less reading) for the DB."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T19:44:20.787",
"Id": "41037",
"Score": "0",
"body": "Yep, I was just waiting for any other answer, but your is also good. Thank you. By the way, I change all my code to NDB today and the use of memcache for list querys. I'm learning a lot in the last days!!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T00:39:16.547",
"Id": "26276",
"ParentId": "26225",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26276",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T08:54:22.560",
"Id": "26225",
"Score": "1",
"Tags": [
"python",
"google-app-engine"
],
"Title": "Defining book models in GAE"
}
|
26225
|
<p>I am solving a problem on calculation of factorial and the challenge is as follows!</p>
<pre><code>You are asked to calculate factorials of some small positive integers.
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines,
each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
</code></pre>
<p>My Code is giving me the correct solution but Time limit is exceeded which is 2 seconds:</p>
<p>The code is as follows:</p>
<pre><code>#include<stdio.h>
#include<stdlib.h>
#include<math.h>
void factorial(int N)
{
printf("\n\n");
int q,i,j,t,d,z;
float p=0.0;
for(i=2;i<=N;i++)
p=p+log10(i);
d=(int)p+1;//No of terms in the factorial
int *b;
//initialization of an array
b=(int *)malloc(d*sizeof(int));
b[0]=1;
for(i=1;i<d;i++)
b[i]=0;
//calculation of factorial
p=0.0;
for(j=2;j<=N;j++)
{
q=0;
p=p+log10(j);
z=(int)p+1;
for(i=0;i<N;i++)
{
t=(b[i]*j)+q;
q=t/10;
b[i]=t%10;
}
}
for(i=d-1;i>=0;i--)
printf("%d",b[i]);
}
int main()
{
int n,i,j;
scanf("%d",&n);
int *b;
b=(int *)malloc(n*sizeof(int));
for(i=0;i<n;i++)
{
scanf("%d",&b[i]);
}
for(i=0;i<n;i++)
factorial(b[i]);
return 0;
}
</code></pre>
<p>How can i make my program more efficient and produce the output in the given time limit? This challenge is from <a href="http://www.hackerearth.com/problem/algorithm/small-factorials/" rel="nofollow">HackerEarth</a></p>
|
[] |
[
{
"body": "<p>The following comments are somewhat related :</p>\n\n<ul>\n<li><p>Your <code>factorial</code> function should probably be called <code>printFactorial</code>.</p></li>\n<li><p>You should separate the computing logic and the printing logic.</p></li>\n<li><p>You could use/implement a way to handle Big Integers in a clearer way. Here you are handling (if I understand correctly) each digit individually. (To be honest, I haven't even tried to understand how things are supposed to work at the moment because as everything is happening in a single place, it's hard to tell what's intended).</p></li>\n<li><p>You could cache the results (you compute the factorial for all numbers from 1 to 100 once and for all and then you just loop on the input, fetch the corresponding value from your cache and print it).</p></li>\n<li><p>You don't need to store the input values in an array:</p></li>\n</ul>\n\n<p>You could just do something like :</p>\n\n<pre><code> int n;\nscanf(\"%d\",&n);\nfor(i=0;i<n;i++)\n{\n int b=0;\n scanf(\"%d\",&b);\n factorial(b);\n}\nreturn 0;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:42:12.743",
"Id": "26238",
"ParentId": "26228",
"Score": "1"
}
},
{
"body": "<p>The best solution is only to compute the factorials you need and only compute them once.</p>\n\n<ol>\n<li>Read all the user input find the maximum value.</li>\n<li>Generate the factorials for all values upto the max<br>\nNote: Saving them as you go:</li>\n<li>Print the factorial values by looking up the result you generated in 2.</li>\n</ol>\n\n<p>So lets look at the code:</p>\n\n<p>I would not bother dynamically allocating the data storage.</p>\n\n<pre><code> b=(int *)malloc(n*sizeof(int));\n</code></pre>\n\n<p>The question specifically limits the maximum value of n to 100.</p>\n\n<pre><code> int b[101]; // should be suffecient\n</code></pre>\n\n<p>When reading values this should work (if you assume that the input is good).</p>\n\n<pre><code> scanf(\"%d\",&b[i]);\n</code></pre>\n\n<p>But the question states that the input is one value per line. Personally I would validate that there is one value per line.</p>\n\n<p>Here you are calculating the factorial multiple times:</p>\n\n<pre><code> for(i=0;i<n;i++)\n factorial(b[i]); // Factorial is O(n)\n // Thus this loop is O(n^2)\n</code></pre>\n\n<p>Technically you only need to call factorial once. If you calculate factorial for 'n' you need to calculate the factorial for 'n-1' (its how it is defined). If you store the numbers then you only need to look up the values to print it once they have been calculated.</p>\n\n<p>It seems like you calculate this value each time.</p>\n\n<pre><code> float p=0.0;\n for(i=2;i<=N;i++)\n p=p+log10(i);\n</code></pre>\n\n<p>The worst case scenario is that you need to calculate this for a value of 100. You only need to calculate this one for 100. Also you can calculate it off line and now it is a const expression.</p>\n\n<p>This is then a const expression and thus you don't need to calculating it.</p>\n\n<pre><code> b=(int *)malloc(d*sizeof(int));\n</code></pre>\n\n<p>But you do need 100 of them so you can store all intermediate values:</p>\n\n<p>You don't need to loop over an array to initialize it:</p>\n\n<pre><code> for(i=1;i<d;i++)\n b[i]=0;\n</code></pre>\n\n<p>You can initialize it already zero'd out. For dynamic memory use <code>calloc()</code> for automatic arrays use <code>= {0};</code></p>\n\n<p>So the above two can be combined into;</p>\n\n<pre><code> const int d = <pre-calculated value>;\n int b[100][d] = {0};\n b[0][0] = 1;\n b[1][0] = 1;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:24:51.907",
"Id": "26250",
"ParentId": "26228",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26250",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:19:49.853",
"Id": "26228",
"Score": "2",
"Tags": [
"c",
"algorithm",
"performance"
],
"Title": "Time limit of a c program while calculating factorial of numbers in c"
}
|
26228
|
<p>I am hiding and fading in different content on the same page using jQuery to <code>hide()</code> and <code>fadeIn()</code> the content depending on which link is clicked.</p>
<p>It works how I want it to, but the way I've written the jQuery looks like it could be simplified.</p>
<pre><code>$("#navItem1").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap1').fadeIn(1000);
});
$("#navItem2").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap2').fadeIn(1000);
});
$("#navItem3").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap3').fadeIn(1000);
});
$("#navItem4").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap4').fadeIn(1000);
});
$("#navItem5").on('click', function(){
$('#content-wrap1').hide();
$('#content-wrap2').hide();
$('#content-wrap3').hide();
$('#content-wrap4').hide();
$('#content-wrap5').hide();
$('#content-wrap5').fadeIn(1000);
});
function fadeInFirstContent(){
$('#content-wrap1').fadeIn(1000);
}
fadeInFirstContent();
</code></pre>
<p><a href="http://jsfiddle.net/VQtwa/">Here's a jfiddle</a></p>
<p>How can I rewrite the jQuery so it does exactly the same thing but in much less code?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:49:02.660",
"Id": "40627",
"Score": "1",
"body": "For some reason all the current answers seem to want you to change the HTML or add random loops. There is no need. My answer here uses basic jQuery functionality to achieve all of this in just 5 lines: http://codereview.stackexchange.com/a/26236/24039. You'll benefit from the official jQuery interactive tutorial: http://try.jquery.com."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:57:42.210",
"Id": "40636",
"Score": "8",
"body": "@JamesDonnelly, the HTML *should* be changed to use classes instead of these repetitive `[id]`s. It makes the HTML more expressive of the fact that these elements obviously share a similar class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T14:56:41.037",
"Id": "40638",
"Score": "1",
"body": "While @crm might be constrained and isn't in a position to update the HTML, I agree with zzzzBov that it's the best direction to take."
}
] |
[
{
"body": "<p>Perhaps change the HTML:</p>\n\n<p>Navitem:</p>\n\n<pre><code><span class=\"navItem\" data-content-id=\"1\"></span>\n</code></pre>\n\n<p>The content</p>\n\n<pre><code><div id=\"content-wrap1\" class=\"content-wrap\"></div>\n</code></pre>\n\n<p>jQuery</p>\n\n<pre><code>$('.navItem').on('click',function(){\n $('.content-wrap').hide();\n $('#content-wrap'+$(this).data('content-id')).fadeIn(1000);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:03:06.703",
"Id": "40662",
"Score": "1",
"body": "This is much better than using a substring of the ID. Also, you’re missing a `.` in front of `navItem`…"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T22:51:20.313",
"Id": "40679",
"Score": "0",
"body": "This is better than the accepted answer, though I feel it would be cleaner with data attributes on the content-wrap elements instead of an ID. A selector like `.content-wrap[data-wrapid=VAR]` wouldn't be noticeably slower. Alternatively, simply use `eq()` to select the nth element."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:33:02.667",
"Id": "26230",
"ParentId": "26229",
"Score": "31"
}
},
{
"body": "<p>yes there is...there are many ways to simplify this.. i am doing it by using <code>data</code> attribute to your <code><a></code> tag...and adding same class to all the contents <code><div></code> .(i am using content here)...</p>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><nav>\n<!-- Start of side menu -->\n<ul id=\"mainNav\">\n <li class=\"mainNavItem\"><a href=\"#\" id=\"navItem1\" data-content=\"content-wrap1\">Home</a>\n </li>\n <li class=\"mainNavItem\"><a href=\"#\" id=\"navItem2\" data-content=\"content-wrap2\">Prices</a>\n </li>\n <li class=\"mainNavItem\"><a href=\"#\" id=\"navItem3\" data-content=\"content-wrap3\">Find us</a>\n </li>\n <li class=\"mainNavItem\"><a href=\"#\" id=\"navItem4\" data-content=\"content-wrap4\">Reviews</a>\n </li>\n <li class=\"mainNavItem\"><a href=\"#\" id=\"navItem5\" data-content=\"content-wrap5\">Gallery</a>\n </li>\n </ul>\n</nav>\n<!-- closes mainNav -->\n<div id=\"content-wrap1\" class=\"content\">Home</div>\n<div id=\"content-wrap2\" class=\"content\">Prices contents</div>\n<div id=\"content-wrap3\" class=\"content\">find us contents</div>\n<div id=\"content-wrap4\" class=\"content\">review contents</div>\n<div id=\"content-wrap5\" class=\"content\">gallery contents</div>\n</code></pre>\n\n<p><strong>jquery</strong></p>\n\n<pre><code>$('ul#mainNav li a').click(function () {\n $('.content').hide();\n $('#' + $(this).data('content')).fadeIn(1000);\n});\n\n\n\nfunction fadeInFirstContent() {\n $('#content-wrap1').fadeIn(1000);\n\n}\nfadeInFirstContent();\n</code></pre>\n\n<p>or without adding classes to content..</p>\n\n<pre><code> $(function(){\n $('ul#mainNav li a').click(function () {\n $('div[id^=\"content-wrap\"]').hide();\n $('#' + $(this).data('content')).fadeIn(1000);\n });\n $('#content-wrap1').fadeIn(1000);\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/bipen/VQtwa/1/\" rel=\"nofollow\">fiddle here</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:36:03.023",
"Id": "26234",
"ParentId": "26229",
"Score": "3"
}
},
{
"body": "<p>I think this should do the trick</p>\n\n<pre><code>for (var j = 1; j <= 5; j++) { \n (function(i){\n $(\"#navItem\" + i).on('click', function(){\n $('#content-wrap1').hide();\n $('#content-wrap2').hide();\n $('#content-wrap3').hide();\n $('#content-wrap4').hide();\n $('#content-wrap5').hide();\n $('#content-wrap' + i).fadeIn(1000);\n });\n })(j);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:37:36.017",
"Id": "40623",
"Score": "0",
"body": "Hi, could you explain what is happening in that for loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:41:31.567",
"Id": "40625",
"Score": "0",
"body": "@crm: inside the loop I'm defining a function that gets a number as parameter. Inmediatly after defining the function, I'm calling it trough this statement `(j)`. This is a closure."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:44:49.117",
"Id": "40626",
"Score": "0",
"body": "How does `i` hold the value? Shouldn't you be calling `j` within the loop? also why is `j` in the parenthesis at the end like that?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:54:28.257",
"Id": "40629",
"Score": "2",
"body": "@crm: it's the magic of closures :) Here you have a SO popular question that may clarify this topic http://stackoverflow.com/questions/111102/how-do-javascript-closures-work. `j` in the parenthesis at the end is the way to call the function I just defined with parameter `j`"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:36:45.290",
"Id": "26235",
"ParentId": "26229",
"Score": "5"
}
},
{
"body": "<p><strong>You don't have to change the HTML markup at all.</strong> You can make use of the starts-with <a href=\"http://www.w3.org/TR/selectors/\">CSS selector</a> (<code>^=</code>):</p>\n\n<pre><code>// All elements with an ID starting with navItem...\n$('[id^=\"navItem\"]').on('click', function() {\n var\n // Get the ID as a string\n id = this.id,\n // Get the last character from the ID\n num = id.charAt(id.length-1)\n ;\n // Hide all elements with an ID starting with content-wrap...\n $('[id^=\"content-wrap\"]').hide();\n // Fade in the relevant ID\n $('#content-wrap'+num).fadeIn(1000);\n});\n</code></pre>\n\n<p>If we assume \"navItem5\" is used, here is what the variables would contain:</p>\n\n<pre><code>id == \"navItem5\"\nnum == \"5\"\n$('#content-wrap'+num) == \"#content-wrap5\"\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/hsDLE/2/\"><strong>JSFiddle example</strong></a>.</p>\n\n<p>This is very basic jQuery. You'd benefit from going through the official jQuery interactive tutorial: <a href=\"http://try.jquery.com\">http://try.jquery.com</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:59:16.150",
"Id": "40630",
"Score": "2",
"body": "Why not just do: `var id = this.id;`? No need for `$(this).attr('id')`... It's also massively faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:01:28.047",
"Id": "40632",
"Score": "2",
"body": "That would be a simple oversight, I've modified the answer. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:15:46.277",
"Id": "40645",
"Score": "0",
"body": "Possibly include `.toggle()` if OP is going to use the same click to show/fadeout."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T22:43:53.237",
"Id": "40678",
"Score": "2",
"body": "While this answer works, it's very hacky to extract numbers out of ID attributes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T23:37:36.007",
"Id": "40685",
"Score": "2",
"body": "I’ll comment on my downvote from a few hours ago: this is incredibly fragile, and wanton abuse of IDs. What if the numbers go past `9`, for example? Why not just use a clean and very efficient class? *Why don't you cache that collection, or put it in an array, or something nice?*"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:40:39.977",
"Id": "26236",
"ParentId": "26229",
"Score": "13"
}
},
{
"body": "<p>Here's one with minimal changes to the HTML (only a common container for the contents):</p>\n\n<pre><code>$( '.mainNavItem a' ).on( 'click', function() {\n $( '#content > div' ).hide() // hide all content divs \n // (immediate div children of the main container)\n .eq( $( this ).parent().index() ) // match the index of the clicked link\n // with the index of the corresponding content\n .fadeIn( 1000 ); // display that div\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/VQtwa/2/\" rel=\"nofollow\">http://jsfiddle.net/VQtwa/2/</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:41:03.563",
"Id": "26237",
"ParentId": "26229",
"Score": "1"
}
},
{
"body": "<p>It could be done much shorter:\n<a href=\"http://jsfiddle.net/2ADyp/\" rel=\"nofollow\">http://jsfiddle.net/2ADyp/</a></p>\n\n<pre><code>function hideAll(){\n $('#content-wrap1').hide();\n $('#content-wrap2').hide();\n$('#content-wrap3').hide();\n$('#content-wrap4').hide();\n$('#content-wrap5').hide();\n}\n\nfunction showSelected(e){\n hideAll();\n $(e.target.hash).fadeIn(100);\n}\n\n$(\"#mainNav\").find(\"a\").each(function(i,o){ \n $(o).click(showSelected);\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-26T18:13:11.947",
"Id": "423413",
"Score": "1",
"body": "`hideAll()` can be minimized to `$('#content-wrap1,#content-wrap2,#content-wrap3,#content-wrap4,#content-wrap5').hide()`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:50:29.570",
"Id": "26240",
"ParentId": "26229",
"Score": "2"
}
},
{
"body": "<p>Assuming you're using an expressive structure such as:</p>\n\n<pre><code><nav>\n <a href=\"#content-wrap1\" id=\"navItem1\" class=\"navItem\">One</a>\n <a href=\"#content-wrap2\" id=\"navItem2\" class=\"navItem\">Two</a>\n <a href=\"#content-wrap3\" id=\"navItem3\" class=\"navItem\">Three</a>\n</nav>\n<div id=\"content-wrap1\" class=\"content-wrap\">...</div>\n<div id=\"content-wrap2\" class=\"content-wrap\">...</div>\n<div id=\"content-wrap3\" class=\"content-wrap\">...</div>\n</code></pre>\n\n<p>You can then toggle the display of the <code>content-wrap</code> items in a short, expressive manner.</p>\n\n<pre><code>$('.navItem').on('click', function (e) {\n $('.content-wrap').hide();\n $($(this).prop('hash')).fadeIn(1000);\n e.preventDefault();\n});\n</code></pre>\n\n<p>This <em>does</em> suggest changing the HTML, but only in ways that make the content semantic.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:45:03.987",
"Id": "40647",
"Score": "0",
"body": "You should make use of the [`data-*`](http://www.w3.org/TR/html5/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes) attribute to store data, not the `href` attribute (`<a data-id=\"#content-wrap1\" .../>` then you can pull it using `$(this).data('id')`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:53:59.947",
"Id": "40648",
"Score": "1",
"body": "@JamesDonnelly, the `href` is more appropriate if the item being clicked on is a link. The fragment identifier is designed to point the user to a particular ID in the DOM, so even if JavaScript is disabled, the same section will be highlighted. If the item is *not* a link, it certainly makes sense to use a `[data-*]` attribute, although I'd probably use `data-target` or `data-content-element` because `data-id` seems a little too ambiguous."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T17:58:22.043",
"Id": "40653",
"Score": "0",
"body": "if JavaScript was disabled the element wouldn't be visible anyway, so it wouldn't matter in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T18:15:55.103",
"Id": "40656",
"Score": "1",
"body": "@JamesDonnelly, \"the element wouldn't be visible anyway\" no, if you set up your styles and scripts correctly, all the elements will be shown with javascript disabled. While it may not be what OP has set up, you have to remember that this *is* [CodeReview.SE]."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T15:33:59.660",
"Id": "26246",
"ParentId": "26229",
"Score": "2"
}
},
{
"body": "<p>why not skip the javascript completely?</p>\n\n<p><a href=\"http://jsfiddle.net/zCd9g/\" rel=\"nofollow\">http://jsfiddle.net/zCd9g/</a></p>\n\n<p>EDIT: sorry that's completely unhelpful seeing as this is a javascript question. Here's a solution with <em>some</em> modifications to the HTML: </p>\n\n<p><a href=\"http://jsfiddle.net/aECMb/\" rel=\"nofollow\">http://jsfiddle.net/aECMb/</a></p>\n\n<pre><code>$('.link').click(function(e) {\n e.preventDefault();\n\n var $con = $('#main-content'),\n tar = $(this).data('show');\n\n $con.find('.contents').fadeOut();\n $con.find(tar).fadeIn();\n\n});\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T10:44:04.947",
"Id": "40766",
"Score": "0",
"body": "It is ok to post a working demo on JSFiddle. Nevertheless, add the relevant code to your answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T22:42:50.617",
"Id": "26312",
"ParentId": "26229",
"Score": "1"
}
},
{
"body": "<p>I've noted some details, let me explain:</p>\n\n<hr>\n\n<ol>\n<li><p><a href=\"http://www.w3schools.com/cssref/css_selectors.asp\" rel=\"nofollow\">CSS Selectors</a>. jQuery allows you to use them too:</p>\n\n<p><code>$(\"[id^='content-wrap']\")</code> --> will select all elements which id starts with 'content-wrap'</p></li>\n</ol>\n\n<hr>\n\n<ol start=\"2\">\n<li><a href=\"https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/String/substring\" rel=\"nofollow\">Substring</a> is an available method of JavaScript:</li>\n</ol>\n\n\n\n<pre><code>var number = \"navItem15\".substring(7);\n// will return what is after position 7.. \n// resulting the number \"15\"\n</code></pre>\n\n<hr>\n\n<ol start=\"3\">\n<li>To start your menu with the first position. <a href=\"http://jsfiddle.net/VQtwa/22/\" rel=\"nofollow\">This is</a> the best way:</li>\n</ol>\n\n\n\n<pre><code>(function(){\n $(\"#navItem1\").trigger(\"click\");\n})();\n// using this approach, you won't need copy your code into a function as you did\n// this approach triggers the \"click\" event in the first menu automatically\n</code></pre>\n\n<hr>\n\n<p>Well, hope you got it!</p>\n\n<p>Nice coding!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-03T15:46:24.767",
"Id": "88704",
"ParentId": "26229",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26230",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T12:31:46.860",
"Id": "26229",
"Score": "25",
"Tags": [
"javascript",
"jquery"
],
"Title": "Set of jQuery .onclick functions"
}
|
26229
|
<p>I just wrote my first Java database program for the purpose of getting feedback on the implementation and coding. It has 1 table and 2 buttons and prompts the user to select a folder, lists the contents of the folder in the table and lists the hash of the files in the table and writes it to a database.</p>
<p>It works fine, but I have no idea if I coded it cleanly and split the program into the proper packages and classes. It's definitely a beginner level project so there is nothing too complex about it. I'm also using the h2 database because I was told its the most efficient for small databases. Could you all please give me feedback on this?</p>
<p>I used NetBeans 7.3 and uploaded the full project <a href="http://www.mediafire.com/?huujeed8oiwonr8" rel="nofollow">here</a>. This is the class I'm using for the database. It contains most of the code I have in question, but there are other parts of the project as a whole I'm concerned if they were organized correctly:</p>
<pre><code>public class CDatabaseLayer {
private static ArrayList<CFileObject> fileList = new ArrayList();
private static Server server;
private static JdbcDataSource ds = new JdbcDataSource();
private static Connection conn;
private static int lastId = 0;
private static Statement stat;
private static ResultSet rs;
private static String query;
static public ArrayList<CFileObject> getFileList() {
connectDatabase();
return fileList;
}
static public boolean connectDatabase()
{
System.out.println("Attempting to connect to database.");
if(server == null) {
try {
server = Server.createTcpServer();
server = server.start();
} catch (SQLException ex) {
System.out.println("connectDatabase createTcpServer() exception: "+ex);
return false;
}
}
//return false if connected
if(conn != null) {
System.out.println("Already established DB connection.");
return false;
} else {
try {
//connect to database
ds.setURL("jdbc:h2:test");
ds.setUser("sa");
ds.setPassword("");
conn = ds.getConnection();
if(conn.isClosed()) {
System.out.println("Connection not established.");
} else {
System.out.println("Connected.");
createFileListTable();
loadFileListTable();
}
} catch (SQLException ex) {
System.out.println("connectDatabase getConnection() exception: "+ex);
}
}
return true;
}
static private void loadFileListTable()
{
try {
stat = newStatement();
rs = stat.executeQuery("select * from fileList");
fileList.clear();
while(rs.next()) {
CFileObject objF = new CFileObject();
objF.fileName = rs.getString("fileName");
objF.filePath = rs.getString("filePath");
objF.fileHash = rs.getString("fileHash");
fileList.add(objF);
}
} catch (SQLException ex) {
System.out.println("loadFileListTable exception: "+ex);
}
}
static public void manipulateFiles() throws SQLException {
try {
if(conn.isClosed()) {
System.out.println("manipulateFiles: Connection is closed.");
}
} catch (SQLException ex) {
System.out.println("manipulateFiles connection exception: "+ex);
}
for(CFileObject f : fileList) {
String hash = new String();
try {
hash = hashFile.getMD5Checksum(f.filePath);
} catch (Exception ex) {
System.out.println("manipulateFiles hash exception: "+ex);
}
f.fileHash = hash;
query = "update filelist set filehash = '"+hash+"' where filepath = '"+f.filePath+"'";
stat = newStatement();
//QUESTION: Why does this return false??
stat.execute(query);
}
}
static public void updateDatabaseWithFilesFromPath(File path)
{
ArrayList<CFileObject> list;
list = CFileObject.getListFromPath(path);
for(CFileObject file : list) {
if(!entryExists("filelist", "filepath", file.filePath)) {
try {
lastId = nextUnusedId();
addFileEntry(lastId, file.fileName, file.filePath);
fileList.add(file);
} catch (SQLException ex) {
System.out.println("updateDatabaseWithFilesFromPath exception: "+ex);
}
}
}
}
/*
static public void updateDatabase() throws SQLException
{
lastId = nextUnusedId();
for (final CFileObject file : fileList) {
if(!entryExists("filelist", "filepath", file.filePath)) {
lastId = nextUnusedId();
addFileEntry(lastId, file.fileName, file.filePath);
}
}
}
*/
private static Statement newStatement()
{
try {
stat = conn.createStatement();
return stat;
} catch (SQLException ex) {
System.out.println("newStatement exception: "+ex);
}
return null;
}
//QUESTION: Is there a more efficient way to do this?
private static void createFileListTable()
{
try {
//see if fileList table exists. if not, catch error and create it
try {
stat = newStatement();
stat.executeQuery("select * from fileList");
} catch(SQLException e) {
if(e.toString().contains("Table \"FILELIST\" not found")) {
System.out.println("Creating filelist table.\n");
stat.execute("create table filelist(id int primary key, fileName varchar(255), filePath varchar(512), fileHash varchar(32))");
} else {
System.out.println(e);
}
}
} catch(SQLException ex) {
System.out.println("createFileListTable exception: "+ex);
}
}
private static int nextUnusedId()
{
try {
stat = newStatement();
rs = stat.executeQuery("select id from fileList");
if(rs.last()) {
lastId = rs.getInt("id");
lastId++;
}
} catch (SQLException ex) {
System.out.println("nextUnusedId exception: "+ex);
}
return lastId;
}
private static boolean entryExists(String table, String prop, String val)
{
try {
stat = newStatement();
query = "select 1 from "+table+" where "+prop+" = '"+val+"'";
rs = stat.executeQuery(query);
return rs.last();
} catch (SQLException ex) {
System.out.println("entryExists exception: "+ex);
}
return true;
}
private static void addFileEntry(int entryId, String fileName, String filePath) throws SQLException
{
query = "insert into fileList values("+entryId+", '"+fileName+"', '"+filePath+"', 0)";
stat = newStatement();
//QUESTION: Why does this return false??
stat.execute(query);
}
static public void disconnectDatabase()
{
server.stop();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>This is what I noticed after taking a quick look:</p>\n\n<ol>\n<li>I'm not a big fan of the static/singleton-ness of this class. Those attributes make this class harder to mock and unit test. Take a look at POJO/dependency injection (you don't need a container to do DI).</li>\n<li>I would consider separating the database/Connection opening stuff into its own class. There should be separation of what the data access/service layer from the resource/connection code. Take a look at DAO/Service patterns.</li>\n<li>getFileList() returns a concrete List implementation instead of the List interface.</li>\n<li>A lot of your methods don't close the ResultSet and Statement objects once they are done with them. They should be closed in finally blocks.</li>\n<li>Your catch blocks aren't doing much besides printing to System.out. You need to either handle recoverable exceptions there or propogate them up the stack as a RuntimeException.</li>\n<li>Not sure why you need newStatement().</li>\n<li>You are manually creating and executing SQL strings. This is a bad idea. Replace these with PreparedStatements.</li>\n<li>This class isn't threadsafe. It should be documented as much.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T03:18:23.867",
"Id": "40697",
"Score": "0",
"body": "Thanks for your comments. It sounds like I'm doing a lot wrong. Where can I find proper implementations of simple programs like this? I learn best through examples and I haven't been able to find any simple tutorials that used databases like this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:49:38.317",
"Id": "40731",
"Score": "1",
"body": "One, pick up a copy of Joshua Bloch's Effective Java, 2nd edition. It is the definitive book about Java programming and best practices. Two, here are a couple of links to get you started: [Core J2EE Patterns - Data Access Object](http://www.oracle.com/technetwork/java/dataaccessobject-138824.html), [Data Access object (DAO) Design Pattern](http://www.roseindia.net/tutorial/java/jdbc/dataaccessobjectdesignpattern.html), [JDBC Basics](http://docs.oracle.com/javase/tutorial/jdbc/basics/index.html)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T18:58:44.720",
"Id": "26255",
"ParentId": "26242",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "26255",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:29:25.500",
"Id": "26242",
"Score": "3",
"Tags": [
"java",
"database"
],
"Title": "Basic Java database"
}
|
26242
|
<p>At this moment I'm reading an <code>XmlNodeList</code> into a <code>ListItemCollection</code> one node at a time using a <code>foreach</code>:</p>
<pre><code>foreach (XmlNode node in authCompXml.SelectNodes("//Code"))
{
CompaniesList.Items.Add(new ListItem(node.InnerText));
}
</code></pre>
<p>How can this be improved, such as without the aforementioned <code>foreach</code>?</p>
|
[] |
[
{
"body": "<pre><code>CompaniesList.Items.AddRange(authCompXml.SelectNodes(\"//Code\")\n .Cast<XmlNode>()\n .Select(node => new ListItem(node.InnerText))\n .ToArray());\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:54:11.173",
"Id": "26244",
"ParentId": "26243",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26244",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T13:42:12.360",
"Id": "26243",
"Score": "1",
"Tags": [
"c#",
"asp.net"
],
"Title": "XmlNodeList to ListItemCollection"
}
|
26243
|
<p>InstaSlider is a lightweight jQuery image slider / carousel plugin that populates content from an Instagram hashtag.</p>
<p>After searching for a similar solution for one of my own projects with no luck I decided there might be others who would benefit from this.</p>
<p>It is the bare minimum function at the moment so there will be more features and updates added soon!</p>
<p><a href="http://jsfiddle.net/pCQkF/1/" rel="nofollow"><strong>Demo</strong></a></p>
<pre><code>(function($, window, document, undefined){
var InstaSlider = {
init: function(options, container){
var self = this;
self.container = container,
self.$container = $(container),
self.current = 0, // Set current to 0 on initialise
self.imgWidth = self.$container.width(); // img width will be the same as the container
self.options = $.extend({}, $.fn.instaSlider.options, options);
self.imgLength = self.options.limit;
this.createSlider(); // Create the slider
self.sliderUL = self.$container.find('.instaslider-wrapper ul');
},
createSlider: function(){
// create the slider
var slider = this.$container.append('<div class="instaslider-wrapper"><ul></ul></div>');
this.createNav();
this.createSlides();
},
createNav: function() {
var self = this;
// create the navigation for the slider
var buttonPrev = '<button class="' + this.options.prevClass + '" data-direction="prev">Prev</button>',
buttonNext = '<button class="' + this.options.nextClass + '" data-direction="next">Next</button>',
nav = '<div class="instaslider-nav">' + buttonPrev + buttonNext + '</div>';
// append it to the container
this.$container.append(nav);
// when a button is clicked set current
this.$container.find('button').on('click', function(){
self.setCurrent( $(this).data('direction') );
self.transition();
});
},
fetch: function() {
// Set the endpoint
var endpoint = 'https://api.instagram.com/v1/tags/' + this.options.hash + '/media/recent?client_id=' + this.options.clientID;
//fetch images from instagram
return $.ajax({
url: endpoint,
data: {},
dataType: 'jsonp',
type:'GET'
});
},
createSlides: function() {
// create the slides
var self = this,
container = this.$container,
sliderUL = container.find('.instaslider-wrapper ul');
self.fetch().done(function(results){
// Limit the amount of results
results = self.limit( results.data, self.options.limit );
// loop over results create a slider for each one.
self.slides = $.map(results, function(obj, i){
var img = '<li><img src="' + results[i].images.standard_resolution.url + '" /></li>';
sliderUL.append(img);
});
});
self.fetch().fail(function(){
sliderUL.remove();
container.html('<div class="error"><p>Sorry,<br /> Could not fetch images at this time.</p></div>');
})
},
setCurrent: function(direction) {
// set the current slide and handle direction here
var self = this;
var pos = self.current;
pos += ( ~~(direction === 'next') || -1);
self.current = ( pos < 0 ) ? self.imgLength -1 : pos % self.imgLength;
return pos;
},
transition: function() {
// handle animation and slide transition here
var self = this;
self.sliderUL.stop().animate({
'margin-left': -( this.current * this.imgWidth )
});
},
limit: function(obj, count) {
return obj.slice( 0, count );
},
};
$.fn.instaSlider = function(options){
return this.each(function(){
var instaSlider = Object.create( InstaSlider );
instaSlider.init(options, this);
$.data(this, 'instaSlider', instaSlider);
});
};
/*----------------------------------------------------------------
Default Options
----------------------------------------------------------------*/
$.fn.instaSlider.options = {
// Default Options
clientID: null,
hash:'photooftheday',
prevClass: 'prev',
nextClass: 'next',
limit: 5,
}
})(jQuery, window, document, undefined);
</code></pre>
|
[] |
[
{
"body": "<p>I think you'd really benefit looking at either jQuery UI's widget factory or (my preference) using some boilerplate such as <a href=\"http://jqueryboilerplate.com/\" rel=\"nofollow\">jQuery Boilerplate</a>.</p>\n\n<p>Other than that, in no particular order:</p>\n\n<ol>\n<li><code>$.fn.instaSlider.options = {...</code> I've never seen anyone do this\nand I'm not sure what you're trying to achieve with it. Just have\nyour defaults as a local variable within the IIFE and close over it.</li>\n<li>You're creating a new endpoint variable on every call of\n<code>fetch()</code>. Create it once in init e.g. <code>self.endPoint = 'theUrl'</code> </li>\n<li><code>self.imgLength = self.options.limit;</code> this is pointless.</li>\n<li>I don't think that you should have prev and next classes as an option, just name them uniquely e.g. 'instaSlider-next' - it's the kind of customisation that most people would never want or need.</li>\n<li><code>createNav</code> has no need for all 3 variables, just create one and build the entire html string and append it.</li>\n<li>Don't use <code><br /></code> tags for spacing - people will come and eat you.</li>\n</ol>\n\n<p>I'd say you're on the right track - just a bit of polishing here and there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T19:04:17.930",
"Id": "40658",
"Score": "0",
"body": "Thanks! Those are some really useful pointers. I was debating leaving the next/prev classes as fixed but I know in the past i've used plugins that had similar names and so I thought i'd just leave that in incase."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T18:58:04.960",
"Id": "26254",
"ParentId": "26245",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T14:40:26.487",
"Id": "26245",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"plugin",
"instagram"
],
"Title": "InstaSlider slider/carousel plugin"
}
|
26245
|
<p>This is on a job listing site and it has a Linkedin apply button plugin - this provides for a callback the someone has applied for a job. I've written the callback function which extracts the Job ID (a primary key in my database) and makes an AJX call to indcate that this Job ID has been applied for.</p>
<p>The Linkedin plugin is described <a href="https://developer.linkedin.com/apply-processing-applications" rel="nofollow">here</a>.</p>
<p>It essentially passes this JSON object to the callback:</p>
<pre><code>{
"event":"success",
"job":{
"companyID":"12345",
"jobID":"9876",
"jobTitle":"Chief Cat Herder"
}
}
</code></pre>
<p>This is the code placed within the head of the page:</p>
<pre><code><script type="text/javascript">
function linkedInApplySuccess(jsonReturnObj)
{
// no need to use any jquery json functions as already jabe a json object from linkedin (instead os a string)
// see second answer here http://stackoverflow.com/questions/3569416/parsing-json-string-with-jquery-parsejson
var job_id = jsonReturnObj.job.jobId;
$.ajax({
url: "/php/cv_db/ajax_log_linkedin_application.php",
data: {job_id: job_id},
type: "POST"
});
};
</script>
</code></pre>
<p>Regarding the AJAX, I am not looking for any return data and nor do I care about success or failure as should it fail. I'm not going to ask someone to apply for the job again. I do have error logging in my PHP file, though.</p>
|
[] |
[
{
"body": "<p>This looks pretty good, not much room for improvement I think. LinkedIn's JavaScript is calling linkedInApplySuccess, correct? All you have to do is specify data-success-callback, or something similar, in your HTML? </p>\n\n<p>The only minor thing I would do is instead of sending <em>just</em> the job ID, send the entire JSON object. As long as resources aren't an issue, it's always best to capture <em>all</em> data and disregard the stuff you don't use rather than only collect the stuff you're currently using; this is because requirements change, and in the future you may want to do something with the data you've been ignoring. For instance, you may want to calculate how many people are applying for jobs with the position \"Chief Weasel Wrangler\".</p>\n\n<p>You can alter your code to something like this:</p>\n\n<pre><code>$.post(\"/php/cv_db/ajax_log_linkedin_application.php\", {application: jsonReturnObj});\n</code></pre>\n\n<p>(application refers to \"job application\" not \"computer application\" – maybe too ambiguous)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T17:23:07.997",
"Id": "40650",
"Score": "0",
"body": "Hi, many thanks. Yes, the callback function is specified in the HTML you use to create the Linkedin button. I actually do only need the job id, as all the other information was in fact passed to the button (and then back to me on the json response) so the \"Chief Weasel Wrangler\" etc is in the database and accessed via the jobid. But I will play with your suggested code as a learning exercise. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T15:51:11.163",
"Id": "26248",
"ParentId": "26247",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26248",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T15:34:57.617",
"Id": "26247",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"json",
"ajax",
"callback"
],
"Title": "Callback for job applicant"
}
|
26247
|
<p>I am relatively new to Ruby and am trying to get a handle on making my code more Ruby-esque. At the same time I am experimenting with the branch and bound algorithm to solve a problem that I outline in this <a href="http://www.mikecordell.com/blog/2013/05/05/branch-bound-problem-in-ruby.html" rel="nofollow">blog post</a>. I would also welcome any feedback on the quality of my implementation. The full source code is on my <a href="https://github.com/mcordell/branch_bound_example" rel="nofollow">github here</a>, but here is the code for the branch bound class:</p>
<pre><code>require './widget'
require './requirements'
require 'benchmark'
class BranchBoundSearch
@best_score = nil
@best_combos = []
def initialize(scorer, main_requirement_label, all_possible)
@scorer = scorer
@main_requirement_label = main_requirement_label
@all_possible = all_possible
end
# Given a widget_array first calculate it's score, and add it as a branch in the
# list of branches based on the quality of it's score. Better scores are first.
# Branches that do not meet the size requirement are not added to the branches
# array. This effectively kills that branch.
def add_branch(widget_array, branches)
score_hash = @scorer.get_score_hash(widget_array)
score = @scorer.get_total_score(score_hash)
added = false
branches_index = 0
if score_hash[@main_requirement_label] >= 0
while not added and branches_index < branches.length do
if @scorer.get_better_score(score, branches[branches_index][1]) >= 0
branches.insert(branches_index, [score_hash,score,widget_array])
added = true
end
branches_index += 1
end
if not added
branches.push([score_hash, score,widget_array])
end
end
end
# Branch and bound recursive search. Provided an in array which represents the
# node which will be branched off of. Roughly, the function first creates a list
# of potential branches which are ordered by the quality of their score.
# Potential branches are then looped through, if a potential branch is viable the
# function is called again with it as the root node. This continues until
# exhaustion of all possiblities.
def branch_and_bound(in_array)
branches = []
@all_possible.each do |widget|
branch_array = in_array + [widget]
add_branch(branch_array, branches)
end
branches.each do |branch|
score_hash = branch[0]
score = branch[1]
widget_array = branch[2]
score_comparison = @scorer.get_better_score(score, @best_score)
if score_comparison == 0
@best_combos.push(widget_array)
continue_branch_investigation = true
elsif score_comparison == 1
@best_combos = [widget_array]
@best_score = score
continue_branch_investigation = true
elsif score > 0
continue_branch_investigation = true
end
if continue_branch_investigation
branch_and_bound(widget_array)
end
end
end
def get_best_score()
return @best_score, @best_combos
end
end
</code></pre>
<p>I'm also concerned about this specific code block:</p>
<pre><code>best_score_90 = nil
best_set_90 = []
best_score_90_bb = nil
best_set_90_bb = []
best_score_400 = nil
best_set_400 = []
best_score_400_bb = nil
best_set_400_bb = []
time=Benchmark.bm(7) do |x|
x.report("brute[90]:") do
scorer = Scorer.new(requirements_90, :size)
brute = BruteSearch.new(scorer, :size)
possible_combos = brute.enumerate_possible([], all_widgets.dup)
best_score_90, best_set_90 = brute.get_best_score
end
x.report("brute[400]:") do
scorer = Scorer.new(requirements_400, :size)
brute = BruteSearch.new(scorer, :size)
possible_combos = brute.enumerate_possible([], all_widgets.dup)
best_score_400, best_set_400 = brute.get_best_score
end
x.report("b&b[90]:") do
scorer = Scorer.new(requirements_90, :size)
bb = BranchBoundSearch.new(scorer, :size, all_widgets)
bb.branch_and_bound([])
best_score_90_bb, best_set_90_bb = bb.get_best_score
end
x.report("b&b[400]:") do
scorer = Scorer.new(requirements_400, :size)
bb = BranchBoundSearch.new(scorer, :size, all_widgets)
bb.branch_and_bound([])
best_score_400_bb, best_set_400_bb = bb.get_best_score
end
end
puts "Best set [90] brute: " + widget_array_to_s(best_set_90)
puts "Score[90] brute: " + best_score_90.to_s
</code></pre>
<p>Thanks for the help! </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:01:20.340",
"Id": "40670",
"Score": "0",
"body": "A note from experience: if you ask to review so many LOC, chances are nobody will answer, too much work. Maybe you can reduce it to a method you're specially worried about."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:01:56.447",
"Id": "40671",
"Score": "1",
"body": "This is just a style suggestion, but please do use the spacebar a little more. It is more \"Ruby'esque\" to write `x = y` and `foo(bar, baz)`, instead of `x=y`, `foo(bar,baz)`. Same with commented lines: `# comment` instead of `#comment`. Last tip: Generally speaking, array variables are plural nouns, so `widgets` instead of `widget_array`. This naming scheme is why Ruby's `Array` has a method called `include?`. The line `widgets.include?(x)` makes grammatical sense, while `widget_array.include?(x)` doesn't really."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T20:07:04.057",
"Id": "44707",
"Score": "0",
"body": "Small thing but you don't need to write `return` in `get_best_score`. Result of last evaluation is returned by default in Ruby."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T20:22:06.257",
"Id": "44708",
"Score": "0",
"body": "Is there any case when this will be false (or nil)? `continue_branch_investigation`"
}
] |
[
{
"body": "<p>One thing that will help a lot is using <code>attr_accessor</code>. You can use is so that you don't have so many instance variables littering your methods. You can also initialize <code>best_score</code> and <code>best_combos</code> and give them default values. (But generally, according to <a href=\"http://cloud.nickcox.me/3Y1R0B343S42\" rel=\"nofollow\">Sandi Metz</a>, you should try to avoid passing in more than 4 arguments to any method.) Also, avoid <code>if not</code>. Opt instead for <code>unless</code>. </p>\n\n<pre><code>class BranchBoundSearch\n\n attr_accessor :scorer, :main_requirement_label, :all_possible, :best_score, :best_combos\n\n def initialize(scorer, main_requirement_label, all_possible, best_score=, best_combos)\n @scorer = scorer\n @main_requirement_label = main_requirement_label\n @all_possible = all_possible\n @best_score = nil\n @best_combos = []\n end\n # That way, you have access to scorer without calling @scorer.\n def add_branch(widget_array, branches)\n score_hash = scorer.get_score_hash(widget_array)\n score = scorer.get_total_score(score_hash)\n ...\n unless added\n branches.push([score_hash,score,widget_array])\n end\n ...\n</code></pre>\n\n<p>That will get you at least some of the way, but you did post quite a bit of code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-14T05:32:01.200",
"Id": "27393",
"ParentId": "26251",
"Score": "1"
}
},
{
"body": "<p><strong>Replace this</strong></p>\n\n<pre><code>branches.each do |branch|\n score_hash = branch[0]\n score = branch[1]\n widget_array = branch[2]\n ...\n</code></pre>\n\n<p>with</p>\n\n<pre><code>branches.each do |score_hash, score, widget_array|\n ...\n</code></pre>\n\n<p><strong>This one</strong></p>\n\n<pre><code>if score_comparison == 0 \n ...\nelsif score_comparison == 1\n ...\nelsif score > 0 \n ...\nend\n</code></pre>\n\n<p>with</p>\n\n<pre><code>case score_comparison\n when 0\n ...\n when 1\n ...\n else\n ...\nend\n</code></pre>\n\n<p><strong>You pass a param but there's no reason for it</strong></p>\n\n<p><code>add_branch(branch_array, branches)</code></p>\n\n<p>because you may make <code>branches</code> an instance variable <code>@branches</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-14T20:11:02.183",
"Id": "28476",
"ParentId": "26251",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T16:29:33.523",
"Id": "26251",
"Score": "3",
"Tags": [
"algorithm",
"ruby"
],
"Title": "Ruby Branch and Bound Algorithm implementation?"
}
|
26251
|
<p>I would appreciate some feedback regarding best practices on the following code for a college project.</p>
<p>What should go in the controller and what in the views? How to attach and remove the views to the single main frame? Change the Controller after successful login?</p>
<p><strong>Studentenverwaltung.java</strong></p>
<pre><code>package com.studentenverwaltung;
import com.studentenverwaltung.controller.LoginController;
import com.studentenverwaltung.model.User;
import com.studentenverwaltung.view.LoginView;
import javax.swing.*;
import java.awt.*;
class Studentenverwaltung implements Runnable {
public static void main(String[] args) {
EventQueue.invokeLater(new Studentenverwaltung());
}
@Override
public void run() {
User user = new User();
LoginView loginView = new LoginView(user);
LoginController loginController = new LoginController(user, loginView);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(loginView);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
</code></pre>
<p><strong>LoginController.java</strong></p>
<pre><code>package com.studentenverwaltung.controller;
import com.studentenverwaltung.model.User;
import com.studentenverwaltung.view.LoginView;
public class LoginController {
private User user;
private LoginView LoginView;
public LoginController(User user, LoginView LoginView) {
this.user = user;
this.LoginView = LoginView;
}
}
</code></pre>
<p><strong>User.java</strong></p>
<pre><code>package com.studentenverwaltung.model;
import java.util.Observable;
public class User extends Observable {
private String lastName;
private String firstName;
private String role;
private String id;
private String password;
private String degreeProgram;
private boolean isLeaderOfDegreeProgram;
private String course;
// Getter & Setter
public boolean checkPassword(String password) {
return this.password.equals(password);
// this.setChanged();
// this.notifyObservers(this);
}
}
</code></pre>
<p><strong>LoginView.java</strong></p>
<pre><code>package com.studentenverwaltung.view;
import com.studentenverwaltung.model.User;
import com.studentenverwaltung.persistence.FileUserDAO;
import javax.swing.*;
import java.awt.event.*;
import java.util.Observable;
import java.util.Observer;
public class LoginView extends JDialog {
private JPanel contentPane;
private JButton btnLogin;
private JButton btnCancel;
private JTextField txtId;
private JPasswordField txtPassword;
private User user;
public LoginView(User user) {
this.user = user;
this.user.addObserver(new UserObserver());
this.init();
}
private void init() {
this.setContentPane(contentPane);
this.setModal(true);
this.getRootPane().setDefaultButton(btnLogin);
this.btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoginView.this.onLogin();
}
});
this.btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoginView.this.onCancel();
}
});
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
LoginView.this.onCancel();
}
});
this.contentPane.registerKeyboardAction(new ActionListener() {
public void actionPerformed(ActionEvent e) {
LoginView.this.onCancel();
}
}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
/*
public static void main(String[] args) {
LoginView dialog = new LoginView();
dialog.pack();
dialog.setVisible(true);
System.exit(0);
}
*/
private void onLogin() {
FileUserDAO userDAO;
String id, password;
User user;
userDAO = new FileUserDAO("Files/stud_info.csv");
id = this.txtId.getText();
password = this.txtPassword.getText();
user = userDAO.getUser(id);
if (user != null && user.checkPassword(password)) {
this.dispose();
// switch (user.getRole()) {
// case "student":
// //
// case "lecturer":
// //
// case "professor":
// if (user.getIsLeaderOfDegreeProgram()) {
// // leader
// }
//
// // professor
// }
frame.add(new StudentView(user).contentPane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
private void onCancel() {
this.dispose();
}
private class UserObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
}
</code></pre>
<p><strong>StudentView.java</strong></p>
<pre><code>package com.studentenverwaltung.view;
import com.studentenverwaltung.model.User;
import javax.swing.*;
public class StudentView {
public JPanel contentPane;
private JLabel lblWelcome;
private JButton btnChangePassword;
private JButton btnLogout;
private JTextField txtId;
private JTextField txtPassword;
private JTextField txtDegreeProgram;
private JTable tblPerformance;
private User user;
public StudentView(User user) {
this.user = user;
// this.tblPerformance.setModel(this.user.getAllCourses());
this.init();
}
private void init() {
this.lblWelcome.setText("Herzlich Willkommen, " + this.user.getFirstName() + " " + this.user.getLastName());
this.txtId.setText(this.user.getId());
this.txtPassword.setText(this.user.getPassword());
this.txtDegreeProgram.setText(this.user.getDegreeProgram());
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:45:21.393",
"Id": "40665",
"Score": "0",
"body": "on popular naming convention is for all private variable to begin with an underscore id `private JLabel _lblWelcome;` this would also eliminate the need for so many uses of `this`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:07:06.157",
"Id": "40674",
"Score": "7",
"body": "@atbyrd that would be true if this was C# code, not Java."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T19:56:12.693",
"Id": "40861",
"Score": "3",
"body": "You are missing source comments...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T08:20:02.043",
"Id": "60137",
"Score": "0",
"body": "Indeed, if it's a college project, good javadoc will be appreciated by the teachers"
}
] |
[
{
"body": "<p>Use <a href=\"http://whitemagicsoftware.com/encapsulation.pdf\" rel=\"nofollow noreferrer\">self-encapsulation</a>, which will help apply the Open-Closed Principle.</p>\n\n<h1>Studentenverwaltung.java</h1>\n\n<p>Use an IDE that will automatically import classes explicitly. Future maintainers should not have to guess what classes are imported:</p>\n\n<pre><code>import javax.swing.*;\nimport java.awt.*;\n</code></pre>\n\n<p>Avoid the <code>.*</code>.</p>\n\n<h1>LoginController.java</h1>\n\n<p>The LoginController has no purpose. An <em>object-oriented</em> class must have both behaviour and attributes. Moreover, classes should be defined first in terms of behaviour.</p>\n\n<p>Typically this means asking, \"What does the LoginController do?\" Then define those responsibilities as methods. Attributes (data) are a secondary consideration. This is more evident after reading \"<a href=\"http://pragprog.com/articles/tell-dont-ask\" rel=\"nofollow noreferrer\">Tell, Don't Ask</a>.\"</p>\n\n<h1>User.java</h1>\n\n<p>A few issues:</p>\n\n<ul>\n<li>Classes should be as generic as possible</li>\n<li>Passwords should not be stored in plaintext</li>\n<li>Password verification might be the LoginController's responsibility</li>\n</ul>\n\n<p>A generic User, for example, would not have the following attributes:</p>\n\n<pre><code>private String password;\nprivate String degreeProgram;\nprivate boolean isLeaderOfDegreeProgram;\nprivate String course;\n</code></pre>\n\n<p>Using a single role imposes an arbitrary limit without necessity. If the User can have multiple roles, then one of those roles can be \"Degree Program Leader\".</p>\n\n<p>At the very least the password should be <a href=\"https://stackoverflow.com/a/2861125/59087\">hashed</a>.</p>\n\n<h1>LoginView.java</h1>\n\n<p>Stylistically, most of the references to <code>this.</code> are superfluous:</p>\n\n<pre><code>this.setContentPane(contentPane);\nthis.setModal(true);\nthis.getRootPane().setDefaultButton(btnLogin);\n</code></pre>\n\n<p>The following seems overly verbose:</p>\n\n<pre><code>LoginView.this.onLogin();\n</code></pre>\n\n<p>I think it can be:</p>\n\n<pre><code>onLogin();\n</code></pre>\n\n<h1>StudentView.java</h1>\n\n<p>There is some duplication between LoginView and StudentView that can be abstracted:</p>\n\n<pre><code>public JPanel contentPane;\nprivate JTextField txtId;\nprivate JTextField txtPassword;\nprivate User user;\n</code></pre>\n\n<p>These can be in a generic \"View\" superclass that contains elements common to both. Or perhaps they can be in a common class that is included by both.</p>\n\n<p>Make all variables private. No exceptions.</p>\n\n<h1>StudentView.java</h1>\n\n<p>Avoid hardcoding text:</p>\n\n<pre><code> this.lblWelcome.setText(\"Herzlich Willkommen, \" + this.user.getFirstName() + \" \" + this.user.getLastName());\n</code></pre>\n\n<p>Use a <a href=\"http://docs.oracle.com/javase/tutorial/i18n/format/messageFormat.html\" rel=\"nofollow noreferrer\">ResourceBundle</a> for compound messages.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-08T19:18:25.167",
"Id": "38850",
"ParentId": "26252",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "38850",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T17:02:05.923",
"Id": "26252",
"Score": "5",
"Tags": [
"java",
"mvc"
],
"Title": "Feedback on college project"
}
|
26252
|
<p>I am working on a <code>java swing project</code> that looks like a Terminal (but with less functionality).</p>
<p>The GUI contains a <code>jTextArea</code> to display output and a <code>jTextField</code> for user input.</p>
<p>Here is an application of the my GUI to perform a simple task.</p>
<ol>
<li>Ask the user to enter a number.</li>
<li>If successful, ask the user to enter a smaller </li>
<li>If successful, prompt out the text "done!".</li>
</ol>
<p>Is there a better way to do this other than state machine?</p>
<p>Here is the code:</p>
<pre><code>package com.TerminalPanelGUI;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TerminalPanel extends javax.swing.JPanel
{
private int state;
/**
* Creates a new Terminal Panel
*/
public TerminalPanel()
{
state = 0;
initComponents();
textArea.setText("Enter a number: \n");
textField.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent ae)
{
System.out.println("In action performed: state is " + state);
switch(state)
{
case 0:
State0();
break;
case 1:
State1();
break;
}
}
});
}
private int dummy;
private void State0()
{
try
{
dummy = Integer.parseInt(textField.getText());
state = 1;
//prompt for next state
textArea.append("Enter a smaller number: \n");
}
catch(NumberFormatException e)
{
textArea.append("Invalid entry. Try again \n");
state = 0;
}
}
private void State1()
{
try
{
if(Integer.parseInt(textField.getText()) < dummy)
{
state = 2;
//prompt for next state
textArea.append("done!");
}
else
{
state = 1;
//prompt for next state
textArea.append("Enter a smaller number: \n");
}
}
catch(NumberFormatException e)
{
textArea.append("Invalid entry. Try again \n");
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
scrollPane = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();
textField = new javax.swing.JTextField();
setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
textArea.setEditable(false);
textArea.setColumns(20);
textArea.setRows(5);
scrollPane.setViewportView(textArea);
add(scrollPane, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 250));
add(textField, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 270, 400, 30));
}// </editor-fold>
// Variables declaration - do not modify
private javax.swing.JScrollPane scrollPane;
protected javax.swing.JTextArea textArea;
protected javax.swing.JTextField textField;
// End of variables declaration
}
</code></pre>
|
[] |
[
{
"body": "<p>Maybe something like this? Note: may add textField as a member of State0 and State1</p>\n\n<pre><code>public interface State\n{\n boolean hasNext();\n State next();\n}\n\npublic final class State0\n implements State\n{\n private boolean okToContinue = false;\n private int number;\n\n @Override\n public boolean hasNext()\n {\n try {\n textArea.append(\"Enter a number\");\n number = Integer.parseInt(textField.getText());\n okToContinue = true;\n } catch (NumberFormatException ignored) {\n textArea.append(\"Input is not a number\");\n }\n return true;\n }\n\n @Override\n public State next()\n {\n return okToContinue ? new State1(number) : this;\n }\n}\n</code></pre>\n\n<p>The State1 implementation is then obvious. In the main loop you can just do:</p>\n\n<pre><code>State state = new State0();\n\nwhile (state.hasNext())\n state = state.next();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T05:16:41.447",
"Id": "26555",
"ParentId": "26258",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "26555",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:26:00.110",
"Id": "26258",
"Score": "1",
"Tags": [
"java",
"swing"
],
"Title": "Better Design Pattern For Terminal-Like GUI"
}
|
26258
|
<p>I have this view that populates an unordered list from values in a JSON file, which I am doing in Node.</p>
<p>Is there a better way to do this, or a more 'node-like' way? Can I load the JSON file without an Ajax call?</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>4&middot;pli -- news</title>
<link rel='stylesheet' href='/stylesheets/style.css'/>
<script src="/javascripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="/javascripts/date.format.js" type="text/javascript"></script>
<link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
</head>
<body>
<% include shared/nav.ejs %>
<div class="wrapper">
<ul class='news'>
<script type="text/javascript">
$.ajax({
url: 'data/news.json',
async: false,
dataType: 'json',
success: function (response) {
var items = [];
$.each(response.news,function(i,item){
items.push('<li><ul><li class="title">'+ item.title +'</li><li>' + dateFormat(item.created_at,"fullDate") + '</li><li><p>'+ item.content +'</p></li></ul></li>');
});
$('.news').append(items.join(''));
}
});
</script>
</ul>
</div>
<% include /shared/footer.ejs %>
</body>
</html>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:37:00.430",
"Id": "40663",
"Score": "2",
"body": "`async: false` --- baaaad"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:38:11.767",
"Id": "40664",
"Score": "0",
"body": "@JanDvorak elaborate futher please."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:46:10.683",
"Id": "40666",
"Score": "4",
"body": "Normally javascript runs from the browser's UI thread. This means that while the browser is waiting for the AJAX response, user interaction is disabled."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:48:57.693",
"Id": "40667",
"Score": "0",
"body": "@JanDvorak Thanks I will try and remember that."
}
] |
[
{
"body": "<p>What you're looking for is <code>JSON.parse</code>. It's not in the Node docs, because it's \"lower\" than that: Every modern javascript runtime has it (<a href=\"https://developer.mozilla.org/en/docs/JSON\" rel=\"nofollow\">see MDN</a>).</p>\n\n<p>Here's a simple function to read a file, parse it as JSON, and send it to a callback (all in Node)</p>\n\n<pre><code>function readJSONFile(filename, callback) {\n require(\"fs\").readFile(filename, function (err, data) {\n if(err) {\n callback(err);\n return;\n }\n try {\n callback(null, JSON.parse(data));\n } catch(exception) {\n callback(exception);\n }\n });\n}\n</code></pre>\n\n<p>In keeping with Node conventions (and just mirroring <code>readFile</code> itself), you pass it a callback with this signature: <code>function(err, json)</code>. E.g.</p>\n\n<pre><code>readJSONFile(\"path/to/file.json\", function (err, json) {\n if(err) { throw err; }\n console.log(json);\n});\n</code></pre>\n\n<p>You can make a none-async one if you prefer, but Node's nature is async.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:50:24.230",
"Id": "26262",
"ParentId": "26259",
"Score": "4"
}
},
{
"body": "<p>your question is not so clear.</p>\n\n<p>if you use express (<a href=\"http://www.expressjs.com/\" rel=\"nofollow\">expressjs.com</a>) it is pretty easy:</p>\n\n<pre><code>/**\n* Module dependencies.\n*/\n\nvar express = require('express')\n , http = require('http')\n , path = require('path');\n\nvar app = express();\n\n// all environments\napp.set('port', process.env.PORT || 80);\napp.use(express.bodyParser());\napp.use(express.methodOverride());\napp.use(app.router);\n\nvar o = require('./news.json');\n\napp.get('/news', function(req, res){\n res.json(o);\n});\n\nhttp.createServer(app).listen(app.get('port'), function(){\n console.log('Express server listening on port ' + app.get('port'));\n});\n</code></pre>\n\n<p>you can create a custon route:</p>\n\n<pre><code>app.get('/news', function(req, res){\n res.json([{title: 'test', content: 'test desc'}, {title: 'test2', content: 'test2 desc'}])\n}\n</code></pre>\n\n<p>or even from a db: (using <a href=\"http://mongoosejs.com\" rel=\"nofollow\">mongoose.js</a>)</p>\n\n<pre><code>app.get('/news', function(req, res){\n news.find().exec(function(err, result) {\n res.json(err || result);\n }); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T21:20:57.240",
"Id": "27207",
"ParentId": "26259",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26262",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:31:39.417",
"Id": "26259",
"Score": "2",
"Tags": [
"javascript",
"json",
"node.js",
"express.js"
],
"Title": "Populating an unordered list from values in a JSON file"
}
|
26259
|
<p>I am trying to show the 6 most popular products on my homepage from left to right, in two rows. My code actually works... but I have the feeling I am making things way too complicated. Is there a simpler way to do this?</p>
<p>Here is my code:</p>
<pre><code>$dynamicList = "";
$sql = mysql_query("SELECT * FROM products ORDER BY popularity DESC LIMIT 6");
$productCount = mysql_num_rows($sql); //Count the output amount
if($productCount>0){
$currentRow=0;
$dynamicListLeft='<div id="homepageLeftProduct">';
$dynamicListMiddle='<div id="homepageMiddleProduct">';
$dynamicListRight='<div id="homepageRightProduct">';
while($row=mysql_fetch_array($sql)){
$currentRow=$currentRow+1;
$id = $row["id"];
$product_name = $row["product_name"];
$date_added=strftime("%b %d, %Y", strtotime($row["date_added"]));
if($currentRow==1 || $currentRow==4) {
$dynamicListLeft .='<p>
<a href="product.php?blablabla"><img class="homepagePic" src="inventory_images/4.jpg" /></a>
</p><br/>';
} else {
if($currentRow==2 || $currentRow==5) {
$dynamicListMiddle .='<p>
<a href="product.php?blablabla"><img class="homepagePic" src="inventory_images/4.jpg" /></a>
</p><br/>';
} else {
if($currentRow==3 || $currentRow==6){
$dynamicListRight .='<p>
<a href="product.php?blablabla"><img class="homepagePic" src="inventory_images/4.jpg" /></a>
</p><br/>';
}
}
}
}
$dynamicListLeft .='</div>';
$dynamicListMiddle .='</div>';
$dynamicListRight .='</div>';
$dynamicList .=$dynamicListLeft;
$dynamicList .=$dynamicListMiddle;
$dynamicList .=$dynamicListRight;
}
</code></pre>
<p>Later on in my body I echo the dynamiclist.</p>
<p>I hope somebody can show me the way to make this smoother?</p>
<p>Thanks!</p>
|
[] |
[
{
"body": "<p>Let's go for a step-by-step cleanup.</p>\n\n<p>1) Get rid of repetition by using a variable to store your html code common to the different branches.</p>\n\n<p>2) Remove useless levels of indentation to make things easier to follow.</p>\n\n<p>The inside of the <code>while</code> loop is now :</p>\n\n<pre><code> $currentRow=$currentRow+1;\n $id = $row[\"id\"];\n $product_name = $row[\"product_name\"];\n $date_added=strftime(\"%b %d, %Y\", strtotime($row[\"date_added\"]));\n $link = '<p><a href=\"product.php?blablabla\"><img class=\"homepagePic\" src=\"inventory_images/4.jpg\" /></a></p><br/>';\n if($currentRow==1 || $currentRow==4) {\n $dynamicListLeft .= $link;\n } else if($currentRow==2 || $currentRow==5) {\n $dynamicListMiddle .= $link;\n } else if($currentRow==3 || $currentRow==6){\n $dynamicListRight .= $link';\n }\n</code></pre>\n\n<p>(I could move the definition of link out of the loop but I guess in your real situation, the content depends on <code>$row</code>).</p>\n\n<p>3) You can try to store your content in an array instead of using different variables. It removes a bit of logic and makes things easier to update if you want 2 or 4 columns in the future. It also removes some code duplication :</p>\n\n<pre><code>$cols=array('','','');\n$nbCol=count($cols);\n$currentRow=0;\nwhile($row=mysql_fetch_array($sql)){\n $id = $row[\"id\"];\n $product_name = $row[\"product_name\"];\n $date_added=strftime(\"%b %d, %Y\", strtotime($row[\"date_added\"]));\n $link = '<p><a href=\"product.php?blablabla\"><img class=\"homepagePic\" src=\"inventory_images/4.jpg\" /></a></p><br/>';\n $cols[$currentRow%$nbCol] .= $link;\n $currentRow=$currentRow+1;\n}\nfor ($col as $i => $content)\n{\n $dynamicList .= '<div id=\"homepageProductCol' . $i . '\">' . $content . '</div>';\n}\n</code></pre>\n\n<p>4) So far, the comments were about the php code and not the HTML output it produces. My last comment is more of a question but wouldn't there be a way to have your HTML defined in such a way that you don't need such a complicated logic. Basically, at the moment, the whole point is that your HTML code contains reference to your item in this order : 1,4,2,5,3,6. Things would be easier if you could have them in the natural order (1,2,3,4,5,6) in your HTML code and then update your HTML to display them in such a such a way.\nMy HTML skills are way too limited to answer this question...</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:25:11.790",
"Id": "26266",
"ParentId": "26260",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:36:25.853",
"Id": "26260",
"Score": "3",
"Tags": [
"php",
"mysql"
],
"Title": "Dynamic homepage with PHP - making things too complicated?"
}
|
26260
|
<p>I've created a singleton by means of an interface. I don't want to make a thing with <code>getInstance()</code> etc because I don't care about inheritance, and it's redundant and non-declarative.</p>
<p>Are there downsides of doing it this way? Any redundancy I can remove? Is there a cleaner/more consise way to do this? I like doing it this way because methods are first class because I can pass them to map etc (e.g: <code>map(Dog.sleep, someListOfNumbers)</code>) and it supports currying if you have functions like <code>F<Pair<X,Pair<Y,Z>>></code>.</p>
<p>Note the <code>F</code> interface is declared elsewhere, I just inlined it here to have less files.</p>
<pre><code>package a;
import static a.Dog.State.*;
public interface Dog {
interface F<X,Y> {
Y f(X x);
}
static final class State {
protected static boolean dead;
protected static String name = "leo";
protected static Integer age = 0;
}
F<Void,String> getName = new F<Void,String>() {
public String f(Void _) {
return name;
}
};
F<Void,Void> die = new F<Void,Void>() {
public Void f(Void _) {
System.out.println("X_X");
dead = true;
return null;
}
};
F<Void,Void> woof = new F<Void,Void>() {
public Void f(Void _) {
if (dead)
throw new IllegalStateException("cannot woof when dead");
System.out.println("woof");
return null;
}
};
F<Integer,Void> sleep = new F<Integer,Void>() {
public Void f(Integer years) {
if (dead)
throw new IllegalStateException("cannot sleep when dead");
age += years;
return null;
}
};
F<Void,Integer> getAge = new F<Void,Integer>() {
public Integer f(Void _) {
return age;
}
};
}
</code></pre>
<p>A test:</p>
<pre><code>import a.Dog;
class Main {
public static void main(String[] args) {
System.out.println(
"The dog's name is " + Dog.getName.f(null) +
" and is " + Dog.getAge.f(null) + " years old"
);
Dog.sleep.f(2);
System.out.println(
"The dog's name is " + Dog.getName.f(null) +
" and is " + Dog.getAge.f(null) + " years old"
);
Dog.woof.f(null);
Dog.die.f(null);
Dog.woof.f(null);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:19:55.513",
"Id": "40676",
"Score": "1",
"body": "I would think passing null in for no parameters would get a little tiresome, and also make the code a little less clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-19T19:13:25.800",
"Id": "147477",
"Score": "0",
"body": "Where exactly in your code are you trying to create a singleton?"
}
] |
[
{
"body": "<p>Your implementation fails to adhere to some important Object Oriented principles.</p>\n\n<ol>\n<li><p>Encapsulation</p>\n\n<p>The state of your singleton can be modified by others.</p>\n\n<pre><code>package a;\n\npublic class Cat implements Dog {\n\n static {\n State.age = 17;\n }\n\n public int age() {\n return Cat.getAge.f(null);\n }\n\n public void setAge(int age) {\n State.age = age;\n }\n\n public static void main(String[] args) {\n System.out.println(new Cat().age());\n }\n}\n</code></pre></li>\n<li><p>Polymorphism</p>\n\n<p>This is basically a problem that comes with the singleton pattern itself. However, a more conventional approach to implementing a singleton can deal with this issue :</p>\n\n<pre><code>package b;\n\npublic interface Dog {\n\n String getName();\n\n void die();\n\n void woof();\n}\n</code></pre>\n\n<p>and the singleton implementation :</p>\n\n<pre><code>package b;\n\npublic enum SingleDog implements Dog {\n INSTANCE;\n\n private String name;\n private boolean dead;\n\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public void die() {\n System.out.println(\"X_X\");\n dead = true;\n }\n\n @Override\n public void woof() {\n if (dead) {\n throw new IllegalStateException(\"cannot woof when dead\");\n }\n System.out.println(\"woof\");\n }\n}\n</code></pre>\n\n<p>This way clients can depend on the interface and not the singleton implementation. i.e. that there can only be one instance is now an implementation detail, and not an unchangeable design decision.</p></li>\n</ol>\n\n<p>If you want to do functional programming, Java is probably not the language you should be using.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T05:26:37.577",
"Id": "26281",
"ParentId": "26263",
"Score": "5"
}
},
{
"body": "<p>1) I don't see what this has to do with singletons. Surely you want to have the possibility of having more than one dog.</p>\n\n<p>2) You clearly come from a functional programming background. When I first read your code, I thought it had mistakenly been labeled as Java. Java is a very rigid language, which makes it very good for team software development since everybody will write similar code. However when you start mixing in a completely different programming paradigm, it becomes very difficult for the team to be efficient. Scala is one language that mixes OO and functional programming and it is not being used that much in real application development because the code ends up a mishmash of different programming paradigms that is very difficult to follow. Google Guava does have a package for <a href=\"https://code.google.com/p/guava-libraries/wiki/FunctionalExplained\" rel=\"nofollow\">functional programming</a> which is similar to what you did. Here is what they say:</p>\n\n<blockquote>\n <p>Excessive use of Guava's functional programming idioms can lead to\n verbose, confusing, unreadable, and inefficient code. These are by far\n the most easily (and most commonly) abused parts of Guava, and when\n you go to preposterous lengths to make your code \"a one-liner,\" the\n Guava team weeps.</p>\n</blockquote>\n\n<p>So if you really want to stick to functional programming (which I am not against), you should probably not use Java.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T12:45:59.903",
"Id": "26292",
"ParentId": "26263",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T20:54:23.707",
"Id": "26263",
"Score": "3",
"Tags": [
"java",
"singleton",
"interface"
],
"Title": "Singleton interface in Java"
}
|
26263
|
<p>I have a WPF application that needs to get a XML document using a web request. The request is based on an id that the user enters. If the user enters a second id, before the first returns, I would like to cancel the first request, and start over with the second id. The following works, but I'm not sure if there is an easier way, or if this is correct. I am basically passing a ManualResetEvent reset event to a BackgroundWorker so that I can signal the thread to cancel the web request.</p>
<p>Is this approach poor form? Is passing in a reset event better than having a loop within the function that tests the DoWorkEventArgs::Cancel property every tenth of a second? Also, is there a way to delay the call to RunWorkerAsync until the background worker isn't busy, without blocking the thread? Or should I just create a new background worker every time?</p>
<p>Any input is much appreciated.</p>
<p>This is what I have in my window.xaml.cs.</p>
<pre><code> BackgroundWorker itemBackgroundWorker = new BackgroundWorker();
ManualResetEvent itemCancel = new ManualResetEvent(false);
private void tbID_TextChanged(object sender, TextChangedEventArgs e)
{
int id;
if (!int.TryParse(textBoxID.Text, out id))
return;
while (itemBackgroundWorker.IsBusy)
{
itemCancel.Set();
}
itemCancel.Reset();
itemBackgroundWorker.RunWorkerAsync(new object[] { id, itemCancel });
}
void baselineSessionBackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
Object[] args = (Object[])e.Argument;
int id = (int)args[0];
ManualResetEvent cancel = (ManualResetEvent)args[1];
try
{
currentItem = webFunctions.getItem(id, cancel);
}
catch (Exception exx)
{
System.Diagnostics.Debug.WriteLine("Find run {0} failed with {1}", id, exx.Message);
currentItem = null;
}
}
void baselineSessionBackgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
currentItemContentControl.GetBindingExpression(ContentControl.ContentProperty).UpdateTarget();
}
</code></pre>
<p>This is what I have for the static getItem method.</p>
<pre><code>static string detailXMLQuery = "http://....";
public static myItem getItem(int id, ManualResetEvent cancelEvent = null)
{
ManualResetEvent readFinishedEvent = new ManualResetEvent(false);
if (cancelEvent == null)
cancelEvent = new ManualResetEvent(true);
else
cancelEvent.Reset();
Stream result = null;
WebClient client = new WebClient();
client.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
System.Diagnostics.Debug.WriteLine("Error getting XML:" + e.Error.Message);
else
result = e.Result;
System.Diagnostics.Debug.WriteLine("Set finished state");
readFinishedEvent.Set();
};
client.OpenReadAsync(new Uri(string.Format(detailXMLQuery, id)));
ManualResetEvent.WaitAny(new WaitHandle[] { cancelEvent, readFinishedEvent }, 10000);
if (!readFinishedEvent.WaitOne(0))
{
client.CancelAsync();
System.Diagnostics.Debug.WriteLine("Error getting XML: The request timed out or was canceled");
throw new Exception("The request timed out or was canceled");
}
XmlDocument doc = new XmlDocument();
doc.Load(result);
//parse xml, test cancelEvent.Wait(0) to see if cancel has been signaled.
return new myItem();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T22:54:27.390",
"Id": "40680",
"Score": "0",
"body": "Can you use C# 5.0? It makes working with asynchronous code much easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T23:08:43.700",
"Id": "40682",
"Score": "0",
"body": "I was looking at the Task stuff, it seems a lot easier than this. I'll have to look into what the min version is, but for now I am guessing it is C# 4."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T11:22:41.303",
"Id": "40767",
"Score": "1",
"body": "@travis - The Task Parallel Library is .Net 4 but I think svick was referring to the new `async` and `await` keywords in C# 5.0 .Net 4.5."
}
] |
[
{
"body": "<blockquote>\n <p>Is this approach poor form?</p>\n</blockquote>\n\n<p>I think yes</p>\n\n<blockquote>\n <p>Is passing in a reset event better than having a loop within the function that tests the DoWorkEventArgs::Cancel property every tenth of a second?</p>\n</blockquote>\n\n<p>Both are wrong. Event is a kernel object! Using a kernel object for this type task is wasteful. It would be better if you used something like this:</p>\n\n<pre><code>webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCallback2);\nclient.DownloadStringAsync (uri);\n</code></pre>\n\n<p>In this case, you don't need to block any thread with a loop. When your request completes, you will take the control in passed method (<code>DownloadStringCallback2</code>).</p>\n\n<blockquote>\n <p>Also, is there a way to delay the call to RunWorkerAsync until the background worker isn't busy, without blocking the thread?</p>\n</blockquote>\n\n<p>At first glance - yes, you can pass in worker method <code>CancellationToken</code>. When the user inputs a new value, you simply cancel the token and start a new task. When the cancelled request takes the control in <code>DownloadStringCallback2</code> it should check the token and return. If it wasn't cancelled, it may continue work. On each user request you should simply cancel the old token and create a new one, then start a new request.</p>\n\n<blockquote>\n <p>Or should I just create a new background worker every time?</p>\n</blockquote>\n\n<p>I think it's OK at first glance. On each user request create a new BackgroundWorker and pass the cancellation token. The BackgroundWorker will use ThreadPool behind the scenes anyway.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T19:42:14.287",
"Id": "41119",
"Score": "0",
"body": "Sorry, I may be missing something, but would this method still call client.CancelAsync method, or just let it finish?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-24T08:24:38.037",
"Id": "41146",
"Score": "0",
"body": "You are right, I missed it. Yes, it will be better if you do that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-21T16:05:49.340",
"Id": "26441",
"ParentId": "26267",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T21:31:04.637",
"Id": "26267",
"Score": "3",
"Tags": [
"c#",
"multithreading"
],
"Title": "Proper way to cancel WebClient in BackgroundWorker"
}
|
26267
|
<p>I like the way Zend Framework works it's views and I make extensive use of partials but every partial include results in it's own file system hit. As I'm building my own framework I thought I could do better so this is what I came up with. What I'm looking for is any potential problems that I should watch out for and just general feedback.</p>
<p>First off lets take a simple template partial - we will call this template.phtml :</p>
<pre><code><tr><td><?= $name ?></td><td><?= $address ?></td><td><?= $phone_number ?></td></tr>
</code></pre>
<p>Next the actual class (proof of concept at this point so don't be hatin' on me too much)</p>
<pre><code>class TemplatePartial {
protected $file;
protected $func;
public function __construct($file){
if (!file_exists($file)){
throw new Exception("Can't get template at [".$file."]");
}
$this->file = $file;
}
public function render($data){
if (!is_callable($this->func)){
$code = 'foreach($data as $k=>$v){${$k} = $v;} ob_start(); ?>';
$code.= file_get_contents($this->file).'<?php return ob_get_clean();';
$this->func = create_function('$data', $code);
}
$f = $this->func;
$f($data);
}
}
</code></pre>
<p>and to use it the code would look like</p>
<pre><code>$a = new TemplatePartial("template.phtml");
echo $a->render(array(
"name"=>"John Doe",
"address"=>"1234 Anystreet Anytown MN 12345-1234",
"phone_number"=>"555-555-5555"));
</code></pre>
<p>So far on simple tests I'm showing about 8x speed increase with almost half the peak memory usage. I'm wondering where the down side is. </p>
<p><em><strong>UPDATE</em></strong></p>
<p>This was too interesting to not do so here is the revised code <a href="https://github.com/cgray/templar" rel="nofollow">also on github</a></p>
<pre><code>class Templar {
protected $templateCache;
protected static $instance;
protected $templatePaths;
protected function __construct(){
$this->templateCache = array();
$this->templatePaths = array();
}
/**
* Return singlton instance
*
* @return Templar The template Engine.
**/
public static function getInstance(){
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Add a directory to the path cache
*
* @param string $path The path to the template
**/
public function addTemplatePath($path){
// Make sure the directory ends in exactly one DIRECTORY_SEPARATOR
$path = rtrim($path,DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
// if the path doesn't exist the fail silently
if (file_exists($path)){
$this->templatePaths[] = $path;
}
}
/**
* Creates a template function
*
* @param string $path The path to the template
* @return the compiled function
* @throws Templar_Exception if the template can't be found or parsed
**/
protected function createTemplate($path){
// Make sure template exist in one of the template directories -- no ../ paths
if (strpos("..", $path) !== false) {
throw new Templar_Exception("Templates must exist in one of the template directories");
}
$path = ltrim($path, DIRECTORY_SEPARATOR);
if (!file_exists($path)) {
foreach($this->templatePaths as $testPath){
if (file_exists($testPath . $path)){
$targetPath = $testPath . $path;
break; // break out of if and foreach;
}
}
// if I make it here and I don't have a valid template there a problem
if (!$targetPath){
throw new Templar_Exception("Could not load template [" . $path . "]");
}
}
// updated to use export vs {foreach($data as $k=>$v){${$k} = $v;}} - thanks to this answer http://codereview.stackexchange.com/a/26297/23307
// slight performance dip but better memory usage and it hurts my eyes less
$code = 'export($__data); unset($__data); ?>' . file_get_contents($targetPath) . '<?php ';
$func = create_function('$__data = array()', $code);
if (!$func){
throw new Templar_Exception("Could not parse template [" . $targetPath . "]");
}
// add to the templateCache
$this->templateCache[$path] = $func;
}
/**
* Returns an instance of a template function
*
* @param string $path The Path to the Template
* @return Callable The template function
**/
public function getTemplateFunction($path){
if (!array_key_exists($path, $this->templateCache)){
$this->createTemplate($path);
}
return $this->templateCache[$path];
}
/**
* Returns a rendered Template
*
* @param string $template Path to the template
* @param array $data
* @return string The renderer Template
**/
public static function render($template, $data = array()){
ob_start();
self::display($template, $data);
return ob_get_clean();
}
/**
* Outputs a rendered Template
*
* @param string $template Path to the template
* @param array $data
* @return string The renderer Template
**/
public static function display($template, $data = array()){
$tmplFunction = self::getInstance()->getTemplateFunction($template);
$tmplFunction($data);
}
}
</code></pre>
<p>Again any feedback you can supply would be helpful. </p>
<p><em><strong>UPDATE</em></strong></p>
<p>Thinking about retooling some of the internals and changing the create_function call to use <code>runkit_method_add</code>. Big advantage that this would give is that template functions could be given a name (I was thinking a bastardization of the path to the template file) that would make any runtime template errors more meaningful. Currently create_function just reports "Error in runtime created function". Disadvantage is it is a PECL extension that doesn't have any windows binaries.</p>
<p>Anyone have any thoughts on that? Monkey patching the Templar object vs just creating anonymous functions is going to determine how view helpers will be implemented. </p>
|
[] |
[
{
"body": "<p>You might have noticed that this is not very clean code:</p>\n\n<pre><code>$code = 'if (is_array($data)) {foreach($data as $k=>$v){${$k} = $v;}} ?>' . file_get_contents($targetPath) . '<?php '; \n$func = create_function('$data = array()', $code);\n</code></pre>\n\n<p>You don't need to use <code>create_function</code> or <code>eval</code>. You can do the same using <code>include</code>.\nAnd instead of using <code>foreach($data as $k=>$v){${$k} = $v;}</code>. You could use the <code>extract</code> function, which does the same for you. Note I put this in a seperate function to avoid problems with the scope.</p>\n\n<pre><code>function parse($data) {\n ob_start();\n extract($data);\n include $this->template_file;\n return ob_get_clean();\n}\n</code></pre>\n\n<p>I also see no reason to use a Singleton for this class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:44:18.110",
"Id": "40721",
"Score": "0",
"body": "I agree that the `create_function` call is ugly but I don't believe the language offers anything more eloquent to address the issue that this template processor is trying to solve, which is to avoid file system hits on iterative `includes`. The referenced snippet allows me to include a template once and wrap it in a function, and call it as many times as needed without any subsequent file system hits. I haven't gotten to deep in it yet, but I am exploring using `ClassKit` as a means to avoid the create_function call but the jury is still out. Thank you for your input and suggestions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:00:00.520",
"Id": "40724",
"Score": "0",
"body": "Thank you for the info on extract. I thought about using that but I thought it dumped the vars to global scope... confirmed it didn't. I will evaluate making all of the protected properties static vs singlton as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:49:37.117",
"Id": "40730",
"Score": "0",
"body": "`extract` worked beautifully. Performance wise there was a slight uptick in how long the test ran vs the loop but peak_memory_usage dropped and it's not as ugly so its going to stay."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:56:52.670",
"Id": "40732",
"Score": "0",
"body": "-1, because the main goal in question is exactly to *reduce* filesystem access."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T17:53:20.617",
"Id": "40739",
"Score": "0",
"body": "@nibra `extract` doesn't touch the filesystem, it imports the the values of an array as variables named for their keys, it replaces the goofy foreach($data as $k=>$v){${$k}=$v;}. To quantify the run time performance it was ~0.07s longer over a run of 100,000 template renders. Peak memory went down about ~200 bytes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T22:57:22.930",
"Id": "40749",
"Score": "0",
"body": "@Orangepill: Yes, but `include` does load the file from the filesystem - each time again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T23:45:03.050",
"Id": "40750",
"Score": "0",
"body": "@nibra Include is what I was using to test against. Not in the code. Only filesystem calls are a file_exists test and a single file_get_contents call"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T15:29:36.000",
"Id": "110305",
"Score": "0",
"body": "Most systems in production use opcode caching, so repetitive include of the same file does not touch the filesystem. http://stackoverflow.com/questions/11301124/apc-disk-hits-and-requires-includes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-08-22T15:33:25.607",
"Id": "110306",
"Score": "0",
"body": "to reduce access to many partial files, you could compile them into one partials manifest file and load just once per request"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:11:45.737",
"Id": "26297",
"ParentId": "26268",
"Score": "0"
}
},
{
"body": "<p>I like your approach, but I see a problem:</p>\n\n<pre><code>public function render($data){\n if (!is_callable($this->func)){\n $code = 'foreach($data as $k=>$v){${$k} = $v;} ob_start(); ?>';\n $code.= file_get_contents($this->file).'<?php return ob_get_clean();';\n</code></pre>\n\n<p>If the file contains PHP code <em>without</em> closing <code>?></code> (which is recommended), you'll get a syntax error.\n<code>trim()</code> the code and remove <code>?></code> at the end.</p>\n\n<pre><code> $this->func = create_function('$data', $code);\n }\n $f = $this->func;\n $f($data);\n} \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T16:06:22.530",
"Id": "40733",
"Score": "0",
"body": "good catch - it would have taken me a while to track that one down."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:55:54.603",
"Id": "26304",
"ParentId": "26268",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T22:19:00.653",
"Id": "26268",
"Score": "3",
"Tags": [
"php",
"php5",
"template",
"zend-framework"
],
"Title": "Potential Problems with this templating technique"
}
|
26268
|
<p>I am working on page titles to be responsive. The code I have works and gets the job done, but I know that this is verbose. I decided upon the widths by trial and error based on how the words were stacking on each other </p>
<p><br />
<strong>Desktop</strong>
<img src="https://i.stack.imgur.com/qnfEy.png" alt="Desktop"><br /><br />
<strong>Tablet</strong>
<img src="https://i.stack.imgur.com/pMCie.png" alt="Tablet"><br /><br />
<strong>Mobile</strong><br />
<img src="https://i.stack.imgur.com/FNkF9.png" alt="enter image description here"></p>
<p>This is the what I currently have as code</p>
<p><strong>HTML</strong></p>
<pre><code> <div class="row">
<div id="page-title">
<h1>BruxZir<sup>&reg;</sup> Solid Zirconia Crowns &amp; Bridges</h1>
</div>
</code></pre>
<p>CSS</p>
<pre><code>#page-title, #page-title-video {
background: url(../img/top-banner.jpg) #273344 no-repeat right top;
padding: 0.2em 0 0.2em 1em;
}
#page-title { margin: 12px 15px 24px 15px; }
#page-title-video { margin: 12px 0 24px 0; }
#page-title h1, #page-title-video h1 {
color: #FFFFFF;
letter-spacing: 0.08em;
}
@media screen and (min-width: 1px) and (max-width: 321px) {
#page-title h1, #page-title-video h1 {
font-size: 18px;
}
}
@media screen and (min-width: 322px) and (max-width: 569px) {
#page-title h1, #page-title-video h1 {
font-size: 20px;
}
}
@media screen and (min-width: 570px) and (max-width: 749px) {
#page-title h1, #page-title-video h1 {
font-size: 22px;
}
}
@media screen and (min-width: 750px) and (max-width: 950px) {
#page-title h1, #page-title-video h1 {
font-size: 24px;
}
}
@media screen and (min-width: 951px) {
#page-title h1, #page-title-video h1 {
font-size: 36px;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T06:55:23.593",
"Id": "40701",
"Score": "0",
"body": "(Note: trial and error based on what you're seeing is error-prone, I often see overflowing text on my browser because of this.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T16:34:37.910",
"Id": "40736",
"Score": "0",
"body": "@QuentinPradet breakpoints were calculated but then when I actually tested, things would often produce undesired results. Hence trial and error was the helpful. And you can prevent overflowing text by containing it in divs with defined widths and padding, and text in the <p> tags (if I am understanding your comment correctly)."
}
] |
[
{
"body": "<p>If you have control over your html, give both headers the same class, for example .header-stretch.\nFor media queries - you actually can get rid of min-width. Yep, your code will be overriden for several times. But browser won't care rewriting the same parameter(font-size in this case - in any other you can do so) so it should be like this: </p>\n\n<pre><code>@media screen and (min-width: 951px) {\n .header-stretch {\n font-size: 36px;\n } \n}\n@media screen and (max-width: 950px) {\n .header-stretch {\n font-size: 24px;\n }\n}\n@media screen and (max-width: 749px) {\n .header-stretch {\n font-size: 22px;\n }\n}\n@media screen and (max-width: 569px) {\n .header-stretch {\n font-size: 20px;\n }\n}\n @media screen and (max-width: 321px) {\n .header-stretch {\n font-size: 18px;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T16:38:29.190",
"Id": "40737",
"Score": "0",
"body": "Yes I am also the person writing the HTML. The reason for two classes is that the page title for the video page needed different margins because of how the rest of the content fits on the page. But after thinking about your suggestion, I am very happy you brought that up because I could reduce some code by just creating an additional class for font sizes."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T00:18:15.190",
"Id": "26275",
"ParentId": "26269",
"Score": "1"
}
},
{
"body": "<p>As an alternative, you can try to use <a href=\"http://fittextjs.com/\" rel=\"nofollow\">http://fittextjs.com/</a>\nMaybe it will suit you even more than creating custom media queries</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T16:48:45.990",
"Id": "26306",
"ParentId": "26269",
"Score": "1"
}
},
{
"body": "<p>It might not be relevant but:</p>\n\n<p>1) Write your default code for mobile, and then use mediaqueries for bigger screens.</p>\n\n<p>2) Dont use tag or id selectors (search web for explanation)</p>\n\n<p>3) Use em based values instead of pixel based. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T16:15:39.280",
"Id": "42289",
"Score": "0",
"body": "The challenge when writing default code for mobile is that our site has 60% visitors from desktop, specifically from IE8. Hence why I tend to write for the main target. Most mobile will support the media queries, hence why I add the media queries for them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-10T17:45:24.443",
"Id": "42293",
"Score": "0",
"body": "You can use https://code.google.com/p/css3-mediaqueries-js/ which is a mediaquery polyfill for IE8"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-09T10:28:45.727",
"Id": "27190",
"ParentId": "26269",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T22:21:20.400",
"Id": "26269",
"Score": "4",
"Tags": [
"html",
"css"
],
"Title": "Minimizing CSS media queries for the page title?"
}
|
26269
|
<p>A common idiom that I use for Python2-Python3 compatibility is:</p>
<pre><code>try:
from itertools import izip
except ImportError: #python3.x
izip = zip
</code></pre>
<p>However, a <a href="https://stackoverflow.com/questions/16598244/zip-and-groupby-curiosity-in-python-2-7/16598378?noredirect=1#comment23859060_16598378">comment</a> on one of my Stack Overflow answers implies that there may be a better way. Is there a more clean way to accomplish this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T23:10:11.107",
"Id": "40683",
"Score": "0",
"body": "Perhaps the commenter meant to use the import to shadow `zip`? I.e., `try: from itertools import izip as zip; except ImportError: pass`. (Please excuse the lack of newlines.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T23:14:21.350",
"Id": "40684",
"Score": "0",
"body": "Perhaps -- (I knew about that one). I was just wondering if there was some magic with `__import__` that I didn't know about or something."
}
] |
[
{
"body": "<p>Not sure this is really an answer, or I should elaborate on my comment, and in hindsight probably not even a very good comment anyway, but:</p>\n\n<p>Firstly, you can just simplify it to:</p>\n\n<pre><code>try:\n from itertools import izip as zip\nexcept ImportError: # will be 3.x series\n pass\n</code></pre>\n\n<p>What I was thinking about was:</p>\n\n<p>From 2.6 you can use <a href=\"http://docs.python.org/2/library/future_builtins.html\">as per the docs</a>:</p>\n\n<pre><code>from future_builtins import map # or zip or filter\n</code></pre>\n\n<p>You do however then have the same problem of <code>ImportError</code> - so:</p>\n\n<pre><code>try:\n from future_builtins import zip\nexcept ImportError: # not 2.6+ or is 3.x\n try:\n from itertools import izip as zip # < 2.5 or 3.x\n except ImportError:\n pass\n</code></pre>\n\n<p>The advantage of using <code>future_builtin</code> is that it's in effect a bit more \"explicit\" as to intended behaviour of the module, supported by the language syntax, and possibly recognised by tools. <strike>For instance, I'm not 100% sure, but believe that the 2to3 tool will re-write <code>zip</code> correctly as <code>list(zip(...</code> in this case, while a plain <code>zip = izip</code> may not be... But that's something that needs looking in to.</strike></p>\n\n<p>Updated - also in the docs:</p>\n\n<blockquote>\n <p>The 2to3 tool that ports Python 2 code to Python 3 will recognize this usage and leave the new builtins alone.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:16:34.380",
"Id": "40692",
"Score": "1",
"body": "Ahh ... I didn't actually know about `future_builtins`. It seems a little silly that they don't have that in python3 though. I don't know why they didn't do something like `from __future__ import zip` instead. That would have made sense to me. Anyway, thanks for the explanation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-25T19:19:53.957",
"Id": "43280",
"Score": "0",
"body": "I also think it's silly that 2to3 recognizes the usage of `future_builtins` yet leaves the `from future_builtins import whatever` statement(s) in the output."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T00:05:37.547",
"Id": "26273",
"ParentId": "26271",
"Score": "14"
}
},
{
"body": "<p>If you are trying to make Python 2.x code compatible with Python 3.x you should look at six:</p>\n\n<p><a href=\"http://pythonhosted.org/six/#module-six.moves\" rel=\"nofollow\">http://pythonhosted.org/six/#module-six.moves</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T23:50:25.413",
"Id": "40867",
"Score": "0",
"body": "Yeah, `six` is nice. Generally, if it's simple enough though, I tend to prefer to avoid the extra dependency."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T23:09:58.363",
"Id": "26391",
"ParentId": "26271",
"Score": "3"
}
},
{
"body": "<p>This is roughly twice as fast as using a try/except:</p>\n\n<pre><code>import itertools\nzip = getattr(itertools, 'izip', zip)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-21T03:28:01.590",
"Id": "316548",
"Score": "0",
"body": "I find this claim hard to believe ... [`getattr`](https://github.com/python/cpython/blob/96c7c0685045b739fdc5145018cddfd252155713/Python/bltinmodule.c#L993) works by catching the `AttributeError` and substituting the default value. Admittedly, that's implemented in C so it might be slightly faster, but I find it hard to believe that there's a factor of 2. I also find it hard to believe that the time would matter in the real world if you have this at the top-level of your module... Finally, this _is_ possibly the cleanest way to write it that I've seen. Kudos for that :-)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-22T11:38:52.837",
"Id": "316781",
"Score": "0",
"body": "@mgilson: Use `timeit` and test it yourself. I thought it might be faster, but I didn't think ~2x."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-06-20T17:48:13.763",
"Id": "166265",
"ParentId": "26271",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26273",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T22:53:34.787",
"Id": "26271",
"Score": "12",
"Tags": [
"python",
"dynamic-loading"
],
"Title": "Import \"izip\" for different versions of Python"
}
|
26271
|
<p>Let's say we need to create a store for selling prime numbers.</p>
<p>Users enter the store and ask to buy a number.</p>
<ol>
<li><p>If the number asked <strong>is a prime number</strong>, </p>
<p>1.1. then it's either <strong>available for sale</strong></p>
<p>1.2. or was purchased earlier, hence <strong>not available for sale</strong>.</p></li>
<li><p>If the number asked is <strong>not a prime number</strong>, then it doesn't exist.</p></li>
</ol>
<p>Let us assume that the store contains the maximum possible number of primes that could be represented by a primitive type (in my implementation I assume the largest prime number isn't larger than <code>Int32</code>'s <code>MaxValue</code>, and to actually run this in a reasonable time, I set a <code>MAX_VALUE</code> constant to 100000).</p>
<blockquote>
<ul>
<li><p>The store must handle <strong>concurrent</strong> calls.</p></li>
<li><p>Buying should be fast as possible!</p></li>
<li><p><strong>When the store opens for business, it should already contain the numbers for sale.</strong></p></li>
<li><p>Users <strong>cannot be blocked</strong> by shopping for numbers, nor by other buyers.</p></li>
<li><p>Example: <code>UserA</code> asks to purchase a number and then <code>UserB</code> arrives and asks to purchase a number, then <code>UserB</code> won't need to wait until the system's dealt with <code>UserA</code>'s transaction. So when <code>UserA</code>'s transaction finishes, a response will be delivered to <code>UserA</code>, then <code>UserB</code>'s transaction will start and once finished a response will be delivered to <code>UserB</code>.</p></li>
</ul>
</blockquote>
<hr>
<p>My Solution:</p>
<p>I define an enum called <code>NumberType</code>, that basically describes whats the buying state of each number.</p>
<p>According to the problem definition, every number could be either prime, then it may be available for sale or not available (because it was bought before), or the number isn't prime, so it doesn't exist.</p>
<p>NumberTypes.cs</p>
<pre><code>namespace PrimeStore
{
public enum NumberType
{
SoldSuccessfully,
NotAvailable,
NotExist
}
}
</code></pre>
<p>Next, I define a Singleton class named Store, that is lazy-initiated on first-access to at most MAX_VALUE number of prime numbers in a Dictionary of {Int32, Boolean} pairs, initiating all the Boolean's to false since nothing was bought yet.</p>
<p>To calculate all those prime numbers on initialization, I use a very known algorithm AKA <strong><a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a></strong> in parallel, because it takes very long to calculate.</p>
<p>This method was taken from the <a href="http://www.albahari.com/nutshell/cs4ch22.aspx" rel="nofollow">.NET 4.0 examples article</a>.</p>
<p>Then the public method that is exposed outside is:</p>
<pre><code>public void BuyNumber(Int32 number, Action {NumberType} callback)
</code></pre>
<p>The user may choose whatever number and supplies a callback method that takes a <code>NumberType</code> as a parameter and decides what to do whether the number was successfully bought, wasn't available or doesn't exist.</p>
<p>To verify that the number is prime (in the boundaries between 2..<code>MAX_VALUE</code> as defined in the source code) a simple <code>ContainsKey</code> check on the dictionary is enough.</p>
<p>But if the number does exist (it is prime) then a lock must be gained in order to exclusively buy the number by one user.</p>
<p>In each case, the user's callback is called with the right choice from the enum.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PrimeStore
{
public sealed class Store
{
public const Int32 MAX_VALUE = 100000 - 2;
private static Store _instance;
private static object syncRoot = new Object();
private readonly Dictionary<Int32, Boolean> _primes;
private Store()
{
_primes = new Dictionary<int, bool>();
IEnumerable<int> numbers = Enumerable.Range(2, MAX_VALUE);
var parallelQuery =
from n in numbers.AsParallel()
where Enumerable.Range(2, (int)Math.Sqrt(n)).All(i => n % i > 0)
select n;
foreach (var number in parallelQuery)
{
_primes.Add(number, false);
}
}
public static Store Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
_instance = new Store();
}
}
return _instance;
}
}
public void BuyNumber(Int32 number, Action<NumberType> callback)
{
// no lock is needed here since just checking if a number is prime
// and its a readonly operation.
if (!_primes.ContainsKey(number))
{
callback(NumberType.NotExist);
}
else
{
BuyPrime(number, callback);
}
}
private void BuyPrime(Int32 number, Action<NumberType> callback)
{
Boolean bought = false;
// the number is prime, then obtain exclusive access
// to the dictionary and try to buy it.
lock (_primes)
{
if (_primes[number] == false)
{
_primes[number] = true;
bought = true;
}
}
if (bought)
{
callback(NumberType.SoldSuccessfully);
}
else
{
callback(NumberType.NotAvailable);
}
}
}
}
</code></pre>
<p>Here's a simple program that makes concurrent buys (in parallel) of many numbers between 0..<code>MAX_VALUE</code>, then repeats itself for a few times in order to re-buy numbers who were already bought (that's the purpose of the outer for loop).</p>
<p>The callback simply writes the result of each case to the Console.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace PrimeStore
{
public class Program
{
public static void Main(string[] args)
{
for (int i = 0; i < 3; i++)
{
Parallel.For(0, Store.MAX_VALUE, (number) =>
{
Store.Instance.BuyNumber(number, (numberType) =>
{
switch (numberType)
{
case NumberType.NotAvailable:
Console.WriteLine("{0} is not available for sale.", number);
break;
case NumberType.NotExist:
Console.WriteLine("{0} is not a prime number.", number);
break;
case NumberType.SoldSuccessfully:
Console.WriteLine("Successfully bought {0}.", number);
break;
}
});
});
}
}
}
}
</code></pre>
<p>Can anyone think of a better way to store the numbers, assuming that all prime numbers must already be stored when opening the store (in my implementation - on the first call to Store's <code>BuyNumber</code>) without causing transactions a run-time worse than \$O(1)\$?</p>
<p>What if we'd tried to increase <code>MAX_VALUE</code> to almost <code>Int32.MaxValue</code>?</p>
<p>What do you think will happen first, an OutOfMemoryException or 3 hours of waiting?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T06:53:02.317",
"Id": "40699",
"Score": "1",
"body": "It's nice to see thoughtful questions. Thanks!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-21T09:13:20.857",
"Id": "88544",
"Score": "0",
"body": "Rolled back Rev 5 → 3. Please [post a new question](http://meta.codereview.stackexchange.com/q/1763) instead of continually revising the code."
}
] |
[
{
"body": "<pre><code>foreach (var number in parallelQuery)\n{\n _primes.Add(number, false);\n}\n</code></pre>\n\n<p>You could simplify this to:</p>\n\n<pre><code>_primes = parallelQuery.ToDictionary(n => n, n => false);\n</code></pre>\n\n<hr>\n\n<pre><code>public void BuyNumber(Int32 number, Action<NumberType> callback)\n</code></pre>\n\n<p>I don't understand why are you using a callback here. The whole method is completely synchronous, so I think you should simply <code>return</code> the result from it.</p>\n\n<hr>\n\n<pre><code>// no lock is needed here since just checking if a number is prime\n// and its a readonly operation.\nif (!_primes.ContainsKey(number))\n</code></pre>\n\n<p>Read-only operation doesn't mean that you don't need a lock. <a href=\"http://msdn.microsoft.com/en-us/library/xfhwa508.aspx\" rel=\"nofollow\">The documentation for <code>Dictionary</code></a> says:</p>\n\n<blockquote>\n <p>A Dictionary<TKey, TValue> can support multiple readers concurrently, as long as the collection is not modified.</p>\n</blockquote>\n\n<p>The problem is, there could be a write occurring from another thread, so according to the documentation, you should use locking in this case (possibly using <code>ReaderWriterLockSlim</code> which allows multiple readers at the same time).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:06:11.347",
"Id": "40690",
"Score": "0",
"body": "That documentation is inconclusive.\nI think that it refers to adding/removing,\nrather then changing the Boolean value, which is the only operation this method could do.\nKeeping in mind that its declared readonly (only initialized once, in the constructor).\nSo since ALL of the primes are already inside the dictionary, and will not be removed and no more primes will be added, it is fine not to use a lock for reading purposes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:18:09.333",
"Id": "40693",
"Score": "0",
"body": "@rycle I really don't think the documentation is inconclusive. Setting the value for some key *is* modification. It's certainly possible that for a certain implementation of `Dictionary`, your code is actually thread-safe. But I don't think it's a good idea to rely on undocumented implementation details."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:21:12.377",
"Id": "40694",
"Score": "2",
"body": "@rycle That method *is* synchronous. If you think it isn't, then you don't know what “synchronous” means. Yes, it can wait on the lock, but it waits on it *synchronously*. Callbacks are useful for methods that are actually asynchronous, that is, return before their work is actually complete. But that's not the case with your code. If you changed the method to return its result, it would behave exactly the same."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:47:53.613",
"Id": "40695",
"Score": "0",
"body": "Yes, you were right! thanks SVICK (: Good work@\n\n\nI've now edited and made it an asynchronous call."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:52:42.870",
"Id": "40696",
"Score": "0",
"body": "About undocumented implementation details, I don't know if its documented or not (it seems not in the documentation on MSDN, the one you gave link to), \nBut I simply think its obvious that a readonly dictionary's keys will forever stay the same, so you don't have to obtain a lock to just check if a key exist."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T06:53:18.113",
"Id": "40700",
"Score": "0",
"body": "@rycle Consider accepting svick post if it helped you."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T00:46:09.590",
"Id": "26277",
"ParentId": "26272",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "26277",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-16T23:39:49.593",
"Id": "26272",
"Score": "7",
"Tags": [
"c#",
"primes",
"singleton",
"callback",
"sieve-of-eratosthenes"
],
"Title": "Prime Numbers Store"
}
|
26272
|
<p>I am creating a game, with Ruby scripting.</p>
<p><code>Sprite</code> and <code>Label</code> objects can be drawn on the screen. Depending on the order you draw them, one will overlap the other.</p>
<p>To make things easier, I want to implement a property in my drawable objects: <strong>Z order</strong>. So the higher the <code>Z</code> order of one object, the closer it will be to the player so to speak.</p>
<p>For this, I decided to create a class that will be in charge of containing my <code>Sprite</code> and <code>Label</code> objects, and depending on their <code>Z</code> property, draw them in order.</p>
<p>When a <code>Sprite</code> or <code>Label</code> object is created, they are automatically assigned to my global <code>Renderer</code> class.</p>
<p>Here is my <code>Renderer</code> class:</p>
<pre><code>class Renderer
EXPECTED_CLASSES = [Sprite,Label]
# ----------------------------------------------------------------------------------------------------
# * Constructor
# ----------------------------------------------------------------------------------------------------
def initialize
@sprite_batch = Sprite_Batch.new
@stack = {}
@assigned_items = []
@sorted_keys = []
end
# ----------------------------------------------------------------------------------------------------
# * Add a drawable element with a Z order value
# ----------------------------------------------------------------------------------------------------
def add(item,z = 0)
if (assignable?(item))
@assigned_items.push(item)
if (@stack.has_key?(z))
@stack[z].push(item)
else
@stack[z] = [item]
end
@sorted_keys = @stack.keys.sort
end
end
# ----------------------------------------------------------------------------------------------------
# * Remove an item from this manager
# ----------------------------------------------------------------------------------------------------
def remove(item)
if (removable?(item))
key = item.z
@stack[key].delete(item)
@assigned_items.delete(item)
if (@stack[key].empty?)
@stack.delete(key)
@sorted_keys.delete(key)
end
end
end
# ----------------------------------------------------------------------------------------------------
# * Reorder item
# ----------------------------------------------------------------------------------------------------
def reorder(item,z)
remove(item)
add(item,z)
end
# ----------------------------------------------------------------------------------------------------
# * Render items in order
# ----------------------------------------------------------------------------------------------------
def render
@sprite_batch.begin
for key in @sorted_keys
for item in @stack[key]
@sprite_batch.draw(item)
end
end
@sprite_batch.end
end
# ----------------------------------------------------------------------------------------------------
# * Determine if an item can be added
# ----------------------------------------------------------------------------------------------------
def assignable?(item)
if (removable?(item) || !EXPECTED_CLASSES.include?(item.class))
return false
end
return true
end
# ----------------------------------------------------------------------------------------------------
# * Determine if an item can be removed
# ----------------------------------------------------------------------------------------------------
def removable?(item)
if (!@assigned_items.include?(item))
return false
end
return true
end
end
</code></pre>
<p>You probably noticed <code>Sprite_Batch</code> there. Don't pay it attention - it is just where the actual drawing occurs, but it is beyond the purpose of this question.</p>
<p>What I want to know - how can I further improve this class to be able to draw the objects in the right order depending on their <code>Z</code> property?</p>
<p>This class works alright, but I'm afraid it could get a bit slow when I have lots of objects for drawing.</p>
<p><strong>Notes</strong></p>
<ul>
<li>The <code>render</code> method is called whenever the window wants to update its contents. So it is called <em>a lot</em> of times in a short interval.</li>
<li>The <code>reorder</code> method is used rarely, so I guess it is fine.</li>
<li>The <code>add</code> method is not called very often throughout gameplay, but at startup of a specific scene (like a new game level), a large batch of new <code>Sprite</code> and <code>Label</code> objects are to be expected.</li>
<li>I've considered removing the validation when adding/removing items and instead let the game crash if I did a mistake in a script.</li>
</ul>
|
[] |
[
{
"body": "<blockquote>\n <p>how can I further improve this class to be able to draw the objects in the right order depending on their Z property?</p>\n</blockquote>\n\n<p>The abstraction for the task is a <a href=\"http://en.wikipedia.org/wiki/Priority_queue\" rel=\"nofollow\">priority queue</a>, that's it, a dynamic structure that keeps elements sorted by a defined order (here the <em>z-index</em>). A priority queue is efficiently implemented with a <a href=\"http://en.wikipedia.org/wiki/Heap_%28data_structure%29\" rel=\"nofollow\">heap</a>, which has <em>O(log n)</em> find/insertion/deletion, which is pretty cool, and can be traversed in <em>O(n)</em>. A Ruby gem that implements a priority queue: <a href=\"https://github.com/rubyworks/pqueue\" rel=\"nofollow\">pqueue</a>. Of course, if you have few sprites it won't improve much and it's not worth the hassle, but it's good to know about these algorithms. In your case:</p>\n\n<pre><code>require 'pqueue'\npq = PQueue.new(initial_sprites) { |s1, s2| s1.z <=> s2.z }\npq.push(new_sprite)\n</code></pre>\n\n<p>You use an imperative approach throughout the code. I won't argue that a game has extremely fast dynamic changes and it may be the only reasonable choice (at least in an imperative language like Ruby), but note that every time that you change some variable in-place, you're making the code harder to understand (because potentially everything can be changed everywhere, functions are no longer black boxes that get things and return things). Try to minimize in-place updates and side-effects. If you are curious: <a href=\"https://code.google.com/p/tokland/wiki/RubyFunctionalProgramming\" rel=\"nofollow\">Functional Programming and Ruby</a>.</p>\n\n<p>Instead of:</p>\n\n<pre><code>for key in @sorted_keys\n for item in @stack[key]\n @sprite_batch.draw(item)\n end\nend\n</code></pre>\n\n<p>This is more idiomatic:</p>\n\n<pre><code>@sorted_keys.each do |key|\n @stack[key].each do |item|\n @sprite_batch.draw(item)\n end\nend\n</code></pre>\n\n<p>Instead of:</p>\n\n<pre><code>def assignable?(item)\n if (removable?(item) || !EXPECTED_CLASSES.include?(item.class))\n return false\n end\n return true\nend\n</code></pre>\n\n<p>First, it's not idiomatic to write explicit <code>return</code>s. Second, it's more clear if you write a full <code>if</code>/<code>else</code>, the branches of the conditional (along with its indendation) conveys a lot of information to the reader. Also, you have a boolean already, <code>if boolean then false else true</code> -> <code>!boolean</code>, so the branches are unnecessary. You can simply write:</p>\n\n<pre><code>def assignable?(item)\n !(removable?(item) || !EXPECTED_CLASSES.include?(item.class))\nend\n</code></pre>\n\n<p>Or using De Morgan law, in possitive form:</p>\n\n<pre><code>def assignable?(item)\n !removable?(item) && EXPECTED_CLASSES.include?(item.class)\nend\n</code></pre>\n\n<p>More on <a href=\"https://code.google.com/p/tokland/wiki/RubyIdioms\" rel=\"nofollow\">idiomatic Ruby</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:27:42.507",
"Id": "26298",
"ParentId": "26278",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T01:07:36.130",
"Id": "26278",
"Score": "2",
"Tags": [
"optimization",
"ruby"
],
"Title": "Drawing game objects using their Z-order property"
}
|
26278
|
<pre><code>try{save.Username = usernamedetails.Rows[0].ItemArray[0].ToString(); }
catch{ save.Username = ""; }
try { save.Firstname = dtdetails.Rows[0].ItemArray[1].ToString(); }
catch { save.Firstname = ""; }
try { save.LastName = dtdetails.Rows[0].ItemArray[2].ToString(); }
catch { save.LastName = ""; }
try { save.Address1 = dtdetails.Rows[0].ItemArray[3].ToString(); }
catch { save.Address1 = ""; }
try { save.Address2 = dtdetails.Rows[0].ItemArray[4].ToString(); }
catch { save.Address2 = ""; }
try { save.Postoffice = dtdetails.Rows[0].ItemArray[5].ToString(); }
catch { save.Postoffice = ""; }
try { save.District = dtdetails.Rows[0].ItemArray[6].ToString(); }
catch { save.District = ""; }
try{ save.State = dtdetails.Rows[0].ItemArray[7].ToString(); }
catch{ save.State = ""; }
try { save.Country = dtdetails.Rows[0].ItemArray[8].ToString(); }
catch { save.Country = ""; }
try { save.MobileNumber = dtdetails.Rows[0].ItemArray[9].ToString(); }
catch { save.MobileNumber = ""; }
try { save.LandLine = dtdetails.Rows[0].ItemArray[10].ToString(); }
catch { save.LandLine = ""; }
try { save.Pin = dtdetails.Rows[0].ItemArray[11].ToString(); }
catch { save.Pin = ""; }
try { save.Cmpnyname = dtdetails.Rows[0].ItemArray[12].ToString(); }
catch { save.Cmpnyname = ""; }
try { save.Design = dtdetails.Rows[0].ItemArray[13].ToString(); }
catch { save.Design = ""; }
try { save.Loc = dtdetails.Rows[0].ItemArray[14].ToString(); }
catch { save.Loc = ""; }
try { save.CmpnyPincode = dtdetails.Rows[0].ItemArray[15].ToString(); }
catch { save.CmpnyPincode = ""; }
try { save.EmailID = dtdetails.Rows[0].ItemArray[16].ToString(); }
catch { save.EmailID = ""; }
try { save.OffNumber = dtdetails.Rows[0].ItemArray[17].ToString(); }
catch { save.OffNumber = ""; }
</code></pre>
<p>Is this type of strategy suitable for coding?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T05:42:35.783",
"Id": "40698",
"Score": "27",
"body": "**YUCK!** "
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T10:01:02.120",
"Id": "40705",
"Score": "0",
"body": "What is the reason for the `catch`es? Are you worries that the column won't exist? That its value will be `null`? Something else? A combination of the above?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T12:52:21.160",
"Id": "40712",
"Score": "0",
"body": "@svick I'd guess both. Either catching null reference exceptions or index out of range exceptions - either way, my eyes are bleeding."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:07:32.090",
"Id": "40718",
"Score": "0",
"body": "As @svick said, you really need to say *why* you're trying to catch line-by-line exceptions for us to be useful."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T17:41:20.503",
"Id": "41112",
"Score": "0",
"body": "My first reaction is that there is a better data object to use for the information than a DataTable. The only two cases I could think of off the top of my head why someone would use it is because they are either reading data out of a database (in which case an ORM would be advisable) or from a DataGridView (in which case data binding `save` or some view model representation of `save` would be preferable)."
}
] |
[
{
"body": "<p>First: Never have an exception raised just because you're too lazy to validate the input.\nSecond: The very repetitive wording begs for some improvement. You're dealing with the same objects in each line pair, so why not implement some array and null checks in sub functions?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T05:54:28.507",
"Id": "26282",
"ParentId": "26280",
"Score": "3"
}
},
{
"body": "<p>I suggest the use of the ternary Operator like this:</p>\n\n<pre><code> String details=(usernamedetails.Rows[0]!=null)?usernamedetails.Rows[0].ItemArray[0] as String:null;\n save.Username=(details!=null)?details.toString():\"\";\n</code></pre>\n\n<p>So you prevent the exceptions. </p>\n\n<p>And besides your code would be much more readable, than a jungle of try-catch-blocks.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T09:55:43.957",
"Id": "40703",
"Score": "1",
"body": "`ItemArray` is an `Object[]` so you'd need to cast `usernamedetails.Rows[0].ItemArray[0]` to a `string`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:03:30.417",
"Id": "40717",
"Score": "1",
"body": "This will still fail if `Rows` is empty. It's also the perfect use for `??`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T07:16:53.723",
"Id": "26284",
"ParentId": "26280",
"Score": "3"
}
},
{
"body": "<ol>\n<li>You shouldn't use general <code>catch</code>, you should always catch only the exceptions that you actually want to catch.</li>\n<li>Avoidable exceptions like index out of range or null reference should indicate an error in your code. Instead of handling them, you should make sure they never happen.</li>\n</ol>\n\n<p>For your specific case, you could write an extension method that checks that the index isn't out of range and that the value isn't <code>null</code> (and returns empty string if it is).</p>\n\n<p>Something like:</p>\n\n<pre><code>public static string GetAsStringOrEmpty(this object[] array, int index)\n{\n if (array == null)\n throw new ArgumentNullException(\"array\");\n\n if (index >= 0 && index < array.Length)\n {\n string value = array[index] as string;\n\n if (value != null)\n return value;\n }\n\n return string.Empty;\n}\n</code></pre>\n\n<p>You would then use it like this:</p>\n\n<pre><code>var array = dtdetails.Rows[0].ItemArray;\nsave.Firstname = array.GetAsStringOrEmpty(1);\nsave.LastName = array.GetAsStringOrEmpty(2);\n…\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:02:48.567",
"Id": "26295",
"ParentId": "26280",
"Score": "14"
}
},
{
"body": "<p>Convert the repeated calls to a function, and remove the generalised catch.</p>\n\n<pre><code>// Assuming DataTable containing the source list\nfunction string GetValue(DataTable dt, int idx)\n{\n // Check if table is not null and contains data\n if (dt == null || dt.Rows.Count == 0) return String.Empty;\n // Check if index exists\n if (dt.Rows[0].ItemArray.Count <= idx && idx >= 0) return String.Empty;\n // Check if the value is null\n if (dt.Rows[0].ItemArray[idx] == null) return String.Empty;\n\n return dt.Rows[0].ItemArray[idx].ToString();\n}\n</code></pre>\n\n<p>You can then call the sub function</p>\n\n<pre><code>save.Firstname = GetValue(dtdetails, 1);\n</code></pre>\n\n<p>And repeat for the various values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-27T00:21:09.387",
"Id": "41302",
"Score": "1",
"body": "`dt.Rows[0].ItemArray` is used several times in your code. Why not store that value in a variable? E.g. `var itemArray = dt.Rows[0].ItemArray`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T13:29:37.840",
"Id": "26529",
"ParentId": "26280",
"Score": "1"
}
},
{
"body": "<hr>\n\n<p>Quoting @svick's answer:</p>\n\n<blockquote>\n <p>Avoidable exceptions like index out of range or null reference should indicate an error in your code. <strong>Instead of handling them, you should make sure they never happen.</strong></p>\n</blockquote>\n\n<p>Seems to me that the <code>try/catch</code>ing as shown is just a substitute for checking for null. Potentially there are casting issues, but that would be real \"rouge data\" and a true <code>Exception</code>al situation. Ensure valid/desired/non-null data in your datarow at the time it's populated. Better use of the .NET <code>System.Data</code> classes & properties will go a long way!</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.datarow.itemarray.aspx\" rel=\"nofollow\">Note the potential exceptions thrown by <code>ItemArray</code></a>. Work with them.</p>\n\n<pre><code>DataRow newRow = new DataRow();\nnewRow.AllowDBNull = false; // or \"true\". As desired.\nnewrow.DefaultValue = string.Empty;\n\n// get the Object[] to populate the row.\n\n// The Dataxxxx classes have mechanisms & properties for handling, in particular, \n// null values relatively seamlessly when coming/going to a database. This code is\n// a hint of that kind of capability\n\ntry {\n newrow.ItemArray = dataObjectArray; // any null values become string.Empty\n}catch (NoNullAllowedException e) {\n // \"this will never happen!\". But if it does, we'll know it explicitly\n}catch(ArgumentException e) { \n // we know column count and array length do not match.\n}catch(Exception e) {\n // I really cared about the 2 specific ones above. The rest we'll get here.\n}\n\n// now we can go through all the `ItemArray[x].ToString` and not worry about null.\n\ntry {\n // all the ToString-ing. All in this one try block.\n // at this point an exception truly is exceptional\n}catch(InvalidCastException e) {}\ncatch (Exception e) {}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-03T21:04:51.710",
"Id": "26953",
"ParentId": "26280",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T05:08:34.823",
"Id": "26280",
"Score": "8",
"Tags": [
"c#",
"exception-handling"
],
"Title": "Saving a contact and dealing with exceptions"
}
|
26280
|
<p>A while ago I started working on a project, which does things mostly with jQuery and PHP. I had some problems with my structure and started using CodeIgniter which uses an MVC pattern. So the PHP part is all good now.</p>
<p>I am just a little worried about my jQuery code. It looks bloated and I feel like there is room for improvement. The problem is that the code is very simple and I don't know how to actually improve it.</p>
<p>My code looks like this:</p>
<pre><code>$(function() {
var baseURL = "index.php/";
/* *
* Fill the list with all available objects
*/
$(document).ready(function() {
$.ajax({
type: "POST",
url: baseURL+"Objects/getList",
dataType: "json",
data: "",
cache: false,
success: function(data) {
$('#object-list').html();
var objects= "";
for (var i = 0; i < data.length; i++) {
objects+= "<option value='" + data.id +"'>" + data[i].name + "</option>";
}
$('#object-list').html(options);
}
});
});
/* *
* Authenticate and login using a username and password
*/
$('#login').click(function(event) {
var username = $("#login-username").val();
var password = $("#login-password").val();
$.ajax({
type: "POST",
url: baseURL+"User/authenticateUser",
dataType: "json",
data: "username="+ username +"&password=" + password,
success: function(data) {
var success = data.result;
if (!success) {
$("#login-window-inner-message").html("The credentials provided were not found. Please try again.");
} else {
$('#login-window').remove();
LoadGame();
}
}
});
});
/* *
* Run all functions part of the startup procedure
*/
function LoadGame() {
UpdateNavigation();
DisplayUserInfo();
}
/* *
* Update the action screen
*/
function UpdateActions() {
$.ajax({
type: "POST",
url: baseURL+"Location/getOptions",
dataType: "json",
data: "",
success: function(data){
$("#action1").html(typeof data.option1 != 'undefined' ? data.option1.title : "<br/>");
$("#action2").html(typeof data.option2 != 'undefined' ? data.option2.title : "<br/>");
$("#action3").html(typeof data.option3 != 'undefined' ? data.option3.title : "<br/>");
}
});
}
/* *
* Display the description of the current zone
*/
function DisplayZoneDescription() {
$.ajax({
type: "POST",
url: baseURL+"Location/getZoneDesciption",
dataType: "json",
data: "",
success: function(data){
$("div#message-log").html("<p class='normal'>" + data.description + "</p>");
}
});
}
});
</code></pre>
<p>That's not the entire code (so some called functions might not be there), which would be too long to post here. But the gist of it is that I have about a hundred "hooks" to HTML elements which all fire an Ajax function which returns data after which the screen is updated.</p>
<p>Some things that come to mind:</p>
<ol>
<li>In an MVC environment, should the Ajax data part be in the URL?</li>
<li>I will be splitting up the functions into different files an the production environment.</li>
<li>The main problem I'm having with this is that it just looks like it's hanging loosely together, and doesn't fit my structured MVC environment/code.</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T12:59:09.973",
"Id": "40713",
"Score": "1",
"body": "What about security? Will the server refuse to send data if the player executes LoadGame() from the browser debug window without having been authentified?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T13:28:00.987",
"Id": "40716",
"Score": "0",
"body": "Yea, it's all caught in the PHP code Ajax makes the call to, it's all pretty secure on that level. I'm making sure I don't put any security measures into the JQuery code. At most, error messages returned by PHP are shown to the users (although not at the moment). But generally speaking if a function returns an error it means the user is trying to mess with the script. I dont'see the point in creating message such as \"Please stop trying to cheat/hack the system\", so that's why you don't see any error messages."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-20T08:49:57.533",
"Id": "40812",
"Score": "0",
"body": "DisplayZoneDescription and UpdateActions seem to be getting information from your server not changing/updating data. To keep in line with practices would these not best be served as GET requests??"
}
] |
[
{
"body": "<p>You say you got a hundred of these? And possibly longer?</p>\n\n<p>I suggest you invest on learning these tools:</p>\n\n<ul>\n<li><p>A client-side MV* framework like <a href=\"http://backbonejs.org/\" rel=\"nofollow\">Backbone</a>. That way, your code will be modular and structured.</p></li>\n<li><p>As for your UI, I suggest you go with <a href=\"https://github.com/janl/mustache.js/\" rel=\"nofollow\">Mustache</a> for a logicless templating solution.</p></li>\n<li><p>An automation tool like <a href=\"http://gruntjs.com/\" rel=\"nofollow\">Grunt</a>, which runs for you the most repetitive tasks like merging files, moving files unit tests etc.</p></li>\n</ul>\n\n<p>I also suggest you watch <a href=\"http://www.youtube.com/watch?v=mKouqShWI4o\" rel=\"nofollow\">this video from Nicholas Zakas</a> regarding scalability and architecture. Though not all points will be applicable, at least you get the idea how to loosely couple your code.</p>\n\n<p>As for the questions:</p>\n\n<blockquote>\n <p>In an MVC environment, should the Ajax data part be in the url?</p>\n</blockquote>\n\n<p>If you were to use MVC, that would be handled in the Models and Routers. Depending on the framework, some handle it for you. Just give them the proper routing and parameters, and you are good to go. No \"low-level\" code.</p>\n\n<blockquote>\n <p>I will be splitting up the functions into different files an the production environment.</p>\n</blockquote>\n\n<p>It's only in development that you actually split them so they make sense. In production, you actually merge and minify them. Check out jQuery. Their source is <a href=\"https://github.com/jquery/jquery/tree/master/src\" rel=\"nofollow\">split into parts during development</a>, but end up with <a href=\"http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js\" rel=\"nofollow\">a squished file during deployment</a>.</p>\n\n<p>The usual procedure (via Grunt tasks) is:</p>\n\n<ul>\n<li>jsbeautifier - Beautify code, so that the linter will be happy</li>\n<li>JShint - Checks for syntax errors, readability issues, possible break areas.</li>\n<li>Qunit - Unit testing for all your functions. to check if it works as expected.</li>\n<li>concat - Join all files into one. Lessens HTTP requests.</li>\n<li>minify - shrinks your concatenated scripts, to lessen download size.</li>\n</ul>\n\n<p>And you end up with one power-packed nKB file (where <code>n</code> is the size of course). </p>\n\n<blockquote>\n <p>The main problem I'm having with this is that it just looks like it's hanging loosely together, and doesn't fit my structured MVC environment/code.</p>\n</blockquote>\n\n<p>I really suggest you invest your time in your toolset. I gave suggestions above based on experience and taste. There are other tools out there, like other MV* frameworks, other template engines. You might even want to learn SASS or LESS for CSS. </p>\n\n<p>Although I encourage you to learn the tools, which will lead you to ultimately abandon your old code, here are a few tips though:</p>\n\n<ul>\n<li><p>The <code>index.php/</code> part of the url can be removed via url-rewriting on the server. As far as I know, there's a solution posted somewhere in the CodeIgniter forums, which can be searched. That way, your code will always start right after the first <code>/</code> of the domain.</p></li>\n<li><p>The <code>data</code> parameter of <code>$.ajax()</code> can accept objects:</p>\n\n<pre><code>data: {\n username : username,\n password : password\n}\n</code></pre></li>\n<li><p>These could be avoided using templating:</p>\n\n<pre><code>$(\"#login-window-inner-message\").html(\"The credentials provided were not found. Please try again.\");\n</code></pre></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-22T08:47:16.003",
"Id": "40990",
"Score": "0",
"body": "Thank you for your answer, guess I have some reading to do. I'm having a hard time finding good examples for Backbone and Mustache though. As in, I can't find any convincing examples that make me want to use it. But thank you again!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T10:06:43.800",
"Id": "26336",
"ParentId": "26286",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26336",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T08:36:15.467",
"Id": "26286",
"Score": "4",
"Tags": [
"javascript",
"jquery",
"design-patterns",
"mvc",
"ajax"
],
"Title": "jQuery code repetition and MVC"
}
|
26286
|
<p>I am currently working on a project that involves Lua. For convenience, I created a wrapper class for the Lua state structure. However, I also added some methods for getting globals and table fields. Since these methods are very similar, I decided do turn them into macros.</p>
<p>Do you consider this a good solution? Would you have done it another way?</p>
<pre><code>#include <lua/lua.hpp>
#include <util/Exception.h>
#include "LuaState.h"
namespace gnaar {
LuaState::LuaState() : ls(luaL_newstate())
{
luaL_openlibs(ls);
}
void LuaState::doFile(const char* file)
{
if (luaL_dofile(ls, file) != 0)
{
throwException(lua_tostring(ls, -1));
}
}
lua_State* LuaState::operator*()
{
return ls;
}
LuaState::~LuaState()
{
lua_close(ls);
}
//==================== ugly macro stuff below, beware ====================
#define _getGlobal(_lua, _type, _check, _conversion) \
template <> \
_type LuaState::getGlobal<_type>(const char* name, _type dfault) \
{ \
lua_getglobal(_lua, name); \
if (_check(_lua, -1)) \
{ \
return (_type) _conversion(_lua, -1); \
} \
else \
{ \
return dfault; \
} \
}
#define _getTableField(_lua, _type, _check, _conversion) \
template <> _type LuaState::getTableField<_type> \
(const char* table, const char* key, _type def) \
{ \
lua_getglobal(_lua, table); \
if (!lua_istable(_lua, -1)) \
{ \
return def; \
} \
_type result; \
lua_pushstring(_lua, key); \
lua_gettable(_lua, -2); \
if (!_check(_lua, -1)) \
{ \
result = def; \
} \
else \
{ \
result = (_type) _conversion(_lua, -1); \
} \
lua_pop(_lua, 1); \
return result; \
}
_getGlobal(ls, int, lua_isnumber, lua_tonumber)
_getGlobal(ls, const char*, lua_isstring, lua_tostring)
_getGlobal(ls, bool, lua_isboolean, lua_toboolean)
_getTableField(ls, int, lua_isnumber, lua_tonumber)
_getTableField(ls, const char*, lua_isstring, lua_tostring)
_getTableField(ls, bool, lua_isboolean, lua_toboolean)
} // namespace gnaar
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T17:49:50.473",
"Id": "40738",
"Score": "1",
"body": "If you change (or wrap) functions like (`lua_isnumber` and `lua_tonumber`) or (`lua_isstring` `lua_tostring`) to function templates (e.g., `lua_is<TypeHere>` and `lua_to<TypeHere>`), you won't have to specialize `getGlobal` and `getTableField` manually/via macros and will be able to statically dispatch inside them automatically/via template-type selection."
}
] |
[
{
"body": "<blockquote>\n <p>Do you consider this a good solution?</p>\n</blockquote>\n\n<p>No.</p>\n\n<blockquote>\n <p>Would you have done it another way?</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<p>Macros are never the solution. There is always a better tool. Macros are designed to deal with Hardware/OS/Compiler variations. You should limit their use to this situaation.</p>\n\n<p>It looks like your macros are used to manually insert functions for specific situations. It seems like these could be deduced using template specializations. It is hard to provide a better solution without more code. But let my give it a go (this will probably be wrong as I don't have enough information).</p>\n\n<pre><code>template<typename Type>\nTypeOfLuaObject LuaState::lua;\n\ntemplate<typename Type>\nstruct DoCheck;\ntemplate<typename Type>\nstruct DoConversion;\n\n// Provide a specialization of these two macros for each\n// type you are using.\ntemplate<>\nstruct DoCheck<int>\n{\n bool operator()(TypeOfLuaObject& lauObjec, int val) const {return lua_isnumber(lauObjec, val);}\n};\ntemplate<>\nstruct DoConversion<int>\n{\n int operator()(TypeOfLuaObject& lauObjec, int val) const {return lua_tonumber(lauObjec, val);}\n};\n\n// The main function can then be left in its generalized form\n// It will pick up the specialization of the above macros.\n// Type will be deduced automatically from `def` parameter and the other two\n// template parameters will be deduced from `Type` so you do not need to manually\n// specify the type when calling.\ntemplate<typename Type, typename Check=DoCheck<Type>, Conversion=DoConversion<T>>\nType LuaState::getTableField(const char* table, const char* key, Type def)\n{\n lua_getglobal(lua, table);\n if (!lua_istable(lua, -1))\n { \n return def;\n } \n Type result;\n lua_pushstring(lua, key);\n lua_gettable(lua, -2);\n Check doCheckObj;\n if (!checkObj(lua, -1))\n { \n result = def;\n } \n else\n { \n Conversion doConversionObj;\n result = doConversionObj(lua, -1);\n } \n lua_pop(lua, 1); \n return result;\n}\n</code></pre>\n\n<p><strong>Other comments:</strong></p>\n\n<p>When you use macros. Make sure they are all uppercase. </p>\n\n<p>Macros do not obey scope boundaries. So we reserve all uppercase letters for macros to prevent accidental smashing of normal variables.</p>\n\n<p>Don't use '_' as a prefix for identifiers.<br>\nMost people don't know the actual rules for this. So even if you do it will confuse them.</p>\n\n<p>But you are breaking the rule with your macros <code>_getGlobal</code> and <code>_getTableField</code>. As they are macros they are not bound by the scope of your namespace and thus could potentially be trampling on some system macro.</p>\n\n<p>See the artile I wrote on SO: <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T22:15:26.920",
"Id": "40776",
"Score": "0",
"body": "Just one more question: Why are the the operators declared as 'const'? Sorry if that's a silly question, but I am relatively new to C++."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-19T06:06:56.123",
"Id": "40782",
"Score": "0",
"body": "Methods declared const can not change the state of the object. Since there is no state held in the object that is not a problem. If an object is const you may only call const methods. So if you have a const object then you can only call methods that are const. As used in this example above it makes no difference. But when I add methods that do not change state I mark them as const. Then I can call them on a const object if I need too. It also provides context to the compiler allowing optimizations."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-18T15:41:39.463",
"Id": "26323",
"ParentId": "26291",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "26323",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T12:29:34.640",
"Id": "26291",
"Score": "6",
"Tags": [
"c++",
"macros",
"lua"
],
"Title": "C++: Generating similar methods with macros"
}
|
26291
|
<p>This question is about the best way to declare functions in Javascript. The app is a small 2 player board game I'm working on as part of a bigger web page. Basically I have a socket which receives and send messages and the game acts according to the content of the message.</p>
<pre><code>$(function () {
var board = document.getElementById('board');
//When a msg is received
//structure of msg : msg = ['action','args']
if (msg[0] === 'action1') {
func1(args);
} else if (msg[0] === 'action2') {
func2(args);
}
}
function func1(args) {
var a, b...;
doAction1(); //uses the DOM element board, the args and local variables
}
function func2(args) {
var a, b...;
doAction2();
}
</code></pre>
<p>Now, I was thinking of using an object the way I would do in Java but it seems that it is not the best practice. Should I use a single function like so?</p>
<pre><code>$(function () {
var game = function () {
var gamevar1, gamevar2, ...;
action1: function (arg) {
doAction1();
}
action2: function (arg) {
doAction2();
}
}
//when a msg is received [action,param]
game.msg[0](msg[1]);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:52:52.267",
"Id": "40722",
"Score": "0",
"body": "I just answered, but now I realize I may have misread your code. are the lines with action1 inside of func1() and action2 inside of func2() meant to be method calls? is doAction1 in your second set of code supposed to be the same method? Is the second doAction1 supposed to be doAction2?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T15:12:19.067",
"Id": "40728",
"Score": "0",
"body": "Cool, no problem. Was my answer sufficient?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T20:48:34.067",
"Id": "40746",
"Score": "0",
"body": "MMM I think so. So the later code would be the best way to do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T23:48:47.100",
"Id": "40751",
"Score": "0",
"body": "Yeah, isn't it more readable?"
}
] |
[
{
"body": "<p>Since this is all the code you posted, I'm going to assume you're only using these functions in the place they're defined, so the later code would be best. It's more readable and doesn't include unnecessary identifiers.</p>\n\n<p>Your question is really about anonymous functions, not closures. To answer this question, you should ask yourself, \"do I plan on using these functions elsewhere\"? Since anonymous functions, by definition, are not bound to an identifier, they will be inaccessible everywhere except where they are defined.</p>\n\n<p>This is the version that I would recommend:</p>\n\n<pre><code>$(function () {\n\n var game = function () {\n var gamevar1, gamevar2, ...;\n action1: function (arg) {\n doAction1();\n }\n\n action2: function (arg) {\n doAction2();\n }\n }\n\n //when a msg is received [action,param]\n game.msg[0](msg[1]);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T14:47:54.077",
"Id": "26299",
"ParentId": "26293",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "26299",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-17T13:11:08.473",
"Id": "26293",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"game"
],
"Title": "2-player board game app"
}
|
26293
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.