body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I've written some code to do the job for me. The final results seems to work fine, but I would like to know if this is how I should Handle classes. And where I can improve or things which are just plain stupid.</p>
<pre><code>class CInit
{
public:
CInit();
~CInit();
void Check(bool);
virtual bool Init();
virtual bool ExInit();
private:
static CInit* _ThisInit;
};
CInit* CInit::_ThisInit;
CInit::CInit()
{
if(_ThisInit == 0)
_ThisInit = this;
}
CInit::~CInit()
{
}
void CInit::Check(bool bStart)
{
if(bStart)
_ThisInit->Init();
else
_ThisInit->ExInit();
}
bool CInit::Init()
{
return true;
}
bool CInit::ExInit()
{
return true;
}
</code></pre>
<p>This is my cInit class, as you may see this has a static value, because in when the program execetues it will first run the global class instance which will be used like this. It will overload Init() and there the program starts.</p>
<pre><code> CRaPE mycp;
bool CRaPE::Init()
{
return true;
}
bool CRaPE::ExInit()
{
return true;
}
</code></pre>
<p>The program runs from here:</p>
<pre><code>CInit* _Init;
void HandleStartUp()
{
_Init = new CInit();
_Init->Check(true); // So Init gets called
}
void HandleExit()
{
_Init->Check(false); // so ExInit gets called
delete _Init;
}
BOOL WINAPI DllMain(
HINSTANCE hinstDLL,
DWORD fdwReason,
LPVOID lpReserved )
{
switch( fdwReason )
{
case DLL_PROCESS_ATTACH:
{
HANDLE hThread = CreateThread(0,0,(LPTHREAD_START_ROUTINE)HandleStartUp,0,0,0);
if(hThread == 0)
return false;
}
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
HandleExit();
break;
}
return TRUE;
}
</code></pre>
<p>I hope I explained well, thanks for reading.</p>
<p>Gz</p>
|
[] |
[
{
"body": "<p>I am sorry but at the moment it is not really clear what are you trying to achieve with this code. Why do you need such confusing initialization scheme? What is CRaPE class and what it's got to do with the rest of the code?</p>\n\n<p>Also, according to C++ rules identifiers beginning with an underscore and an uppercase letter are reserved in any scope and therefore names like _ThisInit and _Init shouldn't be used.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T05:31:06.983",
"Id": "6431",
"Score": "0",
"body": "I'm trying to code a class on top of DllMain/WinMain, so I don't have to handle it everytime and the program starts inside my CRaPE class ( in this case)\n\nclass CRape : public CInit\n\nThat's how I use it, so CRape::Init() is the start of the program for me."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T06:17:23.880",
"Id": "6432",
"Score": "0",
"body": "The question was what are you trying to achieve, not what are you trying to code. Also CRaPE has no relation to CInit in the code you've posted. Also, if you want to execute CRaPE::Init() as your initialization, you should make new CRaPE object in HandleStartUp fuction instead of CInit."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T21:47:59.500",
"Id": "4295",
"ParentId": "4294",
"Score": "0"
}
},
{
"body": "<p>it's better to explicitly call init and exinit than pass a bool to \"Check\" to say which will one will get called. maybe call them \"Start\" and \"Exit\"</p>\n\n<p>Also, I'd suggest not making them virtual, if you want to be able to extend it...use a protected virtual</p>\n\n<pre><code>public: bool Start();\nprotected: virtual bool StartImpl();\n\n\nvoid CInit::Start()\n{\n StartImpl();\n}\n</code></pre>\n\n<p>This gives you a bit more control over the calling in to your API. (Also a mostly recommended best practice for C++). </p>\n\n<p>It's called \"Non Virtual Interface\" or NVI. It does have pros and cons. But in this case I think it would be quite useful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T19:31:29.750",
"Id": "4315",
"ParentId": "4294",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-21T21:24:11.303",
"Id": "4294",
"Score": "7",
"Tags": [
"c++"
],
"Title": "C++ Class wrapper on top of WinMain/DllMain"
}
|
4294
|
<p>Any idea on how to run application continuously? I tried follow suggestions from <a href="https://stackoverflow.com/questions/593273/run-application-continuously">this link</a>, but to no avail. It might be because of my coding but I don't know how to amend it. Someone suggested that I use Windows Service, but I don't want to use it at this moment because I want to learn basics first like in the above link.</p>
<p><strong>Program.cs</strong></p>
<pre><code> static int exitFlag = 0;
private static int m_intErrCounter = 0;
static int Main(string[] args)
{
int retValue = 0;
while (exitFlag != 0)
{
retValue = CounterApp();
}
//return retValue;
return 0;
}
public static int CounterApp()
{
string machineName = ConfigurationManager.AppSettings["MachineName"];
string categoryName = ConfigurationManager.AppSettings["CategoryName"];
string counterName = ConfigurationManager.AppSettings["CounterName"];
string instanceName = ConfigurationManager.AppSettings["InstanceName"];
PerformanceCounterCategory pcc;
PerformanceCounter[] counters;
m_intErrCounter = 0;
try
{
// Create the appropriate PerformanceCounterCategory object.
if (machineName.Length > 0 && instanceName.Length > 0)
{
pcc = new PerformanceCounterCategory(categoryName, machineName);
counters = pcc.GetCounters(instanceName);
}
else
{
pcc = new PerformanceCounterCategory(categoryName);
counters = pcc.GetCounters();
}
}
catch (Exception)
{
Console.WriteLine("Couldn't found the application");
Console.ReadKey();
return 0;
}
String strBody = String.Empty;
if (counters.Length != 0)
{
for (int objX = 0; objX < counters.Length; objX++)
{
if ((counters[objX].CounterName == counterName) && (counters[objX].RawValue > 0))
{
strBody = "Error occured at " + counters[objX].InstanceName.ToString();
strBody += " : " + counters[objX].CounterName.ToString() + " thrown " + counters[objX].RawValue.ToString() + " times.";
m_intErrCounter++;
exitFlag = 1;
}
}
}
if (m_intErrCounter > 0)
{
SendMail("Notification Email", strBody);
exitFlag = 1;
}
return exitFlag;
}
private static void SendMail(String strSubj, String strBody)
{
MailSettingsSectionGroup mMailSettings = new MailSettingsSectionGroup();
string mMailFrom = mMailSettings.Smtp.From;
string mMailHost = mMailSettings.Smtp.Network.Host;
int mMailPort = mMailSettings.Smtp.Network.Port;
string mMailUserName = mMailSettings.Smtp.Network.UserName;
string mMailPassword = mMailSettings.Smtp.Network.Password;
string to = ConfigurationManager.AppSettings["To"];
MailMessage Message = new MailMessage();
Message.From = new MailAddress(mMailFrom);
Message.To.Add(new MailAddress(to));
Message.Subject = strSubj;
Message.Body = strBody;
SmtpClient client = new SmtpClient(mMailHost, mMailPort);
client.EnableSsl = false;
client.Credentials = new System.Net.NetworkCredential(mMailUserName, mMailPassword);
client.Send(Message);
Console.WriteLine("Success Send Message");
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T02:51:36.697",
"Id": "6427",
"Score": "0",
"body": "\"I tried follow suggestion from this link Run Application Continuously but unsuccessfully...\" what is 'unsuccessful'? Is it exiting early or not doing what you intended?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T03:04:28.433",
"Id": "6428",
"Score": "0",
"body": "not doing what I intended. When I run it just close automatically without error or success. I think the issue is looping, but i don't know how to amend it.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T03:17:36.960",
"Id": "6429",
"Score": "0",
"body": "let me explain bout my application, this application(A) use to count exception error that thrown from another application(B). Once Application B thrown error, application A will send notification email. That one I manage to do it. The problem is I don't know how to run application A continuously; so every time application B thrown error, application A will send the notification."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T09:11:39.863",
"Id": "6438",
"Score": "0",
"body": "Welcome srahifah. Code Review is to review working code only, please refer to the faq for more details. Next time, please post similar questions on [StackOverflow](http://stackoverflow.com/)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T12:32:53.220",
"Id": "6441",
"Score": "0",
"body": "Thanks Steven, actually I did post at StackOverflow..someone suggest me to ask here..huhu..do apologize for the inconvenience..will take note next time.. :)"
}
] |
[
{
"body": "<p>Your loop doesn't work because the initial value for <code>exitFlag</code> variable (which is used as condition for the loop) is zero, and it is only being set to 1 under a special set of circumstances which apparently doesn't happen when you run an application.</p>\n\n<p>If you really want to loop forever and only quit application when it fails your loop, have your function return 1 unless it fails. It should look something like this:</p>\n\n<pre><code>int Main(string[] args)\n{\n while (CounterApp() != 0)\n {\n }\n return 0;\n}\n\npublic static int CounterApp()\n{\n // do some stuff\n\n try\n {\n // do some stuff that might fail\n }\n catch (Exception)\n {\n return 0;\n }\n\n // do some other stuff\n\n return 1;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T06:40:57.010",
"Id": "4300",
"ParentId": "4296",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4300",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T01:59:36.433",
"Id": "4296",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Running an application continuously"
}
|
4296
|
<p>Is there any way to refactor this?</p>
<pre><code>objLeadTimeReportResult =
(from prop in propList
join book in booking on prop.PropertyId equals book.PropertyId into j
from book in j.DefaultIfEmpty()
group book by new { prop.PropertyId, prop.PropertyName } into groupedLeadTime
select new LeadTimeReportResult
{
PropertyId = groupedLeadTime.Key.PropertyId,
PropertyName = groupedLeadTime.Key.PropertyName,
Today = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days == 0) ? 1 : 0),
Days1_2 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 1 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 2) ? 1 : 0),
Days3_6 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 3 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 6) ? 1 : 0),
Days7_10 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 7 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 10) ? 1 : 0),
Days11_15 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 11 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 15) ? 1 : 0),
Days16_30 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 16 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 30) ? 1 : 0),
Days31_45 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 31 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 45) ? 1 : 0),
Days46_60 = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days >= 46 && (item.CheckInDate.Date - item.BookingDate.Date).Days <= 60) ? 1 : 0),
Days60Plus = groupedLeadTime.Sum(item => ((item.CheckInDate.Date - item.BookingDate.Date).Days > 60) ? 1 : 0)
}).ToList();
</code></pre>
<hr>
<p><strong>Additional Information</strong></p>
<p>My senior programmer told me to use some instead of count, he claimed that it would make better performance when using on MSSQL Server.</p>
|
[] |
[
{
"body": "<p>(1). You can create an exntession method to check that item is within the range.</p>\n\n<p>(2). I'd use Count instead of Sum because you just count the number of days in specified interval. It's more natural.</p>\n\n<p>(3). I'd check performance of this query and try to cache result of this join and/or grouping by using some method that requires eager evaluation. ToList() for example. It can help with a lot of traverals of every group in Sum()/Count() methods.</p>\n\n<p>(4). <strong>Note for additional information</strong>. Even if Sum() in Linq To SQL is a lot faster than Count() you still can have MyCount() implemented as Sum() inside. This will allow you to have a good performance as your senior programmer mentioned and hide this \"? 1 : 0\" conidition.</p>\n\n<pre><code> var tempQuery = from prop in propList\n join book in booking on prop.PropertyId equals book.PropertyId into j\n from book in j.DefaultIfEmpty()\n group book by new { prop.PropertyId, prop.PropertyName }.ToList();\n\n objLeadTimeReportResult = from tempVar in tempQuery\n select new LeadTimeReportResult\n {\n PropertyId = tempVar.Key.PropertyId,\n PropertyName = tempVar.Key.PropertyName,\n Today = tempQuery.Count(item => (item.WithinRange()),\n Days1_2 = tempQuery.Count(item => (item.WithinRange(1,2)),\n Days3_6 = tempQuery.Count(item => (item.WithinRange(3,6)),\n Days7_10 = tempQuery.Count(item => (item.WithinRange(7,10)),\n Days11_15 = tempQuery.Count(item => (item.WithinRange(11,15)),\n Days16_30 = tempQuery.Count(item => (item.WithinRange(16,30)),\n Days31_45 = tempQuery.Count(item => (item.WithinRange(31,45)),\n Days46_60 = tempQuery.Count(item => (item.WithinRange(46,60)),\n Days60Plus = tempQuery.Count(item => (item.GreaterThan(60));\n}.ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T09:03:10.767",
"Id": "6436",
"Score": "0",
"body": "My senior programmer told me to use some instead of count, he claimed that it would make better performance when using on MSSQL Server."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T09:06:49.877",
"Id": "6437",
"Score": "2",
"body": "It depends on the implementation of specific LINQ provider and he can be right. I posted my comments with assumption that you use standard LINQ to objects. It would better to add this valuable comment to the first post."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T10:27:13.190",
"Id": "6439",
"Score": "0",
"body": "Actually, i just forgot that SQL don't support using bool so i just need to use tolist, this make my query slower anyway :-P as you said eager evaluation."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T09:01:07.423",
"Id": "4303",
"ParentId": "4302",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4303",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T08:35:09.543",
"Id": "4302",
"Score": "4",
"Tags": [
"c#",
"linq"
],
"Title": "Refactoring after grouped in Linq"
}
|
4302
|
<p>This is from a flex app that is for quizzing. It calls the database for the question and then checks to see if it has been tagged (bookmarked) by a user already. "Question" is a value object and "Tag" is also a value object.</p>
<p>I just wanted to post it to see how it could be better. It works fine, but I feel that since I am new to this, it probably isn't best.</p>
<pre><code>public function getQuestionByNumber($itemNum, $userID) {
$stmt = mysqli_prepare($this->connection,
"SELECT
questions.id, questions.question_number, questions.chapter_id, questions.section_id,
questions.question_txt, questions.answers, questions.feedbacks, questions.correct_answer,
questions.question_type, questions.module, questions.shuffle_answer,
questions.tags
FROM questions where questions.question_number=?");
$this->throwExceptionOnError();
mysqli_stmt_bind_param($stmt, 'i', $itemNum); $this->throwExceptionOnError();
mysqli_stmt_execute($stmt); $this->throwExceptionOnError();
$row = new Question();
mysqli_stmt_bind_result($stmt, $row->id, $row->question_number, $row->chapter_id, $row->section_id,
$row->question_txt, $row->answers, $row->feedbacks, $row->correct_answer,
$row->question_type, $row->module, $row->shuffle_answer, $row->tags);
if (mysqli_stmt_fetch($stmt)) {
} else {
return null;
}
mysqli_stmt_free_result($stmt);
mysqli_stmt_close($stmt);
$stmt2 = mysqli_prepare($this->connection,
"SELECT
id
FROM tagged where user_id =? && question_number=?");
$this->throwExceptionOnError();
mysqli_stmt_bind_param($stmt2, 'ii', $userID, $itemNum);
$this->throwExceptionOnError();
mysqli_stmt_execute($stmt2);
$this->throwExceptionOnError();
$tag = new Tag();
mysqli_stmt_bind_result($stmt2, $tag->id);
if (mysqli_stmt_fetch($stmt2)) {
$row->tagged = $tag->id;
return $row;
} else {
$row->tagged = 0;
return $row;
}
mysqli_stmt_free_result($stmt2);
mysqli_close($this->connection);
}
</code></pre>
|
[] |
[
{
"body": "<p>You could combine your two SQL queries so you don't have to hit the database twice.</p>\n\n<p>The new SQL statement would be something like this:</p>\n\n<pre><code>SELECT\n q.id, q.question_number, q.chapter_id, q.section_id, \n q.question_txt, q.answers, q.feedbacks, q.correct_answer, \n q.question_type, q.module, q.shuffle_answer,\n q.tags, COALESCE(t.id, 0) As tagged\nFROM questions q\n LEFT JOIN tagged t ON q.question_number = t.question_number AND t.user_id = ?\nWHERE q.question_number=?\n</code></pre>\n\n<p>The COALESCE function would return the id from the tagged table if one exists, otherwise it returns 0. This eliminates the need for your final if/else statement and gives you a direct mapping for $row->tagged.</p>\n\n<p>You should also release all result sets and close all connections <strong>before</strong> issuing a return statement. Any code after a return statement will not be executed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T21:46:34.960",
"Id": "6494",
"Score": "0",
"body": "Thanks for the information. I will look into the COALESCE function and learn more about it. Also I didn't know that code after a return statement would not be executed. I really appreciate your time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T23:56:04.843",
"Id": "6502",
"Score": "0",
"body": "The re-write worked great! I learned a lot. On your second point about closing connections, I stuck the free result and close statements in the if() statement before the return. Is this the best way to do it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T01:03:39.713",
"Id": "6505",
"Score": "0",
"body": "It's better, but it still wouldn't close the connection in the case where your query didn't return anything. What I'd do is rewrite the `if/else` altogether. Make the condition `if (!mysqli_stmt_fetch($stmt)) { $row = null }`. This would only happen if you got no results from the SQL. After that, free the result, close the connection, then `return $row`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T23:35:50.190",
"Id": "4318",
"ParentId": "4304",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4318",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T10:21:35.807",
"Id": "4304",
"Score": "3",
"Tags": [
"php",
"mysqli",
"quiz"
],
"Title": "Flex app for quizzing"
}
|
4304
|
<p>I have 3 objects and 3 models. The note, have many tags, and every tags must have one note. So, I have a <code>note_tag_list</code> to store the tags and notes relationship. </p>
<p>The program creates a note, with some tags. </p>
<p>First, I create a note object, and put it into the model. And I get back the object from the model. I create the tag if it doesn't exist. Then, I read back the tag object from the DB. And use all the tags and note to create new <code>note_tag_list</code> object, and put this object to the model.</p>
<p>But I think it seems very complex for my flow. Any ways to do it more elegant? Thank you. </p>
<pre><code>//load all the object
$this->load->library('obj_note');
$this->load->library('obj_tag');
$this->load->library('obj_note_tag_list');
//load all the model
$this->load->model('note_model');
$this->load->model('tag_model');
$this->load->model('note_tag_list_model');
//create a note object
$aNewUserNote =new obj_note();
//set the object information
$user_id =get_current_user_id();
$title =$this->input->post('ui_title_input');
$content_url =$this->input->post('ui_url_input');
$content =$this->input->post('ui_textarea');
$right =RIGHT_NOTE_PUBLIC;
$status =STATUS_NOTE_ACTIVE;
$aNewUserNote->set_user_id($user_id);
$aNewUserNote->set_title($title);
$aNewUserNote->set_content_url($content_url);
$aNewUserNote->set_content($content);
$aNewUserNote->set_right($right);
$aNewUserNote->set_status($status);
$aNewlyCreateNoteId = 0;
if(!$this->note_model->create_note_by_note($aNewUserNote, $aNewlyCreateNoteId))
{
//create success
return;
}
//get back the object from the model
$aNewlyCreateObj = $this->note_model->read_note_by_note_id($aNewlyCreateNoteId);
$aTagNameString = $this->input->post('ui_tag');
$tagsStringArray = $this->convert_tags_string_to_lower_case_string_array($aTagNameString);
$aTagArray = array();
$createNewTagIsSuccess = FALSE;
//Create New Tag
for($i = 0; $i < count($tagsStringArray); $i++)
{
$aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$i]);
if($aTagObj == NULL)
{
$aNewTag =new obj_tag();
$aNewTag->set_create_user_id($user_id);
$aNewTag->set_tag_name($tagsStringArray[$i]);
if(!$this->tag_model->create_tag_by_tag($aNewTag)) //create tag fail
{
$createNewTagIsSuccess = FALSE;
}
}
}
//Read all the tag
for($j = 0; $j < count($tagsStringArray); $j++)
{
$aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$j]);
$aTagArray[count($aTagArray)] = $aTagObj;
}
//Make the note, and tag have relationship
for($k = 0; $k < count($aTagArray); $k++)
{
$theTagObj = $aTagArray[$k];
$aNoteTagList = new obj_note_tag_list();
$aNoteTagList->set_note_id($aNewlyCreateObj[0]->get_id());
$aNoteTagList->set_tag_id($theTagObj[0]->get_id());
$this->note_tag_list_model->create_note_tag_list_by_note_tag_list($aNoteTagList);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T12:21:44.197",
"Id": "6443",
"Score": "0",
"body": "I started to give it a try, but not knowing your objects and return types/values, its pretty much impossible. There are a few things I can spot straight away (like setting a var to another var before you use it, and using `for` where you should use `foreach`), but that's all I'm doing."
}
] |
[
{
"body": "<p><strong>This:</strong></p>\n\n<pre><code>//set the object information\n$user_id =get_current_user_id();\n$title =$this->input->post('ui_title_input');\n$content_url =$this->input->post('ui_url_input');\n$content =$this->input->post('ui_textarea');\n$right =RIGHT_NOTE_PUBLIC;\n$status =STATUS_NOTE_ACTIVE; \n\n$aNewUserNote->set_user_id($user_id);\n$aNewUserNote->set_title($title);\n$aNewUserNote->set_content_url($content_url);\n$aNewUserNote->set_content($content);\n$aNewUserNote->set_right($right);\n$aNewUserNote->set_status($status);\n</code></pre>\n\n<p>Should be rewritten as <strong>this</strong></p>\n\n<pre><code>// create and populate note object\n$note = new obj_note(); \n$note->set_user_id(get_current_user_id());\n$note->set_title($this->input->post('ui_title_input'));\n$note->set_content_url($this->input->post('ui_url_input'));\n$note->set_content($this->input->post('ui_textarea'));\n$note->set_right(RIGHT_NOTE_PUBLIC);\n$note->set_status(STATUS_NOTE_ACTIVE);\n</code></pre>\n\n<p>Other than that, my comment on your question will explain the rest.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T12:24:07.097",
"Id": "4307",
"ParentId": "4306",
"Score": "1"
}
},
{
"body": "<p>You could write a constructor for your object:</p>\n\n<pre><code>//create a note object\n$aNewUserNote =new obj_note(get_current_user_id(),\n $this->input->post('ui_title_input'),\n $this->input->post('ui_url_input'),\n $this->input->post('ui_textarea'),\n STATUS_NOTE_ACTIVE\n );\n</code></pre>\n\n<p>Same thing for your tag:</p>\n\n<pre><code> $aNewTag =new obj_tag($user_id, $tagsStringArray[$i]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T13:50:42.367",
"Id": "4308",
"ParentId": "4306",
"Score": "1"
}
},
{
"body": "<p>Just some idea to improve the code a little bit:</p>\n\n<p>1, I wouldn't count the size of the array in every iteration. So I'd change</p>\n\n<pre><code>for($i = 0; $i < count($tagsStringArray); $i++) { ... }\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$size = count($tagsStringArray)\nfor ($i = 0; $i < $size; $i++) { ... }\n</code></pre>\n\n<p>2, Use guard clauses:</p>\n\n<pre><code>//Create New Tag\nfor($i = 0; $i < count($tagsStringArray); $i++)\n{ \n $aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$i]);\n if($aTagObj != NULL) {\n continue;\n }\n\n $aNewTag = new obj_tag();\n $aNewTag->set_create_user_id($user_id);\n $aNewTag->set_tag_name($tagsStringArray[$i]);\n\n if(!$this->tag_model->create_tag_by_tag($aNewTag)) //create tag fail\n {\n $createNewTagIsSuccess = FALSE; \n }\n\n} \n</code></pre>\n\n<p>3, The following comments could be function names:</p>\n\n<pre><code>//Create New Tag\n//Read all the tag\n//Make the note, and tag have relationship\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>function readAllTags($tagsStringArray) {\n $aTagArray = array(); \n for($j = 0; $j < count($tagsStringArray); $j++)\n { \n $aTagObj = $this->tag_model->read_tag_by_tag_name($tagsStringArray[$j]);\n $aTagArray[count($aTagArray)] = $aTagObj;\n } \n return $aTagArray;\n}\n</code></pre>\n\n<p>It makes the code flatten and easier to read: <a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\" rel=\"nofollow\">http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html</a></p>\n\n<p>4, Use the value of <code>$createNewTagIsSuccess</code> or omit the variable. The code set it to <code>FALSE</code> before the <em>create new tag</em> loop and the loop sometimes set it to <code>FALSE</code> again. It looks little bit weird. (Maybe a bug? No code uses this flag.)</p>\n\n<pre><code>$createNewTagIsSuccess = FALSE;\n</code></pre>\n\n<p>5, I agree with <em>@Loki Astari</em> about constructors. Furthermore, <em>Consider static factory methods instead of constructors</em> (See Martin Fowler: Effective Java Second Edition, Item 1.)</p>\n\n<p>6, AFAIK the index in following is unnecessary:</p>\n\n<pre><code>$aTagArray[count($aTagArray)] = $aTagObj;\n</code></pre>\n\n<p>So use</p>\n\n<pre><code>$aTagArray[] = $aTagObj;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-20T21:01:13.207",
"Id": "6173",
"ParentId": "4306",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T11:29:54.613",
"Id": "4306",
"Score": "3",
"Tags": [
"php",
"codeigniter"
],
"Title": "Relationship between notes and tags"
}
|
4306
|
<p>I'm a hobby programmer and have started 2 month ago with C++. I had some knowledge of Python, and I learned it all through Internet tutorials.</p>
<p>I'm looking for your help, since I don't have a tutor I would like to have a comment about my programming style. I used this small "library" to create the Snake4D game (see bottom of question for further information). </p>
<p>Here is a little program that handles mathematical vectors, 4D and 3D. Specifically, I ask you to find any improvements in the code's readability and in the algorithms.</p>
<p>Here is the "vec.h" file:</p>
<pre><code>class V4{
private:
double coords[4];
public:
V4();
V4(double x, double y, double z, double w);
~V4();
void set_cooord(int i, double x); //set_coord (index of coord i, value x)
double module();
double operator[](unsigned int i);
void operator =(V4);
V4 operator +(const V4);
V4 operator -(const V4);
V4 operator *(double k); //moltiplication of vector by a scalar k
double dot4(V4); //the dot product
V4 cross(V4 u, V4 v,V4 w); //the cross product
};
</code></pre>
<p>Here is the "vec.cpp" file:</p>
<pre><code>/****************
V4 class
*****************/
V4::V4(){
//set all coords to 0. if it's called without specific coord
coords[0] = 0.;
coords[1] = 0.;
coords[2] = 0.;
coords[3] = 0.;
}
V4::V4(double x, double y, double z, double w){
coords[0] = x;
coords[1] = y;
coords[2] = z;
coords[3] = w;
}
V4::~V4(){}//nothing to destroy?
void V4::set_cooord(int i, double x){ //i index, x value
coords[i] = x;
}
double V4::module(){
double sum = 0;
for(int i= 0; i<4; i++){
sum += coords[i]*coords[i];
}
return sqrt(sum);
}
double V4::operator[](unsigned int i){
//if(i > 4){return;} //list index out of range ? how to throw give a compile error?
return coords[i];
}
void V4::operator =(V4 v1){
for(int i= 0; i<4; i++){
coords[i] = v1[i];
}
}
V4 V4::operator+(V4 v1) {
double c[4]; // array of 4 double which will be transfered to the returned vector
for(int i= 0; i<4; i++){
c[i] = coords[i] + v1[i];
}
return V4(c[0],c[1],c[2],c[3]);
}
V4 V4::operator-( V4 v1) {
double c[4];
for(int i= 0; i<4; i++){
c[i] = coords[i] - v1[i];
}
return V4(c[0],c[1],c[2],c[3]);
}
V4 V4::operator*(double k){
double c[4];
for(int i= 0; i<4; i++){
c[i] = coords[i] * k;
}
return V4(c[0],c[1],c[2],c[3]);
}
double V4::dot4(V4 v1){
double sum = 0;
for(int i= 0; i<4; i++){
sum += coords[i]*v1[i];
}
return sum;
}
// requires three external vector and doesn't take any coords of the actual vector
//intended use:
// V4 v1(x,y,z,w), v2(x,y,z,w), v3(x,y,z,w), result, op;
// result = op.cross(v1,v2,v3)
V4 V4::cross(V4 u, V4 v, V4 w){
//source Steve Hollasch master thesis
//partial product
double A = (v[0]*w[1])-(v[1]*w[0]);
double B = (v[0]*w[2])-(v[2]*w[0]);
double C = (v[0]*w[3])-(v[3]*w[0]);
double D = (v[1]*w[1])-(v[2]*w[1]);
double E = (v[1]*w[3])-(v[3]*w[1]);
double F = (v[2]*w[3])-(v[3]*w[2]);
double x = (u[1]*F)-(u[2]*E)+(u[3]*D);
double y = -(u[0]*F)+(u[2]*C)-(u[3]*B);
double z = (u[0]*E)-(u[1]*C)+(u[3]*A);
double wc = -(u[0]*D)+(u[1]*B)-(u[2]*A); //defined as wc to not conflic with w vector
return V4(x,y,z,wc);
}
</code></pre>
<p><a href="http://www.mediafire.com/?9p3hj4z11uj1307" rel="nofollow">Here are the source (.h and .cpp) file</a>.</p>
<p>I already see some improvements: </p>
<ol>
<li>I use the vectors as <code>public</code> members, because if they are <code>private</code>, I cannot get access to all the really comfortable functions they offer.</li>
<li>Instead of giving vertex hand by hand for the generation of the hypercube, there should be an algorithm that does this.</li>
<li>It could be used a general purpose class <code>V</code> containing the basic methods and having a variable <code>int</code> dimension then specialize the <code>V3</code> and <code>V4</code> inheriting the class <code>V</code>. </li>
</ol>
<p>PS: <a href="http://www.youtube.com/watch?v=NaeqUp3jbls" rel="nofollow">I've made a little clip that shows the Snake4D game written in C++, Qt and OpenGL</a>. </p>
|
[] |
[
{
"body": "<p>Very good.</p>\n\n<p>Couple of points:</p>\n\n<p>I would remove the set() method, and allow its work to be done by the operator[]. To do this you need return the value you want by reference.</p>\n\n<pre><code>double & operator[](unsigned int i);\n // ^^^ Return double by reference.\n</code></pre>\n\n<p>This allows you to do;</p>\n\n<pre><code>V4 x;\nx[1] = 12;\n</code></pre>\n\n<p>When you pass objects as parameters it is usally best to pass by const reference. This means that no copy will be made and the original object can not be modified by the method using it:</p>\n\n<pre><code>V4 operator +(V4 const & rhs);\n ^^^\n</code></pre>\n\n<p>Note I always put the const on the right of the type (rather than the left). Admittedly this is a religious war so choose a side and stick to it (there is only one minor side instance were it makes difference). But I find it makes reading the type name easier (as types are read from right to left with const always binding to the left (except where it is the leftmost lexeme in the type then it binds right).</p>\n\n<p>Methods that do not change the state of the object should be declared const:</p>\n\n<pre><code>V4 operator -(V4 const & rhs) const;\n // ^^^^^ indicates that calling this method will not\n // change the state of the object.\n</code></pre>\n\n<p>Note: This means you should provide two versions of operator[] a normal one that allows mutation and a const version that can be used in contexts where it is read only.</p>\n\n<pre><code>double& operator[](unsigned int i) { return coord[i];}\ndouble const& operator[](unsigned int i) const { return coord[i];}\n</code></pre>\n\n<p>Note: array access is not validated against the array bounds. Normally you don't check as we do not want to impose an extra burden on the responsible just because there are bad developers. But it is traditional to add at() method that does the same work as operator[] but also validates the bounds of the array access.</p>\n\n<pre><code>double& at(unsigned int i) { if (i > 3) {throw std::range_error(\"BLA\");} return coord[i];}\ndouble const& at(unsigned int i) const { if (i > 3) {throw std::range_error(\"BLA\");} return coord[i];}\n</code></pre>\n\n<p>Implementing operator + - * / is easily done if you implement them in terms of += -= *= /=. This also provides the user of your object the opportunity to use your class more efficiently when a new object is not required (though this should be a secondary though).</p>\n\n<pre><code>V4 operator *(V4 const & rhs) const;\nV4 operator *=(V4 const & rhs); // This does change the sate of the object\n\nV4 V4::operator*(V4 const& rhs) const { V4 result(*this); result *= rhs; return result;}\n</code></pre>\n\n<p>Using a for loop is easy. But sometimes it can be simpler to use the standard algorithms to accomplish simple tasks over short containers:</p>\n\n<pre><code>double sum = 0;\nfor(int i= 0; i<4; i++){\n sum += coords[i]*coords[i];\n}\n</code></pre>\n\n<p>This can be replaced with:</p>\n\n<pre><code>sum = std::accumulate(coords, coords + 4, 0);\n</code></pre>\n\n<p>You can find good documentation here: <a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\">http://www.sgi.com/tech/stl/table_of_contents.html</a> (look for section: <code>5 Algorithms</code>) </p>\n\n<p>In the moto of not doing extra work. Don't write methods that do nothing:</p>\n\n<pre><code>V4::~V4(){}//nothing to destroy?\n</code></pre>\n\n<p>Remove this. The class automatically provides a desttructor that will correctly destroy nothing.</p>\n\n<p>I actually like using void as the return type of assignment (I think it has no down side). But traditionally assignment should return a reference to self. This then allows the object to be part of an assignment chain.</p>\n\n<pre><code>V4 a;\nV4 b;\nV4 c;\n\na = b = c; // assignment chaining.\n// It also allows you to pass the object as a parameter to a mehtod:\n\ndoStuff( a = b); // Assign a to b. Then call doStuff using a.\n</code></pre>\n\n<p>It is also a good idea to define the streaming operators for most classes. This allowsd you to serialize and de-serialize the class to a stream (file/string etc).</p>\n\n<p>So now the class looks like this.</p>\n\n<pre><code>class V4\n{\n double coords[4];\n public:\n V4();\n V4(double x, double y, double z, double w);\n\n double module() const;\n double& operator[](unsigned int i) {return coords[i];}\n double const& operator[](unsigned int i) const {return coords[i];}\n\n V4& operator = (V4 const& rhs);\n V4& operator +=(V4 const& rhs);\n V4& operator -=(V4 const& rhs);\n V4& operator *=(double k); //moltiplication of vector by a scalar k\n\n V4 operator +(V4 const& rhs) const {V4 result(*this); result += rhs; return result;}\n V4 operator -(V4 const& rhs) const {V4 result(*this); result -= rhs; return result;}\n V4 operator *(double rhs) const {V4 result(*this); result *= rhs; return result;}\n\n double dot4(V4 const& rhs) const; //the dot product\n\n V4 cross(V4 const& u, V4 const& v,V4 const& w) const; //the cross product\n};\n</code></pre>\n\n<p>Then rest of the interesting ones:</p>\n\n<pre><code>double V4::module() const\n{\n return std::sqrt(std::accumulate(coords, coords + 4, 0.0);\n}\n\nV4& V4::operator +=(V4 const& rhs)\n{\n std::transform(coord, coord+4, rhs.coord, coord, std::plus);\n return *this;\n}\nV4& V4::operator -=(V4 const& rhs)\n{\n std::transform(coord, coord+4, rhs.coord, coord, std::minus);\n return *this;\n}\nV4& V4::operator *=(double k)\n{\n std::transform(coord, coord+4, coord, std::bind1st(std::multiplies, k));\n return *this;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T19:50:16.780",
"Id": "6492",
"Score": "0",
"body": "thank you, this was really what I was looking for, I really have to thank you because I was really confused about how to use const and the references!Thank you and have a nice day!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T06:23:10.063",
"Id": "6510",
"Score": "0",
"body": "No problem. Pleased I could help."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T13:14:31.697",
"Id": "4333",
"ParentId": "4311",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "4333",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T17:34:23.390",
"Id": "4311",
"Score": "4",
"Tags": [
"c++",
"beginner",
"computational-geometry"
],
"Title": "Small 3D and 4D vector utilities"
}
|
4311
|
<p>I've got this working JavaScript (example is [here][1]), which should work the same as on the Stack Exchange network.</p>
<p>How can I simplify it a bit? </p>
<pre><code>function yellow() {
return 'rgb(255, 255, 0)';
}
$(function() {
$(".post-upvote").click(function() {
// ajax(url + "upvote/" + $(this).attr('data-postid'), false, false);
if ($(this).parent().children('.post-downvote').css('background-color') == yellow()) { // user upvoted so let's delete upvote
$(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) + parseInt(1));
}
$(this).parent().children('.post-downvote').css('background-color', 'white');
if ($(this).css('background-color') == yellow()) { // if it's yellow, user is canceling his downvote
$(this).css('background-color', 'white');
$(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) - parseInt(1));
}
else {
$(this).css('background-color', 'yellow');
$(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) + parseInt(1));
}
});
$(".post-downvote").click(function() {
// ajax(url + "downvote/" + $(this).attr('data-postid'), false, false);
if ($(this).parent().children('.post-upvote').css('background-color') == yellow()) { // user upvoted so let's delete upvote
$(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) - parseInt(1));
}
$(this).parent().children('.post-upvote').css('background-color', 'white');
if ($(this).css('background-color') == yellow()) { // if it's yellow, user is canceling his downvote
$(this).css('background-color', 'white');
$(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) + parseInt(1));
}
else {
$(this).css('background-color', 'yellow');
$(this).parent().children('.post-votes').text(parseInt($(this).parent().children('.post-votes').text()) - parseInt(1));
}
});
});
</code></pre>
|
[] |
[
{
"body": "<p>Get rid of antipatterns like</p>\n\n<pre><code>parseInt(1)\n</code></pre>\n\n<p>Just say <code>1</code> instead.</p>\n\n<p>Factor out common code like</p>\n\n<pre><code>$(this).parent().children('.post-votes')\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$(this).css('background-color')\n</code></pre>\n\n<p>into variables.</p>\n\n<p>Combine the two handlers thus</p>\n\n<pre><code>function vote(isUpvote) {\n var control = $(this);\n var otherControl = control.parent().children(\n isUpvote ? \".post-downvote\" : \".post-upvote\");\n var postVotes = control.parent().children(\".post-votes\");\n var ajaxHandler = isUpvote ? \"upvote/\" : \"downvote/\";\n\n // ajax(url + ajaxHandler + control.attr('data-postid'), false, false);\n\n // user voted so let's delete the other control\n if (otherControl.css(\"background-color\") == yellow()) {\n postVotes.text(+(postVotes.text()) + 1);\n }\n control.parent().children(otherId).css(\"background-color\", \"white\");\n\n // if it's yellow, user is cancelling their vote\n if (control.css(\"background-color\") == yellow()) {\n control.css(\"background-color\", \"white\");\n postVotes.text(+(postVotes.text()) - 1);\n } else {\n control.css(\"background-color\", \"yellow\");\n postVotes.text(+(postVotes.text()) + 1);\n }\n}\n\n$(\".post-upvote\" ).click(function() { vote.call(this, true); });\n$(\".post-downvote\").click(function() { vote.call(this, false); });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T18:48:07.980",
"Id": "6444",
"Score": "0",
"body": "I wasn't able to do `something + 1` because it made `12` from `1`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T18:56:03.973",
"Id": "6445",
"Score": "2",
"body": "@genesis, That happens when `something` is not a number because then `+` does string concatenation instead of addition. `parseInt(something, 10) + 1` is fine as is `(+something) + 1` because they both cause the `something` to be coerced to a number. The `parseInt(1)` does not since `1` is already a number."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T19:41:04.273",
"Id": "6446",
"Score": "0",
"body": "ok so I can \"convert\" string to number with (+var) + 1 ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T20:30:02.027",
"Id": "6447",
"Score": "0",
"body": "@genesis, Yes, assuming \"var\" is the name of a variable instead of the keyword. Try running `+\"42\" + 1 === 43` in the [squarefree shell](http://squarefree.com/shell/shell.html)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T21:17:06.190",
"Id": "6450",
"Score": "0",
"body": "and about your last snippet, I am not 100% how should I include it effectively. Could you add some more please?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T11:43:06.607",
"Id": "6532",
"Score": "0",
"body": "I still didn't get those two last lines. Why do you pass \"this\" as a parameter, and not true and in that second false?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T15:43:08.953",
"Id": "6537",
"Score": "0",
"body": "@genesis, see the docs on [`call`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call): Calls a function with a given this value and arguments provided individually."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T18:00:46.763",
"Id": "4313",
"ParentId": "4312",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4313",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T17:40:47.387",
"Id": "4312",
"Score": "4",
"Tags": [
"javascript",
"jquery"
],
"Title": "Simplifying up/down vote code"
}
|
4312
|
<p>i'm currently writing a generic data access object for the persistent entities I have to handle in my JavaEE application. What this codeReview is about is a findByExample method that is used to find database entries on the basis of a given example object. This may already be implemented for openJPA but I'm bound to openJPA snapshot 1.2.x (old) and I couldn't find it anywhere in the manual. please tell me about the pitfalls, improvements and bad practices you see in my code. I'm willing to learn.</p>
<p>Here we go</p>
<p>Using it as following</p>
<pre class="lang-java prettyprint-override"><code>MyEntity me = new MyEntity();
me.setName("john")
me.setAge(18);
entityAccess.findByExample(me);
</code></pre>
<p>will create the following JPQL query using only the parameters that were set</p>
<pre><code>"SELECT x FROM MyEntity x WHERE x.name = :name AND x.age = :age"
</code></pre>
<p>Then it will set the parameters and exequte the query. </p>
<p>This is how I implemented it.</p>
<p>The two public methods (BasicEntity is a mappedSuperClass)</p>
<pre><code>public <T extends BasicEntity> List<T> findAllByExample(T entity) {
return getQueryFromExample(entity).getResultList();
}
public <T extends BasicEntity> T findByExample(T entity) throws NoResultException, NonUniqueResultException {
return (T) getQueryFromExample(entity).getSingleResult();
}
</code></pre>
<p>The method thats creates the <code>Query</code> and sets the parameters. (em is the jpa entityManager)</p>
<pre><code>private <T extends BasicEntity> Query getQueryFromExample(T entity) {
HashMap<String, Object> fieldNameValuePairs = getFieldNameValuePairs(entity.getClass(), entity);
/* build query string */
StringBuilder queryString = new StringBuilder();
queryString.append("SELECT x FROM ");
queryString.append(entity.getClass().getSimpleName());
queryString.append(" x WHERE ");
for (Iterator<String> iterator = fieldNameValuePairs.keySet().iterator(); iterator.hasNext();) {
String fieldName = iterator.next();
queryString.append("x." + fieldName + " = :" + fieldName);
if (iterator.hasNext()) {
queryString.append(" AND ");
}
}
/* create query and set parameters */
Query q = em.createQuery(queryString.toString());
for (Entry<String, Object> entry : fieldNameValuePairs.entrySet()) {
String fieldName = entry.getKey();
Object fieldValue = entry.getValue();
q.setParameter(fieldName, fieldValue);
}
return q;
}
</code></pre>
<p>The following method puts relevant and non null fields into a HashMap. It walks up the type hierarchy with a recursion. <code>Object.getClass().getSuperClass</code> returns <code>null</code>.</p>
<pre><code>private HashMap<String, Object> getFieldNameValuePairs(Class<?> type, Object instance) {
if (type != null) {
HashMap<String, Object> fieldNameValuePairs = new HashMap<String, Object>();
for (Field field : type.getDeclaredFields()) {
/* we only care for persitent fields */
if (isPersistentField(field)) {
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = null;
try {
fieldValue = field.get(instance);
} catch (Exception e) {
throw new RuntimeException(
"Error reflecting fields while building queryString for findByExample. Cannot read "
+ instance.getClass().getSimpleName() + "." + fieldName, e);
}
/* ignore unset fields */
if (!(fieldValue == null || fieldValue.equals(""))) {
fieldNameValuePairs.put(fieldName, fieldValue);
System.out.println(fieldName + " = " + fieldValue.toString());
}
}
}
/* recursive step up the type hierarchy */
fieldNameValuePairs.putAll(getFieldNameValuePairs(type.getSuperclass(), instance));
return fieldNameValuePairs;
} else {
return new HashMap<String, Object>();
}
}
</code></pre>
<p>the following section of code determines whether a field is relevant (since i don't want for example <code>serialVersionUID</code> in my JPQL query)
I chose to use the fields annotations to decide, because I thought this makes the persisted fields unique.</p>
<pre><code>private static final List<Class<? extends Annotation>> persistenceAnnotations = new ArrayList<Class<? extends Annotation>>();
static {
persistenceAnnotations.add(Id.class);
persistenceAnnotations.add(Column.class);
persistenceAnnotations.add(JoinColumn.class);
persistenceAnnotations.add(OneToOne.class);
persistenceAnnotations.add(ManyToOne.class);
persistenceAnnotations.add(OneToMany.class);
persistenceAnnotations.add(ManyToMany.class);
persistenceAnnotations.add(JoinColumns.class);
persistenceAnnotations.add(Basic.class);
persistenceAnnotations.add(Lob.class);
}
private boolean isPersistentField(Field field) {
for (Annotation annotation : field.getAnnotations()) {
if (persistenceAnnotations.contains(annotation.annotationType())) {
return true;
}
}
return false;
}
</code></pre>
<p><strong>Aug29 - REFACTORED VERSION</strong></p>
<pre><code>private <T extends BasicEntity> Query getQueryFromExample(T entity) {
HashMap<String, Object> fieldNameValuePairs = getFieldNameValuePairs(entity.getClass(), entity);
/* build query string */
String queryString = String.format("SELECT x FROM %s WHERE %s", entity.getClass().getSimpleName(),
join(asJpqlConditions(fieldNameValuePairs.keySet(), "x"), " AND "));
/* create query and set parameters */
Query q = em.createQuery(queryString.toString());
for (Entry<String, Object> entry : fieldNameValuePairs.entrySet()) {
q.setParameter(entry.getKey(), entry.getValue());
}
return q;
}
private List<String> asJpqlConditions(Collection<String> fieldNames, String identifier) {
List<String> conditions = new ArrayList<String>();
for (String fieldName : fieldNames) {
conditions.add(String.format("%1$.%2$s = :%2$s", identifier, fieldName));
}
return conditions;
}
private String join(List<String> parts, String glue) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String part : parts) {
if (!first) {
sb.append(glue);
}
sb.append(part);
first = false;
}
return sb.toString();
}
private HashMap<String, Object> getFieldNameValuePairs(Class<?> type, Object instance) {
/* return empty HashMap in last recursion step (type is null) */
if (type == null) {
return new HashMap<String, Object>();
}
/* recursive call to fill the HashMap with the fields from supertypes */
HashMap<String, Object> fieldNameValuePairs = getFieldNameValuePairs(type.getSuperclass(), instance);
for (Field field : type.getDeclaredFields()) {
/* we only care for persitent fields */
if (!isPersistentField(field)) {
continue;
}
boolean wasAccessible = field.isAccessible();
field.setAccessible(true);
String fieldName = field.getName();
Object fieldValue = null;
try {
fieldValue = field.get(instance);
} catch (Exception e) {
throw new RuntimeException("Error reflecting fields while building queryString for findByExample. Cannot read "
+ instance.getClass().getSimpleName() + "." + fieldName, e);
}
field.setAccessible(wasAccessible);
/* ignore unset fields */
if (!(fieldValue == null || fieldValue.equals(""))) {
fieldNameValuePairs.put(fieldName, fieldValue);
}
}
return fieldNameValuePairs;
}
private boolean isPersistentField(Field field) {
for (Annotation annotation : field.getAnnotations()) {
if (annotation.annotationType().equals(PersistentField.class)) { //added custom marker annotation
return true;
}
}
return false;
}
</code></pre>
|
[] |
[
{
"body": "<p>I found the code an interesting read and quite a pleasant one at that. Nothing really critical jumped out thought there are some precondition checking, logging, style and other violations in respect to what I might do. </p>\n\n<p>1) I like to abstract trivial things away. For example, when you create the query string I would try to emphasize the structure of the query string instead of the noise caused by it's building. This might be done by creating method(s) that create the where condition of the query: </p>\n\n<pre><code>import static java.lang.String.format; \n\n... \n\nString queryString = format(\"SELECT x FROM %s WHERE %s\",\n entity.getClass().getSimpleName(),\n join(asConditions(fieldNameValuePairs.keySet()), \" AND \"));\n\n... \n\nprivate Collection<String> asConditions(Collection<String> fieldNames) {\n List<String> conditions = new ArrayList<String>();\n for(String fieldName : fieldNames) {\n conditions.add(format(\"x.%1$s = :%1$s\", fieldName)); // 1$ reuses the 1st argument\n }\n return conditions;\n}\n\nprivate String join(Collection<String> parts, String glue) {\n StringBuilder sb = new StringBuilder();\n boolean first = true;\n for(String part : parts) {\n if(!first) {\n sb.append(glue);\n }\n sb.append(part);\n first = false;\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>2) I find it that the assigments are not needed here as they create new lines of codes without really increasing the readability of the whole. </p>\n\n<pre><code>for (Entry<String, Object> entry : fieldNameValuePairs.entrySet()) {\n String fieldName = entry.getKey();\n Object fieldValue = entry.getValue();\n q.setParameter(fieldName, fieldValue);\n}\n\n=>\n\nfor (Entry<String, Object> entry : fieldNameValuePairs.entrySet()) {\n q.setParameter(entry.getKey(), entry.getValue());\n}\n</code></pre>\n\n<p>3) In the second method, you have created a long if-block in cas <code>type</code> is null. I would rather have failed early so the preconditions of the method is shown in the beginning. Also I feel that if the precondition is not met then some logging is needed or better yet an exception would be thrown because I would think that the missing type is a programmer error of some sorts and should not be let slip by. </p>\n\n<p>If the null check is because of the recursion, you might want to create a comment as the recursion step is a bit far removed from the branching statement. Better yet, put the recursion in one method and the logic for the recursion step in another. </p>\n\n<p>4) After noticing that the second method is private I noticed that there is no precondition checking in the first method. If the preconditions would be checked there, you can be a bit more relaxed with the checking in private methods although private methods may end up being reused by another developer at some point.</p>\n\n<p>5) Again when branching on <code>isPersistentField()</code> you create a large block instead of exiting quickly. If you rather use this style then I would suggest you put the content of the block in a separate method. This way you can emphasize the logic of selection and keep methods nice a small. </p>\n\n<p>Edit: Current impl: </p>\n\n<pre><code>for (Field field : type.getDeclaredFields()) {\n if (isPersistentField(field)) {\n field.setAccessible(true);\n String fieldName = field.getName();\n Object fieldValue = null;\n try {\n fieldValue = field.get(instance);\n } catch (Exception e) {\n throw new RuntimeException(\"foo\", e);\n }\n\n if (!(fieldValue == null || fieldValue.equals(\"\"))) {\n fieldNameValuePairs.put(fieldName, fieldValue);\n }\n }\n}\n</code></pre>\n\n<p>Alternative 1: </p>\n\n<pre><code>for (Field field : type.getDeclaredFields()) {\n if (!isPersistentField(field)) {\n continue;\n }\n field.setAccessible(true);\n String fieldName = field.getName();\n Object fieldValue = null;\n try {\n fieldValue = field.get(instance);\n } catch (Exception e) {\n throw new RuntimeException(\"foo\", e);\n }\n\n if (!(fieldValue == null || fieldValue.equals(\"\"))) {\n fieldNameValuePairs.put(fieldName, fieldValue);\n }\n}\n</code></pre>\n\n<p>Alternative 2: </p>\n\n<pre><code>for (Field field : type.getDeclaredFields()) {\n if (isPersistentField(field)) {\n addNameValuePair(field, instance, fieldNameValuePairs);\n }\n}\n\n...\n\nprivate void addNameValuePair(Field field, Object instance, Map<String, Object> fieldNameValuePairs) {\n Object fieldValue = valueOf(field, instance);\n if (!(fieldValue == null || fieldValue.equals(\"\"))) {\n fieldNameValuePairs.put(field.getName(), fieldValue);\n }\n}\n\nprivate Object valueOf(Field field, Object instance) {\n boolean wasAccessible = field.isAccessible();\n try {\n field.setAccessible(true);\n return field.get(instance);\n } catch (Exception e) {\n throw new RuntimeException(\"foo\", e);\n } finally { \n field.setAccessible(wasAccessible);\n } \n}\n</code></pre>\n\n<p>6) Set up a logger instead of System.out -> That way you can keep the debug level logs for later use if they needed. </p>\n\n<p>7) JPA does not require that each field is annotated. This might cause some trouble on the long run. You could check how OpenJPA deals with this. They have their own FieldMetaData implementation that has a method <code>setManagement</code> that is used to signal if the field is persistent, transactional or not managed. This value is later used in ClassMetaData to return only those field that are managed. I actually got bored before finding the right place where <code>setManagement</code> is called but that it shouldn't be too hard to google. </p>\n\n<p>8) I assume you have made an intentional decision not to think about the ability to use annotated getters instead of fields. </p>\n\n<p><em>Disclaimer</em> None of the code is tested</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T12:02:26.620",
"Id": "6467",
"Score": "0",
"body": "hi, I replied in a seperate answer because of too much characters. I'd like to also vote up but I can't yet (<15rep)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T08:09:50.830",
"Id": "4323",
"ParentId": "4314",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4323",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-22T19:16:38.180",
"Id": "4314",
"Score": "3",
"Tags": [
"java",
"reflection",
"lookup"
],
"Title": "Method to lookup persistent entities by an example object"
}
|
4314
|
<p>This is my first script in object-oriented JavaScript (jQuery 1.5.2). Its purpose is to simply validate a form (nothing fancy at the moment just checks if any value is present on required fields) and if validation is passed it submits the form via Ajax and alerts the server's response.</p>
<p>It would be great if more experienced programmers could review this and tell me what could be improved and what's dead wrong.</p>
<p>Here is the full working page:</p>
<pre><code><script type="text/javascript">
var formObj = {
validate : function(theForm, required) {
var toValidate = required.split(',');
for (i in toValidate) {
var toValidateField = $('*[name*='+$.trim(toValidate[i])+']', theForm);
var valueLength = toValidateField.val().length;
if (valueLength === 0) {
toValidateField.addClass('invalid');
formObj.inputListener(toValidateField);
}
}
if ($('.invalid').length === 0) {
return 'valid';
} else {
return 'invalid';
}
},
inputListener : function(theField) {
theField.keyup(function() {
if ($(this).val().length > 0) {
theField.removeClass('invalid');
} else {
theField.addClass('invalid');
}
});
},
ajaxSubmit : function(formToSubmit) {
$.ajax({
url: formToSubmit.attr('action'),
type: formToSubmit.attr('method'),
data: formToSubmit.serialize(),
success: function(output) {
//return output;
alert(output);
},
error: function() {
alert('Something went wrong!');
}
});
}
} // end formObj
</script>
<script type="text/javascript">
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var thisForm = $(this);
// validate form
validate = formObj.validate(thisForm, 'username, message');
// if valid submit via ajax
if (validate === 'valid') {
formObj.ajaxSubmit(thisForm);
}
});
});
</script>
<style type="text/css">
.invalid { border: 2px solid red; }
</style>
<form action="script.php" method="post">
<label>Choose Username</label><br />
<input type="text" name="username" /><br />
<label>Choose Password</label><br />
<input type="text" name="password" /><br />
<label>Message to Admin</label><br />
<textarea name="message"></textarea><br />
<button type="submit">Submit</button>
</form>
</code></pre>
<p>Contents of script.php</p>
<pre><code><?php
while (list($key, $value) = each($_POST)) {
echo $_POST[$key].' - ';
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>Its only a small Quibble with your code but I find the naming of <code>formObj</code> a little odd. For me I see this as a <code>FormValidator</code> or <code>FormExtender</code> or some such.</p>\n\n<p>Another point would be the <code>for(i in ....)</code> should be <code>for(var i in ...)</code> it will run either way and I believe it is just a matter of coding style.</p>\n\n<p>Also you have functions like:</p>\n\n<pre><code>validate: function(theForm, required({....\n</code></pre>\n\n<p>I think it helps debugging if you do this instead:</p>\n\n<pre><code>validate: function FormValidate(....\n</code></pre>\n\n<p>It has the disadvantage of polluting the namespace but makes debugging easier as the function is now not anonymous.</p>\n\n<p>If you were making this a class to instantiate you would write it like so:</p>\n\n<pre><code>var FormValidator = function(theForm)\n{\n this.formElement = theForm;\n return this;\n}\n\nFormValidator.prototype = {\n\n validate : function(theForm, required) {\n //...\n },\n inputListener : function(theField) {\n //...\n },\n ajaxSubmit : function(formToSubmit) {\n //...\n }\n\n};\n\nvar mainForm = new FormValidator(document.forms[0]);\n</code></pre>\n\n<p>If you were doing a Singleton pattern something like:</p>\n\n<pre><code>var FormValidator = function()\n{\n return this;\n}\n\nfunction GetFormValidatorInstance()\n{\n return window.__formValidatorInstance || new FormValidator();\n}\n</code></pre>\n\n<p>These last two are probably overkill if you just want a simple Component. A more in depth example of the above can be found at <a href=\"https://codereview.stackexchange.com/questions/1658/javascript-code-class-structure\">https://codereview.stackexchange.com/questions/1658/javascript-code-class-structure</a> </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T12:38:39.040",
"Id": "6470",
"Score": "0",
"body": "+1 the definition, implementation, and instantiation being separated makes my C# dev toes tingle. I think all javascript should be written with the 3 all separated"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T12:47:59.170",
"Id": "6472",
"Score": "0",
"body": "Ugh, the definition & implementation are the same thing in JavaScript. We only have objects."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T13:16:18.087",
"Id": "6474",
"Score": "1",
"body": "Naming conventions like `FormValidator$validate` are going to become overkill and a pain. Those get out of control quickly. It also only pollutes the namespace in legacy versions of IE. Also please don't recommend Singletons like that. Just use object literals."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T00:07:36.837",
"Id": "6503",
"Score": "0",
"body": "@Raynos I do believe I did point out that naming like that pollutes the namespace but I know that it makes debugging much easier. That was the point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T09:18:34.360",
"Id": "6524",
"Score": "0",
"body": "@JamesKhoury polluting the namespace only occurs in legacy versions of IE so that's no problem. It's also no problem to have duplicate function names. The issue is that its verbose and becomes annoying. I was complaining about adding `$validate` on the end as it reminds me of the verbose Id's ASP.NET generates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T12:41:17.290",
"Id": "6534",
"Score": "1",
"body": "@Raynos I was referring to the prototype as the definition, and using the word implementation in the sense of an object inheriting another implements it. I realize prototypes are not the same thing as inheritance, but it's the closest you get with javascript."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T00:00:37.700",
"Id": "6554",
"Score": "1",
"body": "@Raynos I've changed the naming. I wasn't suggesting a naming convention as much as I was suggesting that it be named. seeing \"Anonymous function\" a lot in a call stack really doesn't help."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T00:04:35.260",
"Id": "6556",
"Score": "0",
"body": "@JamesKhoury +1 for that. Anonymous functions in stacks are a nightmare."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T05:02:03.187",
"Id": "4322",
"ParentId": "4321",
"Score": "1"
}
},
{
"body": "<h2>The code:</h2>\n\n<p><a href=\"http://jsfiddle.net/PZN2E/37/\" rel=\"nofollow\">http://jsfiddle.net/PZN2E/37/</a></p>\n\n<h2>The HTML:</h2>\n\n<pre><code><form action=\"script.php\" method=\"post\">\n <label>Choose Username</label><br />\n <input type=\"text\" name=\"username\" id=\"username\" /><br />\n <label>Choose Password</label><br />\n <input type=\"text\" name=\"password\" id=\"password\" /><br />\n <label>Message to Admin</label><br />\n <textarea name=\"message\" id=\"message\"></textarea><br />\n <button type=\"submit\">Submit</button>\n</form>\n</code></pre>\n\n<p>I've added <code>\"id\"</code> fields for all your inputs. This makes it easier to target them using JavaScript</p>\n\n<h2>The JS</h2>\n\n<pre><code>(function($) {\n var inputListener = function _inputListener(field) {\n if (!field[0]._bound) {\n field[0]._bound = true;\n field.keyup(function _listener() {\n if (field.val().length > 0) {\n field.removeClass('invalid');\n } else {\n field.addClass('invalid');\n }\n }); \n }\n };\n\n $.fn.validate = function _validate(required) {\n var valid = true;\n for (var i = 0, ii = required.length; i < ii; i++) {\n var field = $(\"#\" + required[i])\n if (field.val().length === 0) {\n field.addClass('invalid');\n valid = false;\n inputListener(field);\n }\n }\n return valid; \n };\n})(jQuery);\n\njQuery(function($) {\n $('form').submit(function(e) {\n e.preventDefault();\n var $this = $(this);\n\n // if valid submit via ajax\n if ($this.validate(['username', 'message'])) {\n $.ajax({\n url: $this.attr('action'),\n type: $this.attr('method'),\n data: $this.serialize(),\n success: function(output) {\n // return output;\n alert(output);\n },\n error: function() {\n alert('Something went wrong!');\n }\n });\n }\n });\n});\n</code></pre>\n\n<p>I've seperated your cod into two blocks. One is a closure to make avoid leaking global variables and the other is in a ready block.</p>\n\n<p>The <code>inputListener</code> had no business being in an object so it's just a local variable, your ajax function also didn't have to be in an object if it's just being used once. </p>\n\n<p>I've injected your validate function directly into <code>$.fn</code> to make it easier to use.</p>\n\n<h3>inputListener</h3>\n\n<p>This method will now check whether the function is bound to the field. Apart from that the code is the same.</p>\n\n<h3>validate</h3>\n\n<p>Using a flag to check whether it succeeded or failed (<code>valid</code>) is more optimum. I've changed the API so you pass in an array rather then a CSV string (ew!).</p>\n\n<p>It's better to use a for loop, then a for ... in. For ... in on an array is simply inefficient and wrong.</p>\n\n<p>Since we've added ids to the elements we can reference them by id directly.</p>\n\n<h3>your ready block</h3>\n\n<p>I've renamed theForm to <code>$this</code> as it's more readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T00:19:02.513",
"Id": "6504",
"Score": "0",
"body": "+1 I like this Nice clean readable code. The only thing I would change is `i` and `ii`. I'm one for explicit names so I would go for `indx` and `total` or maybe `currentIndex` and `requiredLength` or... etc. etc. You get me point. Not that it is a big deal as it is still readable and easy to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T09:16:42.003",
"Id": "6522",
"Score": "0",
"body": "@JamesKhoury We have a coding practice where `i` is a for loop counter and `ii` is the for loop length. It's quite common."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T23:58:09.437",
"Id": "6553",
"Score": "0",
"body": "I've seen it once or twice before but I didn't realise it was a style. I'm personally not a fan of it but each to his own then ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T13:14:04.423",
"Id": "4332",
"ParentId": "4321",
"Score": "1"
}
},
{
"body": "<p>I'd like to complement James Khoury's answer: </p>\n\n<blockquote>\n <p>Another point would be the <code>for(i in ....)</code> should be <code>for(var i in ...)</code> it will run either way and I believe it is just a matter of coding style.</p>\n</blockquote>\n\n<p>The <code>for(var i in ...)</code> should be used instead of the other one; the <code>for(i in ....)</code> means you are declaring a global variable named <code>i</code>. Whenever you use a variable in javascript you haven't previously declared with <code>var</code> a new one will be created and it'll be a global one. If you execute the example code, a variable named <code>i</code> will be created with the last value it was attributed after the <code>for</code> loop.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T15:56:39.897",
"Id": "4335",
"ParentId": "4321",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4332",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T04:32:03.053",
"Id": "4321",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"object-oriented",
"ajax"
],
"Title": "Validating a form and alerting the server if passed"
}
|
4321
|
<p>Question: What are peoples preferences between the two methods of creating an object (in C# in particular) and setting other fields (that may not be given values during construction)? Are either of them considered best practice? or is it down to the programmer and any styling conventions in place at the company?</p>
<p>My preference is absolutely for the object initializer method. It looks much cleaner and more concise to me.</p>
<p><strong>Object initializer</strong></p>
<pre><code>Type T = new Type(Param1, Param2)
{
Field1 = Value1,
Field2 = Value2,
Field3 = ValueFromFunction()
};
</code></pre>
<p><strong>Constructor</strong></p>
<pre><code>Type T = new Type(Param1, Param2);
T.Field1 = Value1;
T.Field2 = Value2;
T.Field3 = ValueFromFunction();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T10:27:50.090",
"Id": "6460",
"Score": "0",
"body": "As a mostly java developer I find it confusing that lazy and standard is considered as styles. I figure that this is because there's something C# provides that I'm not familiar with that changes the context from which this question should be read. In my understanding - lazy refers to an optimization strategy that defers the creation of expensive resources to the point of time they are actually needed and preferabely never. However, lazy strategy may come with a run-time penalty if everything is deferred instead of preparing things in advance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T10:37:41.307",
"Id": "6461",
"Score": "0",
"body": "As I said at the top of my post, I didn't really know what to call either of those. They both do the same job (building an object and setting values in fields), so I elected to refer to them simply as \"styles\" of doing the job."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T10:57:38.107",
"Id": "6462",
"Score": "0",
"body": "After some reading, I've edited my post to remove the reference to Java. I remembered initializing objects in a similar way to the one documented above, but didn't realise it wasn't strictly the same thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T12:28:19.080",
"Id": "6469",
"Score": "2",
"body": "Your code examples are not doing the same things, the second one has Param1, Param2, where the first version does not have these values at all and therefore the two are constructing different objects which would assumably have different purposes. If they are supposed to be functionaly identical, I would put Value1 and Value2 into the Param1/Param2 slots, or else add Param1/Param2 to the initializer example so they can be comparable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T13:36:11.070",
"Id": "6475",
"Score": "0",
"body": "I forgot to add the params to my first example when I edited the second."
}
] |
[
{
"body": "<p>The method you call here \"constructor\" is not the proper \"constructor way\" to initialize an object. That said, by my experience, most if not all people prefer initialization by constructor, but I mean not the one shown by you. The constructor should take the values for initialization as parameters, like this:</p>\n\n<pre><code>Type T = new Type(Value1, Value2, ValueFromFunction());\n</code></pre>\n\n<p>This is what most prefer. It is even preferred over object initializers, unfortunately, not all types have constructors, and some could but are not under your control. In those cases Object initilaizers in C# is a nice syntax.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T11:20:36.400",
"Id": "6465",
"Score": "0",
"body": "I knew there was something I was missing from my constructor example, thankyou. I did mean to include parameters on the constructor, as well as the setting of some other fields."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T11:15:01.780",
"Id": "4328",
"ParentId": "4325",
"Score": "3"
}
},
{
"body": "<p>These are both techniques born of different goals.</p>\n\n<p>The constructor style is something you will design your classes for when you want them to be faux-immutable, that is, you do not want them changed after construction so you make the setters on your properties protected or private.</p>\n\n<p>The initializer style comes from you ceding control of the object's data members to the object's consumer, which you will do when you do not care about the order or timeliness of them being filled in.</p>\n\n<p>One of the largest decision making factors here is this: Is the object safely usable if the properties are null?</p>\n\n<p>If not, the constructor format allows you to ensure they will never be null by requiring them be set at construction by parameter and disallowing them to be set by the consumer.</p>\n\n<p>Example of this would be a connection string object, without a database catalog it cannot be safely used as anything that attempted to use it would try to use the database catalog and may throw an exception if it is null.</p>\n\n<p>The other reason for the constructor format vs. initialization is dependencies, this falls into the same question as null safety but can be thought about a little differently: If an object is useless without a particular dependency object or piece of data, then there is little reason to allow its construction without that parameter.</p>\n\n<p>Example of this would be a file stream, if you do not give it a path or some way of knowing about a file, it becomes a useless object.</p>\n\n<p>Edit:\nAll that said, as far as using initializer syntax when available, it's really just sugar and I think everyone can agree that you should use it if you know a number of values at construction time.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T12:24:32.983",
"Id": "4330",
"ParentId": "4325",
"Score": "11"
}
},
{
"body": "<p>A little late to this party, but I would add that debugging the 'Object initializer' style is difficult using Visual Studio (VS 2012) but trivial easy using the 'constructor' style. VS only allows a breakpoint on the line that contains <code>new</code> keyword. If you wanted to inspect the value <code>Value2</code> immediately after the <code>Value1</code> assignment...good luck. The breakpoint hits on the <code>new</code> but you don't get control back until after the entire initialization completes (here, that's the closing brace <code>}</code>).</p>\n\n<p>Also, if the <code>Value2</code> assignment throws an <code>Exception</code> for some reason, the stack trace will show the <code>throw</code> as taking place on the line with the <code>new</code> keyword. For a 3 line initialization, may not be a big deal.</p>\n\n<p>But, if you have a 300 line initializer (I have seen this!), then you really have no clue as to where the problem lies.</p>\n\n<p>As both styles are syntactically equivalent I'd go with the style more easily debugged and traced style - #2/ 'constructor' style.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-30T13:18:42.337",
"Id": "55688",
"ParentId": "4325",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4330",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T09:38:14.163",
"Id": "4325",
"Score": "14",
"Tags": [
"c#",
"constructor"
],
"Title": "Styles: \"object initializer\" vs \"constructor\" object creation"
}
|
4325
|
<p>I've been practicing using BSP trees as I hear they are a good start to create procedural spaces such as houses.</p>
<p>For ease-of-deployment purposes, I've tested this code in Lua and it seems to work. However, I want to confirm if I did what I needed to do instead of something else. When I am sure this works I will properly implement it in C.</p>
<p>This would be the code:</p>
<pre><code>MAX_RECURSION = 3
TL = 1
BL = 2
BR = 3
TR = 4
grid = {}
grid.w = 60;
grid.h = 12;
grid.max = grid.w * grid.h
grid.pos = function (self, x, y) return (x * self.w + y)+1 end
grid.get = function (self, x, y) return self.data[self:pos(x, y)] end
grid.set = function (self, x, y, d) self.data[self:pos(x,y)] = d end
grid.data = {}
for i = 1, grid.max do grid.data[i] = " " end
rooms = 1
function node_c(parent, rect)
n = {}
n.child1 = nil
n.child2 = nil
n.parent = parent
n.rect = rect
n.w = rect[TR].x-rect[TL].x
n.h = rect[BL].y-rect[TL].y if n.h < 0 then n.h = 0 end
n.level = parent.level + 1
n.id = 0
n.vertical = direction_get(n)
node_draw(n)
return n
end
function rootnode(rect)
n = {}
n.child1 = nil
n.child2 = nil
n.rect = rect
n.parent = nil
n.w = rect[TR].x-rect[TL].x
n.h = rect[BL].y-rect[TL].y
n.level = 0
n.id = 0
n.vertical = direction_get(n)
node_draw(n)
return n
end
function node_draw(node)
local x, y
local rect = node.rect
for y = rect[TL].y, rect[BL].y do
for x = rect[TL].x, rect[TR].x do
if x==rect[TL].x or x==rect[TR].x or y==rect[TL].y or y==rect[BR].y then
grid:set(x, y, "#")
else
grid:set(x, y, ".")
end
end
end
end
function node_split(node)
if not node or not (node.level < MAX_RECURSION) then
node.id = rooms
rooms = rooms + 1
return
else
local p
if node.vertical then p = "X" else p = "Y" end
local split = node_splitfrom(node)
if split == nil then return end
local c1, c2, r1, r2
r1,r2 = node_rects(node, split)
node.child1 = node_c(node, r1)
node.child2 = node_c(node, r2)
--draw_it(grid)
node_split(node.child1)
node_split(node.child2)
end
end
function direction_get(node)
if math.random(0, 1) == 0 then return true else return false end
end
function node_splitfrom(node)
local result
if node.vertical then
local r = math.floor(((math.random(20, 80)/100) * node.w))
if r < 2 or r > node.w - 2 then return nil else return node.rect[TL].x + r end
else
local r = math.floor(((math.random(20, 80)/100) * node.h))
if r < 2 or r > node.h - 2 then return nil else return node.rect[TL].y + r end
end
end
function print_rect(rect)
return "TL:"..rect[TL].x..","..rect[TL].y.." BL:"..rect[BL].x..","..rect[BL].y.." BR:"..rect[BR].x..","..rect[BR].y.." TR:"..rect[TR].x..","..rect[TR].y
end
function node_rects(node, split)
local rect1, rect2
local t
t = node.rect
if node.vertical then
rect1 = {[TL] = t[TL], [BL] = t[BL], [TR] = {x=split,y=t[TR].y}, [BR] = {x=split,y=t[BR].y}}
rect2 = {[TL] = {x=split,y=t[TL].y}, [BL] = {x=split,y=t[BL].y}, [TR] = t[TR], [BR] = t[BR]}
return rect1,rect2
else
rect1 = {[TL]=t[TL],[TR] = t[TR],[BL]={x=t[BL].x,y=split}, [BR]={x=t[BR].x,y=split}}
rect2 = {[TL]={x=t[TL].x,y=split},[TR]={x=t[TR].x,y=split},[BL]=t[BL],[BR] = t[BR]}
return rect1,rect2
end
end
function bsp_it(g)
local rect = { --Counter clockwise
[TL] = {x=0,y=0},
[BL] = {x=0,y=g.h},
[BR] = {x=g.w,y=g.h},
[TR] = {x=g.w,y=0}
}
local root = rootnode(rect)
node_split(root)
return root
end
function print_it(t)
if(t) then
local spaces = (t.level * 2)
local i
local space = ""
for i = 0, spaces do space = space.." " end
if not t.parent then print(space.."#"..("%X"):format(t.id)) else print(space.."\\"..("%X"):format(t.id)) end
print_it(t.child1) print_it(t.child2)
end
end
function draw_it(grid)
local line = ""
local x,y
for y = 0, grid.h do
for x = 0, grid.w do
line = ""..line..(grid.data[grid:pos(x,y)] or 0)
end
print(line)
line = ""
end
end
math.randomseed(os.time())
test = bsp_it(grid, 3)
print_it(test)
draw_it(grid)
</code></pre>
<p>This is a very naive approach. I don't check for size ratio or anything to make it look good and I am not connecting the rooms yet (I will deal with it later. A table recursively collecting the nodes should do the work). </p>
<p>So the question is if this is actually a BSP tree, and if I am missing something important in here.</p>
<p>Additionally, having this data, how should I check for connectivity among individual rooms? Picking a node, check parent and connect all nodes inside parent, perhaps?</p>
|
[] |
[
{
"body": "<p>Your principal algorithm is a correctly implemented BSP, so yes. You are creating a Binary Space Partitioning tree.</p>\n\n<p>Also, FWIW: You only need two points on opposing corners to define an axis aligned rectangle which you seem to be using here. So you could simplify. </p>\n\n<p><strong>Edit:</strong> Just noticed your question about connectivity:</p>\n\n<p>Just checking the immediate parent will give you a subset of the possible connection information. Since your BSP is axis aligned and 2 dimensional each node can have 1 to 4 neighboring nodes (depending on if it's positioned along the edges or not) or 0 for the root but lets ignore the root because it's not interesting.</p>\n\n<p>If you're interested in the full connectivity you can either traverse the tree top down and keep track of all edges and in that way find which rooms are neighboring. Or you can keep track of north,west,east,south neighbor of a node during tree generation and use this information to determine connectivity. </p>\n\n<p>If you only look at the immediate parent, you only get one connecting node (out of possibly 4). I do not know how you intend to use this connectivity information so this may be enough for you. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-19T19:50:53.090",
"Id": "44786",
"ParentId": "4334",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T15:14:34.863",
"Id": "4334",
"Score": "13",
"Tags": [
"tree",
"lua",
"computational-geometry",
"clustering"
],
"Title": "Is this a BSP tree? Am I missing something?"
}
|
4334
|
<p>I'm new to python but not to programming in general. This is my <a href="https://github.com/hemmer/pyDLA" rel="nofollow">first project</a> beyond the basics.</p>
<p>I was wondering if I could get some feedback on the code in general, in particular on any bad Java/C++ habits I might be dragging along.</p>
<p>I have some specific questions regarding performance of numpy's array vs. lists. As you can see from <a href="https://github.com/hemmer/pyDLA/commit/0956de28884b5f2fbfe822304ae30768a4dd6bc0" rel="nofollow">this diff</a>, I have rewritten some of the code to use the array class, which seems more "pythonic" (code seems to read better) but I find that it is sometimes almost twice as slow. Is this an inevitable performance hit for the abstraction, or am I doing something obviously wrong?</p>
<p>To get a proper working copy of the code:</p>
<pre><code>git clone git://github.com/hemmer/pyDLA.git
</code></pre>
<p>And to checkout the array version use (afterwards):</p>
<pre><code>git checkout numpyarray_slow
</code></pre>
<p>Any advice, however small, is greatly appreciated!</p>
<p><strong>EDIT</strong>: Here is the source of the older (faster code). For the changes I made to use numpy arrays, please see the diff above.</p>
<pre><code>#!/usr/bin/env python
import time
from math import pi, sqrt, cos, sin
from random import choice, random, seed
from pylab import pcolormesh, axes, show
from numpy import zeros, int32, arange
twopi = 2 * pi # 2 pi for choosing starting position
hits = 0 # how many seeds have stuck
birthradius = 5 # starting radius for walkers
deathradius = 10 # radius to kill off walkers
maxradius = -1 # the extent of the growth
numParticles = 1000 # how many walkers to release
seed(42) # fixed seed for debugging
L = 500 # lattice goes from -L : L
size = (2 * L) + 1 # so total lattice width is 2L + 1
# preallocate and initialise centre point as "seed"
lattice = zeros((size, size), dtype=int32)
lattice[L, L] = -1
# possible (relative) nearest neighbour sites
nnsteps = ((0, 1), (0, -1), (1, 0), (-1, 0))
# returns whether site pos = (x, y) has
# an occupied nearest-neighbour site
def nnOccupied(pos):
# convert from lattice coords to array coords
latticepos = (pos[0] + L, pos[1] + L)
for step in nnsteps:
if lattice[latticepos[0] + step[0], latticepos[1] + step[1]] != 0:
return True
else:
return False
# end of nnOccupied
# check if a point is within the
# allowed radius
def inCircle(pos):
if (pos[0] ** 2 + pos[1] ** 2) > deathradius ** 2: # faster than sqrt
return False
else:
return True
# end of inCircle
# registers an extension on the seed
def registerHit(pos):
global hits, birthradius, deathradius, maxradius
# check if this "hit" extends the max radius
norm2 = (pos[0] ** 2 + pos[1] ** 2)
if norm2 > maxradius ** 2:
maxradius = int(sqrt(norm2))
birthradius = maxradius + 5 if (maxradius + 5) < L else L
deathradius = maxradius + 20 if (maxradius + 20) < L else L
hits += 1
lattice[pos[0] + L, pos[1] + L] = hits
# end of registerHit
starttime = time.time()
print "Running", numParticles, "particles..."
for particle in xrange(numParticles):
#print particle
# find angle on [0, 2pi)
angle = random() * twopi
# and convert to a starting position, pos = (x, y),
# on a circle of radius "birthradius" around the centre seed
pos = [int(sin(angle) * birthradius), int(cos(angle) * birthradius)]
isDead = False # walker starts off alive
while not isDead:
# pick one of the nearest neighbour sites to explore
moveDir = choice(nnsteps)
# and apply the selected move to position coordinate, pos
pos[0] += moveDir[0]
pos[1] += moveDir[1]
if not inCircle(pos):
isDead = True
break
elif nnOccupied(pos):
registerHit(pos)
isDead = True
break
endtime = time.time()
print "Ran in time:", (endtime - starttime)
print "Maximum radius:", maxradius
# select only the interesting parts
M = maxradius
grph = L - M, L + M
# and plot
axis = arange(-M, M + 1)
pcolormesh(axis, axis, lattice[grph[0]:grph[1], grph[0]:grph[1]])
axes().set_aspect('equal', 'datalim')
show()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T16:30:22.693",
"Id": "6483",
"Score": "1",
"body": "Welcome to the Code Review stack. You are asking the kind of question this stack was designed for, but you need to include a reasonable amount of the code in your question. Please check the faq."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T16:31:57.760",
"Id": "6484",
"Score": "0",
"body": "Thanks! The code is around 100 lines, I assumed that would be too much to paste in full? It probably needs most of the context to make sense..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T16:36:16.647",
"Id": "6485",
"Score": "0",
"body": "@Hemmer, 100 lines is large, but not completely unreasonable. You'll probably get more people willing to respond if you can find a shorter piece to get advice on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T16:36:52.447",
"Id": "6486",
"Score": "0",
"body": "@Hemmer 100 lines is not necessarily too much to post here. You are much more likely to get responses with 100 lines here than with a link to somewhere else. You should be able to edit your post to add the code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T17:39:30.700",
"Id": "6487",
"Score": "0",
"body": "@jimreeed ok thanks, quite a few of those 100 are whitespace so its not as bad as it seems!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T18:03:45.007",
"Id": "6488",
"Score": "0",
"body": "That's a very reasonable amount of code to be reviewed. If I knew python I'd comment on it, but I'll leave that to those who know what they are talking about. :-)"
}
] |
[
{
"body": "<ol>\n<li>Use of global variables is frowned upon. You should probably define a class, and hold the data as attributes on it.</li>\n<li>Don't put logic at the module level, i.e. your main for loop. That is better placed inside of a main() function</li>\n<li>In your diff, you use python's sum rather then numpy's sum. when dealing with numpy array's numpy's sum will be much faster. Basically, you should never use python math functions on numpy arrays. Always use the numpy equivalents.</li>\n<li>Numpy is really not designed for having small arrays of two elements. Its really focused on having larger arrays so you are going to have trouble getting the speed benefits.</li>\n<li>You should avoid writing loops over numpy arrays, instead you should use numpy's vector operation features</li>\n</ol>\n\n<p>To get an effective use of numpy, you probably need if possible to process multiple particles in parallel so that you are operating on large arrays. The numpy's processing abilities will be able to help.</p>\n\n<p><strong>EDIT: Quick Sample of numpy vector operations</strong></p>\n\n<pre><code>angles = numpy.random.rand(numParticles) * twopi\npositions = numpy.empty((numParticles, 2))\npositions[0,:] = numpy.sin(angles) * birthradius\npositions[1,:] = numpy.cos(angles) * birthradius\n</code></pre>\n\n<p>This constructs a 2D array of positions. No python loops are used, instead operations over arrays are used. I'm not seeing a good way to use it in your case. Ordinarilly, I'd use them to run all particles at the same time. But you have dependency between your different runs.</p>\n\n<p>More thoughts:</p>\n\n<ol>\n<li>By keeping an array of bools marking the positions next to \"hit\" locations, you can avoid checking the neighbours in nnOccupied. Its cheaper to update the \"next_to\" array when a hit is detected.</li>\n<li>Using two coordinate systems 0-based and L-based, confusion results. Standardise on one.</li>\n<li>Setting isDead and using break is redundant. Pick one and stick with it</li>\n<li>Don't <code>if expr: return True else return False</code> just return it</li>\n<li>Why is nnsteps redecared in registerHit?</li>\n</ol>\n\n<p>** EDIT: My rewrite of your code **</p>\n\n<pre><code>#!/usr/bin/env python\nimport time\n\nfrom pylab import pcolormesh, axes, show\nimport numpy as np\n\nL = 500 # lattice goes from -L : L\nSIZE = (2 * L) + 1 # so total lattice width is 2L + 1\nNNSTEPS = np.array([\n (0, 1), \n (0, -1), \n (1, 0), \n (-1, 0)\n])\nCHUNK_SIZE = 1000\n\nclass Simulation(object):\n def __init__(self, num_particles):\n self.hits = 0\n self.birthradius = 5\n self.deathradius = 10\n self.maxradius = -1\n\n self.lattice = np.zeros((SIZE, SIZE), dtype=np.int32)\n self.lattice[L, L] = -1\n # initialize center point as the seed\n\n self.hit_zone = np.zeros((SIZE, SIZE), dtype=bool)\n self.hit_zone[L, L] = True\n self.hit_zone[ NNSTEPS[:,0] + L, NNSTEPS[:,1] + L ] = True\n # the hit_zone is all of the position next to places that have\n # actually hit, these count as hits\n\n self.num_particles = num_particles\n\n def register_hit(self, pos):\n neighbors = NNSTEPS + pos\n self.hit_zone[neighbors[:,0], neighbors[:,1]] = True\n # update hit_zone\n\n # check if this \"hit\" extends the max radius\n norm2 = (pos[0] - L)**2 + (pos[1] - L)**2\n if norm2 > self.maxradius ** 2:\n self.maxradius = int(np.sqrt(norm2))\n self.birthradius = min(self.maxradius + 5, L)\n self.deathradius = min(self.maxradius + 20, L)\n\n self.hits += 1\n self.lattice[pos] = self.hits\n\n\n def run(self):\n for particle in xrange(self.num_particles):\n # find angle on [0, 2pi)\n angle = np.random.random() * 2 * np.pi\n # and convert to a starting position, pos = (x, y),\n # on a circle of radius \"birthradius\" around the centre seed\n pos = (np.sin(angle) * self.birthradius + L, np.cos(angle) * self.birthradius + L)\n\n while True:\n moves = np.random.randint(0, 4, CHUNK_SIZE) # pick the move numbers\n moves = np.cumsum(NNSTEPS[moves], axis = 0) # grab the move and do a sum\n\n # add starting position to all of that\n moves[:,0] += pos[0]\n moves[:,1] += pos[1]\n\n # calculate distance to center for all the points\n from_center = moves - L\n distances_to_center = from_center[:,0]**2 + from_center[:,1]**2\n alive = distances_to_center < self.deathradius ** 2\n alive = np.minimum.accumulate(alive)\n\n particle_hits = self.hit_zone[moves[:,0], moves[:,1]]\n\n if np.any(particle_hits):\n first_hit = particle_hits.nonzero()[0][0]\n if alive[first_hit]:\n pos = tuple(moves[first_hit])\n self.register_hit(pos)\n break\n else:\n if np.all(alive):\n pos = tuple(moves[-1])\n else:\n break\nNUMBER_PARTICLES = 1000\ndef main():\n\n np.random.seed(42)\n simulation = Simulation(NUMBER_PARTICLES)\n starttime = time.time()\n print \"Running\", NUMBER_PARTICLES, \"particles...\"\n simulation.run()\n endtime = time.time()\n print \"Ran in time:\", (endtime - starttime)\n print \"Maximum radius:\", simulation.maxradius\n\n # select only the interesting parts\n M = simulation.maxradius\n grph = L - M, L + M\n\n # and plot\n axis = np.arange(-M, M + 1)\n pcolormesh(axis, axis, simulation.lattice[grph[0]:grph[1], grph[0]:grph[1]])\n axes().set_aspect('equal', 'datalim')\n show()\n\nif __name__ == '__main__':\n main()\n</code></pre>\n\n<p>The tricky part here was to see how I could numpy's vector operations to help in this situation. Here I'll try to explain that.</p>\n\n<pre><code> moves = np.random.randint(0, 4, CHUNK_SIZE) # pick the move numbers\n</code></pre>\n\n<p>Here we pick 1000 different numbers 0, 1, 2, or 3, corresponding to the directions we can move</p>\n\n<pre><code> moves = np.cumsum(NNSTEPS[moves], axis = 0) # grab the move and do a sum\n</code></pre>\n\n<p>We use those numbers to index into the NNSTEPS array, thus we have an array of all the moves. Cumsum adds cumulatively over the whole array. So the nth element is the sum of the first n elements.</p>\n\n<pre><code> # add starting position to all of that\n moves[:,0] += pos[0]\n moves[:,1] += pos[1]\n</code></pre>\n\n<p>Add the start position to all of that producing an array of the next 1000 positions that will be visited.</p>\n\n<pre><code> # calculate distance to center for all the points\n from_center = moves - L\n distances_to_center = from_center[:,0]**2 + from_center[:,1]**2\n</code></pre>\n\n<p>We calculate all of the distances to the center point. Since we don't have to write explicit loops this is pretty efficient.</p>\n\n<pre><code> alive = distances_to_center < self.deathradius ** 2\n alive = np.minimum.accumulate(alive)\n</code></pre>\n\n<p>alive indicates whether the particular is alive during a particular move. We start by marking those element as alive when the distance is less than deathradius. The minimum.accumulate sets the nth element to the be the minimum of the first n elements. The consequence is that after the first false (dead) element, all the rest are dead</p>\n\n<pre><code> particle_hits = self.hit_zone[moves[:,0], moves[:,1]]\n</code></pre>\n\n<p>Here we do a vector operation checking the hit_zone. particle_hits becomes a boolean array of every that the path will hit something.</p>\n\n<pre><code> if np.any(particle_hits):\n first_hit = particle_hits.nonzero()[0][0]\n</code></pre>\n\n<p>If anything of the 1000 we are considering hits, figure out where</p>\n\n<pre><code> if alive[first_hit]:\n</code></pre>\n\n<p>Make sure we are still alive</p>\n\n<pre><code> pos = tuple(moves[first_hit])\n self.register_hit(pos)\n</code></pre>\n\n<p>Record that hit\n break\n else:\n if np.all(alive):\n pos = tuple(moves[-1])</p>\n\n<p>If we survived, take the tuple and run another round.</p>\n\n<pre><code> else:\n break\n</code></pre>\n\n<p>Basically, this way we run 1000 elements of a path at a time avoiding much of the overhead of python.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T18:28:50.767",
"Id": "6490",
"Score": "0",
"body": "Thanks, not looked at python classes yet so this is a good excuse to learn. The rest of the advice is really solid too, already seeing speedups! I was wondering if there were any specific examples for point 5. that I could use?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T21:48:33.103",
"Id": "6495",
"Score": "1",
"body": "@Hemmer, I've added a rewrite of your code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T22:22:19.787",
"Id": "6496",
"Score": "0",
"body": "Wow this is a fantastic update, really good stuff here. With the numpy stuff, it really requires a different way of thinking about the problem, I had just been forcing it into my traditional style (of manually iterating through with loops). \n\nThis is exactly the sort of response I was looking for thanks (a lot to take in too!), I might try applying this kind of thinking to the [Ising Model](http://farside.ph.utexas.edu/teaching/329/lectures/node110.html) next."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T22:47:09.950",
"Id": "6498",
"Score": "0",
"body": "@Hemmer, numpy is bizarre at first, then somehow it eventually becomes oddly natural."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T17:37:12.397",
"Id": "4338",
"ParentId": "4336",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4338",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T16:23:12.167",
"Id": "4336",
"Score": "7",
"Tags": [
"python",
"numpy"
],
"Title": "Code Review of small scientific project, particuarly array vs. list perform"
}
|
4336
|
<p>I've written this bit of JavaScript to just learn basics of drawing on/interacting with the HTML5 canvas element.</p>
<p>Just want to make sure I'm doing things "correctly" in case I have any glaring code gaffs or there's a more efficient way.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function start() {
canvas = document.getElementById("area");
// initiate ball
ball.init({
context: canvas.getContext('2d'),
color: "#F33",
radius: 30,
});
}
var ball = (function() {
var ball;
var mouseMoveEvent;
var prevMouseMoveEvent;
// set default options
var default_options = {
context: "", // required
radius: 20,
color: "#F33",
startX: window.innerWidth / 2,
startY: window.innerHeight / 2
};
return {
draw: function() {
// prep canvas
ball.o.context.canvas.width = window.innerWidth;
ball.o.context.canvas.height = window.innerHeight;
//capture current position values
var cur_x = ball.posX;
var cur_y = ball.posY;
//capture current context dimensions
var ctx_width = ball.o.context.canvas.width;
var ctx_height = ball.o.context.canvas.height;
if (ball.isGrabbed) {
//-------------- track ball with mouse when grabbed
mouseOffsetX = mouseMoveEvent.x - prevMouseMoveEvent.x;
mouseOffsetY = mouseMoveEvent.y - prevMouseMoveEvent.y;
ball.posX += mouseOffsetX;
ball.posY += mouseOffsetY;
// save previous mouse move state
prevMouseMoveEvent = mouseMoveEvent;
} else {
//-------------- bounding
var x_reach = Math.abs(ball.iterX) + ball.o.radius;
var y_reach = Math.abs(ball.iterY) + ball.o.radius;
if ((cur_x + x_reach) > ctx_width || (cur_x - x_reach) < 0)
ball.iterX = -(.70 * ball.iterX);
if ((cur_y + y_reach) > ctx_height || (cur_y - y_reach) < 0)
ball.iterY = -(.70 * ball.iterY);
ball.iterX *= .999;
ball.iterY *= .999;
ball.posX += ball.iterX;
ball.posY += ball.iterY;
}
//-------------- protect browser borders
// North
if (ball.posY - ball.o.radius < 0)
ball.posY = ball.o.radius;
// South
else if (ball.posY + ball.o.radius > ctx_height)
ball.posY = ctx_height - ball.o.radius;
// East
else if (ball.posX + ball.o.radius > ctx_width)
ball.posX = ctx_width - ball.o.radius;
// West
else if (ball.posX - ball.o.radius < 0)
ball.posX = ball.o.radius;
//-------------- draw
ball.o.context.beginPath();
ball.o.context.fillStyle = ball.o.color;
ball.o.context.arc(ball.posX, ball.posY, ball.o.radius, 0, Math.PI * 2, true);
ball.o.context.closePath();
ball.o.context.fill();
},
mouseDown: function(e) {
// grab ball
if (ball.o.context.isPointInPath(e.x, e.y)) {
prevMouseMoveEvent = e;
ball.isGrabbed = true;
}
},
mouseUp: function(e) {
// release
if (ball.isGrabbed) {
// set iter speed based on mouse speed on release
ball.iterX = mouseMoveEvent.x - prevMouseMoveEvent.x;
ball.iterY = mouseMoveEvent.y - prevMouseMoveEvent.y;
ball.isGrabbed = false;
}
},
mouseMove: function(e) {
if (ball.o.context.isPointInPath(e.x, e.y)) {
document.body.style.cursor = "move";
} else {
document.body.style.cursor = "default";
}
mouseMoveEvent = e;
},
init: function(options) {
ball = this;
//load up defaults
ball.o = default_options;
// merge in user options that exist
for (var attr in options) {
ball.o[attr] = options[attr];
};
// set starting values
ball.posX = ball.o.startX;
ball.posY = ball.o.startY;
ball.iterX = 0;
ball.iterY = 0;
ball.isGrabbed = false;
// attach events
window.onmousedown = ball.mouseDown;
window.onmouseup = ball.mouseUp;
window.onmousemove = ball.mouseMove;
// start
setInterval(ball.draw, 1);
},
};
})();</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
margin: 0px;
}
#area {
width: 100%;
height: 100%;
margin: 0px;
background: #FF7
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onLoad="start();">
<canvas id="area"></canvas>
</body></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>This looks pretty good. In your <code>start</code> function, the <code>canvas</code> variable should be declared with a var; implicit globals are one of the Worst Parts.</p>\n\n<pre><code>function start()\n{\n var canvas = document.getElementById(\"area\");\n\n // ...\n}\n</code></pre>\n\n<p>Second, the var statement can declare more than one variable at a time, so lines like</p>\n\n<pre><code>var cur_x = ball.posX;\nvar cur_y = ball.posY;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>var cur_x = ball.posX, cur_y = ball.posY;\n</code></pre>\n\n<p>Third, this line</p>\n\n<pre><code>for (var attr in options) { ball.o[attr] = options[attr]; };\n</code></pre>\n\n<ol>\n<li>has an extra semicolon at the end and more importantly</li>\n<li>doesn't do a hasOwnProperty check.</li>\n</ol>\n\n<p>The vast majority of the time, when you are iterating over object properties, you should check to make sure the properties actually exist on the object instead of the prototype chain. More more information read <a href=\"http://www.yuiblog.com/blog/2006/09/26/for-in-intrigue/\" rel=\"nofollow\">this</a> article by Douglas Crockford. So it should look like:</p>\n\n<pre><code>for (var attr in options) {\n if (options.hasOwnProperty(attr))\n ball.o[attr] = options[attr];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T16:05:18.920",
"Id": "4356",
"ParentId": "4341",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4356",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T20:25:24.207",
"Id": "4341",
"Score": "1",
"Tags": [
"javascript",
"html",
"html5",
"canvas"
],
"Title": "Basic HTML5 Canvas/Javascript testing"
}
|
4341
|
<p><strong>Example 1</strong></p>
<pre><code>if (myList.ContainsKey(myKey))
{
myList[myKey]++;
}
else
{
myList.Add(myKey,1);
}
</code></pre>
<p><strong>Example 2</strong></p>
<pre><code>Where(x =>
(myList.ContainsKey(x.Key) ? x.Value - myList[x.Key] : x.Value) >
</code></pre>
<p><code>myList</code> is <code>Dictionary</code>.</p>
<p>Is there any way or existing method of simplifying or normalizing the code?</p>
<h3>Update</h3>
<p>Now I've learned Python and came across <code>defaultdict</code>:</p>
<ul>
<li><p><a href="https://stackoverflow.com/questions/15622622/analogue-of-pythons-defaultdict">Analogue of Python's defaultdict?</a></p></li>
<li><p><a href="https://stackoverflow.com/questions/2601477/dictionary-returning-a-default-value-if-the-key-does-not-exist/2601501#2601501">Dictionary returning a default value if the key does not exist</a></p></li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T23:18:13.593",
"Id": "6501",
"Score": "1",
"body": "Are these two snippets supposed to be doing the same thing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T22:48:29.267",
"Id": "6545",
"Score": "0",
"body": "@Jimmy Hoffa: if I'm reading the second snippet correctly, If `myList` does *not* contain `x.Key`, it will throw an exception at `x.Value - myList[x.Key]`. It is definitely not doing the same thing ...if I'm reading correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T23:36:35.523",
"Id": "6549",
"Score": "0",
"body": "@IAbstract yeah I know they're not though the second one wont except, I was asking if he meant them to be the same because the way they were presented I first thought he wanted us to pick one over the other, now I think he wants them both improved separately"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T23:44:51.607",
"Id": "6551",
"Score": "0",
"body": "@Jimmy: ...yeah, I was reading backwards ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T00:07:23.790",
"Id": "6557",
"Score": "0",
"body": "@IAbstract: I can thank SO for making me fluent in the ternary operator, seeing it enough times there and realizing how much it can simplify the code in the right place :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T10:44:34.547",
"Id": "6571",
"Score": "0",
"body": "@Jimmy: ...right ...I decided to not be ignorant and force myself to actually use the ternary. I'm getting a lot better with it."
}
] |
[
{
"body": "<p>For example, you can write your own extenession method for this operation and use it everywhere. Something like this</p>\n\n<pre><code>public static void SetOrIncrement<K>(this Dictionary<K, int> dictionary, K key)\n {\n int value;\n if (dictionary.TryGetValue(key, out value))\n {\n dictionary[key] = value + 1;\n }\n else\n {\n dictionary[key] = 1;\n }\n }\n</code></pre>\n\n<p>And then just use it in the following way:</p>\n\n<pre><code> myList.SetOrIncrement(myKey);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:05:45.310",
"Id": "6512",
"Score": "0",
"body": "Why not make a `SetOrIncrementByTwoUnlessGreaterThanTen` method then as well?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:10:23.137",
"Id": "6513",
"Score": "0",
"body": "Don't over exaggerate. This is a very simple operation in original post.There is no need to solve the problem that doesn't exist. Event if this 'SetOrIncrementByTwoUnlessGreaterThanTen' is required to be a very often operation I see no reasons why not to do so. What are the other options? I'm very interested to hear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:19:36.677",
"Id": "6515",
"Score": "0",
"body": "See my more reusable suggestion in [my answer](http://codereview.stackexchange.com/questions/4342/any-way-to-simplify-the-following-two-short-snippets-regarding-dictionary/4352#4352)."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T06:37:49.387",
"Id": "4348",
"ParentId": "4342",
"Score": "7"
}
},
{
"body": "<p>Also an alternative:</p>\n\n<pre><code>if (!myList.ContainsKey(myKey))\n{\n myList.Add(myKey, 0);\n}\nmyList[myKey]++;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T10:46:54.090",
"Id": "6572",
"Score": "0",
"body": "The first example by the OP doesn't always increment the value ...the value is incremented only if the key is within the dictionary."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T08:34:15.493",
"Id": "6605",
"Score": "2",
"body": "The first example adds the default value of 1 for new objects. My example generates the same outcome."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T17:56:40.223",
"Id": "6704",
"Score": "0",
"body": "Just as an FYI, your alternative (logically, not necessarily physically) accesses myList either 2 or 3 times (1 read and either 1 or 2 writes) while the original will always have 1 read and 1 write."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T08:50:16.357",
"Id": "6731",
"Score": "0",
"body": "@Jesse: Actually, the original (first example) did 1-2 reads and 1 write (the post-increment operator triggers both a read and a write). Personally, I would recommend using the `TryGetValue` as shown in some of the other answers rather than `ContainsKey`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T11:33:10.597",
"Id": "6735",
"Score": "0",
"body": "For the sake of readability, i prefer mine or the example 1 from the original post. I can live with the extra reads ;)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T07:52:07.067",
"Id": "4351",
"ParentId": "4342",
"Score": "11"
}
},
{
"body": "<p>Just an idea ...</p>\n\n<pre><code>public static void UpdateOrAdd<TKey, TValue>(\n this Dictionary<TKey, TValue> source,\n TKey key, Func<TValue, TValue> updateValue, Func<TValue> initializeValue )\n{\n TValue value;\n if ( source.TryGetValue( key, out value ) )\n {\n source[ key ] = updateValue( value );\n\n }\n else\n {\n source.Add( key, initializeValue() ); \n }\n}\n</code></pre>\n\n<p>Could be used as a one-liner.</p>\n\n<pre><code>myList.UpdateOrAdd( myKey, v => v + 1, () => 1 );\n</code></pre>\n\n<p>A lambda is used for the initializer so that the initial object for dictionaries with reference types is only created once.</p>\n\n<hr>\n\n<p>Similarly you could do the following for example 2.</p>\n\n<pre><code>public static TValue GetOrDefault<TKey, TValue>(\n this Dictionary<TKey, TValue> source,\n TKey key, TValue defaultValue )\n{\n return source.ContainsKey( key ) ? source[ key ] : defaultValue;\n}\n</code></pre>\n\n<p>To use like:</p>\n\n<pre><code>x.Value - myList.GetOrDefault( x.Key, 0 ) > ...\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:34:56.807",
"Id": "6517",
"Score": "2",
"body": "`myList.SetOrCreate( myKey, myList[ myKey ] + 1, 1 );` \nThis code is plain wrong. Evaluation of 2nd parameter will fail with KeyNotFoundException if there is no such key in a list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:46:45.667",
"Id": "6518",
"Score": "0",
"body": "@Andrei: You are right, probably solveable by using a lambda, but then the solution might get less interesting."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:49:17.313",
"Id": "6519",
"Score": "0",
"body": "Updated the answer accordingly, it's not too bad ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:57:43.027",
"Id": "6520",
"Score": "0",
"body": "Now you access a dictionary 3 times in for a given key in `else` branch versus 2 times in the original post. Still O(1) operation in average case but in case of collision you will traverse underlying chain 1.5 times more. Perfromance is affected but should not."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T09:14:05.653",
"Id": "6521",
"Score": "0",
"body": "@Andrei: Interesting, but you know what they say about premature optimization. ;p However, by using `TryGetValue` this could be optimized again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T09:18:29.530",
"Id": "6523",
"Score": "0",
"body": "Ok. `TryGetValue` will help. One more thing thoug - Why do I need to pass initialValue to the function if I access the same key twice? Can I pass different values and how caller code should know about these assumptions?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T09:23:00.443",
"Id": "6525",
"Score": "0",
"body": "@AndreiTaptunov let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1172/discussion-between-steven-jeuris-and-andrei-taptunov)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T11:16:19.607",
"Id": "6530",
"Score": "0",
"body": "@Steven Just a side note, but you said changing your solution would make it less \"interesting\", I must say any solution or code that is \"interesting\" is a sign of a problem in my eyes"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T11:46:31.457",
"Id": "6533",
"Score": "0",
"body": "@Jimmy, I meant having to use delegates makes it less interesting since it raises complexity for little added value. I don't know whether the given code is reusable enough to warrant splitting it in a separate method. But if it is, I'd use it along those lines."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T08:17:41.297",
"Id": "4352",
"ParentId": "4342",
"Score": "0"
}
},
{
"body": "<p>Let's see, for</p>\n\n<pre><code>Where(x =>\n(myList.ContainsKey(x.Key) ? x.Value - myList[x.Key] : x.Value) >\n</code></pre>\n\n<p>I could think...</p>\n\n<pre><code>public static int GetSubtractedValueForMatchingKey<T>(this KeyValuePair<T,int> target, Dictionary<T,int> dictionaryToFindMatchingKey)\n{\n return dictionaryToFindMatchingKey.ContainsKey(target.Key) ? \n (target.Value - dictionaryToFindMatchingKey[target.Key]) :\n target.Value;\n}\n</code></pre>\n\n<p>then..</p>\n\n<pre><code>Where(x => x.GetSubtractedValueForMatchingKey(myList) >\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T12:22:45.543",
"Id": "4353",
"ParentId": "4342",
"Score": "1"
}
},
{
"body": "<p>Example 1:</p>\n\n<pre><code>var value = 0;\n\n// value is treated as a reference type with the out modifier\nif (myList.TryGetValue(myKey, out value))\n{\n myList[myKey] = value++; // I like this over myList[myKey]++\n\n // either return here \n}\n// or wrap this in the else clause\nmyList.Add(myKey, value);\n</code></pre>\n\n<p>Example 2: <em>the Where method must return a bool</em></p>\n\n<pre><code>var value = -1;\nvar result = myList.Where(x => !myList.TryGetValue(myKey, out value))\n .Select(x => value > -1 ? x.Value - value : x.Value);\n</code></pre>\n\n<p>I don't know what your values are, but I believe it is close enough to get you on the right track. It will compile but I haven't tested any further.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T13:36:37.003",
"Id": "6736",
"Score": "0",
"body": "Just as a note in your example 1 - `value` is incremented, but the value that was in the dictionary is not incremented (if you actually did the return at the commented return here section). You would only get the updated value if you allowed the code to flow to the `myList.Add(...)` line. It would be different if `value` was a reference type, but in the code presented in the question it is a value type."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T14:09:17.973",
"Id": "6738",
"Score": "0",
"body": "@pstrjds: true enough ...will fix."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T11:19:39.090",
"Id": "4382",
"ParentId": "4342",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>myList is <code>Dictionary</code></p>\n</blockquote>\n\n<p>I don't write <code>C#</code> and don't really know what a <code>Dictionary</code> construct is, but I think what you're looking at is a <code>Map</code>. Each word is the key element, as it must be unique and the value is the times the word is met. </p>\n\n<p>So in <code>Java</code> that would be like this: </p>\n\n<pre><code>import java.util.HashMap;\nimport java.util.Map;\n\n/**\n *\n * @author c00kiemon5ter\n */\npublic class MapCountDict {\n\n /**\n * @param args the command line arguments\n */\n public static void main(String[] args) {\n\n /*\n * A testing dictioary\n */\n String[] dictionary = new String[]{ \"foo\", \"foo\", \"foo\", \"bar\", \"bar\", \"yow\" };\n\n /* \n * The collection to hold the times each word is found\n * \n * Each word is unique in the collection. The word is the key.\n * The value is the times the word is met when going through\n * the \"dictionary\".\n */\n Map<String, Integer> occurances = new HashMap<String, Integer>();\n\n /*\n * Run through the dictionary, adding up the times each word is met.\n */\n for (String word : dictionary) {\n Integer value = occurances.get(word);\n occurances.put(word, (value == null) ? 1 : value+1);\n }\n\n /*\n * Print the results\n */\n for (String word : occurances.keySet()) {\n System.out.printf(\"%s\\t%d\\n\", word, occurances.get(word));\n }\n }\n}\n</code></pre>\n\n<p>Results:</p>\n\n<blockquote>\n<pre><code>yow 1\nfoo 3\nbar 2\n</code></pre>\n</blockquote>\n\n<p>Converting your <code>Dictionary</code> to a <code>Map</code> cause some overhead, but depending on what you'll be doing, it might also help you with other things. </p>\n\n<p>Hope that helps a bit. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T15:02:08.177",
"Id": "6741",
"Score": "1",
"body": "\"Converting your Dictionary to a Map cause some overhead, but depending on what you'll be doing, it might also help you with other things.\" `Dictionary` *is* a map."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T01:51:09.480",
"Id": "4506",
"ParentId": "4342",
"Score": "0"
}
},
{
"body": "<p>In terms of readability, my vote goes for the <em>ternary operator</em>:</p>\n\n<pre><code>myList[myKey]=(myList.ContainsKey(myKey))?myList[myKey]+=1:1;\n</code></pre>\n\n<p>Does, what it should. Is simple to read, and was just invented for that purpose. I wonder, why nobody else came up with it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T23:42:31.057",
"Id": "33355",
"ParentId": "4342",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4348",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T22:19:10.663",
"Id": "4342",
"Score": "8",
"Tags": [
"c#",
"hash-map"
],
"Title": "Any way of simplifying the following two short snippets regarding Dictionary?"
}
|
4342
|
<p>This seems like rather too much nesting:</p>
<pre><code>using (XmlReader reader = XmlReader.Create(filename))
{
while (reader.Read())
{
if (reader.IsStartElement())
{
switch (reader.Name)
{
case "Width":
map.Width = ParseXMLValue(reader);
break;
case "Height":
map.Height = ParseXMLValue(reader);
break;
case "TileSize":
map.TileSize = ParseXMLValue(reader);
break;
case "Layers":
map.LayerCount = ParseXMLValue(reader);
break;
case "Layout":
ParseLayout(reader);
break;
case "Layer":
currentLayerIndex = ParseLayer(reader);
break;
case "CollisionLayer":
currentLayerIndex = ParseCollisionLayer();
break;
case "Row":
ParseRow(reader);
break;
}
}
}
}
</code></pre>
<p>This is P<code>arseXMLValue(reader)</code>:</p>
<pre><code>private int ParseXMLValue(XmlReader reader)
{
reader.Read();
return int.Parse(reader.Value);
}
</code></pre>
<p>I'm new to reading XML in C#. Surely there is a better way?</p>
|
[] |
[
{
"body": "<p>Yes, much. <code>XDocument</code> is the easier way. Though it does not perform as well if your documents are of significant size or performance is absolutely imperative:\n<a href=\"http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html\">http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html</a></p>\n\n<p>It works like:</p>\n\n<pre><code>XDocument someXmlDoc = XDocument.Create(fileName);\nIEnumerable<XElement> widthElements = someXmlDoc.Descendants(\"Width\");\nint[] widthValues = widthElements.Select(xelement => int.Parse(xelement.Value)).ToArray();\n</code></pre>\n\n<p>Though I don't understand the logic in your snippet as you're setting elements of the same member repeatedly, so I'm not going to reserve giving a more eleborate use case that might match your functionality better, though I would suggest reading the msdn articles for IEnumerable.Select() and IEnumerable.Where() to get an idea how to use it for your particular purposes.</p>\n\n<p>Select: <a href=\"http://msdn.microsoft.com/en-us/library/bb548891.aspx\">http://msdn.microsoft.com/en-us/library/bb548891.aspx</a></p>\n\n<p>Where: <a href=\"http://msdn.microsoft.com/en-us/library/bb534803.aspx\">http://msdn.microsoft.com/en-us/library/bb534803.aspx</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T23:01:33.857",
"Id": "6499",
"Score": "0",
"body": "Is this actually more performant than the forward looking `XMLReader` approach? I haven't yet had to use Linq2XML, but it's hard to imagine that random access could be faster than a stream-like reader. Interesting, I'll have to run some tests as we use an XML based API at work which involves a fair amount of parsing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T23:09:19.523",
"Id": "6500",
"Score": "0",
"body": "@Ed sorry my memory fails me, I was thinking of the old XmlDocument not XmlReader, XmlReader is quite performant: http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T02:05:05.573",
"Id": "6507",
"Score": "0",
"body": "Ok, that makes sense. The old DOM based XML classes are relatively slow."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T22:38:45.173",
"Id": "4345",
"ParentId": "4343",
"Score": "5"
}
},
{
"body": "<p>I always prefer working with POCO objects instead of Xml documents. If I correctly understand, you just want to parse an xml file into a set of objects.</p>\n\n<p>To do so you need to:</p>\n\n<ol>\n<li><p>Define objects model - that's it, just create a set of classes you want to get after deserialization. There are should be a root class that stands for the root xml element.</p></li>\n<li><p>Put correct attributes into the properties of the classes. That's how you will bind properties with xml elements/attributes</p></li>\n<li><p>Use XmlSerializer to deserialize the file into a normal POCO classes.</p></li>\n</ol>\n\n<p>See a good explanation here - <a href=\"http://www.agiledeveloper.com/articles/XMLSerialization.pdf\" rel=\"nofollow\">http://www.agiledeveloper.com/articles/XMLSerialization.pdf</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T21:59:04.840",
"Id": "6544",
"Score": "0",
"body": "I agree, but you can't always control the format of the XML coming in. Built in serialization is great for saving state between sessions or generating things only your app will consume, but (for example) if your XML is coming from some WebService there is very little chance that it will \"just work\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T06:11:48.757",
"Id": "6568",
"Score": "0",
"body": "I agree, that it might be tricky sometimes. But in the core, your web service consumer should use xml only as intermediate data source. It might be not as easy as I explained to get domain model objects from xml, but we should aim for it..."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T17:17:00.030",
"Id": "4360",
"ParentId": "4343",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4345",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T22:21:55.730",
"Id": "4343",
"Score": "3",
"Tags": [
"c#",
"xml"
],
"Title": "Reading XML in C#"
}
|
4343
|
<p>Running the same test 10,000 times with cProfile tells me that most of the damage happens in the count() function. This is my attempt at a solution to the Quadrant Queries challenge from InterviewStreet (the problem statement can be found <a href="http://pastie.org/2420315" rel="nofollow">here</a>). </p>
<p>According to InterviewStreet, I passed 3/11 testcases and I ran out of CPU time. I have no way of knowing whether I was 3 for 3 and ran out of time or say, 3 for 6 and ran out of time. I don't know if my code works on all input.</p>
<p>Please help me optimize this code:</p>
<pre><code>def reflect_x(i, j, coordinates):
for pair in xrange(i-1, j):
coordinates[pair][1] = -coordinates[pair][1]
return coordinates
def reflect_y(i, j, coordinates):
for pair in xrange(i-1, j):
coordinates[pair][0] = -coordinates[pair][0]
return coordinates
def count(i, j, coordinates):
quad_one, quad_two, quad_three, quad_four = 0, 0, 0, 0
for pair in xrange(i-1, j):
x, y = coordinates[pair][0], coordinates[pair][1]
if x >= 0 and y >= 0:
quad_one += 1
elif x < 0 and y >= 0:
quad_two += 1
elif x < 0 and y < 0:
quad_three += 1
elif x >= 0 and y < 0:
quad_four += 1
print "%d %d %d %d" % (quad_one, quad_two, quad_three, quad_four)
def reflect(coordinates, queries):
for query in queries:
if query[0] == "X":
reflect_x(query[1], query[2], coordinates)
elif query[0] == "Y":
reflect_y(query[1], query[2], coordinates)
elif query[0] == "C":
count(query[1], query[2], coordinates)
else:
print query
if __name__ == "__main__":
N = int(raw_input())
coordinates = [[int(pair[0]), int(pair[1])] for pair in (pair.split() for pair in (raw_input() for i in xrange(N)))]
Q = int(raw_input())
queries = [[query[0], int(query[1]), int(query[2])] for query in (query.split() for query in (raw_input() for i in xrange(Q)))]
reflect(coordinates, queries)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T05:09:12.513",
"Id": "6508",
"Score": "0",
"body": "Add the code from pastie here that is relevant and also be specific about what you need help with. http://codereview.stackexchange.com/questions/how-to-ask"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T06:19:50.290",
"Id": "6509",
"Score": "0",
"body": "It's all relevant .."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T14:24:24.403",
"Id": "6698",
"Score": "0",
"body": "These sites are full of questions like this. In the first place, you need to know about costly lines of code, not just functions. [Try this method](http://stackoverflow.com/questions/4295799/how-to-improve-performance-of-this-code/4299378#4299378)."
}
] |
[
{
"body": "<p>to optimise your count try:</p>\n\n<pre><code>def count(i, j, coordinates):\n quad_one, quad_two, quad_three, quad_four = 0, 0, 0, 0\n current_coordinates = coordsinates[i-1:j]\n\n for pair in current_coordinates:\n x, y = pair[0], pair[1]\n ...\n</code></pre>\n\n<p>And see if that reduces it. I'm not sure what is quicker a slice or an <code>xrange()</code></p>\n\n<p>just as a note: your <code>N=</code> and <code>Q=</code> is (IMHO) an almost unreadable mess. <em>(can you not read everything in and then proccess it?)</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T07:06:09.047",
"Id": "4349",
"ParentId": "4347",
"Score": "0"
}
},
{
"body": "<p>Consider changing your algorithm to perform the task. Every operation that you need to do takes some calculation to perform the operation. Not necessarily cheap as far as the test cases thrown at you are concerned. </p>\n\n<ul>\n<li>Reflect X: for every point in the range, negate the x coordinate</li>\n<li>Reflect Y: for every point in the range, negate the y coordinate</li>\n<li>Count: for every point in the range, count how many lie on each quadrant</li>\n</ul>\n\n<p>Your code appears to be a simple naive implementation to perform these operations and that alone isn't necessarily bad. However if you're taking too much time for their test cases, you need to reconsider your algorithm, how you represent the data and how you perform the calculations if the naive implementation is too slow.</p>\n\n<p>Every operation is an <code>O(n)</code> one. Count will suffer the most since you're trying to figure out which quadrant each point belongs to as you come up with the counts. Profiling your code against your test cases will not be very effective as you can bet they will have a lot more to throw at you. You need to find out how you can reduce these <code>O(n)</code> algorithms somehow to pass their tests. In fact, you can reduce Count to be <code>O(1)</code> with the algorithms I have in mind (the other two will have the same complexity however).</p>\n\n<p>Rather than just giving you the answer, I'll provide some pointers.</p>\n\n<ol>\n<li><p><strong>Is there another way you could effectively count something within a range?</strong><br>\nI'm not sure how I can really explain this but consider this example:<br>\n<br>\nSuppose you kept track of your balance at the bank for every day in the month. You'd have data such as this:<pre>\n1 $5000\n2 $5020\n3 $4980\n4 $4780\n5 $5280\n6 $5280\n7 $5580\netc...\n</pre>How would you determine how much money you earned/lost between day 1 and day 2? How about day 2 and day 4? Is there a way to represent this problem in a similar fashion?</p></li>\n<li><p><strong>Think about what representation of your information is really important here.</strong><br>\nYour code stores a collection of points. Whenever you need to perform the count, you would have to determine what quadrant the point belongs and increment to the appropriate counter. But do you <em>really</em> need to keep track of the coordinates for each point? If you represented the data in another way, would you still be able to perform the three operations that are required while still maintaining the information you need? What would that representation be?</p></li>\n</ol>\n\n<p>If you can answer these, I'll expand more on my answer and we'll probably work out a nice solution together. I'll probably share my answer too (though I haven't actually run it against their tests).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T07:26:01.270",
"Id": "6511",
"Score": "0",
"body": "Hopefully you'll have a revelation seeing this and it will all click."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T09:39:21.943",
"Id": "6526",
"Score": "0",
"body": "I'll face these challenges after I wake up. Hopefully I will be able to think more clearly tomorrow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T15:58:49.083",
"Id": "6538",
"Score": "0",
"body": "The first point here is the main focus, the second will save you a few more cycles but it's not as important to the first."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T02:56:20.657",
"Id": "6561",
"Score": "0",
"body": "1. My first thought is to subtract the balance of day 2 from that of day 1, but I don't see how this can be applied to the challenge I'm working on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T03:10:01.560",
"Id": "6562",
"Score": "0",
"body": "That's pretty much the idea. As long as you have cumulative totals between two distinct times, you can determine how much the total has changed between the two. In your case here, you want to find how many points in the range of point `i` (the first \"time\") and point `j` (the second \"time\") lie in each of the four quadrants. So the algorithm I had in mind is to keep a running total for each of the quadrants for each of the points. When the time comes to count how many of each lie in a range, you'd use the same technique here to determine those counts. You can calculate that immediately."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T22:23:03.120",
"Id": "6636",
"Score": "0",
"body": "Well, I just submitted my solution to this using this algorithm in mind and it was considered suboptimal."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T07:19:18.173",
"Id": "4350",
"ParentId": "4347",
"Score": "1"
}
},
{
"body": "<pre><code>def reflect_x(i, j, coordinates):\n for pair in xrange(i-1, j):\n coordinates[pair][1] = -coordinates[pair][1]\n return coordinates\n</code></pre>\n\n<p>Something like:</p>\n\n<pre><code>def reflect_x(i, j, coordinates):\n coordinates[i-1:j] = ((x,-y) for x,y in coordinates[i-1,j])\n</code></pre>\n\n<p>Is clearer and possibly slightly faster. Also, modify or return, don't do both.</p>\n\n<pre><code>def count(i, j, coordinates):\n quad_one, quad_two, quad_three, quad_four = 0, 0, 0, 0\n</code></pre>\n\n<p>If you have a count attached to your variable, the probably means it should be a list</p>\n\n<pre><code> quad = [0] * 4\n\n for pair in xrange(i-1, j):\n</code></pre>\n\n<p>You may be better off slicing the list. That will be happen entirely in C, but looking up the value each time happens in python.</p>\n\n<pre><code> x, y = coordinates[pair][0], coordinates[pair][1]\n</code></pre>\n\n<p>Same as:</p>\n\n<pre><code> x, y = coordinates[pair]\n</code></pre>\n\n<p>...</p>\n\n<pre><code> if x >= 0 and y >= 0:\n quad_one += 1\n elif x < 0 and y >= 0:\n quad_two += 1\n elif x < 0 and y < 0:\n quad_three += 1\n elif x >= 0 and y < 0:\n quad_four += 1\n\n print \"%d %d %d %d\" % (quad_one, quad_two, quad_three, quad_four)\n\ndef reflect(coordinates, queries):\n</code></pre>\n\n<p>bad name, this function doesn't only reflect</p>\n\n<pre><code> for query in queries:\n if query[0] == \"X\": \n reflect_x(query[1], query[2], coordinates)\n elif query[0] == \"Y\":\n reflect_y(query[1], query[2], coordinates)\n elif query[0] == \"C\":\n count(query[1], query[2], coordinates)\n else:\n print query\n\nif __name__ == \"__main__\":\n N = int(raw_input())\n coordinates = [[int(pair[0]), int(pair[1])] for pair in (pair.split() for pair in (raw_input() for i in xrange(N)))]\n</code></pre>\n\n<p>You don't need to do everything on one line. You can also unpack the tuple in the for clause.</p>\n\n<pre><code> coordinate_lines = (raw_input() for i in xrange(N))\n coordinates = [(int(x),int(y)) for x,y in line.split for line in coordinate_lines]\n</code></pre>\n\n<p>As for optimisation: Firstly, you need to realise that you don't actually care what the coordinates are. All you care about is the quadrants. The reflection operations merely move you from one quadrant to the other.</p>\n\n<p>I have to disagree with Jeff Mercado, as I don't think his approach will work. (maybe I've missed what he's hinting at.) Basically what you have is a worst case O(N*Q) running time. Since both N and Q are large numbers you cannot get away with doing that. His approach reduces the complexity to O(1) for the count operation, but leaves O(N) for the reflect operations. That's still going to give you O(N*Q).</p>\n\n<p>We need to reduce the cost of the reflect operations as well.</p>\n\n<p>Basically, for each quadrant we need to keep track of the points in that quadrant. We'll put them in some sort of data structure. We need a data structure that will allow the efficient implementation of:</p>\n\n<ol>\n<li>Finding all points with indexes between a start/stop index</li>\n<li>Swapping those points between two different versions of the data structure</li>\n<li>Finding the count of all points currently in the data structure</li>\n</ol>\n\n<p>Basically, we need all of these operations in logarithmic time or better. Figuring out what kind of data structure gives you that is left as an exercise for the reader.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T21:53:03.797",
"Id": "6543",
"Score": "0",
"body": "The time complexities I was mentioning were with respect to each operation individually, not when you factor in the different queries that's being done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T22:57:25.773",
"Id": "6546",
"Score": "0",
"body": "@Jeff Mercado, I know. But its the entire program that is running out of time. We can optimize count, but that still leaves reflect as fairly ineffiecient."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T23:20:48.103",
"Id": "6547",
"Score": "0",
"body": "I'd say, take this one step at a time. Solutions for problem sets like this could be submitted as many times as necessary AFAIK. He has determined that count is the killer here so I'd first start at optimizing that. If the optimizations yield an acceptable solution, then make efforts to optimize other parts of the program. Personally, I don't think it would be possible to optimize both counting and reflecting, both types of operations are dependent on each other so one would have to choose which. I could be wrong though as nothing comes to mind at the moment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T23:48:55.470",
"Id": "6552",
"Score": "0",
"body": "@Jeff, that is a perfectly valid approach. But I don't think it'll work. As it is, my curiosity was piqued so I wrote my own solution which has O(log n) for all operations but I'm still not fast enough to satisfy the online judge."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T03:24:55.977",
"Id": "6563",
"Score": "0",
"body": "@Winston Ewert, why does the data structure need to be able to swap between only two different versions? Since there are 4 quadrants, shouldn't we be able to switch between four different versions of the data structure? Or am I misunderstanding something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T03:35:12.713",
"Id": "6564",
"Score": "0",
"body": "@Winston Ewert -- Am I looking for an ordered data structure? (i.e. a list is ordered, a dictionary is not)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T12:14:04.790",
"Id": "6574",
"Score": "0",
"body": "@James, you only need to swap between two at a time. You can then do two swaps. The data structure is ordered. However, as I've noted above, my version doesn't pass the online validator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:04:52.940",
"Id": "6590",
"Score": "0",
"body": "@Winston -- According to the InterviewStreet support team, O(log n) should be sufficient. Send an email to support@interviewstreet.com and they'll help you figure out whats up."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T00:59:09.213",
"Id": "6597",
"Score": "0",
"body": "@James, okay I've contacted them. I've also micro-optimized a C++ version of the algorithm that now passes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T11:00:24.017",
"Id": "6607",
"Score": "0",
"body": "@Winston -- You said that I need a data structure that will allow for finding all points with indexes between a start an stop index. Should I be looking for a list/array? Congratulations on submitting a working solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:28:55.253",
"Id": "6609",
"Score": "0",
"body": "@James, no. It isn't a data structure that is built into in any language (as far as I know.) But if you've had any CS training you'll have been taught about it. You'll also need to augment the structure in order to effeciently count items."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:52:32.010",
"Id": "6611",
"Score": "0",
"body": "@Winston -- I've only had a single CS course so far, an introductory programming course in Java. I won't get to take an algorithms course until January, so for now I'm stuck teaching myself."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:57:53.367",
"Id": "6612",
"Score": "0",
"body": "@James, that puts you at a distinct disadvantage. You are going to have a hard time solving these problems without a knowledge of data structures/algorithms. (Although I've now solve 3/5 problems, and this is the only one that required the building of a custom data structure). The data structure that I used was a binary tree. However, I had to modify the rules for binary trees to suit my purposes."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T13:01:38.087",
"Id": "6613",
"Score": "0",
"body": "@Winston -- I've been trying to solve this one for three days now. I like hard problems. :P Now that I know what type of data structure you used, maybe I can make some progress."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T16:52:26.970",
"Id": "4359",
"ParentId": "4347",
"Score": "3"
}
},
{
"body": "<p>I wrote a solution which takes all the reflections and combines them into a single set of reflection instructions. For example, X i j followed by Y i j is equivalent to a single \"diagonal\" reflection, i.e. all points from first quadrant to to 3 rd quadrant. This was no easy task as you can imagine, but it is correct. The result is that the complexity is still O(N) but it is done efficiently, i.e. instead of first doing an X reflection followed by a Y reflection, we do a single reflection. Unfortunately, this did not pass the online judge either.</p>\n\n<p>The perplexing thing here is that this is the cheapest/easiest problem of the lot, and I don't think it is easy. I already solved Meeting Point, and this seems to be harder than that.</p>\n\n<p>The only thing I can think of is that there is a conservation of points, i.e. reflections do not destroy create points, so the four running totals are not independent. We only need to keep track of two for example and the total. However, this isn't really a big realization which to my mind.</p>\n\n<p>Bottom line. This is a tough problem.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T07:46:43.757",
"Id": "6713",
"Score": "0",
"body": "If it helps, a support member told me the solution must be at least O(lg n * Q)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T14:26:55.810",
"Id": "4484",
"ParentId": "4347",
"Score": "0"
}
},
{
"body": "<p>I've managed to get a submission past the CPU limit, using an approach similar to what Winston Ewert describes above. First I tried it in Ruby, and hit a wall at 5/11 test cases. Switching to Java immediately brought it to 9/11, and a little more optimization got it through.</p>\n\n<p>The CPU limits to this problem are extremely tight. I have doubts whether any interpreted language will be able to meet them, unless there is a better data structure than the one I used. Using a compiled language, the time limits are supposed to be 1/4 of that of an interpreted language, but it is way more than 4 times as fast. My recommendation would be to validate your approach using Python or whatever, then reimplement in Java or C.</p>\n\n<p>If you are using Java, one general hint is to buffer both standard input and output. In my last few attempts, the most time was spent just reading the input and outputting the result. Avoid the use of java.util.Scanner, as it appears to be a real dog.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T20:49:45.300",
"Id": "6754",
"Score": "0",
"body": "+1. I am also quite convinced this is impossible to solve with Python. I wrote a python implementation using the \"correct\" algo/data structure, and got 5/11. I recoded it using string hackery, and got 9/11 with python even though the implementation was O(N*Q). I then ported the \"correct\" python code to java, and got 10/11, made a few modifications, and solved it."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T22:19:43.257",
"Id": "4504",
"ParentId": "4347",
"Score": "1"
}
},
{
"body": "<p>I've tried this problem a number of different ways and I'm still not getting past the speed checks. I've tried using lists and sets as my data structure, and both don't have the required asymptotic performance. @Winston Ewert is right: you need at least O(log N) time for all three operations, and the best way to do this is with a binary search tree.</p>\n\n<p>The way I'm trying to do this is have four BSTs, one for each quadrant. Here's my sketch of the tree so far:</p>\n\n<pre><code>class Node:\n left, right, index, count = None, None, 0, 0\n\n def __init__(self, data):\n self.left = None\n self.right = None\n self.data = data\n self.count = 1\n\nclass Tree:\n root = None\n\n def __init__(self):\n self.root = None\n\n def add_node(self, data):\n return Node(data)\n\n def insert(self, root, data):\n if root == None:\n return self.add_node(data)\n else:\n root.count += 1\n if data < root.data:\n root.left = self.insert(root.left, data)\n else:\n root.right = self.insert(root.right, data)\n return root\n\n def find(self, root, target):\n if root == None:\n print \"Error in find (\", target, \"): root is None\"\n return 0\n else:\n if target == root.data:\n return root\n elif target < root.data:\n return self.find(root.left, target)\n else:\n return self.find(root.right, target)\n</code></pre>\n\n<p>The <em>data</em> variable will be the index of the node in the list representation of the coordinates we are handed. The whole point of using a BST here, as I see it, is that we can potentially move a whole segment of points from one quadrant to another by grabbing a node that the segment as a whole is descended from and inserting that <em>node</em> into the new tree, updating the <em>count</em> parameter of the tree as we go. To do that we need a method for inserting nodes into trees:</p>\n\n<pre><code> def insert_node(self, root, node):\n if root == None:\n return node\n else:\n root.count += node.count\n if node.data < root.data:\n root.left = self.insert_node(root, node)\n else:\n root.right = self.insert_node(root, node)\n return root\n</code></pre>\n\n<p>The tricky method, which I'm not sure how to do yet, is the part that grabs the interval in question but no more than that. Obviously, we do not get a specific [i, j] to look for in the tree, since we don't know which tree i and j are in. We only get a range. This method will grab the first node that falls in the range of [i, j] in the tree:</p>\n\n<pre><code> def find_in_range(self, root, i, j):\n if root == None:\n print \"Error in find_in_range (\", i, j, \"): root is None\"\n return 0\n else:\n if i <= root.data and root.data <= j:\n return root\n elif root.data > i and root.data > j:\n return self.find_in_range(root.left, i, j)\n elif root.data < i and root.data < j:\n return self.find_in_range(root.right, i, j)\n else:\n print \"Error in find_in_range(\", i, j, \"): no criteria matched\"\n</code></pre>\n\n<p>In the case where we recurse left and then find a node in the range, everything descended from the right of that node onwards is in the interval [i, inf), so we can just call find_in_range again with new parameters and fight the right end node. A little snipping here and there and we'll have selected exactly the nodes in [i, j] in our quadrant. The same argument works if we recurse right.</p>\n\n<p>The problem I'm having is that if we start the first find_in_range and we're <em>already in the range</em>, I don't know where the end-points are. Does anyone have a suggestion for me? If I can solve this problem, the rest is just details.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T04:06:15.860",
"Id": "6727",
"Score": "1",
"body": "If you want comments on your code, I recommend opening your own question not posting an answer in somebody else's question. Also, questions about algorithms like that should be stackoverflow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T04:36:11.120",
"Id": "6728",
"Score": "0",
"body": "@Winston My mistake, I haven't been on this site very long and there wasn't any way to reply the discussion you and James were having."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T00:13:55.537",
"Id": "4505",
"ParentId": "4347",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T03:42:45.227",
"Id": "4347",
"Score": "2",
"Tags": [
"python",
"optimization",
"performance",
"programming-challenge"
],
"Title": "Quadrant Queries challenge"
}
|
4347
|
<p>I have an abstract class which holds a hook method for a template method. Not all classes which extend this class will need to implement this method (in fact most will not, but a few will). As such I declared the method this way:</p>
<pre><code>protected void applyExtraCriteria(Object extraCriteria) {
}
</code></pre>
<p>Should it instead be declared this way:</p>
<pre><code>protected abstract void applyExtraCriteria(Object extraCriteria);
</code></pre>
<p>Which one would be considered better practice?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T00:51:19.130",
"Id": "6558",
"Score": "3",
"body": "As a rule you really should never implement an empty method in any class. If you want the method available to consumers of the abstract classes inheritors, declare it abstract. If you don't want to implement it on an inheritor because it doesn't make sense, then it should most likely throw an `InvalidOperationException` in the implementation of that inheritor. Which means you may want your abstract class to have an `public abstract bool ExtraCriteriaAllowed { get; };` so consumers can know whether or not to use the method."
}
] |
[
{
"body": "<p>I would declare as required by all classes. It is easy enough to leave an empty method stub in the sub class.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T18:32:49.100",
"Id": "4363",
"ParentId": "4362",
"Score": "10"
}
},
{
"body": "<p>I agree with IAbstract's answer, but I want to expand upon it with my own 2 cents. </p>\n\n<p>The abstract base should make no assumptions as to whether or not the derived children will \"need\" the method. Indeed, if it does make the assumption, assume the children absolutely need it. </p>\n\n<p>In addition, providing an empty implementation in the abstract base would possibly lead to children believing there is, in fact, some default implementation that might actually <em>do</em> something. You might have children overriding the method with an empty implementation simply because they do not want anything done! </p>\n\n<p>(I realize you may likely be the one writing both the base and the child, but I think it is best to mentally seperate your own roles. When you're writing the base, you're the provider. When you're writing the child, you're the consumer. As a provider, develop the base in a way that will make most sense to your consumers.)</p>\n\n<p>Make the method abstract. Let the children decide what (if any) implementation there needs to be for each step of the algoritm, following in the spirit of the template method patterm.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T20:17:25.340",
"Id": "4368",
"ParentId": "4362",
"Score": "3"
}
},
{
"body": "<p>If you are <em>really sure</em> that an empty method body is okay for most sub-classes, you could follow the example of Swing listeners (e.g. <code>WindowListener</code> / <code>WindowAdapter</code>): Make the methods in your <code>Foo</code> class abstract, but provide an abstract class called <code>FooAdapter</code> extending <code>Foo</code>, which implements that methods with empty bodies. That way you document your intentions: The methods must be implemented, but by extending the <code>FooAdapter</code> you say that you want for most of them the default implementation (which happens to have empty method bodies).</p>\n\n<p><strong>Update</strong>: Of course, if you can use Java 8, you can write default methods in interfaces, hence an abstract class isn't needed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:26:00.157",
"Id": "6608",
"Score": "0",
"body": "Many frameworks have these Adapter classes, so I don't think that extra level of abstraction would be difficult for others on my team to grasp."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T06:21:19.633",
"Id": "4379",
"ParentId": "4362",
"Score": "8"
}
},
{
"body": "<p>I think it's better to distinguish between two cases here:</p>\n\n<ul>\n<li><p>For a template method I believe it's better to have empty virtual\nmethod in base class. If you don't need to add any functionality you\njust ignore this part, but you will add some code only if you need to. This is exactly your case.</p></li>\n<li><p>For a public method I believe it's better to have abstract method in base class. It's very unusual situation that your public method does no-op and at the same time you will not forget to implement it.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T07:26:53.567",
"Id": "4380",
"ParentId": "4362",
"Score": "3"
}
},
{
"body": "<p>Only methods that required to be implemented in subclasses should not have a default implementation. Other methods, whose implementation in subclasses is optional, can have it. The providing a default implementation is a way to say that a custom implementation for a method is not required.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T07:21:40.863",
"Id": "4407",
"ParentId": "4362",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4379",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T18:18:18.313",
"Id": "4362",
"Score": "8",
"Tags": [
"java",
"object-oriented"
],
"Title": "Empty method in abstract class"
}
|
4362
|
<p>I recently discovered/came across <a href="/questions/tagged/linq" class="post-tag" title="show questions tagged 'linq'" rel="tag">linq</a> and have been trying to learn and utilize its features. Here's my first function <code>UpdateTransactionsData()</code>. This method is for a <code>PurchaseDocument</code> class which I have included partially. Basically this function loops through the selected items on the <code>PurchaseDocument</code>, and works out which accounts (chart of accounts, as per accounting) are to be credited/debited for each purchased item. </p>
<p>After I have populated the dictionary properties with the transaction amounts, I use Linq to first remove all the transactions with amount 0 and then to generate XML elements to represent the transactions (provided a sample of the output).</p>
<p>The code works. Am I using LINQ right? Is the code optimal? Can I improve the LINQ code? Should I even be using it?</p>
<p><strong>XmlOutput</strong></p>
<pre class="lang-xml prettyprint-override"><code><Debit Account="26" Amount="36" />
<Debit Account="24" Amount="188.7" />
<Debit Account="80" Amount="-29.21" />
<Credit Account="57" Amount="253.91" />
<Inventory Item="22007" Adjustment="10" />
<Inventory Item="11389" Adjustment="5" />
</code></pre>
<p><strong>PurchaseDocument.cs</strong></p>
<pre class="lang-cs prettyprint-override"><code>public class PurchaseDocument
{
public Dictionary<int, double> DebitTransactions = new Dictionary<int, double>();
public Dictionary<int, double> CreditTransactions = new Dictionary<int, double>();
public Dictionary<int, double> InventoryTransactions = new Dictionary<int, double>();
#region public ObservableCollection<PurchaseDocumentItem> Items;
private ObservableCollection<PurchaseDocumentItem> _Items = new ObservableCollection<PurchaseDocumentItem>();
public ObservableCollection<PurchaseDocumentItem> Items
{
get { return _Items; }
set
{
string property = "Items";
OnPropertyChanging(property);
_Items = value;
OnPropertyChanged(property);
}
}
#endregion
private void UpdateTransactionsData()
{
DebitTransactions.Clear();
CreditTransactions.Clear();
InventoryTransactions.Clear();
Entity.TransactionsData = "";
foreach (PurchaseDocumentItem item in Items.Where(x => x.InventoryItem != null))
{
// asset and expense transactions
int account = (item.InventoryItem.IsService) ? item.InventoryItem.CogsAccountID : item.InventoryItem.AssetAccountID;
if(!DebitTransactions.ContainsKey(account))
DebitTransactions.Add(account, 0);
DebitTransactions[account] += item.Amount;
// inventory transaction
if (!item.InventoryItem.IsService)
{
if(!InventoryTransactions.ContainsKey(item.ItemID))
InventoryTransactions.Add(item.ItemID, 0);
InventoryTransactions[item.ItemID] += item.Quantity;
}
}
// tax transaction
int taxaccount = Session.Company.PurchasesTaxAccountID;
if(!DebitTransactions.ContainsKey(taxaccount))
DebitTransactions.Add(taxaccount, 0);
DebitTransactions[taxaccount] -= (double)Tax;
// freight transaction
int freightaccount = Session.Company.FreightExpenseAccountID;
if(!DebitTransactions.ContainsKey(freightaccount))
DebitTransactions.Add(freightaccount, 0);
DebitTransactions[freightaccount] += (double)Freight;
// payables transaction
int payablesaccount = Session.Company.AccountsPayableID;
if(!CreditTransactions.ContainsKey(payablesaccount))
CreditTransactions.Add(payablesaccount, 0);
CreditTransactions[payablesaccount] += (double)Total;
// take out all transaction with amount 0
DebitTransactions = DebitTransactions.Where(x => x.Value != 0).ToDictionary(x => x.Key, x => x.Value);
CreditTransactions = CreditTransactions.Where(x => x.Value != 0).ToDictionary(x => x.Key, x => x.Value);
InventoryTransactions = InventoryTransactions.Where(x => x.Value != 0).ToDictionary(x => x.Key, x => x.Value);
// convert the data to xml
Entity.TransactionsData += DebitTransactions.Aggregate("", (data, t) => data + "<Debit Account=\"" + t.Key.ToString() + "\" Amount=\"" + t.Value.ToString() + "\" />" + Environment.NewLine);
Entity.TransactionsData += CreditTransactions.Aggregate("", (data, t) => data + "<Credit Account=\"" + t.Key.ToString() + "\" Amount=\"" + t.Value.ToString() + "\" />" + Environment.NewLine);
Entity.TransactionsData += InventoryTransactions.Aggregate("", (data, t) => data + "<Inventory Item=\"" + t.Key.ToString() + "\" Adjustment=\"" + t.Value.ToString() + "\" />" + Environment.NewLine);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>I don't see any problem with the LINQ you have.</p>\n\n<p>If you wanted, you could use a little bit of LINQ to get rid of that foreach loop you have. You can create two LINQ queries to query the Items collection, group accounts/items together, and return the sum of the Amounts/Quantities as a Dictionary:</p>\n\n<pre><code>DebitTransactions = (from item in Items\n where item.InventoryItem != null\n\n let account = (item.InventoryItem.IsService) ? item.InventoryItem.CogsAccountID : item.InventoryItem.AssetAccountID\n\n group item by account into itemGroup\n select new \n {\n Account = itemGroup.Key,\n Amount = itemGroup.Sum(i => i.Amount)\n }).ToDictionary(k => k.Account, v => v.Amount);\n\nInventoryTransactions = (from item in Items\n where item.InventoryItem != null && !item.InventoryItem.IsService\n\n group item by item.ItemID into itemGroup\n select new\n {\n ItemID = itemGroup.Key\n Quantity = itemGroup.Sum(i => i.Quantity)\n }).ToDictionary(k => k.ItemID, v => v.Quantity);\n</code></pre>\n\n<p>It's a little more messy and probably a little less efficient, but good for learning LINQ.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T20:24:07.293",
"Id": "6541",
"Score": "0",
"body": "Ahh that's great, thanks for your help! Learning a few more things from your code :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T19:56:49.943",
"Id": "4367",
"ParentId": "4364",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4367",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T18:35:32.790",
"Id": "4364",
"Score": "6",
"Tags": [
"c#",
"linq",
"finance"
],
"Title": "Determining which accounts are to be credited/debited"
}
|
4364
|
<p>Sometimes, I need to map from a Domain entity to a ViewModel - to display information.</p>
<p>Other times, I need to map from a ViewModel to a Domain entity - for persistance of data.</p>
<p>Is this kosher or does this code smell?</p>
<pre><code>protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
MapObjects();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
private void MapObjects()
{
Mapper.CreateMap<UserModel, User>();
Mapper.CreateMap<ProductBrandModel, ProductBrand>();
Mapper.CreateMap<ProductBrand, ProductBrandModel>();
Mapper.CreateMap<ProductCategoryModel, ProductCategory>();
Mapper.CreateMap<ProductCategory, ProductCategoryModel>();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T01:01:23.343",
"Id": "6560",
"Score": "1",
"body": "I am thoroughly unfamiliar with this mapper stuff, I'm guessing based on the route things I see this is a part of the asp.net mvc which I haven't worked with. That said, even to my eyes I would say this absolutely smells funny. My immediate thought is try drawing your `ProductBrandModel` and `ProductBrand` on a whiteboard showing their relationships, then see if you can't turn make the relationships one way by breaking either of them up such that no two-way relationship exists between any of the classes on the whiteboard."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T05:42:54.043",
"Id": "6722",
"Score": "0",
"body": "[This post](http://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/) by Jimmy Bogard might help."
}
] |
[
{
"body": "<p>Mapping to and from domain models and view models is exactly what automapper is designed for.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T14:25:31.213",
"Id": "4816",
"ParentId": "4369",
"Score": "3"
}
},
{
"body": "<p>This looks fine to me although you may want to extract it out in to a separate class if it starts to get bigger. I usually end up with an Init (or similar) folder with classes for IOC, ORM, Mapper and Routes (if they get big enough). Once out of the Global.asax you can test them if needed as well (not required for basic mappings in your example of course).</p>\n\n<p>Rename it to <code>RegisterViewMapper()</code> or similar and it will smell less.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T22:20:42.953",
"Id": "4827",
"ParentId": "4369",
"Score": "0"
}
},
{
"body": "<h3>Automapper ReverseMap</h3>\n\n<p>This is a more succint way to register your classes. <code>Automapper</code> is able to create a two-way mapping expression using <code>ReverseMap</code>.</p>\n\n<pre><code>private void MapObjects()\n{\n Mapper.CreateMap<UserModel, User>();\n Mapper.CreateMap<ProductBrandModel, ProductBrand>().ReverseMap();\n Mapper.CreateMap<ProductCategoryModel, ProductCategory>().ReverseMap();\n}\n</code></pre>\n\n<p>As opposed to the mirrored registration..</p>\n\n<blockquote>\n<pre><code>private void MapObjects()\n{\n Mapper.CreateMap<UserModel, User>();\n Mapper.CreateMap<ProductBrandModel, ProductBrand>();\n Mapper.CreateMap<ProductBrand, ProductBrandModel>();\n Mapper.CreateMap<ProductCategoryModel, ProductCategory>();\n Mapper.CreateMap<ProductCategory, ProductCategoryModel>();\n}\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-26T16:15:33.713",
"Id": "224973",
"ParentId": "4369",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-24T20:44:39.673",
"Id": "4369",
"Score": "4",
"Tags": [
"c#",
"automapper"
],
"Title": "Using AutoMapper to map to and from"
}
|
4369
|
<p>I've written the following small helper class for use in my WPF applications. It comes up from time to time that I need to display message boxes, or otherwise interact with the UI from a non UI thread.</p>
<pre><code>public static class ThreadContext
{
public static InvokeOnUiThread(Action action)
{
if (Application.Current.Dispatcher.CheckAccess())
{
action();
}
else
{
Application.Current.Dispatcher.Invoke(action);
}
}
public static BeginInvokeOnUiThread(Action action)
{
if (Application.Current.Dispatcher.CheckAccess())
{
action();
}
else
{
Application.Current.Dispatcher.BeginInvoke(action);
}
}
}
</code></pre>
<p>Here is a small example of how this might be used.</p>
<pre><code>public static MyFunction()
{
ThreadContext.InvokeOnUiThread(
delegate()
{
MessageBox.Show("Hello world!");
});
}
</code></pre>
<p>This works, but declaring the delegate the way I do seems overly verbose.</p>
<p>Is there anyway to make the syntax less verbose while still allowing for arbitrary functions to be passed? Is there anything else that you would suggest to improve this solution -- including an entirely different solution?</p>
|
[] |
[
{
"body": "<p>anonymous methods to the rescue! I saw somebody griping about this syntax recently on a blog and found it unfortunate they were dissimenating this. The cleaner new and happy way to define a delegate, is quite simply:</p>\n\n<p>The method signature without a name or types, so for example:</p>\n\n<pre><code>Sum(int a, int b)\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>(a, b)\n</code></pre>\n\n<p>Follow this with our trusty lambda operator <code>=></code> and then our method body! This may be in a statement block between our trusty <code>{}</code> or just in a single line the same way you can put a single line after an <code>if</code> or <code>while</code> etc.</p>\n\n<p>So in conclusion there are 3 ways to create a method:</p>\n\n<p>Standard (must be declared as class member level):</p>\n\n<pre><code>public int Sum(int a, int b)\n{\n return a+b;\n}\n</code></pre>\n\n<p>Delegate (can be declared and instantiated as a method local):</p>\n\n<pre><code>delegate(int a, int b)\n{\n return a+b; // god help me if this syntax is correct, I haven't created a delegate in years\n}\n</code></pre>\n\n<p>Anonymous method (can be declared and instantiated as a method local):</p>\n\n<pre><code>(a, b) => { return a+b; };\n</code></pre>\n\n<p>Back to your example...</p>\n\n<pre><code>ThreadContext.InvokeOnUiThread(\n delegate()\n {\n MessageBox.Show(\"Hello world!\");\n });\n</code></pre>\n\n<p>In anonymous method format becomes:</p>\n\n<pre><code>ThreadContext.InvokeOnUiThread(() => { MessageBox.Show(\"Hello world!\"); });\n</code></pre>\n\n<p>Or if you prefer:</p>\n\n<pre><code>Action actionToInvokeOnUiThread = () => { MessageBox.Show(\"Hello world!\"); };\nThreadContext.InvokeOnUiThread(actionToInvokeOnUiThread);\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T03:30:24.547",
"Id": "6600",
"Score": "0",
"body": "Nice breakdown. +1"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T00:33:18.707",
"Id": "4375",
"ParentId": "4371",
"Score": "4"
}
},
{
"body": "<p>I usually implement it like this:</p>\n\n<pre><code>public class Dialogs : IDialogs\n{\n public static void ShowError(string title, string message)\n {\n Application.Current.Dispatcher.Invoke(() => ShowErrorDialog(title, message));\n }\n\n void IDialogs.ShowError(string title, string message)\n {\n ShowError(title, message);\n }\n\n private static void ShowErrorDialog(string title, string message)\n {\n // pseudo code here\n var dialog = new ErrorDialog { Title = title, DataContext = message };\n dialog.ShowDialog();\n }\n}\n\npublic interface IDialogs\n{\n void ShowError(string title, string text);\n}\n</code></pre>\n\n<p>This allows for:</p>\n\n<ul>\n<li>Showing dialogs from the model as <code>IDialogs</code> can be defined anywhere without adding references to any WPF-assemblies.</li>\n<li>Mocking <code>IDialogs</code> in tests.</li>\n<li>Changing how error messages are rendered in one place.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-02-28T09:15:24.737",
"Id": "121350",
"ParentId": "4371",
"Score": "1"
}
},
{
"body": "<p>To improve upon @Johan Larsson's solution, you can implement a class for showing dialogs globally in a core library without the need to define the actual dialog control in the same library. The big difference (and gain) here is @Johan Larsson's solution assumes both are defined in the same assembly (not always possible), whereas the following does not.</p>\n\n<p>In core library (references <em>whatever</em>):</p>\n\n<pre><code>/// <summary>\n/// Provides facilities for showing a dialog anywhere.\n/// </summary>\npublic static class Dialog\n{\n /// <summary>\n /// Shows a dialog with an error message.\n /// </summary>\n /// <param name=\"title\"></param>\n /// <param name=\"message\"></param>\n public static void ShowError(string title, string message)\n {\n //If application implements the right interface and the instance returned is not null, call the appropriate method\n (Application.Current as IDialogHost)?.GetDialog()?.ShowError(title, message);\n }\n}\n\n/// <summary>\n/// Specifies a dialog.\n/// </summary>\npublic interface IDialog\n{\n void ShowError(string title, string text);\n}\n\n/// <summary>\n/// Specifies an element capable of hosting dialogs.\n/// </summary>\npublic interface IDialogHost\n{\n /// <summary>\n /// Gets a new instance of <see cref=\"IDialog\"/>.\n /// </summary>\n /// <returns></returns>\n IDialog GetDialog();\n}\n</code></pre>\n\n<p>In control library (references core library and <em>whatever</em>):</p>\n\n<pre><code>public class DialogControl : Window, IDialog\n{\n public void ShowError(string title, string message)\n {\n Content = message;\n Title = title;\n ShowDialog();\n }\n\n public DialogControl() : base()\n {\n }\n}\n</code></pre>\n\n<p>In assembly of current application (references core and control library and <em>whatever</em>):</p>\n\n<pre><code>public class MyApp : Application, IDialogHost\n{\n /// <summary>\n /// Initializes a new instance of the dialog type the current application supports.\n /// </summary>\n /// <returns></returns>\n IDialog IDialogHost.GetDialog()\n {\n return new DialogControl();\n }\n}\n</code></pre>\n\n<p>The reason <code>GetDialog</code> is implemented explicitly is to encourage the developer to use <code>Dialog</code> class for calls instead; otherwise, anytime you have a reference to the current application, you'd be able to get a new instance of a dialog (which serves no clear purpose on it's own).</p>\n\n<p>Now, any assembly that references the core library can show a dialog, assuming the current application that references it implements <code>IDialogHost</code>. In addition, each application can specify a different dialog control, though, realistically, you'll probably only ever use one.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-07T21:29:39.930",
"Id": "154751",
"ParentId": "4371",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4375",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T21:25:15.223",
"Id": "4371",
"Score": "3",
"Tags": [
"c#",
"multithreading",
"wpf"
],
"Title": "Helper methods for working with the WPF Dispatcher"
}
|
4371
|
<p>Does my code contain anything invalid?</p>
<pre><code><form name="myForm" id="myForm">
<table id="myTab">
<tr>
<td>
<label for="id">User ID:</label>
<input type="text" id="id" />
</td>
</tr>
<tr>
<td>
<label for="pass">Password:</label>
<input type="password" id="pass" name="pass" />
</td>
<td>
<button type="button" class="submit">Submit</button>
</td>
</tr>
<tr><td><input type="reset" /></td></tr>
</table>
<div class="error"></div><div class="correct"></div>
</form>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T05:25:52.130",
"Id": "6566",
"Score": "2",
"body": "Put your [URL here](http://validator.w3.org/). It will validate the page."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T06:37:58.693",
"Id": "6569",
"Score": "3",
"body": "If it's just html, don't `/` terminate single tags like `input`"
}
] |
[
{
"body": "<p>Mostly. According to <a href=\"http://validator.nu/\" rel=\"nofollow\">http://validator.nu/</a>:</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>Warning: A table row was 2 columns wide and exceeded the column count established by the first row (1).\nFrom line 16, column 18; to line 17, column 13\n </td>↩ </tr>↩\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T22:52:53.317",
"Id": "4373",
"ParentId": "4372",
"Score": "1"
}
},
{
"body": "<p>Set your first and last <code><tr></code> to have <code>colspan=\"2\"</code> so they have the same recognized column count as the second table row. Otherwise it's fine.</p>\n\n<p>I believe it's called XHTML or something when it's XML styling and may need some meta tags, but personally I like the closed tags when they're empty for your error/correct div's below to be <code><div class=\"error\" /><div class=\"correct\" /></code>, somebody else or a Google could speak to necessity of any doctype tags or other such junk for properly closed tags like that to be recognized as valid by clients.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T06:13:37.387",
"Id": "6603",
"Score": "1",
"body": "Self-closed `<div />` tags aren't handled correctly by many browsers even with an XHTML doctype."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T00:15:18.393",
"Id": "4374",
"ParentId": "4372",
"Score": "3"
}
},
{
"body": "<p>According to the W3C <a href=\"http://validator.w3.org/\">(http://validator.w3.org/)</a></p>\n\n<p>Your form tag is not valid.<br>\nTechnically it must have an action attribute:</p>\n\n<blockquote>\n <p>required attribute \"ACTION\" not specified in:<br>\n <form name=\"myForm\" id=\"myForm\"></p>\n \n <p>The attribute given above is required for an element that you've used, but you have omitted it.</p>\n</blockquote>\n\n<p>There are a couple of warnings:</p>\n\n<blockquote>\n <p>Warning: NET-enabling start-tag requires SHORTTAG YES<br>\n <input type=\"text\" id=\"id\" / ><br>\n ^^^ <!-- auto closing tag --></p>\n \n <p>The sequence can be interpreted in at least two different ways, depending on the DOCTYPE of the document. For HTML 4.01 Strict, the '/' terminates the tag '). However, since many browsers don't interpret it this way, even in the presence of an HTML 4.01 Strict DOCTYPE, it is best to avoid it completely in pure HTML documents and reserve its use solely for those written in XHTML. </p>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T05:32:09.223",
"Id": "4378",
"ParentId": "4372",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4378",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-24T21:43:23.930",
"Id": "4372",
"Score": "5",
"Tags": [
"html",
"html5",
"form"
],
"Title": "Is this password-submission form valid?"
}
|
4372
|
<p>In order to secure my page SESSIONS I have the following pages.</p>
<p>My questions are</p>
<ol>
<li>Am I over-reacting with this?</li>
<li>Should I place the token in login.php instead of the loginForm.php ? </li>
<li>When a user logins, I save his IP in the DB. Should I make use of this in authentication ?</li>
</ol>
<p>Thank you community.</p>
<p><strong>Login form loginForm.php</strong></p>
<pre><code>$token = md5(uniqid(rand(),TRUE));
<input name="login" type="text" class="textfield" id="login" />
<input name="password" type="password" class="textfield" id="password" />
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<input type="submit" name="Submit" value="Login" />
</code></pre>
<p><strong>When the user logins login.php</strong></p>
<pre><code>$fingerprint = sha1('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].$_POST['token']);
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['member_id'];
$_SESSION['SESS_TOKEN'] = $_POST['token'];
$_SESSION['SESS_FINGERPRINT'] = $fingerprint;
session_write_close();
header("location: index.php");
exit();
</code></pre>
<p><strong>Authenticating on every page auth.php</strong></p>
<pre><code> session_start();
$fingerprint = sha1('SECRET-SALT'.$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].$_SESSION['SESS_TOKEN']);
if( !isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '') || ($_SESSION['SESS_FINGERPRINT'] != $fingerprint) || !isset($_SESSION['SESS_TOKEN']) || (trim($_SESSION['SESS_TOKEN']) == '') ) {
header("location: denied.php");
exit();
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T19:19:01.297",
"Id": "6587",
"Score": "0",
"body": "It is not good to base your logins on IP. They change often for a large group of users. It's better to watch for **user patterns** and if the IP doesn't change for 6 requests - then it suddenly does - you might want to do something."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-02-19T02:42:55.377",
"Id": "465821",
"Score": "0",
"body": "Don't quote me on this but i think both IP address & .$_SERVER['REMOTE_ADDR'] can Change Especially for mobile devices, so You might be locking some users out of your application."
}
] |
[
{
"body": "<p>1) Overreacting is a question of how valueable your protected information is. My personal oppinion is that by the nature of digital computers and of the internet there is no such thing as overreacting in security. You either want something to be public or you do not, and in the latter case there is quite a bit of work and knowledge involved to counter all the different attacks. On the other hand, a lot of other people will say that if your protected information is not really valueable enough to hackers, then probably no hardcore hacker will invest enough time so your protection might not worth your programming efforts.</p>\n\n<p>2) In the code above you build your fingerprint by hashing a concatenation of different information about the remote user and the token is used as a kind of salt (in addition to 'SECRET-SALT') to make that hash unique. So the answer depends on how secure is your session storage.</p>\n\n<p>If you are alone on the server or you have a secure session storage for $_SESSION (like a password-protected database), then you do not need to worry about someone reading the contents of your session variables. This also means that protecting your fingerprint by hashing it is absolutely useless, in which case you can just remove the token and hashing from your code completely. In this case you also do not need a fingerprint, you can just store the user variables separately and compare them separately.</p>\n\n<p>If there is a way for your $_SESSION contents to leak, then you want to protect private information in it. In this case you will want to keep your token private and do not send it to the user, put it into login.php instead. Normally, you do not have to worry about protecting a salt because even if it is known it will increase the time considerably for a hacker to crack a password, not just because of the longer password string but also because precomputed rainbow tables become useless. But in your case you do not have a password, all you have is the user_agent and the IP, both of which are easily predictable or sniffable. This means that the concatenated information is basically no variable to the hacker, so the only thing keeping him from cracking your fingerprint are your salts. So if you reveal them, the hash becomes useless.</p>\n\n<p>To sum it up: If you want maximum securty in all situations, keep fingerprinting and hashing, but since your protected string is easily guessable, keep your token private this time. Theoretically even if your token is compromised 'SECRET-SALT' will still provide protection, but only as long as your code is safe. If your filesystem is hacked or the sources for the website your are building are public you cannot rely on 'SECRET-SALT' alone. Do not depend on hiding it, 'security by obscurity' is a bad practice.</p>\n\n<p>3) Generally you should not depend on the IP to stay consistent across a session. This is because for a lot of legitimate users the IP can keep changing constantly, this can be because they are behind corporate load balancing, they are using AOL or some other proxy network. A possible solution is to observe the IP of a session and if it is consistent for, say, 10 pages, then it is reasonable to assume that it will stay consistent in the future. So only then will you start making checks on it. However, storing it temporarily in a DB can still be of use, eg. for logging so that it can be analyzed what happened if there is an attack or so.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T10:23:28.520",
"Id": "6570",
"Score": "0",
"body": "This is a great answer. Thank you. At the end you suggest storing the sessions in a secure place is a great way. What are these places?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T13:50:12.683",
"Id": "6575",
"Score": "0",
"body": "Basically you have two choices to store sessions in a more secure way than the PHP default. (1) You can use the 'session.save_path' php setting to change the session files' folder to a private directory which is not shared wih a different site (and not world-readable). (2) Or you can implement your own storage functions and supply them to session_set_save_handler(). Your functins can then store session data to a passworded database or write to encrypted files etc."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T07:53:04.110",
"Id": "4381",
"ParentId": "4376",
"Score": "4"
}
},
{
"body": "<p>ultimA is absolutely right on his points, though security is such a large subject to cover, I would add this addenda:</p>\n\n<p>Generally you want data to be private or non-private, but in the cases that you may <em>want</em> it private but don't <em>need</em> it private due to its lack of value and usefulness, there is another consideration to take in the security implementation: leakiness of the abstraction</p>\n\n<p>That is to say, if the security is in such a way that everything you code has to consider and implement the security making it difficult to apply the abstraction and dry principles effectively, then ratchet it back. Unless your data's privacy is in the <em>need</em> category, then do your best to abstract it away but live with the misgivings.</p>\n\n<p>In short, if your data is in the <em>want</em> privacy but not <em>need</em> privacy category, implement as much security as you can up to but before the point where it becomes a spider's nest to maintain throughout the whole codebase.</p>\n\n<p>On another note, there is something to be said for the risk to security caused by overly difficult to implement/fragile security. If it becomes easy to make a mistake and implement the security incorrectly in one place, or downright break it on accident, then you are stepping into some risky waters.</p>\n\n<p>Just my two cents, though ultimA is also spot on in his points, like I said at the beginning, security is a massive subject and how much/how little to implement can have volumes written about it without repeating the same points.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T11:52:30.467",
"Id": "4383",
"ParentId": "4376",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4381",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T03:11:22.450",
"Id": "4376",
"Score": "2",
"Tags": [
"php",
"security"
],
"Title": "Am I over-reacting with my page SESSIONS security?"
}
|
4376
|
<p>I'm currently making a manga (read: comic) viewer in Python. This project has been a code-as-you-learn project, because I have been trying to code this as I learned about Tkinter. Python I have known for some time, but not too long.</p>
<p>Performance-wise, I'm worried about the image loading and resizing time; it seems slow. I found out one thing by experimenting: when resizing "P" type images it is a lot slower than converting it to "L" (greyscale) and then resizing. Also the fullscreen is buggy, but this (and other minor bugs, coding format problems) is because I have thrown this together and haven't really re-coded it nicely yet (as I often do after I learn what I want it to be like, if you understand what I mean). </p>
<p>Format-wise, I don't think I have the best organization there is, maybe there is a better practice to hold up, or multiple files maybe (but Python can't do this?)?</p>
<p>Once again there are a lot of little bugs, like scrolling with the keyboard reveals extra space on the bottom, and the folder viewer doesn't always scroll to the selected folder in the dialog, and I would like to know how to fix this, but I would like more to know some good practices and optimization for image loading and resizing.</p>
<pre><code>from Tkinter import *
from ttk import *
import Image, ImageTk, tkFileDialog, os
VERSION = "v0.0.3"
"""
folderDialog Class
Dialog that asks the user to select a folder. Returns folder and gets destroyed.
"""
class folderDialog(Toplevel):
def __init__(self, parent, callback, dir="./", fileFilter=None):
Toplevel.__init__(self, parent)
self.transient(parent)
self.title("Browse Folders")
self.parent = parent
self.dir = StringVar()
self.callback = callback
self.fileFilter = fileFilter
if os.path.exists(dir) and os.path.isdir(dir):
self.dir.set(os.path.abspath(dir))
else:
self.dir.set(os.path.abspath("./"))
self.body = Frame(self)
self.body.grid(row=0,column=0,padx=5,pady=5, sticky=(N,S,E,W))
Label(self.body, text="Please select a folder").grid(row=0,column=0, sticky=(N,S,W), pady=3)
Label(self.body, text="You are in folder:").grid(row=1,column=0, sticky=(N,S,W))
Entry(self.body, textvariable=self.dir, state="readonly").grid(row=2,column=0,sticky=(N,S,E,W),columnspan=2)
self.treeview = Treeview(self.body, columns=("dir", "imgs"), show="headings")
self.treeview.grid(row=3,column=0,sticky=(N,S,E,W),rowspan=3,pady=5,padx=(0,5))
self.treeview.column("imgs", width=30, anchor=E)
self.treeview.heading("dir", text="Select a Folder:", anchor=W)
self.treeview.heading("imgs", text="Image Count", anchor=E)
#self.treeview.heading(0, text="Select Directory")
#self.listbox = Listbox(self.body, activestyle="dotbox", font=("Menu", 10))
#self.listbox.grid(row=3,column=0, sticky=(N,S,E,W),rowspan=3,pady=5,padx=(0,5))
ok = Button(self.body, text="Use Folder")
ok.grid(row=3,column=1,sticky=(N,E,W), pady=5)
cancel = Button(self.body, text="Cancel")
cancel.grid(row=4,column=1,sticky=(N,E,W), pady=5)
self.grab_set()
self.protocol("WM_DELETE_WINDOW", self.cancel)
self.bind("<Escape>", self.cancel)
cancel.bind("<Button-1>", self.cancel)
ok.bind("<Button-1>", self.selectFolder)
self.treeview.bind("<Left>", self.newFolder)
self.treeview.bind("<Right>", self.newFolder)
self.treeview.bind("<Return>", self.selectFolder)
self.treeview.bind("<Up>", self.onUpDown)
self.treeview.bind("<Down>", self.onUpDown)
self.treeview.bind("<<TreeviewSelect>>", self.onChange)
self.geometry("%dx%d+%d+%d" % (450, 400,
parent.winfo_rootx()+int(parent.winfo_width()/2 - 200),
parent.winfo_rooty()+int(parent.winfo_height()/2 - 150)
))
self.updateListing()
self.treeview.focus_set()
self.resizable(0,0)
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.body.columnconfigure(0, weight=1)
self.body.rowconfigure(5, weight=1)
self.wait_window(self)
def newFolder(self, event):
newDir = self.dir.get()
if event.keysym == "Left":
#newDir = os.path.join(newDir, "..")
self.upFolder()
return
else:
selected = self.getSelected()
if selected == ".":
#special super cool stuff here
self.selectFolder()
return
elif selected == "..":
self.upFolder()
return
else:
newDir = os.path.join(newDir, selected)
self.dir.set(os.path.abspath(newDir))
self.updateListing()
def upFolder(self):
cur = os.path.split(self.dir.get())
newDir = cur[0]
cur = cur[1]
self.dir.set(os.path.abspath(newDir))
self.updateListing()
children = self.treeview.get_children()
for child in children:
if self.treeview.item(child, "text") == cur:
self.treeview.selection_set(child)
self.treeview.focus(child)
#print "please see"
self.treeview.see(child)
return
def onChange(self, event=None):
#print event
sel = self.treeview.focus()
if sel == '':
return #not possible, but just in case
if self.treeview.item(sel, "values")[1] == "?":
#print "Has ?"
self.imgCount()
def imgCount(self):
folder = os.path.join(self.dir.get(), self.getSelected())
folder = os.path.abspath(folder)
count = 0
dirList = os.listdir(folder)
for fname in dirList:
if self.fileFilter == None:
count = count + 1
else:
ext = os.path.splitext(fname)[1].lower()[1:]
#print ext
for fil in self.fileFilter:
#print fil
if ext == fil:
count = count + 1
break
#print count
sel = self.treeview.focus()
newV = (self.treeview.item(sel, "values")[0], str(count))
self.treeview.item(sel, value=newV)
def onUpDown(self, event):
sel = self.treeview.selection()
if len(sel) == 0:
return
active = self.treeview.index(sel[0])
children = self.treeview.get_children()
length = len(children)
toSelect = 0
if event.keysym == "Up" and active == 0:
toSelect = length - 1
elif event.keysym == "Down" and active == length-1:
toSelect = 0
else:
return
toSelect = children[toSelect]
self.treeview.selection_set(toSelect)
self.treeview.focus(toSelect)
self.treeview.see(toSelect)
return 'break'
def updateListing(self, event=None):
folder = self.dir.get()
children = self.treeview.get_children()
for child in children:
self.treeview.delete(child)
#self.treeview.set_children("", '')
dirList = os.listdir(folder)
first = self.treeview.insert("", END, text=".", values=("(.) - Current Folder", "?"))
self.treeview.selection_set(first)
self.treeview.focus(first)
self.treeview.insert("", END, text="..", values=("(..)", "?"))
#self.listbox.insert(END, "(.) - Current Folder")
#self.listbox.insert(END, "(..)")
for fname in dirList:
if os.path.isdir(os.path.join(folder, fname)):
#self.listbox.insert(END,fname+"/")
self.treeview.insert("", END, values=(fname+"/", "?"), text=fname)
def selectFolder(self, event=None):
selected = os.path.join(self.dir.get(), self.getSelected())
selected = os.path.abspath(selected)
self.callback(selected, self)
self.cancel()
def getSelected(self):
selected = self.treeview.selection()
if len(selected) == 0:
selected = self.treeview.identify_row(0)
else:
selected = selected[0]
return self.treeview.item(selected, "text")
def ok(self):
#print "value is", self.e.get()
self.top.destroy()
def cancel(self, event=None):
self.parent.focus_set()
self.destroy()
"""
Img Class
Stores path to img and manipulates (resizes).
"""
class Img:
def __init__(self, path):
self.path = path
self.size = 0,0
self.oSize = 0,0
self.img = None
self.tkpi = None
split = os.path.split(self.path)
self.folderName = os.path.split(split[0])[1]
self.fileName = split[1]
self.stats()
#print "Loaded " + path
self.img = None
def stats(self):
self.img = Image.open(self.path)
self.size = self.img.size
self.oSize = self.img.size
def load(self):
self.img = Image.open(self.path)#.convert("RGB") #RGB for better resizing
#print self.img.mode
if self.img.mode == "P":
self.img = self.img.convert("L") #L scales much more nicely than P
def unload(self):
self.img = None
self.tkpi = None
self.size = self.oSize
def fit(self, size):
#ratio = min(1.0 * size[0] / self.oSize[0], 1.0 * size[1] / self.oSize[1])
ratio = 1.0 * size[0] / self.oSize[0]
ratio = min(ratio, 1.0)
#print ratio
self.size = (int(self.oSize[0] * ratio), int(self.oSize[1] * ratio))
#print self.size
def resize(self, size):
#self.fit(size)
self.load()
self.img = self.img.resize(self.size, Image.BICUBIC)
#self.img = self.img.resize(self.size, Image.ANTIALIAS)
self.tkpi = ImageTk.PhotoImage(self.img)
return self.tkpi
def quickResize(self, size):
self.fit(size)
if self.img == None:
self.load()
self.img = self.img.resize(self.size)
self.tkpi = ImageTk.PhotoImage(self.img)
return self.tkpi
"""
MangaViewer Class
The main class, runs everything.
"""
class MangaViewer:
def __init__(self, root):
self.root = root
self.setTitle(VERSION)
root.state("zoomed")
self.frame = Frame(self.root)#, bg="#333333")#, cursor="none")
self.canvas = Canvas(self.frame,xscrollincrement=15,yscrollincrement=15,bg="#1f1f1f", highlightthickness=0)
scrolly = Scrollbar(self.frame, orient=VERTICAL, command=self.canvas.yview)
self.canvas.configure(yscrollcommand=scrolly.set)
#self.img = Image.open("C:\\Users\\Alex\\Media\\manga\\Boku wa Tomodachi ga Sukunai\\16\\02-03.png")
#self.tkpi = ImageTk.PhotoImage(self.img)
#self.imgId = self.canvas.create_image(0,0, image=self.tkpi, anchor="nw")
#self.canvas.configure(scrollregion=self.canvas.bbox(ALL))
self.files = []
self.current = 0
self.canvas.bind("<Configure>", self.onConfig)
self.root.bind("<Up>", self.onScroll)
self.root.bind("<Down>", self.onScroll)
self.root.bind("<Left>", self.onNewImg)
self.root.bind("<Right>", self.onNewImg)
self.root.bind("<d>", self.getNewDirectory)
self.root.bind("<f>", self.toggleFull)
self.root.bind("<Motion>", self.onMouseMove)
#Windows
self.root.bind("<MouseWheel>", self.onMouseScroll)
# Linux
self.root.bind("<Button-4>", self.onMouseScroll)
self.root.bind("<Button-5>", self.onMouseScroll)
self.root.bind("<Escape>", lambda e: self.root.quit())
self.frame.grid(column=0, row=0, sticky=(N,S,E,W))
self.canvas.grid(column=0,row=0, sticky=(N,S,E,W))
#scrolly.grid(column=1, row=0, sticky=(N,S))
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
self.frame.columnconfigure(0, weight=1)
self.frame.rowconfigure(0, weight=1)
self.resizeTimeO = None
self.mouseTimeO = self.root.after(1000, lambda x: x.frame.configure(cursor="none"), self)
self.lastDir = os.path.abspath("./")
self.imgId = None
self.fullscreen = False
def toggleFull(self, event=None):
if self.fullscreen:
root.overrideredirect(False)
else:
root.overrideredirect(True)
self.fullscreen = not self.fullscreen
self.onConfig(None)
def setTitle(self, *titles):
st = ""
for title in titles:
st = st + " " + str(title)
self.root.title("MangaViewer - " + st)
def setTitleToImg(self):
self.setTitle(self.files[self.current].folderName,"-",
self.files[self.current].fileName,"(",(self.current+1),"/",len(self.files),")")
def onMouseMove(self, event):
"""hide cursor after some time"""
#print event
self.frame.configure(cursor="")
if self.mouseTimeO != None:
self.root.after_cancel(self.mouseTimeO)
self.mouseTimeO = self.root.after(1000, lambda x: x.frame.configure(cursor="none"), self)
def onMouseScroll(self, event):
#mousewheel for windows, mousewheel linux, or down key
if event.num == 4 or event.delta == 120:
self.canvas.yview("scroll", -3, "units")
else:
self.canvas.yview("scroll", 3, "units")
def onScroll(self, event):
"""called when the up or down arrow key is pressed"""
if event.keysym == "Down":
self.canvas.yview("scroll", 1, "units")
else:
self.canvas.yview("scroll", -1, "units")
def onNewImg(self, event):
"""called when the left or right arrow key is pressed, changes the image"""
change = 1 #right key
if event.keysym == "Left":
change = -1
newImg = self.current + change
if newImg < 0 or newImg >= len(self.files):
self.getNewDirectory()
return
#self.img = self.files[newImg];
#self.tkpi = ImageTk.PhotoImage(self.img)
#self.canvas.delete(self.imgId)
#self.imgId = self.canvas.create_image(0,0, image=self.tkpi, anchor="nw")
#self.canvas.configure(scrollregion=self.canvas.bbox(ALL)) #needed?
self.files[self.current].unload()
self.current = newImg
self.setTitleToImg()
self.onConfig(None, True)
def getNewDirectory(self, event=None):
folderDialog(self.root, self.selNewDirectory, self.lastDir, fileFilter=["jpg", "png", "gif", "jpeg"])
def selNewDirectory(self, dirname, fd):
"""callback given to folderDialog"""
fd.cancel() #destroy the folderDialog
if self.lastDir == dirname:
return
self.lastDir = dirname
#print dirname
dirList = os.listdir(dirname)
self.files = []
self.current = -2
for fname in dirList:
ext = os.path.splitext(fname)[1].lower()
if ext == ".png" or ext == ".jpg" or ext == ".jpeg" or ext == ".gif":
self.files.append(Img(os.path.join(dirname, fname)))
self.current = 0
if len(self.files) == 0:
return
self.setTitleToImg()
self.onConfig(None, True)
def resize(self, finalResize=False):
"""resizes the image"""
canvasSize = (self.canvas.winfo_width(), self.canvas.winfo_height())
tkpi = None
if finalResize:
tkpi = self.files[self.current].resize(canvasSize)
else:
tkpi = self.files[self.current].quickResize(canvasSize)
if self.resizeTimeO != None: #is this the best way to do this?
self.root.after_cancel(self.resizeTimeO)
self.root.after(200, self.onConfig, None, True)
if self.imgId != None:
self.canvas.delete(self.imgId)
self.imgId = self.canvas.create_image(0,0, image=tkpi, anchor="nw")
#self.canvas.configure(scrollregion=self.canvas.bbox(ALL))
bbox = self.canvas.bbox(ALL)
#nBbox = (bbox[0], bbox[1]-60, bbox[2], bbox[3]+60)
nBbox = bbox
self.canvas.configure(scrollregion=nBbox)
#print self.canvas.bbox(ALL)
def onConfig(self, event, finalResize=False):
"""runs the resize method and centers the image"""
if self.current < 0 or self.current >= len(self.files):
return
self.canvas.yview("moveto", 0.0)
self.resize(finalResize)
newX = (self.canvas.winfo_width() - self.files[self.current].size[0])/2
#newY - 60 TODO change to preference padding
newY = (self.canvas.winfo_height() - self.files[self.current].size[1])/2# - 60
newY = max(newY, 0)
self.canvas.coords(self.imgId, newX, newY)
self.canvas.yview("moveto", 0.0)
bbox = self.canvas.bbox(ALL)
nbbox = (0,0, bbox[2], max(bbox[3], self.canvas.winfo_height()))
self.canvas.configure(scrollregion=nbbox)
root = Tk()
MangaViewer(root)
root.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-13T10:57:16.363",
"Id": "7170",
"Score": "1",
"body": "I think you post to the wrong community. This community concentrates on \"code quality\" issues, rather than on a \"functional issues\" of the code. Try to find more appropriate place to ask this question. StackOvervflow or some forums dedicated to ImageProcessing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-19T17:29:11.607",
"Id": "334017",
"Score": "1",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<p>As Moisei pointed out, Code Review isn't about functional issues. I guess performance can be discuted, but I don't know how to make resizing fast.</p>\n\n<p>Your code looks good overall, but I don't know about Tkinter idioms. Here are a few comments:</p>\n\n<ol>\n<li><p>You should check <code>if __name__ == \"__main__\":</code> before running the mainloop. This will allow you or someone else to import the code you written without having it launching the GUI.</p></li>\n<li><pre><code>st = \"\"\nfor title in titles:\n st = st + \" \" + str(title)\n</code></pre>\n\n<p>Write this as <code>\" \".join(titles)</code></p></li>\n<li><p><code>#special super cool stuff here</code> or even <code>#newDir = os.path.join(newDir, \"..\")</code></p>\n\n<p>Please care about comments.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-02T21:32:15.943",
"Id": "9653",
"ParentId": "4377",
"Score": "4"
}
},
{
"body": "<p>There is a problem related to the imports:</p>\n\n<pre><code>from Tkinter import *\nfrom ttk import *\n</code></pre>\n\n<p><a href=\"https://docs.python.org/3/library/tkinter.ttk.html#ttk-widgets\" rel=\"nofollow noreferrer\"><code>ttk</code></a> has 17 widgets, eleven of which already exist in Tkinter. Regarding the way you run the imports, you are going to use only the 11 widgets of ttk. This is because your second import <em>overrides</em> the first one.</p>\n\n<p>What I mean is that when you code, for instance, a button widget <code>button_name = Button(... options ... )</code>, you are using the themed button, not the \"normal\" button of Tkinter. To remedy to this problem, you should code the imports statements like this:</p>\n\n<pre><code>import Tkinter as Tk\nimport ttk\n</code></pre>\n\n<p>Note that this is <a href=\"https://docs.python.org/2/library/ttk.html#using-ttk\" rel=\"nofollow noreferrer\">valid</a> for Python2.x you are using. Otherwise, in Python3.x you ttk is not a package of its own, and you have to code <code>from tkinter import ttk</code>, instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-19T17:28:23.850",
"Id": "176083",
"ParentId": "4377",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T04:59:26.760",
"Id": "4377",
"Score": "16",
"Tags": [
"python",
"performance",
"image",
"tkinter"
],
"Title": "Python Manga Image Viewer"
}
|
4377
|
<p>If you were given the following:</p>
<pre><code>#include <cassert>
struct vec {
float x,y,z;
vec(float x, float y, float z) : x(x), y(y), z(z) {}
};
int main() {
float verts[] = {1,2,3,4,5,6,7,8,9}; // length guaranteed to be a multiple of 3
assert(sizeof(vec) == sizeof(float) * 3);
// Option 1
for (int i = 0; i < 3; ++i) {
auto a = reinterpret_cast<vec*>(verts)[i];
// ...
}
// Option 2
for (int i = 0; i < 9; i += 3) {
vec a(verts[i], verts[i+1], verts[i+2]); // -O3 averts the copy, so d/w
// ...
}
return 0;
}
</code></pre>
<p>Which is considered better practice?</p>
<p>The advantage to the latter option is of course far more explicit, and carries all the advantages/disadvantages that contains; but may not be portable depending on the assertions you can make.</p>
|
[] |
[
{
"body": "<p>I'd say, use the last one until this prooves to by a performance problem (which I highly doubt). \nAlso, be aware that the first two solution would modify the array, should the following code modify <code>a</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T15:50:45.467",
"Id": "6577",
"Score": "0",
"body": "The compile generally brings this all down to the same code (or close enough, perhaps 2 different ops), I'm just asking from a *programmers* point of view; and perhaps from a **standards** point of view as well."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T15:11:51.233",
"Id": "4385",
"ParentId": "4384",
"Score": "0"
}
},
{
"body": "<p>I strongly prefer option 3.</p>\n\n<p>Options 1 and 2 remind me most of K&R C where a pointer is a pointer is a pointer. If one of the types is changed, the compiler may not notice and that can lead to bugs that may be hard to locate.</p>\n\n<p>Option 3 is the style used in a strongly typed language. If one of the types is changed, the compiler is more likely to notice and complain at the point where code needs to be fixed.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T15:25:34.650",
"Id": "4387",
"ParentId": "4384",
"Score": "1"
}
},
{
"body": "<p>Why not do this:</p>\n\n<pre><code>struct vec\n{\n float x,y,z;\n};\n\n\nint main()\n{\n vec verts[] = {{1,2,3}, {4,5,6}, {7,8,9}};\n</code></pre>\n\n<p>It is definitely more clear than any of the proposed solutions.<br>\nIs type safe (a key point) and avoids the copy you want (as they are created in place).</p>\n\n<pre><code>// Option 4\nfor (int i = 0; i < 3; ++i)\n{\n const vec& a = verts[i];\n\n}\n</code></pre>\n\n<p>When writing C++ code you should definitely not use the C cast operator. C++ has four of its own that you can use:</p>\n\n<pre><code>const_cast // If you need this you are either very clever or your design is wrong\nreinterpret_cast // This is an indication that you are doing something non portable.\nstatic_cast // This is a good cast (but any explicit cast is bad)\ndynamic_cast // This casts up and down the class hierarchy (usually just down)\n\n // Note: dynamic_cast is a runtime operation.\n // all others are compile time casts.\n // static_cast/dynamic_cast will actually generate compile\n // time errors if you do something wrong very wrong. dynamic_cast\n // can also throw an exception (or return NULL).\n</code></pre>\n\n<p>In your case when I convert your C-casts into C++</p>\n\n<pre><code> // option 1\n const vec& a = reinterpret_cast<vec&>(verts[i]);\n\n // Option 2\n const vec& a = reinterpret_cast<vec*>(verts)[i];\n</code></pre>\n\n<p>Now if you present your code to a C++ developer the first thing they will do is ask: <code>why do you need reinterpret_cast? That's a bad idea</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T16:49:10.153",
"Id": "6578",
"Score": "0",
"body": "A valid point, but some libraries in my code require the data as a pointer to floats. The POD way triumphs unless I use reinterpret cast for these situations (agreed, yuk)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T16:06:58.237",
"Id": "4391",
"ParentId": "4384",
"Score": "1"
}
},
{
"body": "<p>I would go with a 3rd option that is closest to option 2. But instead of taking the three parameters separately in the constructor, take an array of floats.</p>\n\n<pre><code>struct vec {\n float x,y,z;\n vec(float fv[]) : x(fv[0]), y(fv[1]), z(fv[2]) {}\n};\n\nint main() {\n float verts[] = {1,2,3,4,5,6,7,8,9};\n\n for (int i = 0; i < 9; i += 3) {\n const vec a(&verts[i]);\n // ...\n }\n\n return 0;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:09:29.190",
"Id": "6591",
"Score": "0",
"body": "A great idea, averts extraneous syntax, clear intent, and all the behaviour is defined. Also allows for the original data to be stored as floats."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T21:12:25.713",
"Id": "4402",
"ParentId": "4384",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4402",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T13:12:40.593",
"Id": "4384",
"Score": "4",
"Tags": [
"c++",
"casting"
],
"Title": "Coding Practice - Float* -> Vector3* cast"
}
|
4384
|
<p>I was looking for advice, feedback and information on best practices when designing ASP.NET Web Forms in a .NET web application. </p>
<p>Allow me to post a sample of how I currently do things. I am omitting the ASPX page as it only has 2 textboxes and a button. PersonEntity validates, loads, and saves in this example. Real-world would have a "Person" business object that saves, loads.</p>
<p>The Codebehind file of an "Add / Edit" page:</p>
<pre><code>public partial class PersonAddUpdate : System.Web.UI.Page
{
public int PersonId
{
get
{
int _personId = 0;
if (Int32.TryParse(Request.QueryString["id"], out _personId))
{
return _personId;
}
else
{
return 0;
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (PersonId != 0)
{
var person = GetPersonById(PersonId);
if (person != null)
{
BindFormToData(person);
ViewState.Add("PersonEntity", person);
}
}
}
}
protected bool BindDataToForm(PersonEntity person)
{
person.FirstName = txtFirstName.Text;
person.Lastname = txtLastName.Text;
ViewState.Add("PersonEntity", person);
// internal entity validation
return person.Validate();
}
protected void BindFormToData(PersonEntity person)
{
txtFirstName.Text = person.FirstName;
txtLastName.Text = person.Lastname;
}
protected PersonEntity GetPersonById(int personId)
{
PersonEntity person = new PersonEntity();
return person.LoadById(personId);
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
PersonEntity person;
if (ViewState["PersonEntity"] == null)
{
person = new PersonEntity();
}
else
{
person = (PersonEntity)ViewState["PersonEntity"];
}
if (!BindDataToForm(person))
{
// failed entity validation
return;
}
if (!person.Save())
{
// problem saving
return;
}
else
{
Response.Redirect("PersonDetail.aspx?id=" + person.Id.ToString());
}
}
}
</code></pre>
<p><strong>Workflow:</strong></p>
<p>Page Load:
Get the id from querystring. If a problem arises, return 0. No records in the system have a "0" id. Try to load data. If there's data, set the form values and add it to viewstate.</p>
<p>On Save: Stop if page is invalid. Create an uninitialized PersonEntity. If viewstate contains an entity, then form binding (gets form values) routine does not need new PersonEntity. If viewstate is null, then we are a new record.</p>
<p>Call BindDataToForm which gets form field values and returns false if it fails internal entity validation. Attempt Save and continue if OK.</p>
<p><strong>Questions:</strong></p>
<p>I've been using this pattern for a while now. Do you see anything I can do to improve it? I was trying to find samples of complete forms that handle Add / Edit, but I was unable to find ones that worked as good as this with ORM-generated code.</p>
<p>Any comments, advice, ideas, or questions? </p>
<p>I hope the code is simple to read and understand.</p>
|
[] |
[
{
"body": "<p>This is my feedback, Please let me know if I am misinterpreting :</p>\n\n<p>1) Storing the entire PersonEntity object in viewstate will have following problems</p>\n\n<ul>\n<li>It will make viewstate heavy and thus make page load slower.</li>\n<li>It may not represent the current state of the object. </li>\n</ul>\n\n<p>You can store the personId, recreate personentity object and then call save. \nA lot more about viewstate here <a href=\"http://www.freshegg.com/blog/creating-lean-fast-web-pages-view-state_3377\" rel=\"nofollow\">http://www.freshegg.com/blog/creating-lean-fast-web-pages-view-state_3377</a></p>\n\n<p>2) You can make the LoadById method static</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-05T12:34:04.357",
"Id": "7818",
"Score": "0",
"body": "It does add to viewstate's length. There are many options (a custom state persistence store, compression, etc) to remedy this, if your data object is able to hold a lot of data.\n\nThe current state of the object should be correct. If this is a new object (a create), it is not loaded into viewstate until form binding, right before the constructor is called. \n\nIf this is an edit, we've loaded the object into viewstate and we retrieve and modify it with the binding routine.\n\nThank you for your feedback."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-03T13:23:07.457",
"Id": "5139",
"ParentId": "4386",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "5139",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-23T15:28:56.890",
"Id": "4386",
"Score": "7",
"Tags": [
"c#",
"asp.net"
],
"Title": "Workflow and Design Feedback on an Add / Edit Form"
}
|
4386
|
<p>There's things I know about JavaScript and jQuery, and things I don't. I know that this works, gets and stores what I want so that, when I need to do stuff, I don't have to wait for it. Functionally, I like this. But I'm the only JavaScript guy in my shop, and so I don't see JavaScript I didn't write all that often. </p>
<p>I've heard recently that it is considered wrong to fill up the name space, so you use objects to hold everything. I <em>think</em> I'm doing this right now, but I'm not sure.</p>
<p>And in adding stuff to the DOM, I believe I'm a bit more verbose than I need to be, but I don't really know what to change.</p>
<p>Any comments?</p>
<pre><code>// This uses Javascript, jQuery and jQuery-UI to allow for the addition of accession analysis stubs
// to new requests and accessions
var aa_stub = {
// variables
ajax : 'MY URL HERE' ,
// data storage
data : {} ,
references : {} ,
reference_order : [] ,
analysis : {} ,
analysis_order : [] ,
// functions
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// dialog popped up when "Add AA Stub' button is pressed
do_dialog : function ( sample_num ) {
$( '<div/>' )
.attr( 'id' , 'add_new_stub' )
.attr( 'title' , 'Add Stub' )
.dialog()
$('.ui-icon-closethick').text( 'X' )
$('.ui-dialog-titlebar-close')
.click( function () {
$( '#add_new_stub' ).remove()
} )
$( '<div/>' )
.appendTo( '#add_new_stub' )
.attr( 'id' , 'instructions' )
.text( 'Enter a reference, an analysis, any extra parameters, then click Go' )
$( '<fieldset/>' )
.appendTo( '#add_new_stub' )
.attr( 'id' , 'ref_box' )
$( '<legend/>' )
.appendTo( '#ref_box' )
.text( 'Reference Species' )
$( '<select/>' )
.appendTo( '#ref_box' )
.attr('id' ,'reference')
for ( i in aa_stub.reference_order ) {
var j = aa_stub.reference_order[i]
var ref = aa_stub.references[j]
$( '<option/>' )
.text( ref )
.val( j )
.appendTo( '#reference' )
}
$( '<fieldset/>' )
.appendTo( '#add_new_stub' )
.attr( 'id' , 'anal_box' )
$( '<legend/>' )
.appendTo( '#anal_box' )
.text( 'Analysis Type' )
$( '<select/>' )
.appendTo( '#anal_box' )
.attr('id' ,'analysis')
for ( i in aa_stub.analysis_order ) {
var j = aa_stub.analysis_order[i]
var analysis = aa_stub.analysis[j]
$( '<option/>' )
.text( analysis )
.val( j )
.appendTo( '#analysis' )
}
$( '<fieldset/>' )
.appendTo( '#add_new_stub' )
.attr( 'id' , 'param_box' )
$( '<legend/>' )
.appendTo( '#param_box' )
.text( 'Extra Parameters' )
$( '<input type="text"/>' )
.appendTo( '#param_box' )
.attr('id' ,'extra_parameters')
$( '<input type="hidden"/>' )
.appendTo( '#param_box' )
.attr('id' ,'sample')
.val( sample_num )
$( '<div/>' )
.attr( 'id' , 'stub_go' )
.text( 'Go' )
.appendTo( '#add_new_stub' )
.click( function () {
var reference = $( '#reference' ).val()
var analysis = $( '#analysis' ).val()
var parameters = $( '#extra_parameters' ).val()
var sample = $( '#sample' ).val()
$('.ui-icon-closethick').click( )
if ( sample === '' ) {
$( '.stub_bucket' ).each( function () {
var sample = $( this ).attr( 'sample' )
aa_stub.add_to_bucket( sample , reference , analysis , parameters )
} )
}
else {
aa_stub.add_to_bucket( sample , reference , analysis , parameters )
}
} )
} ,
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// adding AA stubs to the form
add_to_bucket : function ( sample , reference , analysis , parameters ) {
var bucket = '#stub_bucket_' + sample
var ref_text = aa_stub.references[ reference ]
var a_text = aa_stub.analysis[ analysis ]
var number = 1
$( bucket ).children( 'span' ).each( function () {
var num = parseInt( $( this ).attr( 'number' ) )
if ( number <= num ) { number = 1 + num }
} )
var id = [ 'span' , sample , number ].join('_')
$( '<span/>' )
.addClass( 'stub' )
.attr( 'number' , number )
.attr( 'id' , id )
.appendTo( bucket )
.text( [ ref_text , a_text ].join( ' - ' ) )
.attr( 'title' , 'Click to delete' )
.click( function () {
$(this).remove()
} )
$( '<input type="hidden">' )
.attr( 'name' , [ 'reference' , sample , number ].join('_') )
.val( reference )
.appendTo( '#' + id )
$( '<input type="hidden">' )
.attr( 'name' , [ 'analysis' , sample , number ].join('_') )
.val( analysis )
.appendTo( '#' + id )
$( '<input type="hidden">' )
.attr( 'name' , [ 'parameters' , sample , number ].join('_') )
.val( parameters )
.appendTo( '#' + id )
} ,
// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
// the startup part
initialize : function ( ) {
aa_stub.data.flag = 1
// fill data
var url = aa_stub.ajax
$.post( url , function ( data ) {
for ( i in data.references ) {
var ref = data.references[ i ]
aa_stub.references[ i ] = ref
}
for ( i in data.analysis ) {
var ref = data.analysis[ i ]
aa_stub.analysis[ i ] = ref
}
for ( i in data.references_order ) {
var j = data.references_order[ i ]
aa_stub.reference_order.push( j )
}
for ( i in data.analysis_order ) {
var j = data.analysis_order[ i ]
aa_stub.analysis_order.push( j )
}
} , 'json' )
// get all
$( '#add_stubs_to_all' )
.click( function () {
aa_stub.do_dialog( '' )
} )
// get one
$( '.stub_add' )
.click( function () {
var sample = $( this ).attr('sample')
aa_stub.do_dialog( sample )
} )
}
}
$( function() {
aa_stub.initialize()
} )
</code></pre>
|
[] |
[
{
"body": "<p>Let me start with few common observations.</p>\n\n<p>It's better to generate a complete DOM element before you attach it to DOM tree (add to page) if you can, because it tends to be faster. For example setting its text after can trigger another reflow. Do it often enough and it start to matter. Not every change is expensive (e.g. setting ID before or later doesn't matter much), but I think it also reads better (step 1.: build node, step 2: attach it).</p>\n\n<p>If you are building a more complex HTML (DOM subtree), it's also better to create a <a href=\"https://developer.mozilla.org/en/document.createDocumentFragment\">document fragment</a>, add nodes to it and then add that fragment to page to avoid costly reflows.</p>\n\n<p>It's good practice to declare all your variables at the top of function. They will exist from that point onward even if you declare them at the very bottom. Not doing this opens you to subtle errors.</p>\n\n<p>Not every variable has to have its own var statement infront. E.g. it's OK to do var a = 5, b = 3 to declare a and b;</p>\n\n<p>So on to concrete examples:</p>\n\n<pre><code>$( '<div/>' )\n .attr( 'id' , 'add_new_stub' )\n .attr( 'title' , 'Add Stub' )\n .dialog()\n</code></pre>\n\n<p>You could do this same thing in two ways:</p>\n\n<pre><code>$('<div id=\"add_new_stup\" title=\"Add Stub\"></div>').dialog();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$('<div />', { id: 'add_new_stub', title: 'Add Stub })\n .dialog()\n</code></pre>\n\n<p>Personally I'd pick first version when dealing with elements that have fixed attribute values, since it's most obvious and second when attribute values are variables. <a href=\"http://api.jquery.com/jQuery/#jQuery2\">Learn more</a>.</p>\n\n<p>Instead of for() loop over array, you can use</p>\n\n<pre><code>$.each(array, function (i, el) {\n ... your code ...\n});\n</code></pre>\n\n<p>This way you can also localize variables better.</p>\n\n<p>I don't understand the purpose of this part:</p>\n\n<pre><code> var number = 1\n $( bucket ).children( 'span' ).each( function () {\n var num = parseInt( $( this ).attr( 'number' ) )\n if ( number <= num ) { number = 1 + num }\n } )\n var id = [ 'span' , sample , number ].join('_')\n $( '<span/>' )\n .addClass( 'stub' )\n .attr( 'number' , number )\n</code></pre>\n\n<p>Correct me if I'm wrong, but you are trying to set number to 1 higher than highest, right? If yes, than that's an awfully expensive way to do this. You could improve this in two ways. Either you store current maximum or since new span with highest number is always added to the end of a list, just pick that one (\"span:last\") and read what maximum currently is.</p>\n\n<p>You don't use aa_stub.data.flag anywhere.</p>\n\n<p>Btw, I'm not fond of dropped colons at the end of lines and closing } at same depth as end of block, but that's a personal choice.</p>\n\n<p>Anyway, that's a quick overlook of your code. I hope it helped.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T13:41:10.607",
"Id": "6697",
"Score": "0",
"body": "It did, markos. I mostly use the $( \"<div id='foo'/>\" ) style with inputs, because if jQuery will create or modify the TYPE attribute, I don't know it. \n\nI did not know about document fragments. Will try that. It might work similarly if I create an element, add to it, and append it to the page as the last thing. Which gets to a thing I'm curious about: I think I've seen code where you define, for example, an LI inline with the UL it exists in, but I've forgotten where I saw it.\n\naa_stub.data.flag is orphaned and forgotten."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T19:45:05.200",
"Id": "6708",
"Score": "0",
"body": "I got it from somewhere, Crockford maybe?, that ending semicolons are superfluous and should be avoided. I've been trying to get them out of my Javascript, in part so that I don't mentally confuse it with my Perl and end up getting errors by conflating \"my\" with \"var\" and vice versa."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T18:21:14.213",
"Id": "6751",
"Score": "0",
"body": "I guess I knew about .last() but forgot about it. Changed that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T15:35:37.853",
"Id": "6892",
"Score": "2",
"body": "Semicolons mostly are not needed and some argue they should be dropped, but Crockford isn't one of those people :) I personally use them, but as a Python developer am not really attached to them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T15:37:47.070",
"Id": "6893",
"Score": "0",
"body": "I'm not exactly sure what you meant with inline LI comment, but you can add one either by creating whole HTML if necessary (like $(\"<ul><li>item</li></ul\") or if it already exist, by using a method like append ($(\"ul\").append(\"<li>item</li>\")."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T10:56:28.263",
"Id": "6915",
"Score": "0",
"body": "There is append, but at some point, you have to stop talking about the appended LI and go back to the UL, and ... after a little looking, found .end()"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T08:40:07.803",
"Id": "4427",
"ParentId": "4388",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T15:35:04.210",
"Id": "4388",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"ajax",
"jquery-ui"
],
"Title": "Addition of accession analysis stubs to new requests and accessions"
}
|
4388
|
<p>My colleague did some code Optimise work.</p>
<p>Code below is from a public method of a public class (NOT STATIC CLASS OR METHOD)</p>
<p>code before:</p>
<pre><code> Bitmap btMap = new Bitmap(Convert.ToInt32(WebConfig.StatsOpenEmailImageWidth), Convert.ToInt32(WebConfig.StatsOpenEmailImageHeight), PixelFormat.Format32bppArgb);
MemoryStream memStrm = new MemoryStream();
btMap.Save(memStrm, ImageFormat.Png);
memStrm.WriteTo(context.Response.OutputStream);
</code></pre>
<p>Code after:</p>
<pre><code> using (Bitmap btMap = new Bitmap(Convert.ToInt32(WebConfig.StatsOpenEmailImageWidth), Convert.ToInt32(WebConfig.StatsOpenEmailImageHeight), PixelFormat.Format32bppArgb))
{
using (MemoryStream memStrm = new MemoryStream())
{
btMap.Save(memStrm, ImageFormat.Png);
memStrm.WriteTo(context.Response.OutputStream);
}
}
</code></pre>
<p>Is it a necessary optimisation againt memory leak?</p>
|
[] |
[
{
"body": "<p>Absolutely, the 2nd example is the way to ensure disposable objects/resources are released for the GC. The <code>using</code> clause does this by enforcing the rule that the object being created must inherit from <code>IDisposable</code>. At the closing '}' of each using block, the object is disposed. </p>\n\n<p>In the first example, you will have memory leaks occur if you don't close and dispose the <code>MemoryStream</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T15:58:27.000",
"Id": "4390",
"ParentId": "4389",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4390",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T15:48:18.723",
"Id": "4389",
"Score": "3",
"Tags": [
"c#",
"memory-management"
],
"Title": "Does this I/O operation caused a memory leak"
}
|
4389
|
<p>I'm developing a log-on page where users either select or create an associated organization when they sign up. There can be either 1 user per organization or many users per organization, this is specified at runtime via web.config. </p>
<p>I have a separate project that handles all user account creation. I don't know if this code should be in the Webforms project or the user account creation project since it is driven by the user's selection in the GUI?</p>
<pre><code> private IpasLogOnManagement.IpasOrganization EnsureOrganizationExists()
{
IpasLogOnManagement.IpasOrganization organization = null;
if (OrganizationsSeparateFromUsers)
{
if (lstOrganizations.SelectedIndex == -1)
{
try
{
organization = organizationProvider.SearchForOrganizationByName(txtOrganizationName.Text);
}
catch (IndexOutOfRangeException)
{
//Organization does not exist, so create it
organization = manager.CreateOrganization(txtOrganizationName.Text);
}
}
else
{
string selectedName = lstOrganizations.Items[lstOrganizations.SelectedIndex].Text;
organization = organizationProvider.SearchForOrganizationByName(selectedName);
}
}
else
{
organization = manager.CreateOrganization(txtEmail.Text);
}
return organization;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T18:26:08.543",
"Id": "6585",
"Score": "0",
"body": "+1 Perfect question for the site, which will help inform future developers about where boundaries between modules should be."
}
] |
[
{
"body": "<p>Since you actually have a business layer, that's where I'd put it. You should let the business layer handle the finding/creating of an organization, so all the WebForms code needs to do is ask for an <code>IpasLogOnManagement.IpasOrganization</code> object based on the name the user selected (<code>lstOrganizations</code>) or entered (<code>txtOrganizationName</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T18:22:37.433",
"Id": "4397",
"ParentId": "4392",
"Score": "2"
}
},
{
"body": "<p>Your trusty coder's nose led you correctly to question this, <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">Separation of Concerns</a> states you should have these in different modules, and I couldn't agree more. The UI should worry about presenting the UI, and passing along the user activities to the appropriate other modules. When SoC is utilized, your separate modules can be used by more than one UI (or non-UI modules).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T18:24:09.903",
"Id": "4398",
"ParentId": "4392",
"Score": "2"
}
},
{
"body": "<p>A part of this code could be moved to the business logic.<br>\nI would rewrite this method like this:<br>\nManager (BLL): </p>\n\n<pre><code> public IpasLogOnManagement.IpasOrganization FindOrganizationByName(string name)\n {\n IpasLogOnManagement.IpasOrganization result = null;\n try\n {\n result = organizationProvider.SearchForOrganizationByName(name);\n }\n catch (IndexOutOfRangeException)\n {\n result = null;\n }\n return result;\n }\n</code></pre>\n\n<p>UI (WebForm):</p>\n\n<pre><code> private string GetSelectedOrganizationName()\n {\n string result = txtEmail.Text;\n if (OrganizationsSeparateFromUsers)\n {\n if (lstOrganizations.SelectedIndex == -1)\n {\n result = txtOrganizationName.Text;\n }\n else\n {\n result = lstOrganizations.Items[lstOrganizations.SelectedIndex].Text;\n }\n }\n return result;\n }\n\n //Instead of 'EnsureOrganizationExists'\n private IpasLogOnManagement.IpasOrganization GetSelectedOrganization()\n {\n var organizationName = GetSelectedOrganizationName();\n var organization = manager.FindOrganizationByName(organizationName);\n if (organization == null)\n {\n organization = manager.CreateOrganization(organizationName);\n }\n return organization;\n }\n</code></pre>\n\n<p>A couple of notes:<br>\n- I’ve changed the name of the method from EnsureOrganizationExists to GetSelectedOrganization.<br>\n- I would consider another way to check if the organization exists. It’s not right to catch an exception of a specific type to do this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T08:31:13.620",
"Id": "4408",
"ParentId": "4392",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T16:34:05.733",
"Id": "4392",
"Score": "4",
"Tags": [
"c#",
"asp.net"
],
"Title": "Should this code be in the code behind or separate class?"
}
|
4392
|
<p>I have a few different classes in my application, but this specific class is the one I'm interested about. Please review for good practices and potential problems.</p>
<pre><code>using ExactEarth.Utilities.Jaguar.Properties;
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
public class Downlink
{
public string PassId { get; set; }
public string DataId { get; set; }
public string NoradId { get; set; }
public string Spacecraft { get; set; }
public string GroundStation { get; set; }
public string Start { get; set; }
public string End { get; set; }
public string Status { get; set; }
private static string connectionString;
private static SqlConnection connection;
public Downlink(string passId)
{
using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + Resources.connectionStringPath))
{
connectionString = reader.ReadLine();
}
using (connection = new SqlConnection(connectionString))
{
connection.Open();
this.PassId = passId;
this.DataId = GetDataId();
this.NoradId = GetSatelliteId();
this.Spacecraft = GetSpacecraft();
this.GroundStation = GetGroundStation();
this.Start = GetStartTime();
this.End = GetEndTime();
this.Status = GetPassStatus();
}
}
public string GetDataId()
{
string dataId = null;
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@passId", SqlDbType.NVarChar).Value = this.PassId;
command.CommandText = Resources.passDataQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
dataId = reader["gs_pass_data_id"].ToString();
reader.Close();
}
return dataId;
}
public string GetSatelliteId()
{
string satelliteId = null;
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
command.CommandText = Resources.ausInPassQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
satelliteId = reader["acq_id"].ToString().Substring(0, 5);
}
return satelliteId;
}
}
public string GetSpacecraft()
{
string path = AppDomain.CurrentDomain.BaseDirectory;
path += Resources.spacecraftPath;
using (StreamReader reader = new StreamReader(path))
{
string input = null;
while ((input = reader.ReadLine()) != null)
{
string satelliteId = input.Split(',')[0];
if (this.NoradId == satelliteId)
return input.Split(',')[1];
}
}
// Spacecraft not known
return Resources.unknownSpacecraft;
}
public string GetGroundStation()
{
string station = null;
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
command.CommandText = Resources.groundStationQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
station = reader["ground_station_name"].ToString();
}
return station;
}
}
public string GetStartTime()
{
string start = null;
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
command.CommandText = Resources.passStartQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
start = Convert.ToDateTime(reader["downlink_start_time"]).ToString("yyyy-MM-dd HH':'mm':'ss");
reader.Close();
}
return start;
}
public string GetEndTime()
{
string end = null;
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
command.CommandText = Resources.passEndQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
end = Convert.ToDateTime(reader["downlink_end_time"]).ToString("yyyy-MM-dd HH':'mm':'ss");
reader.Close();
}
return end;
}
public string GetPassStatus()
{
string status = null;
if (!JaguarUtilities.IsSatelliteTracked(this.Spacecraft))
status = Resources.statusNotTracked;
else
{
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@passId", SqlDbType.NVarChar).Value = this.PassId;
command.CommandText = Resources.sourceFileQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Close();
using (SqlCommand newCommand = new SqlCommand())
{
newCommand.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
newCommand.CommandText = Resources.passStatusQuery;
newCommand.Connection = connection;
reader = newCommand.ExecuteReader();
status = Resources.statusProcessing;
if (reader.HasRows)
status = Resources.statusProcessed;
}
}
else
{
status = Resources.statusScheduled;
if (Convert.ToDateTime(this.End) < DateTime.UtcNow)
{
TimeSpan span = DateTime.UtcNow.Subtract(Convert.ToDateTime(this.End));
TimeSpan failTime = JaguarUtilities.GetFailTime(this.Spacecraft, this.GroundStation);
if (TimeSpan.Compare(span, failTime) <= 0)
status = Resources.statusUpdate + (Convert.ToDateTime(this.End) + failTime).ToString("HH':'mm");
else
status = Resources.statusWaiting;
}
}
}
}
return status;
}
public bool IsEscalated()
{
bool escalated;
using (connection)
{
if (IsLastSpacePassFail())
escalated = true;
else if (IsNextSpacePassFail())
escalated = true;
else if (IsLastGroundPassFail())
escalated = true;
else if (IsNextGroundPassFail())
escalated = true;
else
escalated = false;
}
return escalated;
}
private bool IsProcessingTooLong()
{
string path = AppDomain.CurrentDomain.BaseDirectory + Resources.processingTimePath;
using (StreamReader reader = new StreamReader(path))
{
string time = reader.ReadLine();
TimeSpan span = DateTime.UtcNow.Subtract(Convert.ToDateTime(this.End));
TimeSpan failTime = JaguarUtilities.GetFailTime(this.Spacecraft, this.GroundStation);
TimeSpan fail = new TimeSpan(0, int.Parse(time), 0);
if (span > (fail + failTime))
return true;
else
return false;
}
}
private bool IsLastSpacePassFail()
{
string passId = null;
connection.ConnectionString = connectionString;
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@satelliteId", SqlDbType.NVarChar).Value = this.NoradId;
command.Parameters.Add("@downlinkTime", SqlDbType.NVarChar).Value = this.Start;
command.CommandText = Resources.lastSpaceDataQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
passId = reader["gs_pass_id"].ToString();
}
Downlink lastDownlink = new Downlink(passId);
if (lastDownlink.Status == Resources.statusWaiting)
return true;
else if (lastDownlink.Status == Resources.statusProcessing)
{
if (lastDownlink.IsProcessingTooLong())
return true;
else
return false;
}
else
return false;
}
private bool IsNextSpacePassFail()
{
string passId = null;
connection.ConnectionString = connectionString;
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@satelliteId", SqlDbType.NVarChar).Value = this.NoradId;
command.Parameters.Add("@downlinkTime", SqlDbType.NVarChar).Value = this.End;
command.CommandText = Resources.nextSpaceDataQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
passId = reader["gs_pass_id"].ToString();
}
Downlink lastDownlink = new Downlink(passId);
if (lastDownlink.Status == Resources.statusWaiting)
return true;
else if (lastDownlink.Status == Resources.statusProcessing)
{
if (lastDownlink.IsProcessingTooLong())
return true;
else
return false;
}
else
return false;
}
private bool IsLastGroundPassFail()
{
string passId = null;
connection.ConnectionString = connectionString;
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@groundId", SqlDbType.NVarChar).Value = this.GroundStation;
command.Parameters.Add("@downlinkTime", SqlDbType.NVarChar).Value = this.Start;
command.CommandText = Resources.lastGroundDataQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
passId = reader["gs_pass_id"].ToString();
}
Downlink lastDownlink = new Downlink(passId);
if (lastDownlink.Status == Resources.statusWaiting)
return true;
else if (lastDownlink.Status == Resources.statusProcessing)
{
if (lastDownlink.IsProcessingTooLong())
return true;
else
return false;
}
else
return false;
}
private bool IsNextGroundPassFail()
{
string passId = null;
connection.ConnectionString = connectionString;
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@groundId", SqlDbType.NVarChar).Value = this.GroundStation;
command.Parameters.Add("@downlinkTime", SqlDbType.NVarChar).Value = this.End;
command.CommandText = Resources.nextGroundDataQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
reader.Read();
passId = reader["gs_pass_id"].ToString();
}
Downlink lastDownlink = new Downlink(passId);
if (lastDownlink.Status == Resources.statusWaiting)
return true;
else if (lastDownlink.Status == Resources.statusProcessing)
{
if (lastDownlink.IsProcessingTooLong())
return true;
else
return false;
}
else
return false;
}
public int GetNumberAusInPass(string query)
{
int planned = 0;
using (connection)
{
connection.ConnectionString = connectionString;
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
command.CommandText = query;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
++planned;
}
reader.Close();
}
return planned;
}
}
public int GetNumberAusMatched()
{
int matched = 0;
using (connection)
{
connection.ConnectionString = connectionString;
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Parameters.Add("@dataId", SqlDbType.NVarChar).Value = this.DataId;
command.CommandText = Resources.producedAusQuery;
command.Connection = connection;
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
long num;
if (long.TryParse(reader["acquisition_id"].ToString().Split('_')[1], out num))
++matched;
}
reader.Close();
}
return matched;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T16:59:52.403",
"Id": "6580",
"Score": "1",
"body": "If youd like us to analyse the classes, maybe dont post all the irrelevant code. Just represent the objects as such."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T17:01:33.173",
"Id": "6581",
"Score": "0",
"body": "Yeah but I would like to know whether the methods and properties in this class fall in as 'good practice'."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T17:02:08.703",
"Id": "6582",
"Score": "0",
"body": "@Daniel: That *is* a single class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T17:40:12.300",
"Id": "6583",
"Score": "0",
"body": "@Jon: For future reference, class structure refers to how a group of classes relate to and interact with one another."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:11:41.323",
"Id": "6592",
"Score": "0",
"body": "@ED S.: it was impossible to read on my handheld, so I just assumed... in any case, we still don't need your implementation; just the members/properties/methods. If their intent isn't clear, then you know you haven't got clear class responsibilities."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:12:56.423",
"Id": "6593",
"Score": "0",
"body": "@Daniel: But in looking at the implementation you can (at a quick glance) at least see the large amount of duplicated code here. I suppose that doesn't speak to the *class* design in particular, but it is something that could be made better."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:49:13.700",
"Id": "6594",
"Score": "0",
"body": "@Ed S. Agreed, but thats not specific to OOP, perhaps his question was less specific then I anticipated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:57:12.980",
"Id": "6596",
"Score": "0",
"body": "@Daniel: No, it's not, but people who need help probably don't know all of the areas where they may possibly improve, hence the utility of sites like this =)"
}
] |
[
{
"body": "<p>First off, might I suggest some reading material? <a href=\"http://en.wikipedia.org/wiki/SOLID\">SOLID OOP Design Principles</a></p>\n\n<p>Now, onto your code. Two things jump out at me. Your class is easy to misuse, and you're attempting to do too many things with a single class.</p>\n\n<p>1 Easy to misuse</p>\n\n<p>You expose a series of Public properties that you populate from the constructor. Additionally, you expose the actual methods used to populate these fields from the database.</p>\n\n<p>Why does this matter? It means that I could construct your class, query the DataId property, then call GetDataId and get different values. </p>\n\n<p>Additionally, setting the various properties has no effect. At the very least you should declare these properties with private set functions.</p>\n\n<p><code>public string DataId { get; private set; }</code></p>\n\n<p>2 You've given this class too many responsibilities.</p>\n\n<p>It appears to me that you want to do two things with this class. Access values from a database and pass them around to other parts of your application.</p>\n\n<p>Split this into two classes. Write one class that knows how to connect and retrieve values from the database and another class whose sole job is to move these values around. This second class I'm describing is commonly referred to as a Data Transfer Object, or DTO.</p>\n\n<p>Your database class would create and populate DTO's upon request for you. Moving to this pattern solves problem one for you too.</p>\n\n<p>You also appear to have some business logic built into this class. Functions like IsNextGroundPassFail seem to be making decisions based on data found in the database. Decisions based on data and should be in a separate class from the code to read and write the database.</p>\n\n<p>Summary:</p>\n\n<p>I think you need at least three classes.</p>\n\n<ol>\n<li>Database Communication Object</li>\n<li>Data Transfer Object</li>\n<li>Business Logic Object</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T18:06:06.953",
"Id": "6584",
"Score": "0",
"body": "Great, thanks a lot for the tips. Much appreciated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:50:10.323",
"Id": "6595",
"Score": "1",
"body": "+1 Design principles are those things good engineers learn slowly over the course of years of laborious mistake making, and great engineers learn from reading before they spend years laboriously making mistakes. I wish I could say I was the ladder.. SOLID is just as it's billed."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T17:36:36.517",
"Id": "4395",
"ParentId": "4394",
"Score": "13"
}
},
{
"body": "<p>No, its not....</p>\n\n<p>firstly, all the database code is mixed in. This is better off being done using something like nhibernate / entityframework or some similar thing. ( lots of differing opinions on tech to use there! )</p>\n\n<p>but you'd endup with something like</p>\n\n<pre><code>DataLink link = Repository.GetDatalinkByPassId(\"mypassid\");\n</code></pre>\n\n<p>which would go away and create the datalink object from the database and populate all the fields, and if applicable, load other objects that the datalink references.</p>\n\n<p>Next there's a whole lot of concepts satellites / ground stations / etc that are represented as strings. There may be objects here that you want to extract.</p>\n\n<p>But you might also want to abstract things a bit, that its not between a ground station and a sat, but between Nodes? or perhaps some other abstract concept. I don't know enough about the domain to suggest actual abstractions, but the key in any OO system is finding abstractions.</p>\n\n<p>If you have time, put it into a DateTime object, not a string</p>\n\n<p>My suspicion is you are using this class mainly for display. This would be better handled through a \"ViewModel\" A view model would take things like DataLink object and convert things, like time, into a form that's for display ( it would be in charge of what format string to use to convert time to something displayable for instance, and could handle different time formats depending on whether you like time the most sensible way d m y, or the silly way m d y ;-) )</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T22:38:52.530",
"Id": "4405",
"ParentId": "4394",
"Score": "1"
}
},
{
"body": "<p>Agree with the previous comments regarding splitting of the class and confusing interface.</p>\n\n<p>Furthermore, I'd suggest you to start using Test Driven Development, it makes it easier to, for example:</p>\n\n<ul>\n<li>figure out what should be public vs what should be private (if other classes never use the \"read/get\" methods and need only the properties, why expose implementation details),</li>\n<li>what should be static (ideally, nothing, otherwise you loose the ease of testing things in isolation, and ease of extension later in development),</li>\n<li>division of responsibilities (database access vs. data objects vs. business logic).</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T19:20:51.023",
"Id": "4565",
"ParentId": "4394",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T16:52:23.657",
"Id": "4394",
"Score": "7",
"Tags": [
"c#",
"object-oriented",
"classes"
],
"Title": "New to OOP; is this a good class design?"
}
|
4394
|
<p>Profiling shows <code>MoveNext</code> takes most time, which I guess is true as it is lazy. But I don't know in what direction I could improve the code. (Open pic in new tab would allow u see bigger chart.)</p>
<p><img src="https://i.stack.imgur.com/YjUsA.jpg" alt="enter image description here"></p>
<pre><code> IEnumerable<string> MixedBlock(List<string> reelLayout, string thisBlock, int length)
{
List<string> recentBlock = RecentBlock(length - 1, reelLayout);
var upper = Enumerable.Range(1, length - 1);
var lower = Enumerable.Range(1, totalWeight[thisBlock].Num);
var query = from x in upper
from y in lower
where x + y == length
select Tuple.Create(x, y);
foreach (var t in query)
{
string upperBlock = string.Join(",", recentBlock.Skip(length - 1 - t.Item1));
string lowerBlock = string.Join(",", thisBlock.Split(',').Take(t.Item2));
yield return upperBlock + "," + lowerBlock;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T20:57:53.490",
"Id": "6589",
"Score": "0",
"body": "and who knows how does the 50.54-20.32=30.2% come from? weird"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T01:44:40.700",
"Id": "6598",
"Score": "0",
"body": "What is `RecentBlock()`? What is `totalWeight`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-27T16:49:13.820",
"Id": "59319",
"Score": "1",
"body": "@colinfang `50.5 - 20.3 = 30.2` somewhere there is rounding going on"
}
] |
[
{
"body": "<p>I believe there is the the problem with MoveNext() from enumerator which is returned from MixedBlock(). Its MoveNext() just does a lot of lazy processing but doesn't cache results at all.</p>\n\n<p>(1). When you iterare over the result from the <code>MixedBlock()</code> your iterate with help of the auto generated class that implements IEnumerable<code><T></code> and IEnumerator<code><T></code>. Its MoveNext() is a heavy function because it has to create all of the anononymouse functions in your code, maintain state and delegate calls to enumerator from SelectMany(). You can avoid this by removing this <code>yield</code> keyword.</p>\n\n<p>(2). Removing <code>yield</code> keyword will also allow complier not to generate instances of helper functions but use only extenssion methods. Now it can look like this</p>\n\n<pre><code> if (MyClass.CS$<>9__CachedAnonymousMethodDelegate5 == null)\n {\n MyClass.CS$<>9__CachedAnonymousMethodDelegate5 = new Func<int, int, <>f__AnonymousType0<int, int>>(MyClass.<MixedBlock>b__2);\n }\n if (MyClass.CS$<>9__CachedAnonymousMethodDelegate6 == null)\n {\n MyClass.CS$<>9__CachedAnonymousMethodDelegate6 = new Func<<>f__AnonymousType0<int, int>, bool>(MyClass.<MixedBlock>b__3);\n }\n if (MyClass.CS$<>9__CachedAnonymousMethodDelegate7 == null)\n {\n MyClass.CS$<>9__CachedAnonymousMethodDelegate7 = new Func<<>f__AnonymousType0<int, int>, int>(MyClass.<MixedBlock>b__4);\n }\n</code></pre>\n\n<p>(3). Before entering foreach over <code>query</code> I'd recommend to cache results of the preceding projection.</p>\n\n<pre><code>var query = from x in upper\n from y in lower\n where x + y == length\n select Tuple.Create(x, y).ToList();\n</code></pre>\n\n<p>(4). This statement can be computed only once when you enter the function. However you do the same work on every iteration.</p>\n\n<pre><code> thisBlock.Split(',')\n</code></pre>\n\n<p>All in one you can have something like this.</p>\n\n<pre><code>IEnumerable<string> MixedBlock(List<string> reelLayout, string thisBlock, int length)\n{\n List<string> result = new List<string>();\n\n string[] splits = thisBlock.Split(','); \n List<string> recentBlock = RecentBlock(length - 1, reelLayout);\n var upper = Enumerable.Range(1, length - 1);\n var lower = Enumerable.Range(1, totalWeight[thisBlock].Num);\n var query = from x in upper\n from y in lower\n where x + y == length\n select Tuple.Create(x, y).ToList();\n foreach (var t in query)\n {\n string upperBlock = string.Join(\",\", recentBlock.Skip(length - 1 - t.Item1));\n string lowerBlock = string.Join(\",\", splits.Take(t.Item2));\n results.Add(upperBlock + \",\" + lowerBlock);\n }\n\n return (results);\n}\n</code></pre>\n\n<p>I've tried both approaches on the code with the similar structure an in my case it seems to be 20% faster.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T14:48:37.380",
"Id": "6616",
"Score": "0",
"body": "+1: great explanations ...#3 was the first issue I spotted. If you are going to query and then immediately use the results in a `foreach`, you should transform to list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T13:38:40.370",
"Id": "7208",
"Score": "0",
"body": "Wait, why? That forces two iterations whereas foreach'ing the query straight to a yield return only incurs one."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T21:19:46.483",
"Id": "4403",
"ParentId": "4400",
"Score": "2"
}
},
{
"body": "<p>You're doing way more iterations than are necessary.. you don't need 2 enumerables of ints just to do this, that's a lot more heap references when all your need are 2 integers right on the stack, and a nested for loop:</p>\n\n<pre><code>int upperLimit = length - 1;\nint lowerLimit = totalWeight[thisBlock].Num;\nList<string> recentBlock = RecentBlock(length - 1, reelLayout);\nList<string> stringResults = new List<string>();\n\nfor(int upper = 1; upper < upperLimit; upper++)\n{\n for(int lower = 1; lower < lowerLimit; lower++)\n {\n if (upper + lower = length)\n {\n stringResults.Add(\n string.Join(\",\", recentBlock.Skip(length - 1 - upper)) + \",\" +\n string.Join(\",\", splits.Take(lower)));\n }\n }\n}\n\nreturn stringResults;\n</code></pre>\n\n<p>also instead of doing the <code>stringResults.Add</code> you could just <code>yield return</code> the string right there if you wanted to allow delayed execution.</p>\n\n<p>Remember, just because we now have tuples and all the happy linqiness, they can be used to simplify complex things, though sometimes they just make operations more complex. If performance is important, study up on what goes on underneath the linq before throwing it around too much.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T23:33:50.523",
"Id": "4406",
"ParentId": "4400",
"Score": "4"
}
},
{
"body": "<p>I think you're doing a second loop that you don't need mathematically.</p>\n\n<pre><code>where x + y == length\n</code></pre>\n\n<p>So therefore</p>\n\n<pre><code>x = length - y\n</code></pre>\n\n<p>Since length is fixed and y is the variable. x seems to be calculated simply to satisfy the where, and can therefore be removed as an iterator and simply calculated.</p>\n\n<p>Also the upper loop only went as far as length-1, so if <code>totalWeight[thisBlock].Num</code> is bigger, we use that instead.</p>\n\n<pre><code>var lower = Enumerable.Range(1, Math.Min(totalWeight[thisBlock].Num, length-1));\nvar query = from y in lower\n select Tuple.Create(length - y, y);\n</code></pre>\n\n<p>Doing this also collapses the LINQ query, which in turn allows us to remove the Tuple. Instead we can just subsitute (length - y) wherever we need the original x.</p>\n\n<pre><code>var lower = Enumerable.Range(1, Math.Min(totalWeight[thisBlock].Num, length-1));\nforeach (var t in lower)\n{\n string upperBlock = string.Join(\",\", recentBlock.Skip(length - 1 - (length-y)));\n string lowerBlock = string.Join(\",\", thisBlock.Split(',').Take(y));\n yield return upperBlock + \",\" + lowerBlock;\n}\n</code></pre>\n\n<p>Turn the Enumerable.Range/Foreach into a for loop.<br>\nAlso <code>length - 1 - (length-y)</code> becomes <code>y - 1</code></p>\n\n<pre><code>for (int y = 1; y <= Math.Min(totalWeight[thisBlock].Num, length-1); y++)\n{\n string upperBlock = string.Join(\",\", recentBlock.Skip(y - 1));\n string lowerBlock = string.Join(\",\", thisBlock.Split(',').Take(y));\n yield return upperBlock + \",\" + lowerBlock;\n}\n</code></pre>\n\n<p>Optimize out the splitting of thisBlock just so it's not done in a loop.</p>\n\n<p>Also combine the string join into 1 function using concat.</p>\n\n<p>So you end up with...</p>\n\n<pre><code>IEnumerable<string> MixedBlock(List<string> reelLayout, string thisBlock, int length)\n{\n List<string> recentBlock = RecentBlock(length - 1, reelLayout);\n var thisSplitBlock = thisBlock.Split(',');\n for (int y = 1; y <= Math.Min(totalWeight[thisBlock].Num, length-1); y++)\n {\n yield return string.Join(\",\", \n recentBlock.Skip(y - 1)\n .Concat(thisSplitBlock.Take(y));\n }\n}\n</code></pre>\n\n<p><strong>Note:</strong> This will output items in the reverse order from the original. If the order is important simply reverse the for loop.</p>\n\n<pre><code>for (int y = Math.Min(totalWeight[thisBlock].Num, length-1); y >= 1; y--)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T15:06:39.173",
"Id": "4531",
"ParentId": "4400",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T19:35:23.720",
"Id": "4400",
"Score": "6",
"Tags": [
"c#"
],
"Title": "plz help optimize the small code snippet, VS2010 profiling chart provided"
}
|
4400
|
<p>I created this class that connects to Gmail contacts, and enables you to add/edit/delete the contact. </p>
<p>I'm curious to see what others think of my code. If you see any areas for improvement, that would be awesome!</p>
<ol>
<li>The <code>contact[]</code> is purely for testing.</li>
<li>I also realize that it could be more robust, but for my needs, this is all that I need.</li>
</ol>
<p></p>
<pre><code><?php
class gmail {
private $email;
private $password;
private $gdata;
private $client;
public $protocolVersion = 3;
// Load Gmail Libraries
function __construct()
{
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata_Query');
Zend_Loader::loadClass('Zend_Gdata_Feed');
}
// SET CLASS VARIABLES
public function setOption($option, $value)
{
$this->$option = $value;
}
// LOGIN TO GMAIL
public function login()
{
if(!isset($this->email)) {
die("Email is not set");
}
if(!isset($this->password)) {
die("Password is not set");
}
$this->client = Zend_Gdata_ClientLogin::getHttpClient($this->email, $this->password, 'cp');
$this->client->setHeaders('If-Match: *');
$this->gdata = new Zend_Gdata($this->client);
$this->gdata->setMajorProtocolVersion($this->protocolVersion);
}
// Get contacts feed
public function getContacts($maxResults = 10)
{
try {
$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full');
$query->maxResults = $maxResults;
$query->setParam('orderby', 'lastmodified');
$query->setParam('sortorder', 'descending');
$feed = $this->gdata->getFeed($query);
return $feed;
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
// Determine the schema type from Google
// Remove everything but the actual Schema
public function determineSchemaType($value, $format = 'remove')
{
if(!isset($value)) {
die("Schema is not set.");
}
$standard = "http://schemas.google.com/g/2005#";
if($format == 'remove') {
$schema = str_replace($standard, '', $value);
} else if ($format == 'add') {
$schema = $standard . $value;
}
return $schema;
}
// Parse Contacts Feed into simpler objects
public function parseContactsFeed($feed)
{
if(empty($feed)) {
die("Feed is not set");
}
try {
$results = array();
foreach($feed as $entry){
$xml = simplexml_load_string($entry->getXML());
$obj = new stdClass;
// EDIT LINK
$obj->editLink = $entry->getEditLink()->href;
// FIRST Name
$obj->firstName = (string) $xml->name->givenName;
// LAST Name
$obj->familyName = (string) $xml->name->familyName;
// MIDDLE Name
$obj->middleName = (string) $xml->name->additionalName;
// Organization
$obj->orgName = (string) $xml->organization->orgName;
$obj->orgNameRel = (string) $this->determineSchemaType($xml->organization['rel']);
// Organization Title
$obj->orgTitle = (string) $xml->organization->orgTitle;
// Get All Email Addresses
foreach ($xml->email as $e) {
$obj->emailAddress[] = (string) $e['address'];
$obj->emailType[] = (string) $this->determineSchemaType($e['rel']);
}
// Get ALL Phone Numbers
foreach ($xml->phoneNumber as $p) {
$obj->phoneNumber[] = (string) $p;
}
// Get ALL Web Addresses
foreach ($xml->website as $w) {
$obj->website[] = (string) $w['href'];
$obj->websiteType[] = (string) $w['rel'];
}
foreach($xml->structuredPostalAddress as $address) {
$obj->addressType[] = (string) $this->determineSchemaType($address['rel']);
$obj->addressStreet[] = (string) $address->street;
$obj->addressPOBox[] = (string) $address->pobox;
$obj->addressPostalCode[] = (string) $address->postcode;
$obj->addressCity[] = (string) $address->city;
$obj->addressRegion[] = (string) $address->region;
$obj->addressCountry[] = (string) $address->country;
}
$results[] = $obj;
}
return $results;
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
// CREATE Contact Object
public function contact($contact, $action = 'add')
{
if(!isset($contact)) {
die("Contact is not set");
}
try {
$contact = array();
$contact['gmailEditLink'] = "http://www.google.com/m8/feeds/contacts/account@gmail.com/base/534653f6089a7ba9";
$contact['name'] = "John Doe";
$contact['firstName'] = "John 2";
$contact['middleName'] = 'Middle';
$contact['lastName'] = 'Doe 2';
$contact['emailWork'] = 'john2@johndoe.com';
$contact['emailPersonal'] = 'john2@gmail.com';
$contact['company'] = "John Deere";
$contact['title'] = "Owner";
$contact['homePhone'] = "250-869-5952";
$contact['mobilePhone'] = "250-869-5952";
$contact['workPhone'] = "250-869-5952";
$contact['workPhone2'] = "250-869-5952";
$contact['fax'] = "250-869-5952";
$contact['workCity'] = "Ktown";
$contact['workAddress'] = "111 Venus Rd";
$contact['workAddress2'] = "Unit 111";
$contact['workProvince'] = "BC";
$contact['workZipCode'] = "v1p 1b1";
$contact['workCountry'] = "Canada";
$contact['homeCity'] = "Ktown";
$contact['homeAddress'] = "222 Venus Rd";
$contact['homeAddress2'] = "Unit 111";
$contact['homeProvince'] = "BC";
$contact['homeZipCode'] = "v1p 1b1";
$contact['homeCountry'] = "Canada";
$doc = new DOMDocument();
$doc->formatOutput = true;
$entry = $doc->createElement('atom:entry');
$entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:atom', 'http://www.w3.org/2005/Atom');
$entry->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:gd', 'http://schemas.google.com/g/2005');
$doc->appendChild($entry);
// NAME
$name = $doc->createElement('gd:name');
$entry->appendChild($name);
$firstName = $doc->createElement('gd:givenName', $contact['firstName']);
$name->appendChild($firstName);
$middleName = $doc->createElement('gd:additionalName', $contact['middleName']);
$name->appendChild($middleName);
$lastName = $doc->createElement('gd:familyName', $contact['lastName']);
$name->appendChild($lastName);
// EMAILS
$email = $doc->createElement('gd:email');
$email->setAttribute('address', $contact['emailWork']);
$email->setAttribute('displayName', $contact['firstName'] ." ". $contact['lastName']);
$email->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
$entry->appendChild($email);
$email = $doc->createElement('gd:email');
$email->setAttribute('address', $contact['emailPersonal']);
$email->setAttribute('displayName', $contact['firstName'] ." ". $contact['lastName']);
$email->setAttribute('rel' ,'http://schemas.google.com/g/2005#home');
$entry->appendChild($email);
// PHONE NUMBERS
$phone = $doc->createElement('gd:phoneNumber', $contact['homePhone']);
$phone->setAttribute('rel', 'http://schemas.google.com/g/2005#home');
$entry->appendChild($phone);
$phone = $doc->createElement('gd:phoneNumber', $contact['mobilePhone']);
$phone->setAttribute('rel', 'http://schemas.google.com/g/2005#mobile');
$entry->appendChild($phone);
$phone = $doc->createElement('gd:phoneNumber', $contact['workPhone']);
$phone->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
$entry->appendChild($phone);
$phone = $doc->createElement('gd:phoneNumber', $contact['workPhone2']);
$phone->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
$entry->appendChild($phone);
$phone = $doc->createElement('gd:phoneNumber', $contact['fax']);
$phone->setAttribute('rel', 'http://schemas.google.com/g/2005#fax');
$entry->appendChild($phone);
// ORGANIZATION
$org = $doc->createElement('gd:organization');
$org->setAttribute('rel' ,'http://schemas.google.com/g/2005#work');
$entry->appendChild($org);
$orgName = $doc->createElement('gd:orgName', $contact['company']);
$org->appendChild($orgName);
$orgName = $doc->createElement('gd:orgTitle', $contact['title']);
$org->appendChild($orgName);
// WORK ADDRESS
$workAddress = $doc->createElement('gd:structuredPostalAddress');
$workAddress->setAttribute('rel', 'http://schemas.google.com/g/2005#work');
$entry->appendChild($workAddress);
$workCity = $doc->createElement('gd:city', $contact['workCity']);
$workAddress->appendChild($workCity);
$workStreet = $doc->createElement('gd:street', $contact['workAddress'] ." :: ". $contact['workAddress2']);
$workAddress->appendChild($workStreet);
$workProvince = $doc->createElement('gd:region', $contact['workProvince']);
$workAddress->appendChild($workProvince);
$workZipCode = $doc->createElement('gd:postcode', $contact['workZipCode']);
$workAddress->appendChild($workZipCode);
$workCountry = $doc->createElement('gd:country', $contact['workCountry']);
$workAddress->appendChild($workCountry);
// WORK ADDRESS
$homeAddress = $doc->createElement('gd:structuredPostalAddress');
$homeAddress->setAttribute('rel', 'http://schemas.google.com/g/2005#home');
$entry->appendChild($homeAddress);
$homeCity = $doc->createElement('gd:city', $contact['homeCity']);
$homeAddress->appendChild($homeCity);
$homeStreet = $doc->createElement('gd:street', $contact['homeAddress'] ." :: ". $contact['homeAddress2']);
$homeAddress->appendChild($homeStreet);
$homeProvince = $doc->createElement('gd:region', $contact['homeProvince']);
$homeAddress->appendChild($homeProvince);
$homeZipCode = $doc->createElement('gd:postcode', $contact['homeZipCode']);
$homeAddress->appendChild($homeZipCode);
$homeCountry = $doc->createElement('gd:country', $contact['homeCountry']);
$homeAddress->appendChild($homeCountry);
// SAVE CONTACT
if($action == 'add') {
$this->addContact($doc->saveXML());
}
// UPDATE CONTACT
if($action == 'update') {
$this->updateContact($doc->saveXML(), $contact['gmailEditLink']);
}
// SHOW CONTACT
if($action == 'show') {
echo "<pre>";
print_r($doc->saveXML());
echo "</pre>";
}
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
// SAVE Contact
public function addContact($xml)
{
if(!isset($xml)) {
die("XML is not set");
}
$results = $this->gdata->insertEntry($xml, 'http://www.google.com/m8/feeds/contacts/default/full');
echo $results->id;
}
// UPDATE Contact
public function updateContact($xml, $editLink)
{
if(!isset($xml)) {
die("XML is not set");
}
try {
$extra_header = array();
$extra_header['If-Match'] = '*';
$entryResult = $this->gdata->updateEntry($xml, $editLink, null, $extra_header);
echo 'Entry updated';
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
// DELETE Contact
public function deleteContact($editUrl)
{
if(!isset($editUrl)) {
die("Url is not set");
}
try {
$this->protocolVersion = 1;
$this->login();
$entry = $this->gdata->getEntry($editUrl);
$this->gdata->delete($entry);
echo '<h2>Delete Contact</h2>';
echo 'Entry deleted';
} catch (Exception $e) {
die('ERROR:' . $e->getMessage());
}
}
}
?>
</code></pre>
|
[] |
[
{
"body": "<p>A few things to point out:</p>\n\n<hr>\n\n<blockquote>\n<pre><code> $feed = $this->gdata->getFeed($query);\n return $feed;\n</code></pre>\n</blockquote>\n\n<p>You can just <code>return</code> feed directly without initialising it.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public function determineSchemaType($value, $format = 'remove')\n{\n if(!isset($value)) {\n die(\"Schema is not set.\");\n }\n\n $standard = \"http://schemas.google.com/g/2005#\";\n\n if($format == 'remove') {\n $schema = str_replace($standard, '', $value);\n\n } else if ($format == 'add') {\n $schema = $standard . $value;\n }\n\n return $schema;\n}\n</code></pre>\n</blockquote>\n\n<ul>\n<li>You should be keeping consistent spacing after your <code>if</code>s</li>\n<li>If the <code>$format</code> is not <code>remove</code> or <code>add</code>, <code>$schema</code> will return undefined/null</li>\n</ul>\n\n<hr>\n\n<blockquote>\n<pre><code> $results[] = $obj;\n }\n\n\n return $results;\n</code></pre>\n</blockquote>\n\n<p>Why are there so many extraneous empty lines?</p>\n\n<hr>\n\n<blockquote>\n<pre><code> $results = $this->gdata->insertEntry($xml, 'http://www.google.com/m8/feeds/contacts/default/full');\n echo $results->id;\n</code></pre>\n</blockquote>\n\n<p>What's wrong with combining them?</p>\n\n<pre><code>echo $this->gdata->insertEntry($xml, 'http://www.google.com/m8/feeds/contacts/default/full')->id;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-01T17:56:35.293",
"Id": "187836",
"Score": "0",
"body": "Hey thanks for the feedback, appreciate the response! Been awhile the class has evolved a bit since then. But the general feedback is always good."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-01T21:06:03.020",
"Id": "187873",
"Score": "0",
"body": "@Justin You might want to consider posting a self-answer to your question, with information about what you improved with your original code and why/how."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-01T13:48:30.207",
"Id": "102500",
"ParentId": "4404",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-25T21:31:05.760",
"Id": "4404",
"Score": "7",
"Tags": [
"php",
"email",
"zend-framework",
"google-contacts-api"
],
"Title": "Gmail contacts API connection"
}
|
4404
|
<p>This may be a naive question, but what are the dangers of the following code (allocate more memory in the new operator for the info struct)?</p>
<pre><code>struct Info
{
Info():nLineNo(0){memset(cFile, 0, 256);}
~Info(){}
char cFile[256];
unsigned int nLineNo;
};
void *operator new(size_t Size, const char *pcFile, const unsigned int nLine)
{
Info *pData = 0;
pData = (Info*)malloc(Size + sizeof(Info));
strcpy(pData->cFile, pcFile);
pData->nLineNo = nLine;
return (void*)pData;
}
void operator delete(void *pData)
{
Info *pInfo = (Info*)pData;
// could use pInfo->nLineNo to check for it within hash table of allocated blocks - just an example
free(pData);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:30:59.720",
"Id": "6610",
"Score": "0",
"body": "Yes. Put that code in a constructor."
}
] |
[
{
"body": "<p>You are not overloading the new operator correctly.</p>\n<p>See: <a href=\"https://stackoverflow.com/q/7194127/14065\">How should I write ISO C++ Standard conformant custom new and delete operators?</a></p>\n<p>But you should not be overloading new at all.\nAll the work you are doing here is stuff that goes in the constructor.</p>\n<p>The sole job of the new operator is to allocate memory (not initialize it).</p>\n<h3>As a side note:</h3>\n<p>Though you can actually add parameters to new.<br />\nDoing so is not a good idea.<br />\nAs it is not normal, and thus makes it harder to maintain.</p>\n<p>The code above will be called if you do:</p>\n<pre><code>// Note: The first parameter (ie size) will be auto inserted as the first parameter.\nInfo* data = new ("File Name", 12) Info;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:35:28.047",
"Id": "4413",
"ParentId": "4412",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T12:25:00.517",
"Id": "4412",
"Score": "5",
"Tags": [
"c++",
"memory-management"
],
"Title": "Overloading the new operator"
}
|
4412
|
<p>I have this JavaScript function which gets prices from a table, adds them up, and outputs the total cost. I want to refactor this to make it as small as possible. </p>
<pre><code>function getTotalPrice(do_request)
{
console.log('Get total price');
var prices_array = new Array(); // Where our prices are held
// For each .total_item_price - a <td> within my table.
$(".total_item_price").each(function(){
var text = $(this).text(); // Get the value
var prices = text.substring(1, text.length); // Format it into a string
prices_array.push(prices); // Push it onto our array
});
var result = eval(0);
// Add up our array
for(i = 0; i < prices_array.length; i++)
{
temp = eval(prices_array[i]);
result += temp;
}
// Round up our result to 2 Decimal Places
result = Math.round(result*100)/100;
// Output/Return our result
if (do_request == null)
{
// We want to add our shipping Price and Display the total
// Get the Shipping Price
//var shipping_price = $(".shipping_price").html();
//shipping_price = shipping_price.substring(1, shipping_price.length);
if ($(".tbl_row").length == 1) // If only 1 row exists (How do I do this?)
{
var size = $(".size").html();
if((size == "A5") && ($('input[name="qty"]').val() == '1'))
{
console.log(' - A5 - ');
$('.shipping_price').html('£0.67'); // Show Shipping Price (A5)
}
else if((size == 'A4') && ($('input[name="qty"]').val() == '1'))
{
console.log(' - A4 - ');
console.log($('input[name="qty"]').val());
$('.shipping_price').html('£0.87'); // Show Shipping Price (A4)
}
else
{
console.log('More then 1 Qty');
$('.shipping_price').html('£0.97'); // Show Shipping Price (A4)
}
}
else // More then 1 row exists, so the price will be £0.97
{
console.log('false, More rows exists');
$('.shipping_price').html('£0.97') // Show Shipping Price (A4)
}
var shipping_price = $(".shipping_price").html();
shipping_price = shipping_price.substring(1, shipping_price.length);
// Add em
//result += eval(shipping_price);
result += eval(shipping_price);
// Round our result to 2 decimal places
var result=Math.round(result*100)/100;
// Update & Display the Result
$('.total_order_price').html("<b>£" + result + "</b>");
}
else
{
// Otherwise we just want the total price and return it.
return result;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T23:47:57.123",
"Id": "6626",
"Score": "1",
"body": "Guard statement anytime you have a statement block (anything in `{}`) where the entire body is an if, reverse the condition of the if and return inside of it, then you don't need the rest in an else and it increases readability. Otherwise, just break this method up into multiple and make this one call the others."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-31T00:50:56.160",
"Id": "105179",
"Score": "0",
"body": "what is `result=eval(0)` -- is that some kind of 'better zero' I don't know about?"
}
] |
[
{
"body": "<p>First, I would switch from using eval to parseFloat, since it appears that eval provides no extra features and allows arbitrary code to be executed unless you just happen to have values other then numbers in total_item_price tds. </p>\n\n<p>Second, since you are performing no extra processing with prices_array, it would be better to skip the array altogether and combine:</p>\n\n<pre><code> var prices_array = new Array(); // Where our prices are held\n // For each .total_item_price - a <td> within my table.\n $(\".total_item_price\").each(function(){\n var text = $(this).text(); // Get the value\n var prices = text.substring(1, text.length); // Format it into a string\n prices_array.push(prices); // Push it onto our array\n });\n\n var result = eval(0);\n // Add up our array\n for(i = 0; i < prices_array.length; i++)\n {\n temp = eval(prices_array[i]);\n result += temp;\n }\n</code></pre>\n\n<p>into (with result renamed as totalSum for readability):</p>\n\n<pre><code> var totalSum = 0;\n // For each .total_item_price - a <td> within my table.\n $(\".total_item_price\").each(function(){\n var text = $(this).text(); // Get the value\n var price = text.substring(1, text.length); // Format it into a string\n price = parseFloat(price);\n totalSum += price;\n });\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T16:20:36.267",
"Id": "4416",
"ParentId": "4415",
"Score": "6"
}
},
{
"body": "<p>Here's one that should take everything into account, including Qty.</p>\n\n<pre><code>function getTotalPrice(do_request){\n\n var result = 0;\n\n $(\".total_item_price\").each(function() { \n result += (+$(this).text().slice(1)); // Retrieve price, trim pound sign, convert to num\n })\n\n // Short circuit early\n if (!do_request) return result.toFixed(2); \n\n // Add shipping depending on qty and size\n var shipping = ( +$('input[name=\"qty\"]').val() > 1 ? 0.97\n : 'A5' === $(\".size\").html() ? 0.87\n : /*Qty === 1 and size must be A4*/ 0.67\n );\n\n // Update & Display the Result\n $('.shipping_price').html('£'+shipping) \n $('.total_order_price').html('<b>£' + (result+shipping).toFixed(2) + '</b>');\n\n // Return result for consistency\n return result;\n\n} \n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T15:03:01.417",
"Id": "4434",
"ParentId": "4415",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4416",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-26T15:27:39.033",
"Id": "4415",
"Score": "3",
"Tags": [
"javascript",
"jquery"
],
"Title": "Displaying total cost of prices from a table"
}
|
4415
|
<p>I'm using this little macro a lot:</p>
<pre><code>#define RUN_ONCE(runcode) \
{ \
static bool code_ran = 0; \
if(!code_ran){ \
code_ran = 1; \
runcode; \
} \
}
</code></pre>
<p>I find it useful when I want to initialize stuff just once when I don't really care about performance (for example, if it's inside a render loop, it takes just 60 if's per sec). In a random generator, I can do <code>RUN_ONCE(init_random())</code>, so I don't need to separately initialize it, which prevents me from crashing when I call the function without initializing it first.</p>
<p>I'd like to know if any of you use a similar system, and if there's better way of doing this. Or if I should stop using this method immediately...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T15:53:56.380",
"Id": "283236",
"Score": "2",
"body": "Note that since C++11 `magic statics` guarantees that a static value in function scope will be initialised exactly once even in the presence of multiple threads. `static int result_of_run_once = runcode()` will do it right if your `runcode()` has a return value. Otherwise use `std::call_once` also since C++11."
}
] |
[
{
"body": "<p>It is not thread safe. You can use <a href=\"http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.once\" rel=\"noreferrer\">Boost</a>, or standard C++11 <a href=\"http://en.cppreference.com/w/cpp/thread/call_once\" rel=\"noreferrer\"><code>std::call_once</code></a>.</p>\n\n<p>Answer to comment:</p>\n\n<p>Boost and C++11 are defining include library for launching threads and thread synchronization (locks, atomic variables…). The <code>call_once</code> function can either use those to ensure thread safety or use the thread lib of the OS (pthreads for *nix).</p>\n\n<p>A very simplified (unefficent) implementation might be:</p>\n\n<pre><code>static std::mutex mutex;\nstatic bool called = false;\n{\n std::lock_guard<std::mutex> lock(mutex);\n if (!called) {\n f(); // <- User code\n called = true;\n }\n}\n</code></pre>\n\n<p>It is not very efficient because the lock is always taken. An optimisation it to atomically check the once flag before taking the mutex:</p>\n\n<pre><code>static std::mutex mutex;\nstatic std::atomic<bool> called = false;\n{\n if (!called) {\n std::lock_guard<std::mutex> lock(mutex);\n if (!called) {\n f(); // <- User code\n called = true;\n }\n }\n}\n</code></pre>\n\n<p>The implementation of <code>pthread_once</code> in glibc is interesting: it is much more complicated as it tries to behave correctly in presence of <code>fork</code>.</p>\n\n<p>Boost/C++11 use a functor (function pointer or object with <code>operator()</code>): this way it can be implemented as a function and not a macro (you can use lambda in C++11 to avoid defining a separate function).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T00:50:01.170",
"Id": "6627",
"Score": "1",
"body": "just out of interest, how does boost solve this problem about thread safety? also, the boost needs a function pointer, why is that better? i wouldnt want to make a function for every of these things, thats the whole point of my method..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-12T11:04:53.407",
"Id": "76439",
"Score": "0",
"body": "The code is more complicated because it deals with multiple threads concurrently entering the function. If so, only one thread should run the code, but all should wait until it is done."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-24T11:07:56.343",
"Id": "193352",
"Score": "0",
"body": "@SebastianRedl, it is already handled by the mutex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-12-21T17:25:53.497",
"Id": "283260",
"Score": "1",
"body": "@ysdx with `std::atomic<>` one can use the`fetch_or()` method to simplify the code a lot. I show how to do it here: http://codereview.stackexchange.com/a/49168/42067"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T00:41:35.710",
"Id": "4423",
"ParentId": "4422",
"Score": "18"
}
},
{
"body": "<p>Why are you putting code that determines correct usage of the function external to the function.</p>\n\n<p>Rather than that why not put the code inside the function then it can never be used incorrectly.<br>\nThe top priority is maintenance and re-use. You should write your code so that it can not be used incorrectly.</p>\n\n<p>Thus rather than:</p>\n\n<pre><code>#define RUN_ONCE(runcode) \\\n{ \\\n static bool code_ran = 0; \\\n if(!code_ran){ \\ \n code_ran = 1; \\\n runcode; \\\n } \\\n}\n\nvoid init_random()\n{\n srand(time(NULL));\n}\n\nint main()\n{\n RUN_ONCE(init_random())\n}\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>void init_random()\n{\n static bool code_ran = 0;\n if(!code_ran)\n {\n code_ran = 1;\n srand(time(NULL));\n }\n}\n\nint main()\n{\n init_random();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T10:46:44.760",
"Id": "6629",
"Score": "0",
"body": "the whole point of my macro was that i dont have to write that what you did in `init_random()`. it is so general thing i have repeated it in dozen of functions, and i always forget what was the variable name i used there (i want consistent code...), also the point of my macro is that it uses curly brackets AROUND the whole code, making the static variable only visible in that part of code i assigned there with my macro, thus i have very little possibility of any variable name collisions, and this eliminates my problem of \"thinking variable name\". also, how exactly is yours easier to maintain ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T10:48:45.770",
"Id": "6630",
"Score": "0",
"body": "the mistake you did in your example was to assume that i would do the check outside of the init_random() function btw, i would do it: `void init_random(){ RUN_ONCE(srand(time(NULL))); }` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T16:52:32.117",
"Id": "6631",
"Score": "0",
"body": "@CocoCoder: Do you actually think that using the macro actually makes the code clearer? In my opinion the answer is no. But if you (and the people that maintain the code) think it is perfectly readable then it is OK. Maintainability is they key as most code will be in maintenance mode a lot longer than it is in development. I think using a macro to save a few keystrokes is not worth the effort and extra cost of maintenance. You are basically swapping easy of programming for more difficult maintenance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T23:19:31.473",
"Id": "6638",
"Score": "0",
"body": "can you tell me why is my macro harder to maintain ? what could possibly go wrong in it and so on."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T23:36:10.390",
"Id": "6640",
"Score": "0",
"body": "@CocoCoder: Its a macro. Thus it is not de-buggable. Macros are not pat of the language (they are simple text replacement tools) thus neither the compiler or debugger understand them. But its not just that you are adding a whole layer of un-needed indirection into the code that makes it hard to read. Also your macro is written badly. If it looks like a function call I expect it to behave like one (and thus be usable wherever a normal function is encountered (your code will fail in several situations). see here: http://codereview.stackexchange.com/q/1679/507"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T06:37:19.500",
"Id": "4425",
"ParentId": "4422",
"Score": "3"
}
},
{
"body": "<p>Note that macros such as this should be placed in a <code>do {</code> ... <code>} while (0)</code> block, otherwise you will encounter problems when the macro is invoked prior to an <code>else</code>, i.e.</p>\n\n<pre><code>#define RUN_ONCE(runcode) \\\ndo \\\n{ \\\n static bool code_ran = 0; \\\n if (!code_ran) \\\n { \\ \n code_ran = 1; \\\n runcode; \\\n } \\\n} while (0)\n</code></pre>\n\n<p>e.g. if you have a situation like this:</p>\n\n<pre><code>if (do_foo)\n RUN_ONCE(foo());\nelse\n printf(\"do_foo is false\\n\");\n</code></pre>\n\n<p>without a <code>do</code> ... <code>while (0)</code> this will expand to:</p>\n\n<pre><code>if (do_foo)\n {\n static bool code_ran = 0;\n if (!code_ran)\n { \n code_ran = 1;\n foo();\n }\n }; // <<< syntax error here !\nelse\n printf(\"do_foo is false\\n\");\n</code></pre>\n\n<p>But using the <code>do</code> ... <code>while (0)</code> form we get:</p>\n\n<pre><code>if (do_foo)\n do\n {\n static bool code_ran = 0;\n if (!code_ran)\n { \n code_ran = 1;\n foo;\n }\n } while (0); // <<< no syntax error here !\nelse\n printf(\"do_foo is false\\n\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T18:20:36.057",
"Id": "6750",
"Score": "0",
"body": "care to show example where there will be an error? i dont really understand the point of this while loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T21:32:56.353",
"Id": "6755",
"Score": "0",
"body": "@CocoCoder: OK - see edited answer for example"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T21:43:22.290",
"Id": "6756",
"Score": "0",
"body": "See also: http://codereview.stackexchange.com/questions/1679/do-statement-while0-against-statement-when-writing-c-macro"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-21T21:25:22.753",
"Id": "7394",
"Score": "0",
"body": "i see, that will be catched via compiler though, so no problems"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-21T21:32:37.777",
"Id": "7396",
"Score": "0",
"body": "@CocoCoder: yes, it will generate a compile error - that's the whole point - better to write the macro properly so that it can be used anywhere *without* generating any errors."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T19:27:32.373",
"Id": "4502",
"ParentId": "4422",
"Score": "13"
}
},
{
"body": "<p>Macros are generally a bad choice because some mad sod always finds a bad way to use them...</p>\n\n<pre><code>RUN_ONCE(}else{ or_not();)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-21T21:26:39.930",
"Id": "7395",
"Score": "0",
"body": "that argument could apply to anything."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-04-05T03:52:59.313",
"Id": "16968",
"Score": "0",
"body": "and the code is wrong too . . . ;)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T13:31:19.907",
"Id": "4680",
"ParentId": "4422",
"Score": "1"
}
},
{
"body": "<p>I prefer this over the macro-with-arguments version.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#define RUN_ONCE \\\n for (static bool _run_already_ = false; \\\n _run_already_ ? false : _run_already_ = true;) \\\n/***/\n</code></pre>\n\n<p>The above <strong>is not</strong> thread-safe, though. To make it thread safe, one could use <code>std::atomic<></code>, but only if using C++11 and above.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <atomic>\n\n#define RUN_ONCE \\\n for (static std::atomic<int> _run_already_(false); \\\n !_run_already_.fetch_or(true);) \\\n/***/\n</code></pre>\n\n<p>I used <code>int</code> rather than <code>bool</code> as the <code>std::atomic<></code> template parameter because the standard <a href=\"https://stackoverflow.com/a/30869374/566849\">doesn't seem to require the <code>bool</code> specialization</a> to implement the <code>fetch_or()</code> method.</p>\n\n<p>Either way, it can be used like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>RUN_ONCE\n{\n printf(\"Hello only once!\\n\");\n /* Other statements follow */\n}\n</code></pre>\n\n<p>Or like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>RUN_ONCE printf(\"Hello only once!\\n\");\n</code></pre>\n\n<p>It also supports returning directly from the <code>RUN_ONCE</code> body:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>// Returns false the first time it's invoked,\n// then it always returns true\nbool test_run_once() {\n RUN_ONCE return false;\n\n return true;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-10-14T13:23:59.840",
"Id": "530572",
"Score": "0",
"body": "But doesn't C++11 already have \"magic static\" variables that get initialised only once, making the use of `std::atomic` redundant? (See `Emily L`'s comment to the initial question.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-07T17:43:12.533",
"Id": "49168",
"ParentId": "4422",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4423",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T00:13:27.237",
"Id": "4422",
"Score": "12",
"Tags": [
"c++",
"macros"
],
"Title": "Macro to run code once during the lifetime of the program"
}
|
4422
|
<p>This is a page that allow user to do register:</p>
<pre><code><?php echo form_open('user/valid_register_page', 'autocomplete="off"');?>
<?php $this->table->set_template(array('table_open'=>'<table class="table_form_register">'));
$this->table->add_row(form_label($label_email.
form_label(form_error('email'),'',array('class' => 'error_label')),
'label_email',
array('class' => 'form_label')),
array('class' => 'align_right_td',
'data' => form_input('email',
set_value('email'),
'class = "align_right_input require"')));
$this->table->add_row(form_label($label_invitation_key.
form_label(form_error('invitation_key'),'',array('class' => 'error_label')),
'label_invitation_key',
array('class' => 'form_label')),
array('class' => 'align_right_td',
'data' => form_password('invitation_key',
set_value('invitation_key'),
'class = "align_right_input require"')));
$this->table->add_row('',array('class' => 'button_td',
'data' => form_submit('register', $button_register, 'class = "form_td_button"')));
echo $this->table->generate();
?>
<?php echo form_close();?>
</code></pre>
<p>This code only have 2 label and 2 fields: one is email, another is the invitation keys. This is the code that render for generation the form, table, and the button with these 2 label and fields. But as you can see, it is very messy, if I need to maintain, it will become a headache. Any suggestions on how to make it simpler?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T15:32:43.890",
"Id": "6745",
"Score": "0",
"body": "Try to avoid mixing PHP and HTML. See this for some advice: http://stackoverflow.com/questions/62617#95027"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T21:05:55.610",
"Id": "6902",
"Score": "1",
"body": "I really don't get these \"HTML helpers\". The name suggests they should be helping, while all I see is an incredibly verbose way to write what would be a lot more readable as plain HTML."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-04-14T18:12:35.620",
"Id": "234594",
"Score": "0",
"body": "Yeah, opening and closing `<?php` is very messy, ideally you should only use that tag once."
}
] |
[
{
"body": "<p>You could start by removing dynamic HTML generation where there is no benefit in it. You would be much better of writing something like this :</p>\n\n<pre><code><?php\n $form = $this->form;\n?>\n<form action=\"<?php echo $form->get_destination(); ?>\" method=\"post\">\n <ul>\n <li>\n <?php echo $form->render_field( 'email' ); ?>\n </li>\n <li>\n <?php echo $form->render_field( 'invitation_key' ); ?>\n </li>\n <li><?php echo $form->render_field( 'submit' ); ?></li>\n </ul>\n</form>\n</code></pre>\n\n<p>Yes, none of it is CodeIgniter , but then again i have huge dislike for frameworks with crappy OOP.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T22:18:07.183",
"Id": "4440",
"ParentId": "4424",
"Score": "3"
}
},
{
"body": "<p>This seems to me to be one single piece of php so therefore you should put all the code above into a single</p>\n\n<pre><code><?php\n//Put your php code here.\n</code></pre>\n\n<p>Use indentation correctly and consistently.</p>\n\n<p>The general consensus for use of end php brakets <code>?></code> is that you do not include it at the end of the file. PHP does this automatically, and it avoids certain hard to find bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T17:31:40.727",
"Id": "6702",
"Score": "0",
"body": "Minus the last ?> as it's not needed and reduces the whitespace being sent to the client."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-14T02:35:27.577",
"Id": "10676",
"Score": "0",
"body": "@TobyAllen I agree with Levinaris as do others: http://stackoverflow.com/questions/3219383/why-do-some-scripts-omit-the-closing-php-tag"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T20:32:22.210",
"Id": "4459",
"ParentId": "4424",
"Score": "1"
}
},
{
"body": "<p>No need to open and close php tags over and over. just open them at the beginning, then close them at the end. </p>\n\n<p>Also, you're stringing array after array in there. create variables to hold the arrays and create them before they're needed. Then, you can use them in the add_row calls. This will clean up most of the code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T15:30:18.147",
"Id": "4485",
"ParentId": "4424",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T04:17:26.480",
"Id": "4424",
"Score": "4",
"Tags": [
"php",
"html",
"codeigniter",
"layout"
],
"Title": "Web register form"
}
|
4424
|
<p>I wrote this program which finds the definite integral of a function. Where in the program could I optimize this code:</p>
<pre><code>def trapezium(f,n,a,b):
h=(b-a)/float(n)
area = (0.5)*h
sum_y = (f(0)+f(b))
i=a
while i<b:
print i
sum_y += 2*f(i)
i += h
area *= sum_y
return area
def f(x):
return x ** 2
print trapezium(f, 10000, 0, 5)
</code></pre>
|
[] |
[
{
"body": "<p>First, there is an error where you have:</p>\n\n<pre><code>sum_y = (f(0)+f(b))\n</code></pre>\n\n<p>f(0) should be f(a). It doesn't matter on your example, because you start with 0, but would otherwise.</p>\n\n<p>Another error is that you add f(a) 3x instead of just once. i=a+h should be the line before while.</p>\n\n<p>Your while loop makes O(n) multiplications and twice as many additions. Instead you should have something like:</p>\n\n<pre><code>i = a+h\npart_sum = 0\nwhile i<b:\n part_sum += f(i)\n i += h\nsum_y += 2*part_sum\n</code></pre>\n\n<p>Still same number of additions, but only one multiplication.</p>\n\n<p>Using list comprehensions might be a bit faster, but you'd spend too much memory at scale where it matters.</p>\n\n<p>print significantly slows your function. If you actually need to print this, then store intermediate results in array and then print them before final result with print \"\\n\".join(intermediates).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T09:37:05.813",
"Id": "4430",
"ParentId": "4426",
"Score": "6"
}
},
{
"body": "<pre><code>def trapezium(f,n,a,b):\n</code></pre>\n\n<p>I recommend a docstring explaining the arguments</p>\n\n<pre><code> h=(b-a)/float(n)\n</code></pre>\n\n<p>I recommend adding <code>from __future__ import division</code> so that division always results in a float rather then doing this.</p>\n\n<pre><code> area = (0.5)*h\n</code></pre>\n\n<p>Drop the (): <code>area = 0.5*h</code></p>\n\n<pre><code> sum_y = (f(0)+f(b))\n</code></pre>\n\n<p>Drop the (): <code>sum_y = f(0) + f(b)</code></p>\n\n<pre><code> i=a\n while i<b:\n print i\n sum_y += 2*f(i)\n i += h\n</code></pre>\n\n<p>Should you be printing here? I assume not. You should use a for loop</p>\n\n<pre><code>for i in xrange(a,b,h):\n sum_y += 2 * f(i)\n</code></pre>\n\n<p>Or better yet a generator expression:</p>\n\n<p>sum_y += sum(2*f(i) for i in xrange(a,b,h))</p>\n\n<p>...</p>\n\n<pre><code> area *= sum_y\n\n\n return area\n</code></pre>\n\n<p>Why so many blank lines?</p>\n\n<pre><code>def f(x):\n return x ** 2\n\n\n\nprint trapezium(f, 10000, 0, 5)\n</code></pre>\n\n<p>If you are interested in getting more speed, you should look at numpy.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T08:42:34.313",
"Id": "6645",
"Score": "0",
"body": "I had to use a `while` loop because `range` doesn't accept a float value(here, h needs to be float). Know of any way around that? Thanks for all the other advice too, I'll keep them in mind."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T13:07:53.200",
"Id": "6647",
"Score": "0",
"body": "@infoquad, I should have known that. I'd solve it by using numpy which has arange which allows floats."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T14:42:08.037",
"Id": "4433",
"ParentId": "4426",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T07:46:22.863",
"Id": "4426",
"Score": "2",
"Tags": [
"python"
],
"Title": "finding definite integrals in Python using Trapezium rule"
}
|
4426
|
<p>Imagine a UTF-8 decoder that takes a list of bytes and returns human-readable code points like: </p>
<pre><code>> (utf-8->human-readable-code-points '(32 32 195 160 160))
("u+0020" "u+0020" "u+00E0" ("Error: trailing byte without preceding start byte" 160))
</code></pre>
<p>This list builder functionality is meant for that function:</p>
<pre><code>;; a list builder will allow us to build a list
;; by successively adding to the end without retracing
;; the list each time. And without having a stack of
;; cons calls to unwind. Will allow constructing a list
;; in order in a tail call fashion
;; (list-builder 'add! item) -- returns list so far
;; (list-builder 'list) -- returns list so far
(define (make-list-builder)
(let [(list-under-construction '())
(last-cons-cell '())]
(lambda (dispatch . parameters)
(case dispatch
[(add!) (if (null? list-under-construction)
(begin
(set! list-under-construction (list (car parameters)))
(set! last-cons-cell list-under-construction))
(let ((new-cons-cell (list (car parameters))))
(set-cdr! last-cons-cell new-cons-cell)
(set! last-cons-cell new-cons-cell)))
list-under-construction]
[(list) list-under-construction]
[else (error "unmatched dispatch" dispatch)]))))
</code></pre>
<p>Sample use:</p>
<pre><code>> (define lb (make-list-builder))
> (lb 'list)
()
> (lb 'add! "here's an atom")
("here's an atom")
> (lb 'add! '(here's a list))
("here's an atom" (here 's a list))
</code></pre>
<p>Questions for review: </p>
<ol>
<li><p>Is there a standard scheme function or way of doing this that I missed? The problem I am trying to ultimately solve can't be solved by a map because a map produces a list of the same size as the input, and <a href="http://www.scheme.com/tspl3/control.html#./control:s28" rel="nofollow noreferrer">map does not guarantee the order that elements of a Lisp or processed</a>. Googling and searching Stack Overflow for <em>scheme list builder</em> or <em>scheme list accumulater</em> did not return useful results.</p></li>
<li><p>Is <code>make-list-builder</code> expressed in idiomatic Scheme?</p></li>
<li><p>How would you improve <code>make-list-builder</code>, or what would you do differently?</p></li>
</ol>
|
[] |
[
{
"body": "<p>Wow, so sorry I missed seeing this question! (Normally I get emails when someone posts something tagged with <a href=\"/questions/tagged/scheme\" class=\"post-tag\" title=\"show questions tagged 'scheme'\" rel=\"tag\">scheme</a>, but didn't see this one till now. :-()</p>\n\n<p>So, the idiomatic way to build a list in Scheme is to <code>cons</code> elements to the front each time, then reverse the whole list at the end. This is still O(n) on the number of items to insert, so you're no worse off compared to the <code>set-cdr!</code> solution.</p>\n\n<p>However, for this situation, a better solution (IMHO) in your case is actually to use <a href=\"http://srfi.schemers.org/srfi-1/srfi-1.html#unfold\" rel=\"nofollow\"><code>unfold</code></a>, which takes any given object (not necessarily a list) and results in a list. This is perfect for your situation because you are processing variable numbers of items in your input list at each step, which would make it a poor fit for <code>map</code>, <code>fold</code>, and the like (which processes exactly one item at each step).</p>\n\n<p>Here's an example (require SRFIs <a href=\"http://srfi.schemers.org/srfi-1/srfi-1.html\" rel=\"nofollow\">1</a>, <a href=\"http://srfi.schemers.org/srfi-8/srfi-8.html\" rel=\"nofollow\">8</a>, and <a href=\"http://srfi.schemers.org/srfi-60/srfi-60.html\" rel=\"nofollow\">60</a>):</p>\n\n<pre><code>(define (decode-utf8 bytes)\n (define (invalid byte)\n (list 'invalid byte))\n (define (non-shortest val)\n (list 'non-shortest val))\n (define (end-of-input val)\n (list 'end-of-input val))\n\n (define (decode-start bytes)\n (define byte (car bytes))\n (define rest (cdr bytes))\n (cond ((< byte #x80) (values (integer->char byte) rest))\n ((< byte #xC0) (values (invalid byte) rest))\n ((< byte #xE0) (decode-rest 1 #x80 (logand byte #x1F) rest))\n ((< byte #xF0) (decode-rest 2 #x800 (logand byte #x0F) rest))\n ((< byte #xF8) (decode-rest 3 #x10000 (logand byte #x07) rest))\n (else (values (invalid byte) rest))))\n (define (decode-rest count minval val bytes)\n (cond ((zero? count) (values ((if (< val minval)\n non-shortest\n integer->char) val) bytes))\n ((null? bytes) (values (end-of-input val) bytes))\n (else\n (let ((byte (car bytes))\n (rest (cdr bytes)))\n (cond ((< byte #x80) (values (invalid byte) rest))\n ((< byte #xC0)\n (decode-rest (- count 1) minval\n (+ (ash val 6) (logand byte #x3F))\n rest))\n (else (values (invalid byte) rest)))))))\n\n (define (decode bytes)\n (receive (value rest) (decode-start bytes)\n value))\n (define (next bytes)\n (receive (value rest) (decode-start bytes)\n rest))\n\n (unfold null? decode next bytes))\n</code></pre>\n\n<p>The real action happens in <code>decode-start</code> and <code>decode-rest</code>, of course; both functions return two values:</p>\n\n<ol>\n<li>the character decoded (or an error)</li>\n<li>a reference to the next byte to process</li>\n</ol>\n\n<p>The <code>decode</code> function extracts the first value, while <code>next</code> extracts the second.</p>\n\n<hr>\n\n<p>If you still want to use a list builder, that's fine too. Here's a simple version: it builds the list when given no arguments, and otherwise appends the arguments given:</p>\n\n<pre><code>(define (make-list-builder)\n (define cur '())\n (case-lambda\n (() (reverse cur))\n ((item) (set! cur (cons item cur))) ; redundant\n (items (set! cur (append-reverse items cur)))))\n</code></pre>\n\n<p>(where <code>append-reverse</code> comes from SRFI 1). Note that <code>append-reverse</code> with only one item is identical to <code>cons</code>, so the <code>cons</code> line above is redundant; it just demonstrates how you would do it if you want to add items one by one.</p>\n\n<p>If you want to be able to send messages like in your version, here's how one might implement it:</p>\n\n<pre><code>(define (make-list-builder)\n (define cur '())\n (lambda (msg . args)\n (case msg\n ((add) (set! cur (append-reverse args cur)))\n ((get) (reverse cur))\n ((clear) (set! cur '())))))\n</code></pre>\n\n<p>In both cases, we keep track of a single variable only, not the start and end of list, because we are prepending elements rather than appending them.</p>\n\n<hr>\n\n<p>There is still a valid use for the start-and-end approach you had, though: it's a common approach for implementing a queue. You enqueue by using the end reference, <code>set-cdr!</code>ing the new value in, then resetting the end reference; and of course, you dequeue by using the start reference. Here's an example (zero arguments means dequeue; otherwise enqueue the given arguments):</p>\n\n<pre><code>(define (make-queue)\n (define start (list 'queue-head))\n (define end start)\n (case-lambda\n (() (when (null? (cdr start))\n (error \"empty queue\"))\n (let ((result (cadr start)))\n (set-cdr! start (cddr start))\n (when (null? (cdr start))\n (set! end start))\n result))\n (items (set-cdr! end items)\n (set! end (last-pair end)))))\n</code></pre>\n\n<p>(here, <code>last-pair</code> comes from SRFI 1).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-12T04:35:07.513",
"Id": "5316",
"ParentId": "4428",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T08:56:10.660",
"Id": "4428",
"Score": "3",
"Tags": [
"scheme"
],
"Title": "A list builder or list accumulator"
}
|
4428
|
<p>For a messenger program I am writing a <code>Server</code> class that will run a non-blocking server in one thread. A messenger thread will use this server thread to communicate with other clients.</p>
<h3>What the server should do</h3>
<ul>
<li>Accept connections from / connect to other instances of the server and associate the selection keys for the connections in <code>Map<Integer, SelectionKey> keys</code> wit an ID so the messenger thread can access the connections by ID</li>
<li>Read from / write to connections</li>
<li>Store incoming messages in a queue</li>
<li>Messenger thread can
<ul>
<li>Fetch incoming messages</li>
<li>Queue messages to be sent: <code>send_message(int id, String msg)</code></li>
</ul></li>
</ul>
<p></p>
<pre><code>package snserver;
/* imports */
//class SNServer (Simple non-blocking Server)
public class SNServer extends Thread {
private int port;
private Selector selector;
private ConcurrentMap<Integer, SelectionKey> keys; // ID -> associated key
private ConcurrentMap<SocketChannel,List<byte[]>> dataMap_out;
ConcurrentLinkedQueue<String> in_msg; //incoming messages to be fetched by messenger thread
public SNServer(int port) {
this.port = port;
dataMap_out = new ConcurrentHashMap<SocketChannel, List<byte[]>>();
keys = new ConcurrentHashMap<Integer, SelectionKey>();
}
public void start_server() throws IOException {
// create selector and channel
this.selector = Selector.open();
ServerSocketChannel serverChannel = ServerSocketChannel.open();
serverChannel.configureBlocking(false);
// bind to port
InetSocketAddress listenAddr = new InetSocketAddress((InetAddress)null, this.port);
serverChannel.socket().bind(listenAddr);
serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);
log("Echo server ready. Ctrl-C to stop.");
// processing
while (true) {
// wait for events
this.selector.select();
// wakeup to work on selected keys
Iterator keys = this.selector.selectedKeys().iterator();
while (keys.hasNext()) {
SelectionKey key = (SelectionKey) keys.next();
// this is necessary to prevent the same key from coming up
// again the next time around.
keys.remove();
if (! key.isValid()) {
continue;
}
if (key.isAcceptable()) {
this.accept(key);
}
else if (key.isReadable()) {
this.read(key);
}
else if (key.isWritable()) {
this.write(key);
}
else if(key.isConnectable()) {
this.connect(key);
}
}
}
}
private void accept(SelectionKey key) throws IOException {
ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
SocketChannel channel = serverChannel.accept();
channel.configureBlocking(false);
send_message(key, "Welcome."); //DEBUG
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
log("Connected to: " + remoteAddr);
// register channel with selector for further IO
dataMap_out.put(channel, new ArrayList<byte[]>());
channel.register(this.selector, SelectionKey.OP_READ);
//store key in 'keys' to be accessable by ID from messenger thread //TODO first get ID
keys.put(0, key);
}
//TODO verify, test
public void init_connect(String addr, int port){
try {
SocketChannel channel = createSocketChannel(addr, port);
channel.register(this.selector, channel.validOps()/*, SelectionKey.OP_?*/);
}
catch (IOException e) {
//TODO handle
}
}
//TODO verify, test
private void connect(SelectionKey key) {
SocketChannel channel = (SocketChannel) key.channel();
try {
channel.finishConnect(); //try to finish connection - if 'false' is returned keep 'OP_CONNECT' registered
//store key in 'keys' to be accessable by ID from messenger thread //TODO first get ID
keys.put(0, key);
}
catch (IOException e0) {
try {
//TODO handle ok?
channel.close();
}
catch (IOException e1) {
//TODO handle
}
}
}
private void read(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
ByteBuffer buffer = ByteBuffer.allocate(8192);
int numRead = -1;
try {
numRead = channel.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
}
if (numRead == -1) {
this.dataMap_out.remove(channel);
Socket socket = channel.socket();
SocketAddress remoteAddr = socket.getRemoteSocketAddress();
log("Connection closed by client: " + remoteAddr); //TODO handle
channel.close();
return;
}
byte[] data = new byte[numRead];
System.arraycopy(buffer.array(), 0, data, 0, numRead);
in_msg.add(new String(data, "utf-8"));
}
private void write(SelectionKey key) throws IOException {
SocketChannel channel = (SocketChannel) key.channel();
List<byte[]> pendingData = this.dataMap_out.get(channel);
Iterator<byte[]> items = pendingData.iterator();
while (items.hasNext()) {
byte[] item = items.next();
items.remove();
//TODO is this correct? -> re-doing write in loop with same buffer object
ByteBuffer buffer = ByteBuffer.wrap(item);
int bytes_to_write = buffer.capacity();
while (bytes_to_write > 0) {
bytes_to_write -= channel.write(buffer);
}
}
key.interestOps(SelectionKey.OP_READ);
}
public void queue_data(SelectionKey key, byte[] data) {
SocketChannel channel = (SocketChannel) key.channel();
List<byte[]> pendingData = this.dataMap_out.get(channel);
key.interestOps(SelectionKey.OP_WRITE);
pendingData.add(data);
}
public void send_message(int id, String msg) {
SelectionKey key = keys.get(id);
if (key != null)
send_message(key, msg);
//else
//TODO handle
}
public void send_message(SelectionKey key, String msg) {
try {
queue_data(key, msg.getBytes("utf-8"));
}
catch (UnsupportedEncodingException ex) {
//is not thrown: utf-8 is always defined
}
}
public String get_message() {
return in_msg.poll();
}
private static void log(String s) {
System.out.println(s);
}
@Override
public void run() {
try {
start_server();
}
catch (IOException e) {
System.out.println("IOException: " + e);
//TODO handle exception
}
}
// Creates a non-blocking socket channel for the specified host name and port.
// connect() is called on the new channel before it is returned.
public static SocketChannel createSocketChannel(String hostName, int port) throws IOException {
// Create a non-blocking socket channel
SocketChannel sChannel = SocketChannel.open();
sChannel.configureBlocking(false);
// Send a connection request to the server; this method is non-blocking
sChannel.connect(new InetSocketAddress(hostName, port));
return sChannel;
}
}
</code></pre>
<h3>General problem</h3>
<p>Because I am new to Java and networking there may be several things incorrect or not good in this code. Please help me improve this code so it does what I'd like it to do. Also give suggestions to improve the concept!</p>
<h3>Current problems:</h3>
<ul>
<li>After calling <code>init_connect()</code> there seems to be no event on the selector so the connection is not built.</li>
</ul>
|
[] |
[
{
"body": "<p>I have little experience with networking, so I cannot criticize the logic itself, alas. I have some minor remarks on the form, though:</p>\n\n<ul>\n<li>It is controversial because you will find some people proponent of this style, but I personally (and it is shared by many people!) avoid to use <code>this.fieldName</code> outside of constructors, because it is redundant. I see it as visual noise. It can help distinguishing local variables from fields, I chose to use a prefix for that, which is controversial too...</li>\n<li><code>in_msg</code> field isn't declared private, not sure if it is intentional.</li>\n<li>Don't swallow the exception in <code>init_connect</code>, you might miss some problem...</li>\n</ul>\n\n<p>That's most of what I can think of; you might need to clean up resources if you catch an exception at the level of <code>run()</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T09:43:40.330",
"Id": "6689",
"Score": "0",
"body": "Thanks that you try to help! 1) I normally do not use \"this\" but the code is based on examples of the internet and I didn't change everything. 2)+3) At the moment I am just trying to get the server working so I didn't really care about data encapsulation etc. Also see the \"TODO\"s in the code... I do not really know how to handle the exception in `init_connect` so I left it as a TODO. Anyway I'll change the code a little now."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T09:00:09.133",
"Id": "4471",
"ParentId": "4432",
"Score": "0"
}
},
{
"body": "<p>Recently I came across a nice library for doing network stuff in Java called <a href=\"http://www.jboss.org/netty\" rel=\"nofollow\">netty</a>. It's not even a library - it is rather a framework for building scalable apps, so it imposes some architecture decisions on application architecture. Even though using it might be an overkill in your situation I suggest you to check its docs out as you might learn the approaches implemented there.</p>\n\n<p>What I can see can be improved:</p>\n\n<ul>\n<li><strong>Code layering</strong>. In your code you have everything in one place: network handling, packet queuing and so on. So it is difficult to see which is where, to test and debug it. I'd try to separate the layers somehow.</li>\n<li><strong>Separation of network and business logic threads</strong>. In-case your business logic or I/O gets significantly more load then the counterpart the whole performance will degrade since it is done in a single thread. This might be not an issue in this particular case since the logic is rather simple, but nevertheless. If you move the business logic into a separate thread I/O won't block waiting for it to perform its work and the overall performance will increase. The pitfall is the proper communication/synchronization between the threads so that they don't thrash the data.</li>\n</ul>\n\n<p>The points above are pretty much handled in that lib, so I suggest you to peek into their docs and examples to understand the rationale and the way they implemented it. Even if you won't opt for it you might learn something useful for your project.</p>\n\n<p>P.S.: I'm not affiliated neither with JBoss nor with netty, but I really fell in love with it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-23T09:55:59.270",
"Id": "5541",
"ParentId": "4432",
"Score": "1"
}
},
{
"body": "<h3>Short answer</h3>\n\n<p>Use a state machine.</p>\n\n<h3>Longer answer</h3>\n\n<p>I haven't read your code in detail, but I already worked with the Java's non-blocking sockets. So I can say it's pretty difficult to get it right.</p>\n\n<p>I once inherited a codebase that was similar to your code. My task was to write unit tests, in order to be close to 100% branches coverage. I tried to write tests without touching the code, but there are so much states to track (the selector, the buffers, the socket's state) that I was not able to reliably test the code.</p>\n\n<p>So, I re-wrote the code, using a state-machine to encapsulate these states. I ended up with 7 small classes, each one representing the state of the sockets, or the state of the request processing. The resulting code was more robust (many missing edge-cases became obvious), easier to understand and to maintain. Writing the tests was easier, then.</p>\n\n<p>If I had to do it again, I'd try to use Netty (as Ihor suggested). Netty encapsulates the states too, and manages the connection errors in a more unified way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-22T13:50:34.473",
"Id": "6201",
"ParentId": "4432",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T11:23:55.213",
"Id": "4432",
"Score": "2",
"Tags": [
"java"
],
"Title": "Simple Server for messenger"
}
|
4432
|
<p>So the way I understand this code I wrote, it is thread safe, as long as the retrievers and depositors are thread safe. The only bad state I could see occurring is that a thread is using a retriever as a method local while another thread calls RefreshDependencies(), which would mean the thread with it as a method local would continue to use it even though it wasn't one of the current depositors/retrievers, but that one should be cleaned up when the method local using it exited as there would be no root anymore.</p>
<p>also open to any other notes on the code.</p>
<pre><code>public static class DependencyContainer
{
private const string DEPENDENCIES_LOCATION_APP_SETTINGS_KEY = "DependenciesLocation";
private static object _lockDependenciesManagement;
private static string _dependenciesLocation;
public static IEnumerable<IEntryRetriever> Retrievers { get; private set; }
public static IEnumerable<IEntryDepositor> Depositors { get; private set; }
static DependencyContainer()
{
_lockDependenciesManagement = new object();
string dependenciesLocation = ConfigurationManager.AppSettings[DEPENDENCIES_LOCATION_APP_SETTINGS_KEY] ?? typeof(DependencyContainer).Assembly.CodeBase.Replace(@"file:///", "");
SetDependenciesLocation(dependenciesLocation);
RefreshDependencies();
}
public static string GetDependenciesLocation()
{
lock (_lockDependenciesManagement)
{
return _dependenciesLocation;
}
}
public static void SetDependenciesLocation(string newDependenciesLocation)
{
lock (_lockDependenciesManagement)
{
_dependenciesLocation = newDependenciesLocation;
}
}
public static void RefreshDependencies()
{
lock (_lockDependenciesManagement)
{
// compose/load dependencies in here for writing and retrieving blog entries
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T17:28:00.680",
"Id": "6632",
"Score": "1",
"body": "*'it is thread safe, as long as the retrievers and depositors are thread safe.'* ...the class is either thread-safe or it isn't, IMO ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T22:16:38.330",
"Id": "6635",
"Score": "0",
"body": "I mean, the class is thread safe- though that does not guarantee the retrievers or depositors are. The implementor of those has to make them independently thread safe."
}
] |
[
{
"body": "<p>First item I see is:</p>\n\n<pre><code>private static object _lockDependenciesManagement;\n</code></pre>\n\n<p>...should be: </p>\n\n<pre><code>private static readonly object _lockDependenciesManagement; \n</code></pre>\n\n<p>I don't see any reason this should/would change.</p>\n\n<p>With the possibility of having <code>Retrievers</code> overwritten while being used, you should return a copy of the collection instead:</p>\n\n<pre><code>// fields that could be altered while in use if made public\nstatic IEnumerable<IEntryRetriever> _retrievers { get; private set; }\nstatic IEnumerable<IEntryDepositor> _depositors { get; private set; }\n\npublic static IEnumerable<IEntryRetriever> Retrievers\n{\n get\n {\n // return copy of _retrievers\n lock (_lockDependenciesManagement)\n { return _retrievers.ToList(); }\n }\n}\n</code></pre>\n\n<p>Your consumers can now <strike>manipulate</strike> work from it's own copy of the _retrievers collection. Handle <code>_depositors</code> in the same manner ...I think these steps will make the collections safer to use.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T20:37:40.390",
"Id": "6633",
"Score": "1",
"body": "You should lock _retrievers.ToList(), too or you defeat the point of using the locks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T22:15:31.670",
"Id": "6634",
"Score": "0",
"body": "Good point on making the lock object readonly, though I'm not sure there's benefit in the .ToList() as the IEnumerable's cannot be manipulated by consumers, IEnumerable just implements read operations, manipulations would be done to the retriever elements which would be the same ones referenced in the .ToList"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T22:54:40.267",
"Id": "6637",
"Score": "0",
"body": "Correct me if i'm wrong, but every thread calling getenumerator on an enumerable, gets its own new enumerator right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T03:13:48.623",
"Id": "6644",
"Score": "0",
"body": "@Jimmy: *'every thread calling getenumerator on an enumerable, gets its own new enumerator right?'* ...yes, that is the intent."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T13:08:00.613",
"Id": "6648",
"Score": "0",
"body": "After thinking about it, you're right, I *think* it's thread safe without this immutable style, but I *know* it's thread safe the way you did it. Smartass. Will put the lock around it too. Glad I asked on here. You can see my changes at https://github.com/JimmyHoffa/IndyBlog"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T17:31:54.247",
"Id": "4436",
"ParentId": "4435",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4436",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T17:20:57.820",
"Id": "4435",
"Score": "5",
"Tags": [
"c#",
"thread-safety"
],
"Title": "How thread safe is this class?"
}
|
4435
|
<p>In this project I've taken my first shot at OO JavaScript, and I'm not sure how it turned out. The script dynamically makes a tooltip with different text if you so choose. As of now it takes <em>a lot</em> to create the tooltip and show it, is there a way to make this smaller?</p>
<p><a href="http://jsfiddle.net/zachdunn/6hMbg/" rel="nofollow">Here</a> is the code at JSFiddle. Let me know if it would be easier to paste in here.</p>
<pre><code>/*global window, document*/
var note;
function Note() {
'use strict';
this.identifier = 0;
}
Note.prototype.makeWrap = function () {
'use strict';
var wrap;
wrap = document.createElement('div');
wrap.id = 'wrap' + this.identifier;
wrap.style.border = '1px solid #43484A';
wrap.style.boxShadow = '-1px -1px 5px #292929, 1px 1px 5px #292929';
wrap.style.height = '185px';
wrap.style.opacity = '.95';
wrap.style.position = 'absolute';
wrap.style.width = '300px';
return wrap;
};
Note.prototype.makeHead = function () {
'use strict';
var head;
head = document.createElement('div');
head.id = 'head' + this.identifier;
head.style.backgroundColor = '#43484A';
head.style.color = '#EEEEEE';
head.style.height = '30px';
head.style.paddingLeft = '6px';
head.style.position = 'relative';
head.style.width = '294px';
return head;
};
Note.prototype.makeTitle = function (text) {
'use strict';
var title;
title = document.createElement('div');
title.id = 'title' + this.identifier;
title.style.backgroundColor = 'inherit';
title.style.color = 'inherit';
title.style.float = 'left';
title.style.fontFamily = 'Georgia, "Times New Roman", serif';
title.style.height = '17px';
title.style.paddingTop = '6px';
title.style.paddingBottom = '7px';
title.style.position = 'relative';
title.style.width = '80%';
title.innerHTML = text;
return title;
};
Note.prototype.makeMini = function () {
'use strict';
var mini;
mini = document.createElement('div');
mini.id = 'min' + this.identifier;
mini.style.backgroundColor = 'inherit';
mini.style.color = '#EEEEEE';
mini.style.cursor = 'pointer';
mini.style.float = 'left';
mini.style.fontFamily = 'Consolas, monospace';
mini.style.height = '17px';
mini.style.paddingTop = '6px';
mini.style.paddingBottom = '7px';
mini.style.position = 'relative';
mini.style.textAlign = 'center';
mini.style.width = '10%';
mini.innerHTML = '&#151;';
return mini;
};
Note.prototype.makeClose = function () {
'use strict';
var close;
close = document.createElement('div');
close.id = 'close' + this.identifier;
close.style.backgroundColor = 'inherit';
close.style.color = '#EEEEEE';
close.style.cursor = 'pointer';
close.style.float = 'left';
close.style.fontFamily = 'Consolas, monospace';
close.style.height = '17px';
close.style.paddingTop = '6px';
close.style.paddingBottom = '7px';
close.style.position = 'relative';
close.style.textAlign = 'center';
close.style.width = '10%';
close.innerHTML = 'X';
return close;
};
Note.prototype.makeBody = function (passage) {
'use strict';
var body;
body = document.createElement('div');
body.id = 'body' + this.identifier;
body.style.backgroundColor = '#EEEEEE';
body.style.color = '#22282A';
body.style.fontFamily = 'Georgia, "Times New Roman", serif';
body.style.height = '118px';
body.style.overflow = 'auto';
body.style.padding = '6px';
body.style.position = 'relative';
body.style.width = '288px';
body.innerHTML = passage;
return body;
};
Note.prototype.makeFoot = function () {
'use strict';
var foot, link;
foot = document.createElement('div');
foot.id = 'foot' + this.identifier;
foot.style.backgroundColor = '#EEEEEE';
foot.style.heigth = '16px';
foot.style.padding = '4px 6px 5px 6px';
foot.style.position = 'relative';
foot.style.textAlign = 'right';
foot.style.width = '288px';
link = document.createElement('a');
link.href = '#';
link.style.color = '#0088CC';
link.style.textDecoration = 'none';
link.onmouseover = function () {
this.style.borderBottom = '1px solid #0088CC';
};
link.onmouseout = function () {
this.style.borderBottom = 'none';
};
link.innerHTML = 'Link';
foot.appendChild(link);
return foot;
};
Note.prototype.create = function (titleText, bodyText) {
'use strict';
var wrap, head, title, mini, close, body, foot;
wrap = this.makeWrap();
head = this.makeHead();
title = this.makeTitle(titleText);
mini = this.makeMini();
close = this.makeClose();
body = this.makeBody(bodyText);
foot = this.makeFoot();
head.appendChild(title);
head.appendChild(mini);
head.appendChild(close);
wrap.appendChild(head);
wrap.appendChild(body);
wrap.appendChild(foot);
document.body.appendChild(wrap);
this.identifier = this.identifier + 1;
};
note = new Note();
note.create(
'Lorem',
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu orci nibh. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis posuere rutrum pellentesque.'
);
</code></pre>
|
[] |
[
{
"body": "<p>Woahhhh, that is a LOT of repetition. You have a lot of similar functionality, all your functions do basically the same stuff:</p>\n\n<ul>\n<li>Create an element</li>\n<li>Set the ID</li>\n<li>Apply styles</li>\n<li>Maybe do something else</li>\n</ul>\n\n<p>You should look into DRYing your code by:</p>\n\n<ol>\n<li>Factoring out often used features into helper functions</li>\n<li>Adjusting structure of the code in order to allow for more of the above</li>\n<li>Go back to 1 and repeat until it's no longer feasible</li>\n</ol>\n\n<p>As a quick start I refactored and dryed your code quite a bit, I left out re-adding all the styling stuff, but it should give you a pretty good idea on how to structure your code.</p>\n\n<pre><code>/*global window, document*/\n\n// Let's use an anonymous wrapper\n(function() {\n 'use strict'; // only one pragma needed\n\n // You are using alot of .style assignments... let's create a helper\n function css(elem, styles) {\n\n for(var i in styles) {\n if (styles.hasOwnProperty(i)) {\n elem.styles[i] = styles[i];\n }\n }\n\n }\n\n // You are also creating a lot of similiar elements, so will use another wrapper\n function element(type, id, styles) {\n\n var elem = document.createElement(type);\n elem.id = id;\n css(elem, styles);\n\n return elem;\n\n }\n\n function Note() {\n this.identifier = 0;\n }\n\n // Prototype is just an object, let's get rid of all those assignments\n Note.prototype = {\n\n create: function (titleText, bodyText) {\n\n 'use strict';\n var wrap, head, title, mini, close, body, foot;\n\n wrap = this.element('div', 'wrap', {\n\n border: '1px solid #43484A',\n boxShadow: '-1px -1px 5px #292929, 1px 1px 5px #292929',\n height: '185px',\n opacity: '.95',\n position: 'absolute',\n width: '300px',\n\n });\n\n // etc....\n\n this.identifier++;\n\n },\n\n element: function(type, name, styles) {\n return element(type, name + this.identifier, styles));\n }\n\n }\n\n window.Note = Note; // expose the local stuff to the window\n\n});\n\nnote = new Note();\nnote.create(\n 'Lorem',\n 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur eu orci nibh. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Duis posuere rutrum pellentesque.'\n);\n</code></pre>\n\n<p>Also have a look at <a href=\"http://rads.stackoverflow.com/amzn/click/0596806752\" rel=\"noreferrer\">JavaScript Design Patterns</a> book by O'Reilly.</p>\n\n<p>PS: I'd further suggest that you move out your CSS into actually CSS class declarations and use those on your elements.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T23:32:47.400",
"Id": "6639",
"Score": "0",
"body": "Thank you for the great answer, I really appreciate it. Your answer raises another question which I noticed while browsing jQuery, what is the difference between doing `(function(){window.Note = Note;}())` vs `var Note; (function(){ Note = Note; }())`? Thanks again!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T15:53:57.473",
"Id": "6677",
"Score": "0",
"body": "+1 Design principles to the rescue, http://en.wikipedia.org/wiki/Don't_repeat_yourself"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T21:43:58.320",
"Id": "4438",
"ParentId": "4437",
"Score": "8"
}
},
{
"body": "<p>As @IvoWetzel already said : CSS has no place in javascript code. Instead you should have configurable classnames for elements of that <em>Note widget</em>. Leave styling of elements to CSS in *.css file.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T23:36:34.243",
"Id": "6641",
"Score": "0",
"body": "The thing is is that this will eventually be a project where people who desire to use it will simply put `<script src='project.js'></script>` at the bottom of their html and I want it to work without them having to add more stuff . . . what is wrong with styling in JavaScript, anyway? Just curious . . ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T00:19:48.713",
"Id": "6642",
"Score": "0",
"body": "@Zach , 2 major reasons : **1)** preformance - each time you change any of `style` attribute via JS for any tag it causes browser's rendering engine to perform [reflow](http://www.bitcurrent.com/browser-rendering-and-web-performance-reflow/). **2)** code quality - in frontend you have 3 \"layers\" : html, css and js .. or content, presentation and behavior. They should be kept separate. Besides , your usecase is flawed. Do you really expect people to design pages around **your** widget's design ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T00:31:22.483",
"Id": "6643",
"Score": "0",
"body": "if by design you mean the colors and stuff, then no. I already have a customization system in the works. Also thank you for the article about reflow. What do you think about adding a css file to the user's webpage via JavaScript?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T15:52:05.723",
"Id": "6676",
"Score": "0",
"body": "@Zach make the javascript simpler by requiring consumers to do one more little simple step: `<link rel=\"stylesheet\" type=\"text/css\" href=\"theme.css\" /><script src='project'js' />` this also makes it very explicit to the consumer how they can alter the styling to match their page."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T22:02:45.010",
"Id": "4439",
"ParentId": "4437",
"Score": "3"
}
},
{
"body": "<p>The most obviuos way is to move all styles to the external css file and add a link to it dynamically. Disqus is doing like this. The next thing is to stop doing the same again and again.</p>\n\n<p>In fact you need only one function with definition like this:</p>\n\n<pre><code>funciton createElement(name, attrs, styles, parent)\n</code></pre>\n\n<p>Also you can add more specific function to stop further duplication in your case</p>\n\n<pre><code>function createDiv(id, styles, parent, innerHTML) {\n var el = createElement('div', {id: id}, styles, parent);\n if(innerHTML) el.innerHTML = innerHTML;\n return el;\n}\n</code></pre>\n\n<p>With this function you could create all the DOM in much shorter way:</p>\n\n<pre><code>var wrap = createDiv('wrap', wrapStyles),\n header = createDiv('head', headStyles, wrap),\n title = createDiv('title', titleStyles, headerm titleText);\n..etc..\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T06:00:54.740",
"Id": "4493",
"ParentId": "4437",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-27T21:07:45.330",
"Id": "4437",
"Score": "3",
"Tags": [
"javascript",
"dom"
],
"Title": "Dynamic Tooltip Generator"
}
|
4437
|
<p><em>FileBro</em> is a basic GUI based File Browser. </p>
<p><img src="https://i.stack.imgur.com/yswnE.png" width="677" height="398"></p>
<h2>FileBro Functionality</h2>
<ul>
<li>Directory tree - shows the file system roots at start-up, but is otherwise built lazily as the user browses around the file system. <em>FileBro</em> displays a progress bar as it is loading new entries.</li>
<li>The file list (a table) displays a list of the directories and files in the current directory tree selection. Sort by clicking on the column header.</li>
<li>Buttons - all use the <code>Desktop</code> class for their functionality. If the action cannot be completed, a meaningful reason should by displayed in a <code>JEditorPane</code> error message.
<ul>
<li><code>Locate</code> - opens the parent directory of the currently selected file. </li>
<li><code>Open</code> - launches whatever application is the default consumer for that file type.</li>
<li><code>Edit</code> - opens the file for edit in the default consumer.</li>
<li><code>Print</code> - prints the file using the default consumer.</li>
</ul></li>
<li>Details on the selected file are displayed below the buttons.</li>
</ul>
<hr>
<p>Does the current functionality work as per above description?</p>
<h2>FileBrowser.java</h2>
<pre><code>import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Container;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.table.*;
import javax.swing.filechooser.FileSystemView;
import javax.imageio.ImageIO;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.io.*;
import java.nio.channels.FileChannel;
import java.net.URL;
/**
A basic File Browser. Requires 1.6+ for the Desktop & SwingWorker
classes, amongst other minor things.
Includes support classes FileTableModel & FileTreeCellRenderer.
@TODO Bugs
<li>Fix keyboard focus issues - especially when functions like
rename/delete etc. are called that update nodes & file lists.
<li>Needs more testing in general.
@TODO Functionality
<li>Double clicking a directory in the table, should update the tree
<li>Move progress bar?
<li>Add other file display modes (besides table) in CardLayout?
<li>Menus + other cruft?
<li>Implement history/back
<li>Allow multiple selection
<li>Add file search
@author Andrew Thompson
@version 2011-06-08
@see http://codereview.stackexchange.com/q/4446/7784
@license LGPL
*/
class FileBrowser {
/** Title of the application */
public static final String APP_TITLE = "FileBro";
/** Used to open/edit/print files. */
private Desktop desktop;
/** Provides nice icons and names for files. */
private FileSystemView fileSystemView;
/** currently selected File. */
private File currentFile;
/** Main GUI container */
private JPanel gui;
/** File-system tree. Built Lazily */
private JTree tree;
private DefaultTreeModel treeModel;
/** Directory listing */
private JTable table;
private JProgressBar progressBar;
/** Table model for File[]. */
private FileTableModel fileTableModel;
private ListSelectionListener listSelectionListener;
private boolean cellSizesSet = false;
private int rowIconPadding = 6;
/* File controls. */
private JButton openFile;
private JButton printFile;
private JButton editFile;
/* File details. */
private JLabel fileName;
private JTextField path;
private JLabel date;
private JLabel size;
private JCheckBox readable;
private JCheckBox writable;
private JCheckBox executable;
private JRadioButton isDirectory;
private JRadioButton isFile;
/* GUI options/containers for new File/Directory creation. Created lazily. */
private JPanel newFilePanel;
private JRadioButton newTypeFile;
private JTextField name;
public Container getGui() {
if (gui==null) {
gui = new JPanel(new BorderLayout(3,3));
gui.setBorder(new EmptyBorder(5,5,5,5));
fileSystemView = FileSystemView.getFileSystemView();
desktop = Desktop.getDesktop();
JPanel detailView = new JPanel(new BorderLayout(3,3));
table = new JTable();
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setAutoCreateRowSorter(true);
table.setShowVerticalLines(false);
listSelectionListener = new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent lse) {
int row = table.getSelectionModel().getLeadSelectionIndex();
setFileDetails( ((FileTableModel)table.getModel()).getFile(row) );
}
};
table.getSelectionModel().addListSelectionListener(listSelectionListener);
JScrollPane tableScroll = new JScrollPane(table);
Dimension d = tableScroll.getPreferredSize();
tableScroll.setPreferredSize(new Dimension((int)d.getWidth(), (int)d.getHeight()/2));
detailView.add(tableScroll, BorderLayout.CENTER);
// the File tree
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
treeModel = new DefaultTreeModel(root);
TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent tse){
DefaultMutableTreeNode node =
(DefaultMutableTreeNode)tse.getPath().getLastPathComponent();
showChildren(node);
setFileDetails((File)node.getUserObject());
}
};
// show the file system roots.
File[] roots = fileSystemView.getRoots();
for (File fileSystemRoot : roots) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);
root.add( node );
File[] files = fileSystemView.getFiles(fileSystemRoot, true);
for (File file : files) {
if (file.isDirectory()) {
node.add(new DefaultMutableTreeNode(file));
}
}
//
}
tree = new JTree(treeModel);
tree.setRootVisible(false);
tree.addTreeSelectionListener(treeSelectionListener);
tree.setCellRenderer(new FileTreeCellRenderer());
tree.expandRow(0);
JScrollPane treeScroll = new JScrollPane(tree);
// as per trashgod tip
tree.setVisibleRowCount(15);
Dimension preferredSize = treeScroll.getPreferredSize();
Dimension widePreferred = new Dimension(
200,
(int)preferredSize.getHeight());
treeScroll.setPreferredSize( widePreferred );
// details for a File
JPanel fileMainDetails = new JPanel(new BorderLayout(4,2));
fileMainDetails.setBorder(new EmptyBorder(0,6,0,6));
JPanel fileDetailsLabels = new JPanel(new GridLayout(0,1,2,2));
fileMainDetails.add(fileDetailsLabels, BorderLayout.WEST);
JPanel fileDetailsValues = new JPanel(new GridLayout(0,1,2,2));
fileMainDetails.add(fileDetailsValues, BorderLayout.CENTER);
fileDetailsLabels.add(new JLabel("File", JLabel.TRAILING));
fileName = new JLabel();
fileDetailsValues.add(fileName);
fileDetailsLabels.add(new JLabel("Path/name", JLabel.TRAILING));
path = new JTextField(5);
path.setEditable(false);
fileDetailsValues.add(path);
fileDetailsLabels.add(new JLabel("Last Modified", JLabel.TRAILING));
date = new JLabel();
fileDetailsValues.add(date);
fileDetailsLabels.add(new JLabel("File size", JLabel.TRAILING));
size = new JLabel();
fileDetailsValues.add(size);
fileDetailsLabels.add(new JLabel("Type", JLabel.TRAILING));
JPanel flags = new JPanel(new FlowLayout(FlowLayout.LEADING,4,0));
isDirectory = new JRadioButton("Directory");
flags.add(isDirectory);
isFile = new JRadioButton("File");
flags.add(isFile);
fileDetailsValues.add(flags);
JToolBar toolBar = new JToolBar();
// mnemonics stop working in a floated toolbar
toolBar.setFloatable(false);
JButton locateFile = new JButton("Locate");
locateFile.setMnemonic('l');
locateFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
try {
System.out.println("Locate: " + currentFile.getParentFile());
desktop.open(currentFile.getParentFile());
} catch(Throwable t) {
showThrowable(t);
}
gui.repaint();
}
});
toolBar.add(locateFile);
openFile = new JButton("Open");
openFile.setMnemonic('o');
openFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
try {
System.out.println("Open: " + currentFile);
desktop.open(currentFile);
} catch(Throwable t) {
showThrowable(t);
}
gui.repaint();
}
});
toolBar.add(openFile);
editFile = new JButton("Edit");
editFile.setMnemonic('e');
editFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
try {
desktop.edit(currentFile);
} catch(Throwable t) {
showThrowable(t);
}
}
});
toolBar.add(editFile);
printFile = new JButton("Print");
printFile.setMnemonic('p');
printFile.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
try {
desktop.print(currentFile);
} catch(Throwable t) {
showThrowable(t);
}
}
});
toolBar.add(printFile);
// Check the actions are supported on this platform!
openFile.setEnabled(desktop.isSupported(Desktop.Action.OPEN));
editFile.setEnabled(desktop.isSupported(Desktop.Action.EDIT));
printFile.setEnabled(desktop.isSupported(Desktop.Action.PRINT));
flags.add(new JLabel(":: Flags"));
readable = new JCheckBox("Read ");
readable.setMnemonic('a');
flags.add(readable);
writable = new JCheckBox("Write ");
writable.setMnemonic('w');
flags.add(writable);
executable = new JCheckBox("Execute");
executable.setMnemonic('x');
flags.add(executable);
int count = fileDetailsLabels.getComponentCount();
for (int ii=0; ii<count; ii++) {
fileDetailsLabels.getComponent(ii).setEnabled(false);
}
count = flags.getComponentCount();
for (int ii=0; ii<count; ii++) {
flags.getComponent(ii).setEnabled(false);
}
JPanel fileView = new JPanel(new BorderLayout(3,3));
fileView.add(toolBar,BorderLayout.NORTH);
fileView.add(fileMainDetails,BorderLayout.CENTER);
detailView.add(fileView, BorderLayout.SOUTH);
JSplitPane splitPane = new JSplitPane(
JSplitPane.HORIZONTAL_SPLIT,
treeScroll,
detailView);
gui.add(splitPane, BorderLayout.CENTER);
JPanel simpleOutput = new JPanel(new BorderLayout(3,3));
progressBar = new JProgressBar();
simpleOutput.add(progressBar, BorderLayout.EAST);
progressBar.setVisible(false);
gui.add(simpleOutput, BorderLayout.SOUTH);
}
return gui;
}
public void showRootFile() {
// ensure the main files are displayed
tree.setSelectionInterval(0,0);
}
private TreePath findTreePath(File find) {
for (int ii=0; ii<tree.getRowCount(); ii++) {
TreePath treePath = tree.getPathForRow(ii);
Object object = treePath.getLastPathComponent();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)object;
File nodeFile = (File)node.getUserObject();
if (nodeFile==find) {
return treePath;
}
}
// not found!
return null;
}
private void showErrorMessage(String errorMessage, String errorTitle) {
JOptionPane.showMessageDialog(
gui,
errorMessage,
errorTitle,
JOptionPane.ERROR_MESSAGE
);
}
private void showThrowable(Throwable t) {
t.printStackTrace();
JOptionPane.showMessageDialog(
gui,
t.toString(),
t.getMessage(),
JOptionPane.ERROR_MESSAGE
);
gui.repaint();
}
/** Update the table on the EDT */
private void setTableData(final File[] files) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (fileTableModel==null) {
fileTableModel = new FileTableModel();
table.setModel(fileTableModel);
}
table.getSelectionModel().removeListSelectionListener(listSelectionListener);
fileTableModel.setFiles(files);
table.getSelectionModel().addListSelectionListener(listSelectionListener);
if (!cellSizesSet) {
Icon icon = fileSystemView.getSystemIcon(files[0]);
// size adjustment to better account for icons
table.setRowHeight( icon.getIconHeight()+rowIconPadding );
setColumnWidth(0,-1);
setColumnWidth(3,60);
table.getColumnModel().getColumn(3).setMaxWidth(120);
setColumnWidth(4,-1);
setColumnWidth(5,-1);
setColumnWidth(6,-1);
setColumnWidth(7,-1);
setColumnWidth(8,-1);
setColumnWidth(9,-1);
cellSizesSet = true;
}
}
});
}
private void setColumnWidth(int column, int width) {
TableColumn tableColumn = table.getColumnModel().getColumn(column);
if (width<0) {
// use the preferred width of the header..
JLabel label = new JLabel( (String)tableColumn.getHeaderValue() );
Dimension preferred = label.getPreferredSize();
// altered 10->14 as per camickr comment.
width = (int)preferred.getWidth()+14;
}
tableColumn.setPreferredWidth(width);
tableColumn.setMaxWidth(width);
tableColumn.setMinWidth(width);
}
/** Add the files that are contained within the directory of this node.
Thanks to Hovercraft Full Of Eels for the SwingWorker fix. */
private void showChildren(final DefaultMutableTreeNode node) {
tree.setEnabled(false);
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
SwingWorker<Void, File> worker = new SwingWorker<Void, File>() {
@Override
public Void doInBackground() {
File file = (File) node.getUserObject();
if (file.isDirectory()) {
File[] files = fileSystemView.getFiles(file, true); //!!
if (node.isLeaf()) {
for (File child : files) {
if (child.isDirectory()) {
publish(child);
}
}
}
setTableData(files);
}
return null;
}
@Override
protected void process(List<File> chunks) {
for (File child : chunks) {
node.add(new DefaultMutableTreeNode(child));
}
}
@Override
protected void done() {
progressBar.setIndeterminate(false);
progressBar.setVisible(false);
tree.setEnabled(true);
}
};
worker.execute();
}
/** Update the File details view with the details of this File. */
private void setFileDetails(File file) {
currentFile = file;
Icon icon = fileSystemView.getSystemIcon(file);
fileName.setIcon(icon);
fileName.setText(fileSystemView.getSystemDisplayName(file));
path.setText(file.getPath());
date.setText(new Date(file.lastModified()).toString());
size.setText(file.length() + " bytes");
readable.setSelected(file.canRead());
writable.setSelected(file.canWrite());
executable.setSelected(file.canExecute());
isDirectory.setSelected(file.isDirectory());
isFile.setSelected(file.isFile());
JFrame f = (JFrame)gui.getTopLevelAncestor();
if (f!=null) {
f.setTitle(
APP_TITLE +
" :: " +
fileSystemView.getSystemDisplayName(file) );
}
gui.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
// Significantly improves the look of the output in
// terms of the file names returned by FileSystemView!
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception weTried) {
}
JFrame f = new JFrame(APP_TITLE);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FileBrowser FileBrowser = new FileBrowser();
f.setContentPane(FileBrowser.getGui());
try {
URL urlBig = FileBrowser.getClass().getResource("fb-icon-32x32.png");
URL urlSmall = FileBrowser.getClass().getResource("fb-icon-16x16.png");
ArrayList<Image> images = new ArrayList<Image>();
images.add( ImageIO.read(urlBig) );
images.add( ImageIO.read(urlSmall) );
f.setIconImages(images);
} catch(Exception weTried) {}
f.pack();
f.setLocationByPlatform(true);
f.setMinimumSize(f.getSize());
f.setVisible(true);
FileBrowser.showRootFile();
}
});
}
}
/** A TableModel to hold File[]. */
class FileTableModel extends AbstractTableModel {
private File[] files;
private FileSystemView fileSystemView = FileSystemView.getFileSystemView();
private String[] columns = {
"Icon",
"File",
"Path/name",
"Size",
"Last Modified",
"R",
"W",
"E",
"D",
"F",
};
FileTableModel() {
this(new File[0]);
}
FileTableModel(File[] files) {
this.files = files;
}
public Object getValueAt(int row, int column) {
File file = files[row];
switch (column) {
case 0:
return fileSystemView.getSystemIcon(file);
case 1:
return fileSystemView.getSystemDisplayName(file);
case 2:
return file.getPath();
case 3:
return file.length();
case 4:
return file.lastModified();
case 5:
return file.canRead();
case 6:
return file.canWrite();
case 7:
return file.canExecute();
case 8:
return file.isDirectory();
case 9:
return file.isFile();
default:
System.err.println("Logic Error");
}
return "";
}
public int getColumnCount() {
return columns.length;
}
public Class<?> getColumnClass(int column) {
switch (column) {
case 0:
return ImageIcon.class;
case 3:
return Long.class;
case 4:
return Date.class;
case 5:
case 6:
case 7:
case 8:
case 9:
return Boolean.class;
}
return String.class;
}
public String getColumnName(int column) {
return columns[column];
}
public int getRowCount() {
return files.length;
}
public File getFile(int row) {
return files[row];
}
public void setFiles(File[] files) {
this.files = files;
fireTableDataChanged();
}
}
/** A TreeCellRenderer for a File. */
class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private FileSystemView fileSystemView;
private JLabel label;
FileTreeCellRenderer() {
label = new JLabel();
label.setOpaque(true);
fileSystemView = FileSystemView.getFileSystemView();
}
@Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
File file = (File)node.getUserObject();
label.setIcon(fileSystemView.getSystemIcon(file));
label.setText(fileSystemView.getSystemDisplayName(file));
label.setToolTipText(file.getPath());
if (selected) {
label.setBackground(backgroundSelectionColor);
label.setForeground(textSelectionColor);
} else {
label.setBackground(backgroundNonSelectionColor);
label.setForeground(textNonSelectionColor);
}
return label;
}
}
</code></pre>
<p>The <code>FileBrowser.java</code> source code is around 650 lines.</p>
<h2>Also</h2>
<ul>
<li>Here are 2 icons for the app. (but it will run OK without them). They will be used if found in the same directory as the classes. The icons use <code>Color.WHITE</code> to represent unselected table rows & tree nodes, so those are invisible in a web page with white background. ;)
<ol>
<li><code>fb-icon-16x16.png</code> <img src="https://i.stack.imgur.com/m0KKu.png" alt="fm-icon-16x16.png"></li>
<li><code>fb-icon-32x32.png</code> <img src="https://i.stack.imgur.com/LVVMb.png" alt="fm-icon-32x32.png"></li>
</ol></li>
<li>Any other comments/tips/suggestions are welcome.</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T02:02:59.423",
"Id": "6649",
"Score": "0",
"body": "I so far have not been able to reproduce your error. Are there any actions which usually precipitates the problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T03:16:09.813",
"Id": "6650",
"Score": "0",
"body": "@Andrew: I see that you've added a bounty to this question. Does that mean that you're still getting the same error, that changing the SwingWorker didn't fix things? Or if not, what problems are still issues with the updated code? /Pete"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-03T05:07:42.387",
"Id": "6651",
"Score": "0",
"body": "@HFOE: Your changes to the SwingWorker fixed that problem just fine. I'm trying to get more testing in general. (To spot the next 7 bugs.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T18:26:25.010",
"Id": "6652",
"Score": "0",
"body": "@HFOE: I was just thinking about the problems with this thread earlier. The code is getting too big to make substantial additions & still post at SO. Also I was thinking to maybe use this code as my first foray into SourceForge. So yes, that is a big possibility. Having said that, I'll let it run till near the end of the bounty period, just to see if any new & brilliant points come up. Though, (whispers) it'd be hard for anybody to top the advice offered before the bounty was posted. ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-04T18:38:35.203",
"Id": "6653",
"Score": "0",
"body": "@Andrew: I wonder if you're at the stage where you'd be better served by creating a project with multiple classes likely in several packages and posting it on SourceForge for all to contribute to. I'm not saying that the problems currently present aren't worth solving, just that perhaps the complexity of these problems are beyond what stackoverflow is best at solving. This would be a neat project for all to contribute to in an organized way. **Sorry**, I edited this to add `version control` by deleting my original comment just before you added yours and adding mine just afterward."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-25T12:52:03.773",
"Id": "380041",
"Score": "0",
"body": "Just wondering why you need to click a folder in the file system view to see if it's expandable. i.e., the \"+\" icon doesn't appear next to a folder until you click it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-06-25T15:08:11.803",
"Id": "380057",
"Score": "0",
"body": "@ryvantage The example might be tweaked to display the files and directories of a newly opened branch, but **also count the files at the top level of each directory found.** BNI - it was already getting very close to the character limit for a question. ;)"
}
] |
[
{
"body": "<p>Mac OS X 10.5 and Ubuntu 10.04: Repeated non-fatal NPE on delete.</p>\n\n<p>Addendum: In line 441, <code>findTreePath()</code> always returns <code>null</code>, because <code>currentFile.getParentFile()</code> returns the path to the file, not the file itself. In effect, the path cannot match itself. I don't see an obvious work-around.</p>\n\n<p>Addendum: I am unable to find an acceptable solution. I suspect the problem revolves around the dichotomy between view (<code>JTree</code>) and model (<code>DefaultTreeModel</code>). In particular, <code>findTreePath()</code> is searching among visible rows rather than the nodes of the tree model. It may prove useful to implement <code>TreeModel</code> explicitly, as shown in this <a href=\"https://dzone.com/articles/taking-new-swing-tree-table-a-\" rel=\"nofollow noreferrer\"><code>FileTreeModel</code></a>. It may also help to abstract view-model conversion methods analogous to those provided by <a href=\"http://download.oracle.com/javase/6/docs/api/javax/swing/JTable.html\" rel=\"nofollow noreferrer\"><code>JTable</code></a>.</p>\n\n<p>As an alternative approach, consider <a href=\"http://bits.netbeans.org/dev/javadoc/org-netbeans-swing-outline/org/netbeans/swing/outline/Outline.html\" rel=\"nofollow noreferrer\"><code>org.netbeans.swing.outline.Outline</code></a>, pictured below. It accepts the <a href=\"https://dzone.com/articles/taking-new-swing-tree-table-a-\" rel=\"nofollow noreferrer\"><code>FileTreeModel</code></a>, mentioned earlier. By extending <a href=\"http://download.oracle.com/javase/6/docs/api/javax/swing/JTable.html\" rel=\"nofollow noreferrer\"><code>JTable</code></a>, it uses the familiar <a href=\"http://download.oracle.com/javase/tutorial/uiswing/components/table.html#editrender\" rel=\"nofollow noreferrer\">renderer and editor schema</a> via a convenient <a href=\"http://bits.netbeans.org/dev/javadoc/org-netbeans-swing-outline/org/netbeans/swing/outline/RowModel.html\" rel=\"nofollow noreferrer\"><code>RowModel</code></a> interface similar to <code>TableModel</code>. Most importantly, it provides <a href=\"http://bits.netbeans.org/dev/javadoc/org-netbeans-swing-outline/org/netbeans/swing/etable/ETable.html#convertRowIndexToModel%28int%29\" rel=\"nofollow noreferrer\"><code>convertRowIndexToModel()</code></a>, as well as <a href=\"http://bits.netbeans.org/dev/javadoc/org-netbeans-swing-outline/org/netbeans/swing/etable/ETable.html#convertRowIndexToView%28int%29\" rel=\"nofollow noreferrer\"><code>convertRowIndexToView()</code></a>. The <a href=\"http://download.oracle.com/javase/6/docs/api/javax/swing/JTable.html\" rel=\"nofollow noreferrer\"><code>JTable</code></a> method <code>getValueAt()</code> is overridden to call <a href=\"http://bits.netbeans.org/dev/javadoc/org-netbeans-swing-outline/org/netbeans/swing/etable/ETable.html#convertRowIndexToModel%28int%29\" rel=\"nofollow noreferrer\"><code>convertRowIndexToModel()</code></a>, making the selection listener in this <a href=\"https://stackoverflow.com/questions/2841183/access-tree-object-in-netbeans-outline/2841582#2841582\">example</a> straightforward. The JAR is independent, small (~230 KiB) and stable; it may be found in the NetBeans distribution:</p>\n\n<blockquote>\n <p><code>NetBeans/platform/modules/org-netbeans-swing-outline.jar</code></p>\n</blockquote>\n\n<p><img src=\"https://i.stack.imgur.com/CrJKc.png\" alt=\"outline view\"></p>\n\n<p>Addendum: <code>FileBrowser</code> version 2011-06-08 operates correctly on both systems cited above.</p>\n\n<pre>\ncurrentFile: /temp.txt\nparentPath: null\njava.lang.NullPointerException\n at FileManager.deleteFile(FileManager.java:443)\n at FileManager.access$1000(FileManager.java:56)\n at FileManager$9.actionPerformed(FileManager.java:306)\n at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)\n at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)\n at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)\n at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)\n at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)\n at java.awt.Component.processMouseEvent(Component.java:6374)\n at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)\n at java.awt.Component.processEvent(Component.java:6139)\n at java.awt.Container.processEvent(Container.java:2085)\n at java.awt.Component.dispatchEventImpl(Component.java:4736)\n at java.awt.Container.dispatchEventImpl(Container.java:2143)\n at java.awt.Component.dispatchEvent(Component.java:4566)\n at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4621)\n at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)\n at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)\n at java.awt.Container.dispatchEventImpl(Container.java:2129)\n at java.awt.Window.dispatchEventImpl(Window.java:2478)\n at java.awt.Component.dispatchEvent(Component.java:4566)\n at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:680)\n at java.awt.EventQueue.access$000(EventQueue.java:86)\n at java.awt.EventQueue$1.run(EventQueue.java:639)\n at java.awt.EventQueue$1.run(EventQueue.java:637)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)\n at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)\n at java.awt.EventQueue$2.run(EventQueue.java:653)\n at java.awt.EventQueue$2.run(EventQueue.java:651)\n at java.security.AccessController.doPrivileged(Native Method)\n at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)\n at java.awt.EventQueue.dispatchEvent(EventQueue.java:650)\n at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)\n at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)\n at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)\n at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)\n at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)\n at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)\n</pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T04:43:31.937",
"Id": "6657",
"Score": "0",
"body": "I've never seen an application that dynamically changes the icon of the frame. Would this not be confusing if you are trying to find your applicaton by icon on the task bar or when you use Alt-tab to find the application. I would suggest you can just create a FileManager icon and not change it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-02-27T05:13:36.530",
"Id": "35781",
"Score": "0",
"body": "See also [`PanelBrowser`](http://stackoverflow.com/a/15104660/230513)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-05-31T02:07:33.993",
"Id": "4447",
"ParentId": "4446",
"Score": "23"
}
},
{
"body": "<p>This code concerns me:</p>\n\n<pre><code> SwingWorker worker = new SwingWorker() {\n @Override\n public String doInBackground() {\n tree.setEnabled(false);\n progressBar.setVisible(true);\n progressBar.setIndeterminate(true);\n File file = (File) node.getUserObject();\n if (file.isDirectory()) {\n File[] files = fileSystemView.getFiles(file, true);\n if (node.isLeaf()) {\n for (File child : files) {\n if (child.isDirectory()) {\n node.add(new DefaultMutableTreeNode(child));\n }\n }\n }\n setTableData(files);\n }\n progressBar.setIndeterminate(false);\n progressBar.setVisible(false);\n tree.setEnabled(true);\n return \"done\";\n }\n };\n worker.execute();\n</code></pre>\n\n<p>as you're making Swing calls to a JProgressBar off of the EDT. Best to start the progress bar before the SwingWorker and end it in the done method. Either that or add a PropertyChangeListener to the SwingWorker and end the progress bar when the worker's state property is StateValue.DONE.</p>\n\n<p>Another issue is that you're using a DefaultMutableTreeNode, and per the API, concurrency care must be taken when using this since you do appear to be using this in more than one thread:</p>\n\n<blockquote>\n <p>This is not a thread safe class.If you intend to use a DefaultMutableTreeNode (or a tree of TreeNodes) in more than one thread, you need to do your own synchronizing. A good convention to adopt is synchronizing on the root node of a tree.</p>\n</blockquote>\n\n<p><strong>EDIT</strong><br>\nOne way to <em>possibly</em> get DefaultMutableTreeNode at least out of the equation is to add nodes to it in one thread only, the EDT, by using SwingWorker's publish/process. For example:</p>\n\n<pre><code> private void showChildren(final DefaultMutableTreeNode node) {\n tree.setEnabled(false);\n progressBar.setVisible(true);\n progressBar.setIndeterminate(true);\n\n SwingWorker<Void, File> worker = new SwingWorker<Void, File>() {\n @Override\n public Void doInBackground() {\n File file = (File) node.getUserObject();\n if (file.isDirectory()) {\n File[] files = fileSystemView.getFiles(file, true); //!!\n if (node.isLeaf()) {\n for (File child : files) {\n if (child.isDirectory()) {\n publish(child);\n }\n }\n }\n setTableData(files);\n }\n return null;\n }\n\n @Override \n protected void process(List<File> chunks) {\n for (File child : chunks) {\n node.add(new DefaultMutableTreeNode(child));\n }\n }\n\n @Override\n protected void done() {\n progressBar.setIndeterminate(false);\n progressBar.setVisible(false);\n tree.setEnabled(true);\n }\n };\n worker.execute();\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T02:28:11.673",
"Id": "6663",
"Score": "0",
"body": "It is the call to `fileSystemView.getFiles(file, true);` that is the problem - it takes some time for drives that have been powered down, or the Network folder. It stands to reason that if I should not be updating GUI elements in the doInBG() method, I also should not be adding nodes to the tree. Right? Or does the last para. & quote address that problem?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T02:33:28.513",
"Id": "6664",
"Score": "0",
"body": "@Andrew: please see edit to my post above with updated SwingWorker that uses publish and process in order to add to node on the EDT."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T02:56:41.040",
"Id": "6665",
"Score": "2",
"body": "Right, the model can only be changed on the EDT."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T03:12:46.700",
"Id": "6666",
"Score": "0",
"body": "@AndrewThompson: also, are you logging your program's state when the error occurs? Any helpful information in the messages?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T10:10:14.077",
"Id": "6667",
"Score": "0",
"body": "@HFOE: Implemented your more rigorous treatment of SwingWorker. Have not seen any NPEs since (fingers crossed). See edit for latest code. As to the stacktraces, they never indicated a line in FileManager.java, they were so infrequent that I would often only realize they occurred as the CLI was disappearing from behind the closing app. Always either an AIOOBE on the table or NPE on table or tree. I suspect they are now sorted."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T10:55:57.050",
"Id": "6668",
"Score": "0",
"body": "Andrew Thompson +1, but that's typically Windows OS issue, if I tried that inside Local Network, where is Intranet access controled by Domain Controller or Novell (Ldap), then by click to the Network Icon freeze Desktop for long time (same as from Windows OS), sure there maybe doesn't exists direct/correct way fot that, how to redirect it if icon conntains Network to the background task, (ignore that if is only for native English Localization), because looks like as nonsense to get all Labels from Windows FullLocalizations and from Windows Language Pack for Network Label"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T14:12:34.333",
"Id": "6669",
"Score": "0",
"body": "Since this improvement to the SwingWorker solved the most pervasive bug in the original code (now edited out of existence), I have marked it 'correct'. Thanks for your help. The latest FileBro code is added."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T02:08:20.607",
"Id": "4448",
"ParentId": "4446",
"Score": "42"
}
},
{
"body": "<p>Andrew, it looks good. I use XP and JDK6.07 and haven't had any problems when browsing or using New/Delete/Rename functionality.</p>\n\n<p>A couple of comments:</p>\n\n<ol>\n<li><p>The Icon header and all the check box headers are truncated and show \"...\". The following fixed it for me:</p>\n\n<pre><code>// width = (int)preferred.getWidth()+10; \n width = (int)preferred.getWidth()+14;\n</code></pre></li>\n<li><p>I found the reading the text of a selected node difficult. It is black text on a dark blue background. The JTable was much easier to read with white text on a dark blue background. I see the default tree renderer also supports text selection/non-selection colours.</p></li>\n<li><p>If you really want to give users a bang for their buck, then maybe when deleting a directory you can prompt the user to see if they want to delete all the files first before deleting the directory.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T05:27:29.763",
"Id": "4449",
"ParentId": "4446",
"Score": "14"
}
},
{
"body": "<p>It works on WinXP and Win2008_64b (JRE64b) and everything looks correct. For deepest tests, just click on each accessible <code>Component</code>s, without any errors.</p>\n<p>But as I mentioned, selection on Network hanged (on WinXP, no errors, killed from IDE), JProgresBar too, in contrast with win2008, there ProgresBar works and just short time and diplay right contents of network tree.</p>\n<p><img src=\"https://i.stack.imgur.com/ohW0I.jpg\" alt=\"Network_WinXP _SP3 JRE 1.6.025\" /></p>\n<p>My assumption about the Active Directory daemon (next only AD) is that I have local admin access for Intranet and it looks like as from end user PC by local admin account AD some*** restricted view for Network's tree, AD some*** managed this access, and I can't access the AD setting because that's an outsourced service.</p>\n<ol>\n<li><p>WinXP SP3 SK LanguagePack (that isn't full localizations as Spain, Germany, ...) logged here by a local admin account click to Network icon in JTree died without any errors as I described twice.</p>\n</li>\n<li><p>Win7 64b SK (sorry no time for deepest analyses, only logged here by local admin account and runs your child out of console) icon in JTree returns null to the JTable and click by Open JButton and returns just a Win7 error.</p>\n<p><img src=\"https://i.stack.imgur.com/cfF12.jpg\" alt=\"FilemanNetworkWin7.JPG\" /></p>\n</li>\n<li><p>Win2008 is access managed by AD accessible context, because there isn't possible to create local account (internal rules).</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-02T13:58:38.653",
"Id": "4450",
"ParentId": "4446",
"Score": "7"
}
},
{
"body": "<p>This is the last edit of the code before I decided to turn FileMan(ager) into FileBro(wser) (<strong>FileBro</strong> is coming to an edit on the original question, 'real soon now'). This version of FileMan is posted here for the benefit of the people who want to extend this (very incomplete, buggy) code in that direction.</p>\n\n<p><img src=\"https://i.stack.imgur.com/iueSU.png\" width=\"677\" height=\"398\"></p>\n\n<h2>FileManager.java</h2>\n\n<pre><code>import java.awt.BorderLayout;\nimport java.awt.FlowLayout;\nimport java.awt.GridLayout;\nimport java.awt.Desktop;\nimport java.awt.Dimension;\nimport java.awt.Container;\nimport java.awt.Component;\nimport java.awt.Graphics;\nimport java.awt.Image;\nimport java.awt.event.*;\nimport java.awt.image.*;\n\nimport javax.swing.*;\nimport javax.swing.border.*;\nimport javax.swing.event.*;\nimport javax.swing.tree.*;\nimport javax.swing.table.*;\nimport javax.swing.filechooser.FileSystemView;\n\nimport javax.imageio.ImageIO;\n\nimport java.util.Date;\nimport java.util.List;\nimport java.util.ArrayList;\n\nimport java.io.*;\nimport java.nio.channels.FileChannel;\n\nimport java.net.URL;\n\n/**\nA basic File Manager. Requires 1.6+ for the Desktop & SwingWorker\nclasses, amongst other minor things.\n\nIncludes support classes FileTableModel & FileTreeCellRenderer.\n\n@TODO Bugs\n<li>Still throws occasional AIOOBEs and NPEs, so some update on\nthe EDT must have been missed.\n<li>Fix keyboard focus issues - especially when functions like\nrename/delete etc. are called that update nodes & file lists.\n<li>Needs more testing in general.\n\n@TODO Functionality\n<li>Implement Read/Write/Execute checkboxes\n<li>Implement Copy\n<li>Extra prompt for directory delete (camickr suggestion)\n<li>Add File/Directory fields to FileTableModel\n<li>Double clicking a directory in the table, should update the tree\n<li>Move progress bar?\n<li>Add other file display modes (besides table) in CardLayout?\n<li>Menus + other cruft?\n<li>Implement history/back\n<li>Allow multiple selection\n<li>Add file search\n\n@author Andrew Thompson\n@version 2011-06-01\n@see http://stackoverflow.com/questions/6182110\n@license LGPL\n*/\nclass FileManager {\n\n /** Title of the application */\n public static final String APP_TITLE = \"FileMan\";\n /** Used to open/edit/print files. */\n private Desktop desktop;\n /** Provides nice icons and names for files. */\n private FileSystemView fileSystemView;\n\n /** currently selected File. */\n private File currentFile;\n\n /** Main GUI container */\n private JPanel gui;\n\n /** File-system tree. Built Lazily */\n private JTree tree;\n private DefaultTreeModel treeModel;\n\n /** Directory listing */\n private JTable table;\n private JProgressBar progressBar;\n /** Table model for File[]. */\n private FileTableModel fileTableModel;\n private ListSelectionListener listSelectionListener;\n private boolean cellSizesSet = false;\n private int rowIconPadding = 6;\n\n /* File controls. */\n private JButton openFile;\n private JButton printFile;\n private JButton editFile;\n private JButton deleteFile;\n private JButton newFile;\n private JButton copyFile;\n /* File details. */\n private JLabel fileName;\n private JTextField path;\n private JLabel date;\n private JLabel size;\n private JCheckBox readable;\n private JCheckBox writable;\n private JCheckBox executable;\n private JRadioButton isDirectory;\n private JRadioButton isFile;\n\n /* GUI options/containers for new File/Directory creation. Created lazily. */\n private JPanel newFilePanel;\n private JRadioButton newTypeFile;\n private JTextField name;\n\n public Container getGui() {\n if (gui==null) {\n gui = new JPanel(new BorderLayout(3,3));\n gui.setBorder(new EmptyBorder(5,5,5,5));\n\n fileSystemView = FileSystemView.getFileSystemView();\n desktop = Desktop.getDesktop();\n\n JPanel detailView = new JPanel(new BorderLayout(3,3));\n //fileTableModel = new FileTableModel();\n\n table = new JTable();\n table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\n table.setAutoCreateRowSorter(true);\n table.setShowVerticalLines(false);\n\n listSelectionListener = new ListSelectionListener() {\n @Override\n public void valueChanged(ListSelectionEvent lse) {\n int row = table.getSelectionModel().getLeadSelectionIndex();\n setFileDetails( ((FileTableModel)table.getModel()).getFile(row) );\n }\n };\n table.getSelectionModel().addListSelectionListener(listSelectionListener);\n JScrollPane tableScroll = new JScrollPane(table);\n Dimension d = tableScroll.getPreferredSize();\n tableScroll.setPreferredSize(new Dimension((int)d.getWidth(), (int)d.getHeight()/2));\n detailView.add(tableScroll, BorderLayout.CENTER);\n\n // the File tree\n DefaultMutableTreeNode root = new DefaultMutableTreeNode();\n treeModel = new DefaultTreeModel(root);\n\n TreeSelectionListener treeSelectionListener = new TreeSelectionListener() {\n public void valueChanged(TreeSelectionEvent tse){\n DefaultMutableTreeNode node =\n (DefaultMutableTreeNode)tse.getPath().getLastPathComponent();\n showChildren(node);\n setFileDetails((File)node.getUserObject());\n }\n };\n\n // show the file system roots.\n File[] roots = fileSystemView.getRoots();\n for (File fileSystemRoot : roots) {\n DefaultMutableTreeNode node = new DefaultMutableTreeNode(fileSystemRoot);\n root.add( node );\n //showChildren(node);\n //\n File[] files = fileSystemView.getFiles(fileSystemRoot, true);\n for (File file : files) {\n if (file.isDirectory()) {\n node.add(new DefaultMutableTreeNode(file));\n }\n }\n //\n }\n\n tree = new JTree(treeModel);\n tree.setRootVisible(false);\n tree.addTreeSelectionListener(treeSelectionListener);\n tree.setCellRenderer(new FileTreeCellRenderer());\n tree.expandRow(0);\n JScrollPane treeScroll = new JScrollPane(tree);\n\n // as per trashgod tip\n tree.setVisibleRowCount(15);\n\n Dimension preferredSize = treeScroll.getPreferredSize();\n Dimension widePreferred = new Dimension(\n 200,\n (int)preferredSize.getHeight());\n treeScroll.setPreferredSize( widePreferred );\n\n // details for a File\n JPanel fileMainDetails = new JPanel(new BorderLayout(4,2));\n fileMainDetails.setBorder(new EmptyBorder(0,6,0,6));\n\n JPanel fileDetailsLabels = new JPanel(new GridLayout(0,1,2,2));\n fileMainDetails.add(fileDetailsLabels, BorderLayout.WEST);\n\n JPanel fileDetailsValues = new JPanel(new GridLayout(0,1,2,2));\n fileMainDetails.add(fileDetailsValues, BorderLayout.CENTER);\n\n fileDetailsLabels.add(new JLabel(\"File\", JLabel.TRAILING));\n fileName = new JLabel();\n fileDetailsValues.add(fileName);\n fileDetailsLabels.add(new JLabel(\"Path/name\", JLabel.TRAILING));\n path = new JTextField(5);\n path.setEditable(false);\n fileDetailsValues.add(path);\n fileDetailsLabels.add(new JLabel(\"Last Modified\", JLabel.TRAILING));\n date = new JLabel();\n fileDetailsValues.add(date);\n fileDetailsLabels.add(new JLabel(\"File size\", JLabel.TRAILING));\n size = new JLabel();\n fileDetailsValues.add(size);\n fileDetailsLabels.add(new JLabel(\"Type\", JLabel.TRAILING));\n\n JPanel flags = new JPanel(new FlowLayout(FlowLayout.LEADING,4,0));\n isDirectory = new JRadioButton(\"Directory\");\n isDirectory.setEnabled(false);\n flags.add(isDirectory);\n\n isFile = new JRadioButton(\"File\");\n isFile.setEnabled(false);\n flags.add(isFile);\n fileDetailsValues.add(flags);\n\n int count = fileDetailsLabels.getComponentCount();\n for (int ii=0; ii<count; ii++) {\n fileDetailsLabels.getComponent(ii).setEnabled(false);\n }\n\n JToolBar toolBar = new JToolBar();\n // mnemonics stop working in a floated toolbar\n toolBar.setFloatable(false);\n\n openFile = new JButton(\"Open\");\n openFile.setMnemonic('o');\n\n openFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n try {\n desktop.open(currentFile);\n } catch(Throwable t) {\n showThrowable(t);\n }\n gui.repaint();\n }\n });\n toolBar.add(openFile);\n\n editFile = new JButton(\"Edit\");\n editFile.setMnemonic('e');\n editFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n try {\n desktop.edit(currentFile);\n } catch(Throwable t) {\n showThrowable(t);\n }\n }\n });\n toolBar.add(editFile);\n\n printFile = new JButton(\"Print\");\n printFile.setMnemonic('p');\n printFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n try {\n desktop.print(currentFile);\n } catch(Throwable t) {\n showThrowable(t);\n }\n }\n });\n toolBar.add(printFile);\n\n // Check the actions are supported on this platform!\n openFile.setEnabled(desktop.isSupported(Desktop.Action.OPEN));\n editFile.setEnabled(desktop.isSupported(Desktop.Action.EDIT));\n printFile.setEnabled(desktop.isSupported(Desktop.Action.PRINT));\n\n toolBar.addSeparator();\n\n newFile = new JButton(\"New\");\n newFile.setMnemonic('n');\n newFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n newFile();\n }\n });\n toolBar.add(newFile);\n\n copyFile = new JButton(\"Copy\");\n copyFile.setMnemonic('c');\n copyFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n showErrorMessage(\"'Copy' not implemented.\", \"Not implemented.\");\n }\n });\n toolBar.add(copyFile);\n\n JButton renameFile = new JButton(\"Rename\");\n renameFile.setMnemonic('r');\n renameFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n renameFile();\n }\n });\n toolBar.add(renameFile);\n\n deleteFile = new JButton(\"Delete\");\n deleteFile.setMnemonic('d');\n deleteFile.addActionListener(new ActionListener(){\n public void actionPerformed(ActionEvent ae) {\n deleteFile();\n }\n });\n toolBar.add(deleteFile);\n\n toolBar.addSeparator();\n\n readable = new JCheckBox(\"Read \");\n readable.setMnemonic('a');\n //readable.setEnabled(false);\n toolBar.add(readable);\n\n writable = new JCheckBox(\"Write \");\n writable.setMnemonic('w');\n //writable.setEnabled(false);\n toolBar.add(writable);\n\n executable = new JCheckBox(\"Execute\");\n executable.setMnemonic('x');\n //executable.setEnabled(false);\n toolBar.add(executable);\n\n JPanel fileView = new JPanel(new BorderLayout(3,3));\n\n fileView.add(toolBar,BorderLayout.NORTH);\n fileView.add(fileMainDetails,BorderLayout.CENTER);\n\n detailView.add(fileView, BorderLayout.SOUTH);\n\n JSplitPane splitPane = new JSplitPane(\n JSplitPane.HORIZONTAL_SPLIT,\n treeScroll,\n detailView);\n gui.add(splitPane, BorderLayout.CENTER);\n\n JPanel simpleOutput = new JPanel(new BorderLayout(3,3));\n progressBar = new JProgressBar();\n simpleOutput.add(progressBar, BorderLayout.EAST);\n progressBar.setVisible(false);\n\n gui.add(simpleOutput, BorderLayout.SOUTH);\n\n }\n return gui;\n }\n\n public void showRootFile() {\n // ensure the main files are displayed\n tree.setSelectionInterval(0,0);\n }\n\n private TreePath findTreePath(File find) {\n for (int ii=0; ii<tree.getRowCount(); ii++) {\n TreePath treePath = tree.getPathForRow(ii);\n Object object = treePath.getLastPathComponent();\n DefaultMutableTreeNode node = (DefaultMutableTreeNode)object;\n File nodeFile = (File)node.getUserObject();\n\n if (nodeFile==find) {\n return treePath;\n }\n }\n // not found!\n return null;\n }\n\n private void renameFile() {\n if (currentFile==null) {\n showErrorMessage(\"No file selected to rename.\",\"Select File\");\n return;\n }\n\n String renameTo = JOptionPane.showInputDialog(gui, \"New Name\");\n if (renameTo!=null) {\n try {\n boolean directory = currentFile.isDirectory();\n TreePath parentPath = findTreePath(currentFile.getParentFile());\n DefaultMutableTreeNode parentNode =\n (DefaultMutableTreeNode)parentPath.getLastPathComponent();\n\n boolean renamed = currentFile.renameTo(new File(\n currentFile.getParentFile(), renameTo));\n if (renamed) {\n if (directory) {\n // rename the node..\n\n // delete the current node..\n TreePath currentPath = findTreePath(currentFile);\n System.out.println(currentPath);\n DefaultMutableTreeNode currentNode =\n (DefaultMutableTreeNode)currentPath.getLastPathComponent();\n\n treeModel.removeNodeFromParent(currentNode);\n\n // add a new node..\n }\n\n showChildren(parentNode);\n } else {\n String msg = \"The file '\" +\n currentFile +\n \"' could not be renamed.\";\n showErrorMessage(msg,\"Rename Failed\");\n }\n } catch(Throwable t) {\n showThrowable(t);\n }\n }\n gui.repaint();\n }\n\n private void deleteFile() {\n if (currentFile==null) {\n showErrorMessage(\"No file selected for deletion.\",\"Select File\");\n return;\n }\n\n int result = JOptionPane.showConfirmDialog(\n gui,\n \"Are you sure you want to delete this file?\",\n \"Delete File\",\n JOptionPane.ERROR_MESSAGE\n );\n if (result==JOptionPane.OK_OPTION) {\n try {\n System.out.println(\"currentFile: \" + currentFile);\n TreePath parentPath = findTreePath(currentFile.getParentFile());\n System.out.println(\"parentPath: \" + parentPath);\n DefaultMutableTreeNode parentNode =\n (DefaultMutableTreeNode)parentPath.getLastPathComponent();\n System.out.println(\"parentNode: \" + parentNode);\n\n boolean directory = currentFile.isDirectory();\n boolean deleted = currentFile.delete();\n if (deleted) {\n if (directory) {\n // delete the node..\n TreePath currentPath = findTreePath(currentFile);\n System.out.println(currentPath);\n DefaultMutableTreeNode currentNode =\n (DefaultMutableTreeNode)currentPath.getLastPathComponent();\n\n treeModel.removeNodeFromParent(currentNode);\n }\n\n showChildren(parentNode);\n } else {\n String msg = \"The file '\" +\n currentFile +\n \"' could not be deleted.\";\n showErrorMessage(msg,\"Delete Failed\");\n }\n } catch(Throwable t) {\n showThrowable(t);\n }\n }\n gui.repaint();\n }\n\n private void newFile() {\n if (currentFile==null) {\n showErrorMessage(\"No location selected for new file.\",\"Select Location\");\n return;\n }\n\n if (newFilePanel==null) {\n newFilePanel = new JPanel(new BorderLayout(3,3));\n\n JPanel southRadio = new JPanel(new GridLayout(1,0,2,2));\n newTypeFile = new JRadioButton(\"File\", true);\n JRadioButton newTypeDirectory = new JRadioButton(\"Directory\");\n ButtonGroup bg = new ButtonGroup();\n bg.add(newTypeFile);\n bg.add(newTypeDirectory);\n southRadio.add( newTypeFile );\n southRadio.add( newTypeDirectory );\n\n name = new JTextField(15);\n\n newFilePanel.add( new JLabel(\"Name\"), BorderLayout.WEST );\n newFilePanel.add( name );\n newFilePanel.add( southRadio, BorderLayout.SOUTH );\n }\n\n int result = JOptionPane.showConfirmDialog(\n gui,\n newFilePanel,\n \"Create File\",\n JOptionPane.OK_CANCEL_OPTION);\n if (result==JOptionPane.OK_OPTION) {\n try {\n boolean created;\n File parentFile = currentFile;\n if (!parentFile.isDirectory()) {\n parentFile = parentFile.getParentFile();\n }\n File file = new File( parentFile, name.getText() );\n if (newTypeFile.isSelected()) {\n created = file.createNewFile();\n } else {\n created = file.mkdir();\n }\n if (created) {\n\n TreePath parentPath = findTreePath(parentFile);\n DefaultMutableTreeNode parentNode =\n (DefaultMutableTreeNode)parentPath.getLastPathComponent();\n\n if (file.isDirectory()) {\n // add the new node..\n DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(file);\n\n TreePath currentPath = findTreePath(currentFile);\n DefaultMutableTreeNode currentNode =\n (DefaultMutableTreeNode)currentPath.getLastPathComponent();\n\n treeModel.insertNodeInto(newNode, parentNode, parentNode.getChildCount());\n }\n\n showChildren(parentNode);\n } else {\n String msg = \"The file '\" +\n file +\n \"' could not be created.\";\n showErrorMessage(msg, \"Create Failed\");\n }\n } catch(Throwable t) {\n showThrowable(t);\n }\n }\n gui.repaint();\n }\n\n private void showErrorMessage(String errorMessage, String errorTitle) {\n JOptionPane.showMessageDialog(\n gui,\n errorMessage,\n errorTitle,\n JOptionPane.ERROR_MESSAGE\n );\n }\n\n private void showThrowable(Throwable t) {\n t.printStackTrace();\n JOptionPane.showMessageDialog(\n gui,\n t.toString(),\n t.getMessage(),\n JOptionPane.ERROR_MESSAGE\n );\n gui.repaint();\n }\n\n /** Update the table on the EDT */\n private void setTableData(final File[] files) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n if (fileTableModel==null) {\n fileTableModel = new FileTableModel();\n table.setModel(fileTableModel);\n }\n table.getSelectionModel().removeListSelectionListener(listSelectionListener);\n fileTableModel.setFiles(files);\n table.getSelectionModel().addListSelectionListener(listSelectionListener);\n if (!cellSizesSet) {\n Icon icon = fileSystemView.getSystemIcon(files[0]);\n\n // size adjustment to better account for icons\n table.setRowHeight( icon.getIconHeight()+rowIconPadding );\n\n setColumnWidth(0,-1);\n setColumnWidth(3,60);\n table.getColumnModel().getColumn(3).setMaxWidth(120);\n setColumnWidth(4,-1);\n setColumnWidth(5,-1);\n setColumnWidth(6,-1);\n setColumnWidth(7,-1);\n setColumnWidth(8,-1);\n setColumnWidth(9,-1);\n\n cellSizesSet = true;\n }\n }\n });\n }\n\n private void setColumnWidth(int column, int width) {\n TableColumn tableColumn = table.getColumnModel().getColumn(column);\n if (width<0) {\n // use the preferred width of the header..\n JLabel label = new JLabel( (String)tableColumn.getHeaderValue() );\n Dimension preferred = label.getPreferredSize();\n // altered 10->14 as per camickr comment.\n width = (int)preferred.getWidth()+14;\n }\n tableColumn.setPreferredWidth(width);\n tableColumn.setMaxWidth(width);\n tableColumn.setMinWidth(width);\n }\n\n /** Add the files that are contained within the directory of this node.\n Thanks to Hovercraft Full Of Eels. */\n private void showChildren(final DefaultMutableTreeNode node) {\n tree.setEnabled(false);\n progressBar.setVisible(true);\n progressBar.setIndeterminate(true);\n\n SwingWorker<Void, File> worker = new SwingWorker<Void, File>() {\n @Override\n public Void doInBackground() {\n File file = (File) node.getUserObject();\n if (file.isDirectory()) {\n File[] files = fileSystemView.getFiles(file, true); //!!\n if (node.isLeaf()) {\n for (File child : files) {\n if (child.isDirectory()) {\n publish(child);\n }\n }\n }\n setTableData(files);\n }\n return null;\n }\n\n @Override\n protected void process(List<File> chunks) {\n for (File child : chunks) {\n node.add(new DefaultMutableTreeNode(child));\n }\n }\n\n @Override\n protected void done() {\n progressBar.setIndeterminate(false);\n progressBar.setVisible(false);\n tree.setEnabled(true);\n }\n };\n worker.execute();\n }\n\n /** Update the File details view with the details of this File. */\n private void setFileDetails(File file) {\n currentFile = file;\n Icon icon = fileSystemView.getSystemIcon(file);\n fileName.setIcon(icon);\n fileName.setText(fileSystemView.getSystemDisplayName(file));\n path.setText(file.getPath());\n date.setText(new Date(file.lastModified()).toString());\n size.setText(file.length() + \" bytes\");\n readable.setSelected(file.canRead());\n writable.setSelected(file.canWrite());\n executable.setSelected(file.canExecute());\n isDirectory.setSelected(file.isDirectory());\n\n isFile.setSelected(file.isFile());\n\n JFrame f = (JFrame)gui.getTopLevelAncestor();\n if (f!=null) {\n f.setTitle(\n APP_TITLE +\n \" :: \" +\n fileSystemView.getSystemDisplayName(file) );\n }\n\n gui.repaint();\n }\n\n public static boolean copyFile(File from, File to) throws IOException {\n\n boolean created = to.createNewFile();\n\n if (created) {\n FileChannel fromChannel = null;\n FileChannel toChannel = null;\n try {\n fromChannel = new FileInputStream(from).getChannel();\n toChannel = new FileOutputStream(to).getChannel();\n\n toChannel.transferFrom(fromChannel, 0, fromChannel.size());\n\n // set the flags of the to the same as the from\n to.setReadable(from.canRead());\n to.setWritable(from.canWrite());\n to.setExecutable(from.canExecute());\n } finally {\n if (fromChannel != null) {\n fromChannel.close();\n }\n if (toChannel != null) {\n toChannel.close();\n }\n return false;\n }\n }\n return created;\n }\n\n public static void main(String[] args) {\n SwingUtilities.invokeLater(new Runnable() {\n public void run() {\n try {\n // Significantly improves the look of the output in\n // terms of the file names returned by FileSystemView!\n UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());\n } catch(Exception weTried) {\n }\n JFrame f = new JFrame(APP_TITLE);\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n\n FileManager fileManager = new FileManager();\n f.setContentPane(fileManager.getGui());\n\n try {\n URL urlBig = fileManager.getClass().getResource(\"fm-icon-32x32.png\");\n URL urlSmall = fileManager.getClass().getResource(\"fm-icon-16x16.png\");\n ArrayList<Image> images = new ArrayList<Image>();\n images.add( ImageIO.read(urlBig) );\n images.add( ImageIO.read(urlSmall) );\n f.setIconImages(images);\n } catch(Exception weTried) {}\n\n f.pack();\n f.setLocationByPlatform(true);\n f.setMinimumSize(f.getSize());\n f.setVisible(true);\n\n fileManager.showRootFile();\n }\n });\n }\n}\n\n/** A TableModel to hold File[]. */\nclass FileTableModel extends AbstractTableModel {\n\n private File[] files;\n private FileSystemView fileSystemView = FileSystemView.getFileSystemView();\n private String[] columns = {\n \"Icon\",\n \"File\",\n \"Path/name\",\n \"Size\",\n \"Last Modified\",\n \"R\",\n \"W\",\n \"E\",\n \"D\",\n \"F\",\n };\n\n FileTableModel() {\n this(new File[0]);\n }\n\n FileTableModel(File[] files) {\n this.files = files;\n }\n\n public Object getValueAt(int row, int column) {\n File file = files[row];\n switch (column) {\n case 0:\n return fileSystemView.getSystemIcon(file);\n case 1:\n return fileSystemView.getSystemDisplayName(file);\n case 2:\n return file.getPath();\n case 3:\n return file.length();\n case 4:\n return file.lastModified();\n case 5:\n return file.canRead();\n case 6:\n return file.canWrite();\n case 7:\n return file.canExecute();\n case 8:\n return file.isDirectory();\n case 9:\n return file.isFile();\n default:\n System.err.println(\"Logic Error\");\n }\n return \"\";\n }\n\n public int getColumnCount() {\n return columns.length;\n }\n\n public Class<?> getColumnClass(int column) {\n switch (column) {\n case 0:\n return ImageIcon.class;\n case 3:\n return Long.class;\n case 4:\n return Date.class;\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n return Boolean.class;\n }\n return String.class;\n }\n\n public String getColumnName(int column) {\n return columns[column];\n }\n\n public int getRowCount() {\n return files.length;\n }\n\n public File getFile(int row) {\n return files[row];\n }\n\n public void setFiles(File[] files) {\n this.files = files;\n fireTableDataChanged();\n }\n}\n\n/** A TreeCellRenderer for a File. */\nclass FileTreeCellRenderer extends DefaultTreeCellRenderer {\n\n private FileSystemView fileSystemView;\n\n private JLabel label;\n\n FileTreeCellRenderer() {\n label = new JLabel();\n label.setOpaque(true);\n fileSystemView = FileSystemView.getFileSystemView();\n }\n\n @Override\n public Component getTreeCellRendererComponent(\n JTree tree,\n Object value,\n boolean selected,\n boolean expanded,\n boolean leaf,\n int row,\n boolean hasFocus) {\n\n DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;\n File file = (File)node.getUserObject();\n label.setIcon(fileSystemView.getSystemIcon(file));\n label.setText(fileSystemView.getSystemDisplayName(file));\n label.setToolTipText(file.getPath());\n\n if (selected) {\n label.setBackground(backgroundSelectionColor);\n label.setForeground(textSelectionColor);\n } else {\n label.setBackground(backgroundNonSelectionColor);\n label.setForeground(textNonSelectionColor);\n }\n\n return label;\n }\n}\n</code></pre>\n\n<h2>Addendum</h2>\n\n<p>In the end I decided that I did not need anything more than a file browser. When it came to <em>managing</em> files, simply opening the parent directory & using the OS' inbuilt functionality to make new files, rename them, copy or delete them, as well as change the flags, would suffice.</p>\n\n<p>That not only got rid of many of the remaining bugs, but also removed any possibility that a user's lawyers might contact me about how my software deleted everything on their client's LAN when they asked it to delete a symbolic link. ;)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T12:25:49.280",
"Id": "6674",
"Score": "0",
"body": "access to the Network works +1, what did you change, :-) and sleep too :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-06-08T12:00:51.760",
"Id": "4451",
"ParentId": "4446",
"Score": "17"
}
},
{
"body": "<p>There is a bug: when the table is sorted, the mapping between the selection model row index and the table model row index is broken and the buttons end up operating on other files.</p>\n\n<p>The <code>ListSelectionListener</code> should correct that:</p>\n\n<pre><code>int row = table.getSelectionModel().getLeadSelectionIndex();\nRowSorter sorter = table.getRowSorter();\nif ( sorter != null ) {\n row = sorter.convertRowIndexToModel( row ); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-05-23T07:55:32.553",
"Id": "26517",
"ParentId": "4446",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": "4448",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-05-31T01:28:07.810",
"Id": "4446",
"Score": "93",
"Tags": [
"swing",
"java"
],
"Title": "File Browser GUI"
}
|
4446
|
<p>Is this a good method to optionally run some code on a background thread depending on a configuration setting? This will primarily be called from an ASP.NET front-end (although others are possible) under Framework 3.5. I'm attempting to keep this as DRY as possible.</p>
<pre><code>Dim sendEmails = Sub()
Dim emailToSend As New SendEmailRequest()
TransferCommonValuesTo(emailToSend, request, sendingUser)
usersToSendEmailTo.ForEach(Sub(u)
TransferValuesTo(emailToSend, u, m_EmailMessageMerger.GetMergedMessage(request.Message, u))
m_EmailSender.Send(emailToSend)
End Sub)
End Sub
If cfg.SendBulkEmailUsingBackgroundThread Then
Dim worker As New Thread(sendEmails)
worker.IsBackground = True
worker.Start()
Else
sendEmails()
End If
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T17:03:46.373",
"Id": "6678",
"Score": "3",
"body": "In a nutshell.. yes. This is basically spot on, any style points aside, the only other thing I can think is frequently in the context of IIS people tend to use the threadpool instead of their own threads, but the threadpool doesn't have a guaranteed start time which is plausibly necessary for your instance. There may be some style mishaps in there but I have thoroughly forgotten my old VB chops so I couldn't speak to them."
}
] |
[
{
"body": "<p>Maybe.</p>\n\n<p>Depends, as always, what happens if you get multiple threads running.</p>\n\n<p>So you start this thread going, your code will move on, and if you start this again, and it hasn't finished the previous round of sending emails. What happens?</p>\n\n<p>If its all thread safe, then no problem, but it might send some emails out of order.\nIf its not thread safe, then hilarity ( or calamity ) ensues :-)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T05:13:09.940",
"Id": "4467",
"ParentId": "4452",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4467",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T16:10:54.817",
"Id": "4452",
"Score": "1",
"Tags": [
"asp.net",
"multithreading",
"vb.net"
],
"Title": "Optionally running some code on a background thread"
}
|
4452
|
<p>I'm seeking review comments (design, performance, etc.) based on the problem statement:</p>
<blockquote>
<p>Write a CashWithDrawal function from an ATM which based on user
specified amount dispenses bank notes. Ensure that the following is
taken care of</p>
<ul>
<li>Minimum number of bank notes are dispensed</li>
<li>Availability of various denominations in the ATM is maintained</li>
<li>Code should be flexible to take care of any bank denominations as long as it is a multiple of 10</li>
<li>Code should support parallel withdrawals i.e. two or more customers can withdraw money simultaneously</li>
<li>Take care of exceptional situation</li>
</ul>
</blockquote>
<hr>
<pre><code>package com.assignment.atm;
import java.util.Scanner;
/**
* The Class Main.
*/
public class Main
{
/**
* The main method.
*
* @param args the arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter Amount to be withdrawn: ");
int amount = input.nextInt();
if(amount%10!=0){
System.out.println("Please enter the amount in multiples of 10");
}
else{
ATM atm = new ATM(amount);
ATM.calcTotalCorpus();
Thread t1 = new Thread(atm);
t1.start();
/*ATM.calcTotalCorpus();
Thread t1 = new Thread(new ATM(1200));
Thread t2 = new Thread(new ATM(2400));
t1.start();
t2.start();
try{
t2.sleep(2000);
}
catch(Exception e){
//Sysout Exception trace
}*/
}
}
}
</code></pre>
<hr>
<pre><code>package com.assignment.atm;
/**
* The Class ATM.
*/
class ATM implements Runnable{
/** The Constant Currency Denominations. */
protected static final int[] currDenom = { 1000, 500, 100, 50 , 10 };
/** The Number of Currencies of each type*/
protected static int[] currNo = {1,4,2,2,10};
/** The count. */
protected int[] count = { 0, 0, 0, 0 ,0};
/** The total corpus. */
protected static int totalCorpus = 0;
/** The amount. */
protected int amount=0;
/**
* Instantiates a new aTM.
*
* @param amount The Amount of type int
*/
public ATM(int amount){
this.amount=amount;
}
/**
* Calc total corpus.
*/
public static void calcTotalCorpus(){
for(int i = 0; i < currDenom.length; i++){
totalCorpus=totalCorpus+currDenom[i]*currNo[i];
}
}
/**
* Withdraw cash.
*/
public synchronized void withdrawCash(){
if(amount<=totalCorpus){
for (int i = 0; i < currDenom.length; i++) {
if (currDenom[i] <= amount) {//If the amount is less than the currDenom[i] then that particular denomination cannot be dispensed
int noteCount = amount / currDenom[i];
if(currNo[i]>0){//To check whether the ATM Vault is left with the currency denomination under iteration
//If the Note Count is greater than the number of notes in ATM vault for that particular denomination then utilize all of them
count[i] = noteCount>=currNo[i]?currNo[i]:noteCount;
currNo[i] = noteCount>=currNo[i]?0:currNo[i]- noteCount;
//Deduct the total corpus left in the ATM Vault with the cash being dispensed in this iteration
totalCorpus=totalCorpus-(count[i]*currDenom[i]);
//Calculate the amount that need to be addressed in the next iterations
amount = amount -(count[i]*currDenom[i]);
}
}
}
displayNotes();
displayLeftNotes();
}
else{
System.out.println("Unable to dispense cash at this moment for this big amount");
}
}
/**
*
*
*/
public void run()
{
withdrawCash();
}
/**
* Display notes.
*/
private void displayNotes(){
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.println(currDenom[i] + " * " + count[i] + " = "+ (currDenom[i] * count[i]));
}
}
}
/**
* Display left notes.
*/
private void displayLeftNotes(){
for(int i = 0; i < currDenom.length; i++){
System.out.println("Notes of "+currDenom[i]+" left are "+currNo[i]);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>(1) API is a bit odd. Why do I need to call some static methods after I instatiated an object and want to use it already? <code>ATM atm = new ATM(amount); ATM.calcTotalCorpus();</code></p>\n\n<p>(2) There is a slight mess with access modifiers. For example, Why protected ? <code>protected int amount=0;</code>\n And why is this method public ? <code>public synchronized void withdrawCash()</code></p>\n\n<p>(3)This method <code>void withdrawCash()</code> is full of coments but it would be a lot better to divide this method into a smaller functions to make it more readable. Consider</p>\n\n<pre><code>public synchronized void withdrawCash(){\nif(isAmountSufficient()){\n for (int i = 0; i < currDenom.length; i++) {\n if (canDispenseDenomination()) {\n getNoteCount();\n if(canProceedWithIterations()){\n doCalculations();\n deductTotalCorpuse()\n calculateAmmountForNextIteration();\n } \n }\n }\n displayNotes();\n displayLeftNotes();\n\n}\nelse{\n reportInsufficientAmmount();\n}\n</code></pre>\n\n<p>(4) There is also some odd synchronization. The presense of 2 customers means that you have 2 threads which work with a single ATM however in your case you have only one thread for a single ATM and no concurrent access to this ATM from different customers. I would do it in the follwoing way:</p>\n\n<pre><code> public class Consumer extends Thread {\n private final ATM atm; \n public Consumer (ATM atm) {this.atm = atm;} \n\n public void Run() {\n this.atm.dispense(10);\n Thread.sleep(10);\n this.atm.dispense(20);\n }\n } \n\n public static void main(String[] args) {\n ATM atm = new ATM(1000);\n Consumer c1 = new Consumer(atm);\n Consumer c2 = new Consumer(atm);\n c1.Start();\n c2.Start();\n ....\n }\n</code></pre>\n\n<p>The <code>dispsense()</code> function can implement the logic from <code>withdrawCash()</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T19:18:26.660",
"Id": "4456",
"ParentId": "4453",
"Score": "9"
}
},
{
"body": "<p>In this type of problem (money handling), I would zealously focus on exceptional cases first and then ensure that the code is well structured and easy to understand.</p>\n\n<p>First thing that hit me was that you have no check for negative number input.</p>\n\n<p>If you go with the ATM class with amount in constructor, I would suggest to add a input checking in the constructor - for starters testing that input is positive and is multiple of ten. If input is invalid then IllegalArgumentException (or your own subclass of it) flies.</p>\n\n<p>Furthermore, I would make the amount field private final - and then change the rest of the code (use a method variable to keep track of the amount left to dispose) and eventually design to accommodate this change. The reasoning being that I prefer to be extra paranoid with a sensitive data like this.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T20:45:18.610",
"Id": "4503",
"ParentId": "4453",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-28T17:30:55.223",
"Id": "4453",
"Score": "5",
"Tags": [
"java",
"performance",
"multithreading",
"homework",
"finance"
],
"Title": "Cash-withdrawal from an ATM"
}
|
4453
|
<p>For practice, I am working through some Google Code Jam problems. The code below is for the Milkshakes problem, which is located <a href="http://code.google.com/codejam/contest/dashboard?c=32016#s=p1" rel="nofollow">here</a>.</p>
<blockquote>
<p><strong>Problem</strong></p>
<p>You own a milkshake shop. There are N different flavors that you can
prepare, and each flavor can be prepared "malted" or "unmalted". So,
you can make \$2N\$ different types of milkshakes.</p>
<p>Each of your customers has a set of milkshake types that they like,
and they will be satisfied if you have at least one of those types
prepared. At most one of the types a customer likes will be a "malted"
flavor.</p>
<p>You want to make \$N\$ batches of milkshakes, so that:</p>
<p>There is exactly one batch for each flavor of milkshake, and it is
either malted or unmalted. For each customer, you make at least one
milkshake type that they like. The minimum possible number of batches
are malted. Find whether it is possible to satisfy all your customers
given these constraints, and if it is, what milkshake types you should
make. If it is possible to satisfy all your customers, there will be
only one answer which minimizes the number of malted batches.</p>
<p>Input</p>
<ul>
<li>One line containing an integer \$C\$, the number of test cases in the
input file.</li>
</ul>
<p>For each test case, there will be:</p>
<ul>
<li>One line containing the
integer \$N\$, the number of milkshake flavors.</li>
<li>One line containing the
integer \$M\$, the number of customers.</li>
<li>\$M\$ lines, one for each customer, each containing:
<ul>
<li>An integer \$T >= 1\$, the number of milkshake types the
customer likes, followed by</li>
<li>\$T\$ pairs of integers "X Y", one for each
type the customer likes, where \$X\$ is the milkshake flavor between 1 and
\$N\$ inclusive, and \$Y\$ is either 0 to indicate unmalted, or 1 to indicated
malted. Note that:
<ul>
<li>No pair will occur more than once for a single
customer.</li>
<li>Each customer will have at least one flavor that they like
(\$T >= 1\$).</li>
<li>Each customer will like at most one malted flavor. (At most
one pair for each customer has \$Y = 1\$).</li>
</ul></li>
</ul></li>
</ul>
<p>All of these numbers are separated by single spaces.</p>
<p><strong>Output</strong></p>
<ul>
<li>C lines, one for each test case in the order they occur in the input
file, each containing the string "Case #X: " where X is the number of
the test case, starting from 1, followed by:
<ul>
<li>The string "IMPOSSIBLE",
if the customers' preferences cannot be satisfied; OR</li>
<li>N space-separated integers, one for each flavor from 1 to N, which are 0
if the corresponding flavor should be prepared unmalted, and 1 if it
should be malted. Limits</li>
</ul></li>
</ul>
<p><strong>Small dataset</strong></p>
<p>\$C = 100\$<br>
\$1 <= N <= 10\$<br>
\$1 <= M <= 100\$</p>
<p><strong>Large dataset</strong></p>
<p>\$C = 5\$<br>
\$1 <= N <= 2000\$<br>
\$1 <= M <= 2000\$</p>
<p>The sum of all the \$T\$ values for the customers in a test case will not
exceed 3000.</p>
</blockquote>
<p>This solution solves for both the small and large data sets. Please let me know how I can improve this code.</p>
<pre><code>import java.util.*;
import java.io.*;
public class MilkShake {
private final int UNMALTED = 0;
private final int NOCHOICE = 2;
private boolean isPossible;
private ArrayList<ArrayList<Integer>> customerPreferenceList = new ArrayList<ArrayList<Integer>>();
private int[] finalBatchAr;
private StringBuilder result = new StringBuilder();
public static void main(String[] args) {
new MilkShake().go();
}
public void go() {
File inputFile = new File("/* File name */");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(inputFile));
int numTests = Integer.parseInt(br.readLine());
//Loop through each test
for(int testCounter = 0; testCounter < numTests; ++testCounter) {
customerPreferenceList.clear();
int numFlavors = Integer.parseInt(br.readLine());
initializeFlavorAr(numFlavors);
int numCustomers = Integer.parseInt(br.readLine());
isPossible = true;
//For each test, loop through each customer
for(int customerCounter = 0; customerCounter < numCustomers; ++customerCounter) {
String[] customerPrefs = br.readLine().split(" ");
ArrayList<Integer> custRow = new ArrayList<Integer>();
for(int j = 0; j < customerPrefs.length; ++j) {
custRow.add(Integer.parseInt(customerPrefs[j]));
}
customerPreferenceList.add(custRow);
}
//Eliminate first element of each row. Number of elements each customer likes is not used.
if(!customerPreferenceList.isEmpty()) {
for(ArrayList<Integer> a : customerPreferenceList) {
if(!a.isEmpty()) { a.remove(0); }
}
}
boolean customerPreferenceListChanged = true;
while(customerPreferenceList.size() > 0 && isPossible && customerPreferenceListChanged == true) {
customerPreferenceListChanged = false;
ArrayList<Integer> removeList = new ArrayList<Integer>();
//Deal with rows with only one choice
for(int oneChoiceCounter = 0; oneChoiceCounter < customerPreferenceList.size(); ++oneChoiceCounter) {
if(customerPreferenceList.get(oneChoiceCounter).size() == 2) {
int indexOfFlavorInQuestion = customerPreferenceList.get(oneChoiceCounter).get(0);
if(finalBatchAr[indexOfFlavorInQuestion - 1] == NOCHOICE) {
finalBatchAr[indexOfFlavorInQuestion - 1] = customerPreferenceList.get(oneChoiceCounter).get(1);
removeList.add(oneChoiceCounter);
customerPreferenceListChanged = true;
}
else if(finalBatchAr[indexOfFlavorInQuestion - 1] != customerPreferenceList.get(oneChoiceCounter).get(1)) {
isPossible = false;
break;
}
else {
//flavor already in map - remove from customerPreferenceList
removeList.add(oneChoiceCounter);
customerPreferenceListChanged = true;
}
}
}
if(!removeList.isEmpty()) {
cleanUpCustomerPreferenceList(removeList);
removeList.clear();
}
//Loop through all other cases, if any element already in finalBatchAr remove the row from customerPreferenceList
for(int elementExistsCounter = 0; elementExistsCounter < customerPreferenceList.size(); ++elementExistsCounter) {
for(int j = 0; j < customerPreferenceList.get(elementExistsCounter).size(); j += 2) {
if(finalBatchAr[customerPreferenceList.get(elementExistsCounter).get(j) - 1] == customerPreferenceList.get(elementExistsCounter).get(j + 1)) {
removeList.add(elementExistsCounter);
customerPreferenceListChanged = true;
break;
}
}
}
if(!removeList.isEmpty()) {
cleanUpCustomerPreferenceList(removeList);
removeList.clear();
}
//Loop through customerPreferenceList again, get rid of all elements that conflicts with finalBatchAr
//If currentRow empty afterwards, set isPossible to false
for(int conflictCounter = 0; conflictCounter < customerPreferenceList.size(); ++conflictCounter) {
int currentRowSize = customerPreferenceList.get(conflictCounter).size();
for(int j = 0; j < currentRowSize; j += 2) {
if((finalBatchAr[customerPreferenceList.get(conflictCounter).get(j) - 1] != NOCHOICE) && (finalBatchAr[customerPreferenceList.get(conflictCounter).get(j) - 1] != customerPreferenceList.get(conflictCounter).get(j + 1))) {
customerPreferenceList.get(conflictCounter).remove(j);
customerPreferenceList.get(conflictCounter).remove(j);
j -= 2;
currentRowSize -= 2;
customerPreferenceListChanged = true;
}
}
if(customerPreferenceList.get(conflictCounter).size() == 0) {
isPossible = false;
break;
}
}
}
finalizeFlavorAr(numFlavors);
appendResult(testCounter + 1, numFlavors);
}
} catch(FileNotFoundException fe) {
fe.printStackTrace();
} catch(IOException ie) {
ie.printStackTrace();
} finally {
try {
if(br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
writeResultToFile();
}
private void initializeFlavorAr(int numFlavors) {
finalBatchAr = null;
finalBatchAr = new int[numFlavors];
for(int i = 0; i < numFlavors; ++i) {
finalBatchAr[i] = NOCHOICE;
}
}
private void finalizeFlavorAr(int numFlavors) {
for(int i = 0; i < numFlavors; ++i) {
if(finalBatchAr[i] == NOCHOICE) {
finalBatchAr[i] = UNMALTED;
}
}
}
private void appendResult(int testCase, int numFlavors) {
result.append("Case #" + testCase + ": ");
if(!isPossible) {
result.append("IMPOSSIBLE");
}
else {
for(int i = 0; i < finalBatchAr.length; ++i) {
result.append(finalBatchAr[i] + " ");
}
}
result.append("\n");
}
private void writeResultToFile() {
PrintWriter pr = null;
try {
pr = new PrintWriter(new File("/* File name */"));
pr.print(result);
} catch(FileNotFoundException e) {
e.printStackTrace();
} finally {
if(pr != null) {
pr.close();
}
}
}
private void cleanUpCustomerPreferenceList(ArrayList<Integer> removeList) {
for(int i = 0; i < removeList.size(); ++i) {
int removeIndex = removeList.get(i);
customerPreferenceList.remove(removeIndex - i);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your <code>go()</code> method is <strong>waaaaaaaayyyyyyyyyyyyyy</strong> to long, break it up in digestible parts. Try to think in different abstraction levels, and don't mix them in one method (e.g. you deal with file input directly, but have a separate method for writing into a file). Follow the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">Single Responsibility Principle</a>.</p>\n\n<p>You should use extended for loops where possible, e.g.</p>\n\n<pre><code>for(int j = 0; j < customerPrefs.length; ++j) {\n custRow.add(Integer.parseInt(customerPrefs[j]));\n}\n\n-->\n\nfor(String customerPref : customerPrefs) {\n custRow.add(Integer.parseInt(customerPref));\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T17:43:47.987",
"Id": "6703",
"Score": "0",
"body": "thanks for the input. In your words, why do you think a smaller method is necessarily better than a larger one? How would you respond to the argument that given a solution that requires steps A, B, and C to complete it is easier to code them sequentially in one function rather than forcing whoever wants to understand the program to jump back and forth in the code between method definitions? Not saying I disagree with your response, I would just like to hear your opinion."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T07:08:18.887",
"Id": "6711",
"Score": "1",
"body": "The answer is \"level of abstraction\". If your method needs to do A, B and C to perform a task, it must do it. However if you have to do A1, A2 and A3 in order to do A, you should have a separate method encapsulating these steps, which is called from the top-level method. In your method, you have more or less a comment for every logical step, which are top-level abstractions. Pack the code after every comment a separate method, and call it from `go()`. But all of this is just an application of the Single Responsibility Principle."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T18:39:17.353",
"Id": "6790",
"Score": "2",
"body": "@fiddlesticks Have a read at this great article by Uncle Bob http://blog.objectmentor.com/articles/2009/09/11/one-thing-extract-till-you-drop\nYou don't have to extract it so much as in the article, but that gives you a good idea. And you don't have to worry about someone having to jump back and forth to understand the code. With more methods (with each method name suggesting the intent) a reader would be skipping the methods he doesn't care about. And that's a very good thing !"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-10T13:42:58.513",
"Id": "21847",
"Score": "0",
"body": "You can't foreach through an array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-10T13:50:24.150",
"Id": "21848",
"Score": "0",
"body": "@sproule When A,B,and C are longer than 15 lines of code put together (or more practically when the code starts to [smell](http://en.wikipedia.org/wiki/Code_smell)), it's easier to jump between different well-named methods than slog through one poorly-named one."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-07-11T06:56:46.107",
"Id": "21927",
"Score": "0",
"body": "@Eva: Actully you *can* foreach thru an array."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T07:39:45.130",
"Id": "4469",
"ParentId": "4463",
"Score": "3"
}
},
{
"body": "<p>Move <code>try/catch/finally</code> block body to separate method. Its main goal is an error processing, and body is a main functionality, so they have different responsibility.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T10:04:44.890",
"Id": "4543",
"ParentId": "4463",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T00:37:40.227",
"Id": "4463",
"Score": "3",
"Tags": [
"java",
"programming-challenge"
],
"Title": "Google Code Jam (Milkshakes) solution"
}
|
4463
|
<p>What are your thoughts on using an <code>IDisposable</code> to stripe an HTML table like so? It's a blatant abuse of <code>IDisposable</code> but this allows you to use the counter in a <code>using(){}</code> block which gives you a clear block in the markup.</p>
<pre><code>public class StripeCounter : IDisposable
{
private string cssClass = "stripe";
private int counter = 0;
public StripeCounter(){}
public StripeCounter(string cssClass)
{
this.cssClass = cssClass;
}
public MvcHtmlString Stripe()
{
return MvcHtmlString.Create(counter++ % 2 == 1 ? cssClass : string.Empty);
}
public void Dispose() { }
}
</code></pre>
<p>And then the markup</p>
<pre><code>@using (var counter = new StripeCounter())
{
foreach (var item in Model)
{
<tr class="@counter.Stripe()">
<td>
...
</td>
...
</tr>
}
}
</code></pre>
<p>Regarding comments on using JavaScript to stripe the table:</p>
<p>JavaScript is for behaviour and the striped rows of a table aren't behaviour; they are style, so while it is possible to do so on the client, it seem to me to be something that should be done on the server. For example, if someone has scripts disabled, they would still see the CSS striping, but not JavaScript striping.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T17:52:41.037",
"Id": "6720",
"Score": "3",
"body": "Why are you striping in custom code instead of using jquery (which comes with MVC3)? It is server side work that you can push down to the client."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T18:30:51.423",
"Id": "189576",
"Score": "0",
"body": "This falls into the \"Just because you can do something doesn't mean you should\" category. Art's comment above is the best response to this. A great option is to do this client side via jQuery or even in plain ole' Javascript."
}
] |
[
{
"body": "<p>Don't do the striping on the server. Don't do the striping with JavaScript. Since it's styling, <a href=\"http://dev.opera.com/articles/view/zebra-striping-tables-with-css3/\" rel=\"nofollow\">do the striping with CSS</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T15:14:15.713",
"Id": "8711",
"Score": "2",
"body": "Note, though, that `:nth-child` (the CSS pseudo-class that lets you do striping with CSS) doesn't work in IE <9 -- or any other browser that doesn't know CSS3."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T15:19:40.603",
"Id": "8712",
"Score": "1",
"body": "At that point, you can probably use JavaScript to read the attribute and fake it, though I'm not absolutely sure. Or do it on the server. Or decide that striping is a minor point and it doesn't have to look identical in every browser."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-02T14:58:38.010",
"Id": "5760",
"ParentId": "4470",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T08:12:13.843",
"Id": "4470",
"Score": "2",
"Tags": [
"c#",
"asp.net-mvc-3"
],
"Title": "Using IDisposable to stripe a table"
}
|
4470
|
<p>Im running a photocontest and making a list of winners with one winner each day. My loop is running very slow. It seams to be the toList() that is time consuming. Any suggestions on how to make it run faster?</p>
<pre><code>foreach (var date in dates)
{
var voteList = _images.Select(image => new ImageWinnerVotes
{
ID = image.ID,
Image = image.ImagePath,
Thumbnail = image.ThumbnailImagePath,
Title = image.Name,
Url = GetFriendlyUrl(image.ID),
Date = image.CreatedDate,
WinnerDateString = date.Date.ToString("dd/MM"),
WinnerDate = date.Date,
TotalVotes =
(votes.Where(vote => vote.ItemId == image.ID)).Count(),
Name = image.Fields["Name"].ToString(),
Votes =
(votes.Where(
vote =>
vote.ItemId == image.ID &&
vote.Date.DayOfYear == date.Date.DayOfYear)).Count()
}).ToList();
voteList = voteList.OrderByDescending(v => v.Votes).ToList();
var j = 0;
var findingWinner = true;
while(findingWinner)
{
var inWinnersList = false;
if (winnersList.Count() != 0)
{
if(!winnersList.Contains(voteList.ElementAt(j)))
{
winnersList.Add(voteList.ElementAt(j));
findingWinner = false;
}
}
else
{
winnersList.Add(voteList.ElementAt(j));
findingWinner = false;
}
j++;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T09:39:15.293",
"Id": "6688",
"Score": "0",
"body": "What does `GetFriendlyUrl(image.ID)` do ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T12:14:10.137",
"Id": "6691",
"Score": "2",
"body": "Aside from my answer which speaks to the code you posted, I would say the code you posted may speak to a larger issue in that you appear to be assembling the winning images list ahead of knowing it's entirety. I think you should probably try working with the `votes` and a list of `image.ID`s to assemble your winners list long before constructing the `ImageWinnerVotes`, once you have that `winnersList` of `image.ID` then construct the `ImageWinnerVotes` from that so you don't have to create any extras that end up throw away."
}
] |
[
{
"body": "<p>The toList() executes everything in the select-clause.\nMy guess is that the votes-collection that you are quering against, without knowing how it operates, is the performance thief. </p>\n\n<p>Try running the example again without setting the Votes-variable. If it runs smoothly, then you know what to optimize. </p>\n\n<p>What DAL are you using?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T09:37:06.527",
"Id": "4474",
"ParentId": "4473",
"Score": "2"
}
},
{
"body": "<p>You have a <em>lot</em> of iterations in there. the votes.Where's are both a complete iteration of the votes enumerable, and you are doing those once for each Image. As mentioned earlier, everything in that linq query is just a definition of a query, the query itself isn't executed until you call <code>.ToList()</code> which is why it seems that's the time sink.</p>\n\n<p>Save yourself the trouble and cache your votes results:</p>\n\n<pre><code>Tuple<int, int> numberOfVotesPerImageId =\n votes.GroupBy(vote => vote.ItemId)\n .Select(voteGroup => Tuple.Create(voteGroup.Key, voteGroup.Count()))\n .ToArray();\n\nTuple<int, int, int> numberOfVotesPerImageIdAndDayOfYear =\n votes.GroupBy(vote => new { vote.ItemId, vote.Date.DayOfYear })\n .Select(voteGroup => Tuple.Create(voteGroup.Key.Item1, voteGroup.Key.Item2, voteGroup.Count()))\n .ToArray();\n</code></pre>\n\n<p>Then you're select will have far fewer iterations as you'll have these aggregates on the votes to match up against the itemid where these tuples have: <code>.Item1 == image.ID</code> and in the second one <code>Item2 == date.Date.DayOfYear</code>, and in the first one <code>.Item2 == TotalVotes</code> while the second one <code>.Item3 = Votes</code></p>\n\n<p>Also, put the order by in the first clause before calling <code>.ToList()</code> so it doesn't need to reiterate twice.</p>\n\n<p>Also, you're while loop should be a for loop because the iterator, you need to test against length or risk going out of index. And anytime you see an if block nested in an if block with no space leftover, that means you should modify your clauses.. actually I would do this (doing the count and the contains is two iterations when the contains alone is all you need) also your <code>inWinnersList</code> variable is unused.. oh and the .ElementAt is another iteration across the list which makes it O(j) when lists directly expose the array index which is O(1):</p>\n\n<pre><code>for (int j = 0; j < voteList.Count; j++)\n{\n inWinnersList = winnersList.Contains(voteList[j]);\n if (inWinnersList)\n {\n continue;\n }\n\n winnersList.Add(voteList[j]);\n break;\n}\n</code></pre>\n\n<p>There's probably more things I'm missing and details I'm not going into, but I think this is a good start for improving performance and readability. Once you get these pieces put together, other improvements may become obvious as the intent becomes clearer.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T11:55:39.450",
"Id": "4478",
"ParentId": "4473",
"Score": "4"
}
},
{
"body": "<p>First up calls to <code>.ToList()</code> are not inherently slow - it's only when each element in the list is slow to compute that <code>.ToList()</code> appears slow.</p>\n\n<p>So then, what makes the time to compute each element slow?</p>\n\n<p>Well, you're querying <code>votes</code> twice in each query - and computing <code>TotalVotes</code> for each iteration of the <code>foreach</code> loop.</p>\n\n<p>After the query you are then sorting all the candidates by daily votes and then searching through the candidates and picking the first candidate image that hasn't previously won. The search for the winner uses <code>Count</code>, <code>Contains</code>, and <code>ElementAt</code> - all of which can cause the list to be enumerated each time.</p>\n\n<p>All of this is surrounded by a <code>foreach</code> loop to iterate through each date.</p>\n\n<p>Lots of nested iterating - and most of which is unnecessary.</p>\n\n<p>I've got a solution which I've timed to be 135 times faster.</p>\n\n<p>Here it is:</p>\n\n<pre><code>var query =\n from image in _images\n join tvote in votes on image.ID equals tvote.ItemId into tvs\n let TotalVotes = tvs.Count()\n join vote in votes on image.ID equals vote.ItemId\n join date in dates on vote.Date.DayOfYear equals date.Date.DayOfYear \n group vote by new\n {\n image,\n date.Date,\n TotalVotes,\n } into dvs\n let Date = dvs.Key.Date\n let Image = dvs.Key.image\n let DailyVotes = dvs.Count()\n orderby DailyVotes descending\n orderby Date\n group new\n {\n Image = dvs.Key.image,\n dvs.Key.TotalVotes,\n DailyVotes = dvs.Count(),\n } by Date;\n\n\nvar winners = query.Aggregate(new ImageWinnerVotes[] { }, (iwvs, gs) =>\n{\n var previousWinners = iwvs.Select(iwv => iwv.ID).ToArray();\n var winner = gs\n .Where(g => !previousWinners.Contains(g.Image.ID))\n .Select(g => new ImageWinnerVotes\n {\n ID = g.Image.ID,\n Image = g.Image.ImagePath,\n Thumbnail = g.Image.ThumbnailImagePath,\n Title = g.Image.Name,\n Url = GetFriendlyUrl(g.Image.ID),\n Date = g.Image.CreatedDate,\n WinnerDateString = gs.Key.ToString(\"dd/MM\"),\n WinnerDate = gs.Key,\n TotalVotes = g.TotalVotes,\n Name = g.Image.Fields[\"Name\"].ToString(),\n Votes = g.DailyVotes,\n })\n .FirstOrDefault();\n return winner == null ? iwvs.ToArray() : iwvs.Concat(new [] { winner, }).ToArray();\n}).ToArray();\n</code></pre>\n\n<p>This is purely a LINQ solution. It's a good idea not to mix LINQ & non-LINQ.</p>\n\n<p>Now, if you didn't have the requirement to eliminate previous winners then I have a solution that is twice as fast again:</p>\n\n<pre><code>var query =\n from image in _images\n join tvote in votes on image.ID equals tvote.ItemId into tvs\n let TotalVotes = tvs.Count()\n join vote in votes on image.ID equals vote.ItemId\n join date in dates on vote.Date.DayOfYear equals date.Date.DayOfYear \n group vote by new\n {\n image,\n date.Date,\n TotalVotes,\n } into dvs\n group new\n {\n Image = dvs.Key.image,\n dvs.Key.TotalVotes,\n DailyVotes = dvs.Count(),\n } by dvs.Key.Date into gxs\n let winners =\n from x in gxs\n orderby x.DailyVotes descending\n select x\n let winner = winners.First()\n let image = winner.Image\n let winnerDate = gxs.Key\n orderby winnerDate\n select new ImageWinnerVotes\n {\n ID = image.ID,\n Image = image.ImagePath,\n Thumbnail = image.ThumbnailImagePath,\n Title = image.Name,\n Url = GetFriendlyUrl(image.ID),\n Date = image.CreatedDate,\n WinnerDateString = winnerDate.ToString(\"dd/MM\"),\n WinnerDate = winnerDate,\n TotalVotes = winner.TotalVotes,\n Name = image.Fields[\"Name\"].ToString(),\n Votes = winner.DailyVotes,\n };\n\nvar winners = query.ToArray();\n</code></pre>\n\n<p>Let me know if these help and/or if you need more info.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T02:49:58.830",
"Id": "4520",
"ParentId": "4473",
"Score": "7"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T09:25:26.867",
"Id": "4473",
"Score": "9",
"Tags": [
"c#",
"linq"
],
"Title": "Linq in foreach with c#"
}
|
4473
|
<p>I suspect there is a simpler way to find if a <code>select</code> has a certain <code>option</code>, but don't know what. The objective of the following is to check if the desired option exists or not, and if it does, set it as the selected option:</p>
<p><strong>Markup</strong></p>
<pre><code><input type="text" size="2" id="selectVal"/>
<button onclick="setSelect()">Set the select</button>
<select id="mySelect">
<option value="0">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
</select>
</code></pre>
<p><strong>JS</strong></p>
<pre><code>function setSelect() {
var desiredOption = $("#selectVal").val();
if (desiredOption == '') {
$("#selectVal").focus();
return false;
}
var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
if (hasOption.length == 0) {
alert('No such option');
} else {
$('#mySelect').val(desiredOption);
}
$("#selectVal").select();
}
</code></pre>
<p>To be clear, I wonder if a single method could do the job of the following two lines:</p>
<pre><code>var hasOption = $('#mySelect option[value="' + desiredOption + '"]');
if (hasOption.length == 0)
</code></pre>
<p>Any suggestions?</p>
<p><a href="http://jsfiddle.net/majidf/SPvrA/" rel="noreferrer">jsfiddle here</a>. </p>
|
[] |
[
{
"body": "<p>You could try and force the option to be selected. Because jQuery doesn't throw errors when it doesn't have a set of elements, you can use this to your advantage inside an <code>if</code> statement. Couple this with jQuery's chaining and you can do something like:</p>\n\n<pre><code>function setSelect() {\n var desiredOption = $(\"#selectVal\").val();\n if (desiredOption == '') {\n $(\"#selectVal\").focus();\n return false;\n }\n if (!$('#mySelect option[value=\"' +desiredOption+ '\"]').prop(\"selected\", true).length) {\n alert('No such option');\n }\n $(\"#selectVal\").select();\n}\n</code></pre>\n\n<blockquote>\n <p><b>Updated fiddle: <a href=\"http://jsfiddle.net/SPvrA/7/\" rel=\"nofollow\">http://jsfiddle.net/SPvrA/7/</a></b></p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T11:44:57.323",
"Id": "6690",
"Score": "1",
"body": "Thanks. If indeed forcing selection of non-existing options does not throw an error (have not tested that in mainstream browsers), for my present use case that is all I care for."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T11:30:11.890",
"Id": "4477",
"ParentId": "4476",
"Score": "4"
}
},
{
"body": "<p>The original JS code is prone to injection (e.g. <code>]</code>) and unnecessarily verbose, as you said.</p>\n\n<p>Here's a one-liner that also plays nice with dodgy user input (say, injecting <code>]\"</code> into the <code>#selectVal</code> field, which would break Andy E's approach.</p>\n\n<pre><code>function setSelect() {\n $(\"#mySelect\").val($(\"#selectVal\").val()).val($(\"#mySelect\").val());\n $(\"#selectVal\").select();\n}\n</code></pre>\n\n<p>Why this works: the first call to <code>$(\"#mySelect\").val(...)</code> selects the option if it exists, or makes the select input empty if it doesn't. The second call takes that value (either the same value, or an empty string), and sets it again, either keeping the value in place (if it exists), otherwise returning to the default (first) option.</p>\n\n<p>Calling <code>.val()</code> four times in one line is a bit ugly, I know, but you can't argue with results. ;)</p>\n\n<p><a href=\"http://jsfiddle.net/z8d0vLyw/1/\" rel=\"nofollow noreferrer\">Fiddle with an example here</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T09:41:13.070",
"Id": "468039",
"Score": "0",
"body": "Welcome to Code Review! You have presented an alternative solution, but haven't reviewed the code. Please [edit] to show what aspects of the question code prompted you to write this version, and in what ways it's an improvement over the original. It may be worth (re-)reading [answer]."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-03-10T04:02:22.923",
"Id": "238651",
"ParentId": "4476",
"Score": "0"
}
},
{
"body": "<p>How about plain vanilla Javascript:</p>\n\n<pre><code>if(document.getElementById(\"selectVal\").options.namedItem(desiredOption)===null){\n // option in desiredOption variable not found\n}else{\n // option in desiredOption variable found\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T16:08:55.033",
"Id": "473044",
"Score": "0",
"body": "Good answers require at least one insightful observation about the code posted. Code only answers are considered poor answers and may be down voted or deleted. Please see the code review guidelines at https://codereview.stackexchange.com/help/how-to-answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-04-23T08:10:54.830",
"Id": "241052",
"ParentId": "4476",
"Score": "-1"
}
}
] |
{
"AcceptedAnswerId": "4477",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T11:07:16.700",
"Id": "4476",
"Score": "8",
"Tags": [
"javascript",
"jquery"
],
"Title": "Check if select has a certain option"
}
|
4476
|
<p>I've been trying to implement a fast Huffman decoder in order to encode/decode video. However, I'm barely able to decode a 1080p50 video using my decoder. On the other hand, there are lots of codecs in ffmpeg that entropy decode 4-8 times faster.</p>
<p>I have been trying to optimize and profile my code, but I don't think I can get it to run much faster. Does anyone have any suggestion as to how one can optimize Huffman decoding?</p>
<p>My profiler says my application is spending most of the time in the following code:</p>
<pre><code>current = current->children + data_reader.next_bit();
*ptr = current->value;
ptr = ptr + current->step;
</code></pre>
<p>Here is the entire code:</p>
<pre><code>void decode_huff(void* input, uint8_t* dest)
{
struct node
{
node* children; // 0 right, 1 left
uint8_t value;
bool step;
};
CACHE_ALIGN node nodes[512] = {};
node* nodes_end = nodes+1;
auto data = reinterpret_cast<unsigned long*>(input);
size_t table_size = *(data++); // Size is first 32 bits.
size_t num_comp = *(data++); // Data size is second 32 bits.
bit_reader table_reader(data);
unsigned char n_bits = ((table_reader.next_bit() << 2) | (table_reader.next_bit() << 1) | (table_reader.next_bit() << 0)) & 0x7; // First 3 bits are n_bits-1.
// Unpack huffman-tree
std::stack<node*> stack;
stack.push(nodes); // "nodes" is root
while(!stack.empty())
{
node* ptr = stack.top();
stack.pop();
if(table_reader.next_bit())
{
ptr->step = true;
ptr->children = nodes->children;
for(int n = n_bits; n >= 0; --n)
ptr->value |= table_reader.next_bit() << n;
}
else
{
ptr->children = nodes_end++;
nodes_end++;
stack.push(ptr->children+0);
stack.push(ptr->children+1);
}
}
// Decode huffman-data
// THIS IS THE SLOW PART
auto huffman_data = reinterpret_cast<long*>(input) + (table_size+32)/32;
size_t data_size = *(huffman_data++); // Size is first 32 bits.
uint8_t* ptr = dest;
auto current = nodes;
bit_reader data_reader(huffman_data);
size_t end = data_size - data_size % 4;
while(data_reader.index() < end)
{
current = current->children + data_reader.next_bit();
*ptr = current->value;
ptr = ptr + current->step;
current = current->children + data_reader.next_bit();
*ptr = current->value;
ptr = ptr + current->step;
current = current->children + data_reader.next_bit();
*ptr = current->value;
ptr = ptr + current->step;
current = current->children + data_reader.next_bit();
*ptr = current->value;
ptr = ptr + current->step;
}
while(data_reader.index() < data_size)
{
current = current->children + data_reader.next_bit();
*ptr = current->value;
ptr = ptr + current->step;
}
// If dest is not filled with num_comp, duplicate the last value.
std::fill_n(ptr, num_comp - (ptr - dest), ptr == dest ? nodes->value : *(ptr-1));
}
class bit_reader
{
public:
typedef long block_type;
static const size_t bits_per_block = sizeof(block_type)*8;
static const size_t high_bit = 1 << (bits_per_block-1);
bit_reader(void* data)
: data_(reinterpret_cast<block_type*>(data))
, index_(0){}
long next_bit()
{
const size_t block_index = index_ / bits_per_block;
const size_t bit_index = index_ % bits_per_block;
++index_;
return (data_[block_index] >> bit_index) & 1;
}
size_t index() const {return index_;}
private:
size_t index_;
block_type* data_;
};
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T12:05:25.150",
"Id": "6693",
"Score": "0",
"body": "Have a look at ffmpeg and their solution for inspiration..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T12:09:11.720",
"Id": "6694",
"Score": "0",
"body": "no - it's not the code that is slow. Its the chosen algorithm."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-06-23T18:36:32.223",
"Id": "63665",
"Score": "0",
"body": "in addition to zlib's inflate, you can also read tornado huffman decoder: http://freearc.org/Research.aspx, and look at 7-zip sources that includes several huffamn decoders, in particular for inflate, unrar and cabarc/lzx"
}
] |
[
{
"body": "<p>You seem to work on single bit basis. This is very slow. You have to combine several bits together, look up the appropriate pattern in the table and then continue from there (if necessary) in the tree.</p>\n\n<p>You can see an outline to this solution presented here <a href=\"http://www.gzip.org/algorithm.txt\">http://www.gzip.org/algorithm.txt</a>. Of course, googling for \"fast huffman decoding\" reveals several papers on that subject as well. Reading them might be worthy as well.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T12:08:22.017",
"Id": "4480",
"ParentId": "4479",
"Score": "13"
}
},
{
"body": "<p>Without profiling, your <code>next_bit</code> performs a division and a modulus at each call (though the operations will most likely be coalesced into a single <code>divmod</code>).</p>\n\n<p>I would lose this abstraction and unroll the main loop eight times (instead of four): once for each separate bit in a byte in the input. That way, you could completely omit division and just pick off bytes one at a time.</p>\n\n<p>But the first step should certainly be an algorithmic improvement, as proposed by Tobias.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T12:45:13.040",
"Id": "4481",
"ParentId": "4479",
"Score": "7"
}
},
{
"body": "<p>The fastest way I've found is simple and very compact code-wise, especially if you're able to compress using canonical or semi-canonical Huffman codes. Start by reading about how to decode all the codeword bits simultaneously using Dan Hirschberg and Debra Lelewer's \"Efficient Decoding of Prefix Codes\" in Communications of the ACM, April 1990, Volume 33 Number 4 pages 449-459.</p>\n\n<p>Over the years (decades, actually) I've developed further speed improvements based on that basic 'zero-extension' table idea, and I've done a lot of speed optimization in C.</p>\n\n<p>Also, you might be able to set up the decoder to decode two consecutive codewords per table loop iteration. How much that helps depends on processor cache sizes, the translation lookaside buffer, bus speeds, chip architecture, and a lot of other things.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-28T23:30:41.393",
"Id": "38253",
"ParentId": "4479",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4480",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T11:51:39.123",
"Id": "4479",
"Score": "12",
"Tags": [
"c++",
"performance",
"compression",
"video"
],
"Title": "Huffman decoding for video"
}
|
4479
|
<p>I have been playing around with tables and random colors to generate some mosaic.</p>
<p>As I find it rather slow, tell me how it can be improved in terms of speed.</p>
<pre><code>function generate_mosaic(cols, rows) {
var i, ncol, trans, colspan, style, html;
html += "<table>";
for (i = 0; i < rows; i += 1) {
html += "<tr>";
ncol = 0;
while (ncol < cols) {
trans = ncol / cols * 0.5 + i / rows * 0.5;
colspan = Math.floor(Math.random() * 2) + 1;
if (ncol === cols - 1) {
colspan = 1;
}
ncol += colspan;
style = "background-color: rgba(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + trans + ");";
html += "<td colspan=" + colspan + " style='" + style + " line-height: 5px'>&nbsp;<\/td>";
}
html += "<\/tr>";
}
html += "<\/table>";
return html;
}
document.write(generate_mosaic(250, 250));
</code></pre>
<p>Code is also available as a <a href="http://jsfiddle.net/ragnar123/yHxxT/" rel="nofollow">jsfiddle</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T23:33:39.397",
"Id": "6710",
"Score": "0",
"body": "I think you're better off using a html5 canvas. $0.02"
}
] |
[
{
"body": "<p>I suggest using <code>document.body.innerHTML</code> instead of <code>document.write()</code></p>\n\n<pre><code>document.body.innerHTML = generateMosaic();\n</code></pre>\n\n<p>also put <code>Math.random</code> in a variable so it doesn't have to go back to the math object each time:</p>\n\n<pre><code>var random = Math.random;\nrandom() * 255;\n</code></pre>\n\n<p>Also Math.Floor is apparently quite slow try <code>>> 0</code> instead</p>\n\n<pre><code>((random() * 255) >>0);\n</code></pre>\n\n<p><em>(an example using HTML5 canvas):</em> </p>\n\n<p><a href=\"http://jsfiddle.net/yHxxT/1/\" rel=\"nofollow\">http://jsfiddle.net/yHxxT/1/</a></p>\n\n<pre><code>function generate_mosaic2(cols, rows, canvasElement) {\n var colUnitSize = canvasElement.width / cols;\n var rowUnitSize = canvasElement.height/ rows;\n var nrows = rows;\n var rows2 = rows * 2;\n var cols2 = cols * 2;\n var trans = 0;\n var random = Math.random;\n var floor = function (number){ return (number >> 0); };\n var context = canvasElement.getContext(\"2d\");\n var colspan = 0;\n context.fillStyle = \"#000\";\n context.fillRect(0,0, 1000, 1250); //Black background\n do\n {\n var ncols= cols;\n do\n {\n trans = ncols / cols2 + nrows / rows2;\n\n if(ncols === 1)\n {\n colspan = 1;\n }\n else\n {\n colspan = floor(random() * 2);\n }\n context.fillStyle = \"rgba(\" + floor(random() * 255) + \", \" + floor(random() * 255) + \", \" + floor(random() * 255) + \", \" + trans + \")\";\n context.fillRect(ncols * colUnitSize , nrows * rowUnitSize , colspan * colUnitSize , rowUnitSize);\n ncols -= colspan;\n }while(ncols)\n }while(--nrows)\n\n}\n</code></pre>\n\n<p><a href=\"http://jsperf.com/mosaic\" rel=\"nofollow\">http://jsperf.com/mosaic</a> jsperf would suggest that the canvas solution is more than 2 times faster for a 250x250 or 150x150</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T01:42:07.147",
"Id": "4490",
"ParentId": "4488",
"Score": "4"
}
},
{
"body": "<p>Since you are looking for performance issues, you might consider this:</p>\n\n<p><code>html += \"<tr>\";</code></p>\n\n<p>Continually appending to a string is often O(n) where n is the length of the string. Using an array and <code>push()</code>ing the string snips onto it, then using <code>.join()</code> at the end can often be faster.</p>\n\n<p>Different javascript engines will optimize the two methods differently -- test cross browser to see if it's fast enough.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T00:44:48.253",
"Id": "6758",
"Score": "0",
"body": "+1 I actually tested in chrome and I found little difference. But if the target audience is mostly IE users then definitely a good Suggestion. I read somewhere that it is better to do `mylist[mylist.length] = \"new string\";` as it is quicker than `.push()`. I haven't tested that theory though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T13:14:27.593",
"Id": "6771",
"Score": "0",
"body": "http://www.quirksmode.org/dom/innerhtml.html"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T12:20:33.903",
"Id": "4511",
"ParentId": "4488",
"Score": "4"
}
},
{
"body": "<p>I'm with Sean: string concatenation is slow. Replace your function by:</p>\n\n<pre><code>function generate_mosaic(cols, rows) { \n var i, ncol, trans, colspan, style;\n var html = [], j=0; \n html[j++] = \"<div><table>\"; \n\n for (i = 0; i < rows; i += 1) { \n html[j++] = \"<tr>\"; \n ncol = 0; \n while (ncol < cols) { \n trans = ncol / cols * 0.5 + i / rows * 0.5; \n colspan = Math.floor(Math.random() * 2) + 1; \n\n if (ncol === cols - 1) { \n colspan = 1; \n } \n\n ncol += colspan; \n\n html[j++] = '<td colspan=\"';\n html[j++] = colspan;\n html[j++] = '\" style=\"background-color: rgba(';\n html[j++] = Math.floor(Math.random() * 255);\n html[j++] = ',';\n html[j++] = Math.floor(Math.random() * 255);\n html[j++] = ',';\n html[j++] = Math.floor(Math.random() * 255);\n html[j++] = ',';\n html[j++] = trans;\n html[j++] = '); line-height: 5px\">&nbsp;<\\/td>';\n } \n html[j++] = '<\\/tr>'; \n } \n html[j++] = '<\\/table></div>'; \n return html.join(''); \n}\n</code></pre>\n\n<p>you should find it much faster. For more information see my answer to a similar query posted here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/4864294/dynamic-creation-of-large-html-table-in-javascript-performance/4865247#4865247\">https://stackoverflow.com/questions/4864294/dynamic-creation-of-large-html-table-in-javascript-performance/4865247#4865247</a></p>\n\n<p>Testing with IE9 shows this method to take only about half the time to execute than the \"canvas\" solution.</p>\n\n<p>Testing with CHROME shows the 125x125 case to be slower, but the 250x250 case faster.</p>\n\n<p>Testing with FIREFOX shows both methods to be about the same.</p>\n\n<p>See: <a href=\"http://jsperf.com/mosaic/2\" rel=\"nofollow noreferrer\">http://jsperf.com/mosaic/2</a></p>\n\n<p>Regards\n Neil </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T20:32:36.420",
"Id": "4535",
"ParentId": "4488",
"Score": "2"
}
},
{
"body": "<p>Did you try <code>document.body.appendElement</code> / <code>document.createElement(\"tr\")</code> etc instead of modifying <code>innerHTML</code>.</p>\n\n<p>Note though that you should append everything to a non-visible (actually not even add it to the DOM) element while in the loop and after that append that base-element to the actual dome.</p>\n\n<p>something like:</p>\n\n<pre><code>var myCanvas = document.createElement(\"div\");\nfor(blabla)\n{\n var myTd = document.createElement(\"td\");\n myTd.style.backgroundColor = ...;\n ...\n myCanvas.appendChild(myTd);\n}\ndocument.body.appendChild(myCanvas);\n</code></pre>\n\n<p>btw, is it the generation that is slow or the whole page after the generation is done? This is a terrible way to create such a dense and large mosaic, use html5-canvas or a server-side generated image instead.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T15:32:04.543",
"Id": "4560",
"ParentId": "4488",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4490",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-29T21:45:33.313",
"Id": "4488",
"Score": "3",
"Tags": [
"javascript"
],
"Title": "Generating a mosaic"
}
|
4488
|
<p>In our hg workflow we use <code>default</code> as testing branch and <code>stable</code> as the one that contains stable code. All changes are made in feature-branches that are started from latest <code>stable</code>. This hook checks if there is a "direct" commit to <code>default</code> or <code>stable</code> (they are denied, only merges may change contents of <code>default</code> and <code>stable</code>) or that new feature branch has been started from <code>default</code> (which is denied by conventions too).</p>
<p>Any proposal to make it more "pythonic" (or just better)?</p>
<pre><code>from mercurial import context
def check(ui, repo, hooktype, node=None, source=None, **kwargs):
for rev in xrange(repo[node].rev(), len(repo)):
ctx = context.changectx(repo, rev)
parents = ctx.parents()
if len(parents) == 1:
if ctx.branch() in ['default', 'stable']:
ui.warn('!!! You cannot commit directly to %s at %s !!!' % (ctx.branch(), ctx.hex()))
return True
if parents[0].branch() == 'default':
ui.warn('!!! You cannot start your private branch from default at %s !!!' % (ctx.hex()))
return True
return False
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T12:06:23.923",
"Id": "6715",
"Score": "0",
"body": "The correct word is pythonic not pythonish."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T12:08:13.743",
"Id": "6716",
"Score": "0",
"body": "@Winston Ewert: fixed ;-)"
}
] |
[
{
"body": "<pre><code> for rev in xrange(repo[node].rev(), len(repo)):\n ctx = context.changectx(repo, rev)\n</code></pre>\n\n<p>In Python, I generally try to avoid iterating using xrange. I prefer to iterate over what I'm interested in.</p>\n\n<pre><code>def revisions(repo, start, end):\n for revision_number in xrange(start, end):\n yield context.changectx(repo, revision_number)\n\nfor rev in revisions(repo, repo[node].rev(), len(repo)):\n ...\n</code></pre>\n\n<p>Although I'm not sure its worthwhile in this case. </p>\n\n<p>The only other issue is your use of abbreviations like repo and rev. They aren't that bad because its pretty clear from the context what they stand for. But I'd write them fully out.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T01:15:21.757",
"Id": "6723",
"Score": "1",
"body": "I think you mean `for revision_number in xrange(start, end):` in that second snippet."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T12:16:05.483",
"Id": "4498",
"ParentId": "4494",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4498",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T06:57:18.353",
"Id": "4494",
"Score": "5",
"Tags": [
"python"
],
"Title": "My python hook for mercurial"
}
|
4494
|
<p>There can be some errors in the script, if u find them thanks, but the main thing is to get useful suggestions about how can I do this better and secure.</p>
<pre><code>ini_set('session.use_only_cookies', true);
session_start();
//Create a random salt value
$salt = 'Hjkhkjh9089&j98098';
$tokenstr = (str) date('W') . $salt;
//Create a md5 hash to be used for token.
$token = md5($tokenstr);
///checking if already logged in
if ($_REQUEST['token'] == $token AND $_SESSION['user_ip']=$_SERVER['REMOTE_ADDR'] ) {
...grant user with some data
}
//user login block
if (($_POST['login']!="") OR ($_COOKIE["username"]!='' AND $_COOKIE["password"]!='') AND $_SESSION['user']=='')
{
if ($_SESSION['temp_ban']==1)
{
$p='login_error';
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
$result2= mysql_query("SELECT * FROM banned_ip_list WHERE banned_ip='$ip'") or die("unable to connect to msql server: " . msql_error()) ;
$row2 = mysql_fetch_array($result2);
if (!$row2=="")
{
$_SESSION['temp_ban']=1;
$p='login_error';
}
else
{
if ($_COOKIE["username"]!='' AND $_COOKIE["password"]!='')
{
$login_username=security2($_COOKIE["username"]);
$login_password=security2($_COOKIE["password"]);
$remember_me='on';
}
else
{
$login_username=security2($_POST['username']);
$login_password=security2($_POST['password']);
$remember_me=security2($_POST['remember_me']);
}
$result = mysql_query("SELECT * FROM users WHERE username='$login_username' AND password=SHA1('$login_password')") or die("unable to connect to msql server: " . msql_error()) ;
$row = mysql_fetch_array($result);
if ($row!="")
{
if($remember_me!='')
{
$expire=time()+60*60*24*7;
setcookie("username", $login_username , $expire);
setcookie("password", $login_password , $expire);
}
$_SESSION['user_ip']=$_SERVER['REMOTE_ADDR'];
$_SESSION['user_id']=$row['id'];
$_SESSION['user']=$row['username'];
$_SESSION['ch_insert_temp_key']=1;
$_SESSION['token'] = $token;
output_add_rewrite_var('token', $token);
$_POST['login']='';
unset($_SESSION['try_error']);
}
else
{
if (!$_SESSION['try_error'] AND !$_SESSION['temp_ban'])
{
$_SESSION['try_error']=11;
}
if ($_SESSION['try_error']-1==1)
{
$_SESSION['temp_ban']=1;
$ip=$_SERVER['REMOTE_ADDR'];
$banned_time=date('Y-m-d H:i:s');
$result3 = mysql_query("INSERT INTO banned_ip_list (banned_ip,banned_time) VALUES ('$ip','$banned_time')") or die("unable to connect to msql server: " . msql_error()) ;
/////////////log
$event_type_id=10;
$additional_info='';
$event_object='';
include $log_entry;
//////////////////
}
else {$_SESSION['try_error']--;}
$p='login_error';
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T14:16:03.407",
"Id": "6717",
"Score": "2",
"body": "This is not something you should write yourself. Find an appropriate module OS project where this is already implemented and use it. It is way to easy to add security leaks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T14:47:46.937",
"Id": "6718",
"Score": "0",
"body": "can u suggest me something via link ? :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-28T15:13:56.633",
"Id": "7524",
"Score": "0",
"body": "I really like the _random_ salt ;-) For the password hashing, use [PHPass](http://www.openwall.com/phpass/), for how to handle the login or remember me you can check [this answer](http://stackoverflow.com/questions/5095503/login-system-concept-logic/5096201#5096201) (mine) on StackOverflow. Last note: **Never** store passwords other than in the database, and hashed."
}
] |
[
{
"body": "<p>Let's start with the SQL injection vulnerability in your code in </p>\n\n<pre><code>mysql_query(\"SELECT * FROM users WHERE username='$login_username' AND password=SHA1('$login_password')\") or die(\"unable to connect to msql server: \" . msql_error()) ;\n</code></pre>\n\n<p>In this piece of code you put the user defined <code>$login_username</code> straight to a SQL query. I see that there's a function called <code>security2</code> that does something to username but I cannot be sure that it executes <code>mysql_real_escape_string</code> that would prevent SQL injection. If it does not, then a malevolent user might be tempted to enter a user name that may corrupt your database. </p>\n\n<p>Poor <a href=\"http://xkcd.com/327/\" rel=\"nofollow\">Bobby Tables</a> might cause problems here . </p>\n\n<p>Rest of the thoughts are (at least at first) in random order</p>\n\n<p>Uou should probably migrate from mysql_ to mysqli_ functions. mysqli is the MySQL Improved Extension for PHP that is supposed to work better and do much more. </p>\n\n<p>In PHP, it's almost always better to use <code>===</code> than <code>==</code> to test equality. </p>\n\n<p>You could try to be consistent with the use of <code>''</code>and <code>\"\"</code>. </p>\n\n<p>The code would benefit if you would define more functions to partition the logic. Maybe even define some classes. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T10:44:02.857",
"Id": "6714",
"Score": "0",
"body": "can u explain both things you've said ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T15:50:18.937",
"Id": "6746",
"Score": "0",
"body": "Actually, he said four things. 1- He gave you two operator use advices 2- He told you to write smaller, more to-the-point functions (divide and conquer principle) 3- he showed you your code has a weakness since it hasn't got classes 4- he told you to use MySQLi and explained why. And on top of that he showed you a vulnerability, which means a exploitable bug. It's a great post, kudos Aleksi!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T10:40:29.523",
"Id": "4496",
"ParentId": "4495",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T10:29:57.440",
"Id": "4495",
"Score": "1",
"Tags": [
"php"
],
"Title": "please check my user session login system and tell me what can be done to make it better"
}
|
4495
|
<p>I currently have this encoding function which simply subtracts one from each character code:</p>
<pre><code>String.fromCharCode.apply(null, text.split("").map(function(v) {
return v.charCodeAt() - 1;
}));
</code></pre>
<p>E.g. <code>test</code> becomes <code>sdrs</code>.</p>
<p>I know that this function is silly because it isn't a strong encoding algorithm, but that's not my point. The problem is that it is slow and causes a stack overflow for large strings (~130.000 in length).</p>
<p>I tried a regexp but that's even slower:</p>
<pre><code>text.replace(/./g, function(v) {
return String.fromCharCode(v.charCodeAt() - 1);
});
</code></pre>
<p>I tested both on <a href="http://jsperf.com/replacing-regexp-vs-map" rel="nofollow noreferrer">jsPerf</a>.</p>
<p>Currently, I'm executing a function for each character in both functions. How can I make a function that does the same thing as what these functions are doing, but executes faster without stack overflows?</p>
|
[] |
[
{
"body": "<p>Try looping through it with a simple for loop:</p>\n\n<pre><code>var b = '';\nfor (var i = 0; i < a.length; i++)\n{\n b += String.fromCharCode(a.charCodeAt(i) - 1)\n}\nreturn b;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T15:17:25.240",
"Id": "6719",
"Score": "0",
"body": "Wow, that seems amazingly fast. More than 20 times as fast in fact. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-30T15:15:01.750",
"Id": "4500",
"ParentId": "4499",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4500",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-08-30T15:03:33.253",
"Id": "4499",
"Score": "1",
"Tags": [
"javascript",
"performance",
"strings",
"comparative-review",
"caesar-cipher"
],
"Title": "Encode strings by subtracting one from each character code"
}
|
4499
|
<p>I came up with the following class that I can use as an XNA service to manage rendering to things other than the screen as I didn't want to be passing <code>Game</code>s/<code>GraphicsDevice</code>s around all over the place for testing reasons. I can't see anything wrong with it, but I'm curious what other people think about the design/etc. of it and the general theory of it. Is this abusing <code>IDisposable</code>, or is this an ok way to do things?</p>
<p><strong>Typical Usage:</strong></p>
<pre><code>using(Services.GetService<IRenderTargetController>().SetRenderTarget(renderTarget, Color.Black)) {
// [snip] Render stuff as normal here.
}
</code></pre>
<p><strong>Implementation:</strong></p>
<pre><code>using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
sealed class RenderTargetController : IRenderTargetController
{
private readonly GraphicsDevice _graphicsDevice;
private readonly Stack<RenderTarget2D> _targets;
public RenderTargetController(GraphicsDevice graphicsDevice)
{
_graphicsDevice = graphicsDevice;
_targets = new Stack<RenderTarget2D>();
}
public IDisposable SetRenderTarget(RenderTarget2D target)
{
return SetRenderTarget(target, Color.Transparent);
}
public IDisposable SetRenderTarget(RenderTarget2D target, Color resetColor)
{
_targets.Push(target);
_graphicsDevice.SetRenderTarget(target);
_graphicsDevice.Clear(resetColor);
return new TargetManager(this);
}
private class TargetManager : IDisposable
{
private readonly RenderTargetController _controller;
public TargetManager(RenderTargetController controller)
{
_controller = controller;
}
public void Dispose()
{
_controller._targets.Pop();
RenderTarget2D target = null;
if (_controller._targets.Count > 0)
{
target = _controller._targets.Peek();
}
// Setting render target to null returns control to the screen.
_controller._graphicsDevice.SetRenderTarget(target);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>An approach itself is fine IMO, but the API is misleading. Why would <code>SetXXX</code> method ever return something, let alone return an <code>IDisposable</code>? Maybe come up with a better name.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T11:36:03.447",
"Id": "6784",
"Score": "0",
"body": "The approach reminds me of the way an observable (Rx observer/observable pattern) returns an IDisposable when the observables' Subscribe method is called ...might help in determining a better name for the method."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T14:58:38.447",
"Id": "6787",
"Score": "0",
"body": "@IAbstract: In my head, I actually likened it more to a transaction based system. When you call `SetRenderTarget` you are opening a transaction which is returned and kept open till it is disposed. Naming is hard though, and I can't quite think of what it should be named instead."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T11:12:35.077",
"Id": "4545",
"ParentId": "4507",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4545",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T03:27:41.620",
"Id": "4507",
"Score": "2",
"Tags": [
"c#"
],
"Title": "Managing rendering targets in XNA using IDisposable"
}
|
4507
|
<p>I hope this is not a really bad question for a first time here beginner.</p>
<p>This piece of code selects from the left table and will list the content in the right hand table. This is a working code but I would like to see how a professional would protect and make it faster. </p>
<p>Any suggestion (with some code) would be appreciated. Thanks a lot</p>
<p>PS: There is also a little glitch with it: after deleting it lose the selected item on the right list.</p>
<pre><code><?php include("db_con1.php");?>
<html>
<head>
</head>
<body>
<form method="post" action="test.php">
<div id="left">
<?php
$queryl = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');
$queryl->execute();
?>
<ul>
<?php foreach ($queryl as $i => $rowl) { ?>
<li>
<?php if ($i) {?>
<input name="checkbox1_del[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowl['id']; ?>"/>
<label for="test_<?php echo $i ?>">
<a href="test1.php?gid=<?php echo $rowl['id']; ?>"><?php echo $rowl['name']; ?></a>
</label>
</li>
<?php } ?>
</ul>
</div>
<div id="right">
<?php
if(isset($_GET['gid'])) {
$gid=$_GET['gid'];
$queryr = $pdo->prepare('SELECT test3.name FROM test1, test2, test3 WHERE test1.id=test2.groupid AND test3.id=test2.peopleid AND test1.id='.$gid.' ORDER BY test3.name ASC');
$queryr->execute();
}
?>
<ul>
<?php foreach ($queryr as $i => $rowr) { ?>
<li>
<?php if ($i) {?>
<input name="checkbox2_del[]" id="test_<?php echo $i ?>" type="checkbox" value="<? echo $rowr['id']; ?>"/>
<label for="test_<?php echo $i ?>"><?php echo $rowr['name']; ?></label>
</li>
<?php } ?>
</ul>
</div>
<input type="submit" name="del" value="Delete the selected items">
</form>
<?php
if (isset($_POST['del'])) {
echo "Don't delete:)";
for ($c = 0; $c < count($_POST['checkbox1_del']); $c++){
$checkbox1_del = $_POST['checkbox1_del'][$c];
$sql = 'UPDATE test1 SET status=0, log="'.date("Y-m-d").'"WHERE id='.$checkbox1_del;
echo $sql;
$query = $pdo->prepare($sql);
$query->execute();
}
for ($c = 0; $c < count($_POST['checkbox2_del']); $c++){
$checkbox2_del = $_POST['checkbox2_del'][$c];
$sql = 'UPDATE test2 SET status=0, log="'.date("Y-m-d").'"WHERE id='.$checkbox2_del;
echo $sql;
$query = $pdo->prepare($sql);
$query->execute();
}
if($query){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=test1.php\">";
}
}
?>
</body>
</html>
</code></pre>
<p><strong>Revise 1:</strong> This is a extracted part of my program, however here is the definition of this function:</p>
<p>Having 3-5000 contact, to send emails them easier to group them to Distribution list.
So this part of the program provide 3 tables:</p>
<p>Distribution list | Members of selected group | People</p>
<p>you can make group names and can add people into it.</p>
<p>So basic functions that I wrote for this part:</p>
<ul>
<li>new distribution list can be added</li>
<li>By clicking on any Distribution list you'll get the Members table ($_GET)</li>
<li>Also by clicking on Distribution list should be BOLD (class="bold") as highlighted</li>
<li>Selecting any members in the member list can be deleted (checkbox2_del())</li>
<li>From people list anyone can be added to the list</li>
</ul>
<p>This is what I tried to write and this test shows that basic steps of it. I just didn't want to overload anybody to read through the whole script. If anyone would like to see I happy to replace with it. Thanks</p>
|
[] |
[
{
"body": "<p>You are using prepared SQL statements, but not using parameterised queries in them, so you're still wide open to SQL injections. This is how you should be doing it:</p>\n\n<pre><code>$gid = $_GET['gid']; \n$queryr = $pdo->prepare('SELECT test3.name FROM test1, test2, test3 WHERE test1.id = test2.groupid AND test3.id = test2.peopleid AND test1.id = :gid ORDER BY test3.name ASC');\n$queryr->bindParam(':gid', $gid, PDO::PARAM_STR);\n$queryr->execute();\n</code></pre>\n\n<p>Assuming that your <code>$gid</code> is supposed to be numeric, you should probably extract it this way too:</p>\n\n<pre><code>if(is_numeric($_GET['gid'])) {\n $gid = (int)$_GET['gid'];\n // ...\n $queryr->bindParam(':gid', $gid, PDO::PARAM_INT);\n</code></pre>\n\n<p>The same applies to your later queries that are being generated from <code>$_POST</code>.</p>\n\n<hr>\n\n<p>This segment also seems to be missing a set of braces. If it works, then it's likely only a coincidence. <code>if</code> without braces is hard enough to read in just PHP, but if you drop out of PHP, I honestly have no idea how PHP will react.</p>\n\n<pre><code> <?php foreach ($queryl as $i => $rowl) { ?>\n\n <li>\n <?php if ($i)?> <!-- **** BRACES MISSING HERE? **** -->\n <input name=\"checkbox_del[]\" id=\"test_<?php echo $i ?>\" type=\"checkbox\" value=\"<? echo $rowl['id']; ?>\"/>\n <label for=\"test_<?php echo $i ?>\">\n <a href=\"test1.php?gid=<?php echo $rowl['id']; ?>\"><?php echo $rowl['name']; ?></a>\n </label>\n </li>\n <?php } ?>\n</code></pre>\n\n<hr>\n\n<p>There is a larger problem with this script in general. Mixing logic with the output can cause design problems. Ideally you would load all your data at the top, then generate your page all at once. I don't know how big a system this is, but in general it's much easier to manage the system as a whole if you structure your pages this way. What happens if you want to conditionally show something at the top of the page, but the condition isn't generated till later when you are processing data?</p>\n\n<p>Eg, you might end up with something like the following:</p>\n\n<pre><code><?php \ninclude(\"db_con1.php\");\n$queryl = $pdo->prepare('SELECT id, name FROM test1 ORDER BY name ASC');\n$queryl->execute();\n\n$lists = array();\nwhile (($rowl = $queryl->fetch(PDO::FETCH_ASSOC)) !== false) {\n $lists[] = $rowl;\n}\n\n// And so on for all the data you need to load\n?>\n<html>\n<head>\n<!-- And so on... -->\n</code></pre>\n\n<p>It seems your right bar and left bar aren't associated directly, but if they were then you could put more in that <code>while</code> loop to load stuff into <code>$rowl</code> before adding it to <code>$lists</code>. You can then just iterate over this array in your code. All your SQL is at the top of the file and easy to change, all your presentation is at the bottom of the file and will read a lot nicer too, with just some loops and some <code>echo</code>'s.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T10:00:03.357",
"Id": "6732",
"Score": "0",
"body": "+1. Thanks very much your effort and help whit this code. I am going to explain about this program a bit more in the question so people might give more ideas."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T10:28:34.950",
"Id": "6733",
"Score": "0",
"body": "could you show me how would you design the whole page? So I could learn from it and I would redesign my other codes. Thanks"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T10:55:41.563",
"Id": "6734",
"Score": "1",
"body": "@Andras: I use `->fetch` explicitly in my code because I'm not sure what the iterator returns by default. If it returns a standard associative array and not some class that acts like one, then feel free to use that too. I just wasn't sure, so didn't use it."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T09:30:02.423",
"Id": "4510",
"ParentId": "4509",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "4510",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T08:11:06.653",
"Id": "4509",
"Score": "2",
"Tags": [
"php",
"mysql"
],
"Title": "SQL Injection and php performance checking"
}
|
4509
|
<p>I'm attempting to implement a simple long-polling/comet/reverse AJAX solution, and came across the concept of delegates, specifically with the <code>BeginInvoke</code> and <code>EndInvoke</code> methods. I've built a Web Service that uses these concepts, but, having never used these, they make me a little nervous, and I have my doubts as to whether they are actually what I want.</p>
<p>The goal, of course, is to offload the actual processing from IIS processes onto other framework processes, for a reduction in server load when waiting on a long-poll request for data. I can't have gotten this right, but I want to know <em>why</em> and at least get some direction in <em>how it might be better accomplished</em> (not necessarily a solution, but maybe an article or some documentation).</p>
<p>The Web Service code:</p>
<pre><code>Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Threading
Imports System.Runtime.InteropServices
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function HelloWorld() As String
Dim threadId As Integer
Dim thing As New Things
Dim caller As New AsyncDoStuff(AddressOf thing.doStuff)
Dim result As IAsyncResult = caller.BeginInvoke(3000, threadId, Nothing, Nothing)
result.AsyncWaitHandle.WaitOne()
Dim returnValue As String = caller.EndInvoke(threadId, result)
result.AsyncWaitHandle.Close()
Return returnValue
End Function
End Class
Public Class Things
Public Function doStuff(ByVal callDuration As Integer, <Out()> ByRef threadId As Integer) As String
' Imagine this method was accessing a database, looking for new information, and returning when it found some
Thread.Sleep(callDuration)
threadId = Thread.CurrentThread.ManagedThreadId()
Return String.Format("My call time was {0}.", callDuration.ToString())
End Function
End Class
Public Delegate Function AsyncDoStuff(ByVal callDuration As Integer, <Out()> ByRef threadID As Integer) As String
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T02:48:39.670",
"Id": "58515",
"Score": "1",
"body": "You've never used an event handler? `EventHandler` is just a delegate with a `(Object, EventArgs)` signature and no return value. You know delegates more than you think you do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T16:36:02.113",
"Id": "58611",
"Score": "0",
"body": "Wow. Blast from the past. I never actually got this implemented, opting instead for simple polling with increased intervals when no data was returned. I guess I never trusted myself with off-processes."
}
] |
[
{
"body": "<p><a href=\"https://stackoverflow.com/a/7050854/1188513\">This Stack Overflow answer</a> to the question \"Is there a VB.NET equivalent of C# out parameters\" is pretty clear:</p>\n\n<blockquote>\n <p><em>No, there is no equivalent construct that allows a non-initialised variable to be passed to a method without a warning [...]</em></p>\n</blockquote>\n\n<p>However specifying the <code><Out()></code> attribute, despite being ignored by VB (<code>ByRef</code> is all you need, really), does allow a C# client to use it as an <code>out</code> parameter - so good call then!</p>\n\n<hr>\n\n<p>Declaring the delegate at the bottom of the module, <em>after</em> it's being used, makes it uselessly confusing and prompts for unnecessary scrolling; I would have put it at the top... actually, I would have made the delegate a public member of the <code>WebService</code> class:</p>\n\n<pre><code>Public Class WebService\n Inherits System.Web.Services.WebService\n\n Public Delegate Function AsyncDoStuff(ByVal callDuration As Integer, <Out()> ByRef threadID As Integer) As String\n\n '...\n</code></pre>\n\n<hr>\n\n<p>I very, very seldom declare my own delegate types, if at all. I don't like <s><code>ref</code></s> <code>ByRef</code> and <s><code>out</code></s> <code><Out()></code> parameters either - I think they should be avoided.</p>\n\n<p>In this case I would have gone with a <code>Func<int,AsyncStuffResult></code> (please excuse the C# notation), where the <code>int</code> parameter is the <code>callDuration</code>, and the <code>AsyncStuffResult</code> is a class that encapsulates everything you want to return from the function call - whatever that is.</p>\n\n<p>This way if/when you need to return more things, your signature doesn't need to change, you only add new members to your result class - note that the <code>EventArgs</code> class fulfills the same goal.</p>\n\n<pre><code>Public Class AsyncStuffResult\n '- expose ThreadId as a get-only property\n '- expose your String result as a get-only property, too\n '- expose a constructor to assign the members\nEnd Class\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-26T18:46:56.260",
"Id": "116984",
"Score": "0",
"body": "Death to delegates!!!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-26T18:10:38.060",
"Id": "63972",
"ParentId": "4516",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T15:54:14.770",
"Id": "4516",
"Score": "8",
"Tags": [
".net",
"ajax",
"vb.net",
"asynchronous"
],
"Title": "Using Delegates and BeginInvoke with .NET 2.0 WebServices"
}
|
4516
|
<p>I've been working on implementing a fast Huffman decoder for video decoding. With some <a href="https://codereview.stackexchange.com/questions/4479/faster-huffman-decoding">help from you</a>, I have been able to produce a decent implementation. However I am still not satisfied with the results. I have done some research both on Stack Overflow and some research papers, however I haven't found anything to further improve my current implementation.</p>
<p>I'm using a lookup-table for decoding. I've removed most of the branches and byte moves (MOVZX). And also aligned my data for optimal cache usage. </p>
<p>I think I've got the decoding itself as fast as it can get, however building the lookup-table (build_tables2) takes as much time as the decoding itself.</p>
<p>My profiler gives me:</p>
<ul>
<li>decoding: 52%</li>
<li>build lookup-table (build_tables2): 45%</li>
</ul>
<p>In average my decoder is building ~100 tables per frame (of max 256, one for each node in the biggest tree), which is much but I don't see how I could reduce it. 16 bit tables seems out of the question.</p>
<p>Does anyone have any ideas as to how I can speed up building the lookup-table? Maybe I could somehow encode some kind of additional data in the frame/"input" which would help for building the tables?</p>
<pre><code>typedef uint8_t block_type;
static const int bits_per_block = 8;
static const int values_per_block = 256;
struct node_t
{
node_t* children; // 0 right, 1 left
int32_t value; // if leaf then its the value of the current node, if not leaf then its the index of the next lookup-table
int32_t is_leaf;
};
// NOTE:
// entry is 16 bytes and will be aligned during allocation, thus "values" will always be on 16 byte alignment
struct entry
{
uint8_t values[bits_per_block];
std::array<entry, values_per_block>* next_table;
int32_t num_values;
};
typedef std::array<entry, values_per_block> table_t;
typedef std::array<table_t, values_per_block-1> tables_t;
void build_tables2(node_t* nodes, tables_t& tables, int& table_count);
void unpack_tree(void* data, node_t* nodes);
void decode_huff(void* input, uint8_t* dest)
{
// Initial setup
std::shared_ptr<node_t> nodes(reinterpret_cast<node_t*>(scalable_aligned_malloc(sizeof(node_t)*(513), 64)), scalable_aligned_free); // cacheline alignment
memset_sse(nodes.get(), 0, sizeof(node_t)*512);
auto data = reinterpret_cast<uint32_t*>(input);
size_t table_size = *(data++); // Size is first 32 bits.
size_t result_size = *(data++); // Data size is second 32 bits.
// Unpack huffman-tree.
unpack_tree(data, nodes.get());
if(nodes->children != nullptr)
{
// BUILD LOOKUP-TABLE
std::shared_ptr<tables_t> tables(reinterpret_cast<tables_t*>(scalable_aligned_malloc(sizeof(tables_t), 64)), scalable_aligned_free); // cacheline alignment
int table_count = 0;
// Build lookup-table from huffman-tree.
build_tables2(nodes.get(), *tables, table_count);
// INIT DECODING
auto huffman_data = data + table_size/32;
auto ptr = dest;
auto end = ptr + result_size;
entry entry2;
entry2.next_table = tables->data();
// NOTE:
// Use 2x MOVQ instead of memcpy, could use MOVDQA and MOVDQU but we only care about 64 bits, thus we use MOVQ which might be faster?
// _mm_storel_epi64(reinterpret_cast<__m128i*>(ptr), _mm_loadl_epi64(reinterpret_cast<__m128i*>(entry))); load is aligned, store is unaligned
// <=>
// memcpy(ptr, entry, entry->num_values);
//
// The decoding loop will always be overwriting some values ahead (which haven't been decoded), this means
// that the target memory buffer will need to have extra padding in the end to avoid access violations.
// DECODING
auto entry = &entry2;
while(ptr < end)
{
auto elem = *(huffman_data++); // Use single mov and shift and masking, instead of 4x movzx/byte-moves
entry = entry->next_table->data() + (elem & 0xff); // entry = &entry->next_table->at(elem & 0xff);
_mm_storel_epi64(reinterpret_cast<__m128i*>(ptr), _mm_loadl_epi64(reinterpret_cast<__m128i*>(entry)));
ptr += entry->num_values;
entry = entry->next_table->data() + ((elem >> 8) & 0xff);
_mm_storel_epi64(reinterpret_cast<__m128i*>(ptr), _mm_loadl_epi64(reinterpret_cast<__m128i*>(entry)));
ptr += entry->num_values;
entry = entry->next_table->data() + ((elem >> 16) & 0xff);
_mm_storel_epi64(reinterpret_cast<__m128i*>(ptr), _mm_loadl_epi64(reinterpret_cast<__m128i*>(entry)));
ptr += entry->num_values;
entry = entry->next_table->data() + (elem >> 24);
_mm_storel_epi64(reinterpret_cast<__m128i*>(ptr), _mm_loadl_epi64(reinterpret_cast<__m128i*>(entry)));
ptr += entry->num_values;
}
}
else
memset_sse(dest, static_cast<char>(nodes->value), result_size);
}
void build_tables2(node_t* nodes, tables_t& tables, int& table_count)
{
// Using a stack instead of function recursion helps the profiler.
std::stack<node_t*> stack;
stack.push(nodes);
while(!stack.empty())
{
auto root = stack.top();
stack.pop();
auto& table = tables[root->value];
for(int n = 0; n < values_per_block; ++n)
{
auto current = root;
auto& entry = table[n];
entry.num_values = 0;
// Looped and branched version
//for(int i = 0; i < 8; ++i)
//{
// current = current->children + ((n >> i) & 1);
// if(current->is_leaf)
// entry.values[entry.num_values++] = current->value;
//}
// NOTE:
//*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
// <=>
// entry.values[entry.num_values] = current->value;
//
// Avoids byte moves, the last write can overwrite the next element in the entry structure, "next_table",
// this is not a problem since we set "next_table" below and don't care about its current value
current = current->children + (n & 1); // +0 is left and +1 is right child
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value; // dummy write if not leaf
entry.num_values += current->is_leaf; // only increment if it was a leaf
current = current->children + ((n >> 1) & 1);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
current = current->children + ((n >> 2) & 1);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
current = current->children + ((n >> 3) & 1);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
current = current->children + ((n >> 4) & 1);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
current = current->children + ((n >> 5) & 1);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
current = current->children + ((n >> 6) & 1);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
current = current->children + (n >> 7);
*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;
entry.num_values += current->is_leaf;
if(!current->is_leaf)
{
// a non-leaf, then current->value is the next lookup-table
if(current->value == 0)
{
current->value = ++table_count;
stack.push(current);
}
table[n].next_table = &tables[current->value];
}
else
table[n].next_table = &tables[0]; // All bits were used, back to root
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T08:08:04.677",
"Id": "6781",
"Score": "0",
"body": "do you really need to rebuild the table every time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T10:06:16.853",
"Id": "6782",
"Score": "0",
"body": "yes, since every frame is coded with its own huffman tree."
}
] |
[
{
"body": "<p>Do you have some control over the input encoder?\nIf so it should be providing you with a Huffman tree delta, rather than a whole new tree for every frame. In the same way that the HT algorithm applies similarity rules to encoded data, from frame to frame the HT will have also have a very high degree of similarity.</p>\n\n<p>Also some efficiency and platform concerns:\nPlease rewrite expressions of the form</p>\n\n<pre><code>((n >> #) & 1)\n</code></pre>\n\n<p>where # is a digit as,</p>\n\n<pre><code>(((n & (1 << #)) != 0) ? 1 : 0)\n</code></pre>\n\n<p>Compile time versus run time calculation is always going to be faster.</p>\n\n<pre><code>*reinterpret_cast<int32_t*>(entry.values + entry.num_values) = current->value;\n</code></pre>\n\n<p>Is dependent on the little endian architecture. Prefer correct over fast.</p>\n\n<pre><code>auto* next_value = entry.values; // get the starting value element address\n...\n*next_value = static_cast<uint_8>(current->value); // set its value\nnext_value += current->is_leaf;\n...\n// at the end of the loop unrolling do this calculate num_value \n// from the offset, thus avoiding multiple dereferences of the struct member\nentry.num_values = next_value - entry.values;\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-10T10:09:06.327",
"Id": "7058",
"Score": "1",
"body": "I have control over the input decoder. Great idea!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-10T07:28:33.737",
"Id": "4722",
"ParentId": "4518",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4722",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T20:43:44.760",
"Id": "4518",
"Score": "7",
"Tags": [
"c++",
"optimization",
"lookup",
"compression",
"video"
],
"Title": "Optimizing Huffman Decoding"
}
|
4518
|
<p>I am trying to create a new website, and i am using a class that has many functions on it.
First i want to say that my class has about 5000 rows , is this a problem ?</p>
<p>The main function i have used on my class is this one : </p>
<pre><code>function f3($id = '') {
$id = mysql_real_escape_string ($id);
$sql = 'SELECT id,post_title,post_content,post_date,post_status,term_taxonomy_id,object_id FROM wp_posts, wp_term_relationships WHERE term_taxonomy_id = 60 AND post_status = "publish" AND wp_term_relationships.object_id = id ORDER BY post_date DESC LIMIT 1 OFFSET 2';
$res = mysql_query($sql) or die (mysql_error());
if (mysql_num_rows($res) !=0):
$row = mysql_fetch_assoc($res);
$mycontent = $row['post_content'];
$mycontent = strip_tags($mycontent);
$mycontent = substr($mycontent,0,150);
$mycontent = preg_replace("/\[caption.*\[\/caption\]/", '', $mycontent);
$title = AvinD($row['post_title']);
$old_date = $row['post_date']; // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('d.m.Y H:i', $old_date_timestamp);
$first_img = '';
$my1content = AvinD($row['post_content']);
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $my1content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/img/default.png";
}
echo '
'.$new_date.'
<a href="single.php?id='.$row['id'].'"> '.$title.' </a> </div>
<a href="single.php?id='.$row['id'].'"> <img src="timthumb.php?src='.$first_img.'&amp;h=107&amp;w=190amp;zc=1" alt="" /> </a> </div>
'.$mycontent.'
'; //echo
else:
echo 'Page dont exist';
endif;
} // end
</code></pre>
<p>Also wanted to ask, when should i close the connection with database? at the end of the class? or after every function like this ? </p>
<p>Thank you for reading this post.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:18:28.257",
"Id": "6761",
"Score": "0",
"body": "what exactly is the problem, does it not work, does it run slow?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:20:36.267",
"Id": "6762",
"Score": "0",
"body": "i am just asking for any improvments if there is any , also the number of rows that i have for my class .. is it a problem ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:22:37.760",
"Id": "6763",
"Score": "1",
"body": "Do you really need to improve response times? remember that `premature optimization is the root of all evil`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:24:35.017",
"Id": "6764",
"Score": "0",
"body": "yes i want improve response times , any suggestion please ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:32:07.290",
"Id": "6765",
"Score": "0",
"body": "When you say \"rows in your class\", do you mean rows in your database table?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:41:01.740",
"Id": "6766",
"Score": "0",
"body": "no i mean rows in my class class myclass { ......... ...}"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-08-26T17:55:18.680",
"Id": "48082",
"Score": "0",
"body": "@Meo means 5000 lines of code"
}
] |
[
{
"body": "<p>The code looks fine to me, can't see anything obvious that i would improve on</p>\n\n<p>Normally I don't ever explicitly close a database connection on my scripts.\nwhen the script ends, the database connection is closed automatically</p>\n\n<p>5,000 lines of code for one class is quite a lot, but nothing really wrong with that.\nSome people prefer to split them up in to classes which each contain similar functionality, making it easier to find things, but this is not essential. </p>\n\n<p>If you have large methods sometimes it is good to split them up for readability purposes, like if you have to scroll down more then 2-3 pages to see how one functions works.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:26:06.290",
"Id": "4523",
"ParentId": "4522",
"Score": "1"
}
},
{
"body": "<p>Seems essentially clean to me as well but I have some minor beefs (beefettes?).</p>\n\n<p>Personally I like descriptive names as it makes reading easier when I have to return to older code for maintenance. Names like <code>f3</code> and <code>AvinD</code> do not lend themselves for clear interpretation of what they are supposed to do. The separation of <code>mycontent</code> and <code>my1content</code> is not clear either. Names such as <code>old_date</code> and <code>new_date</code> are also misleading as they are used to transform the date format not the date value. </p>\n\n<p>I also try to separate responsibilities to different functions. Now <code>f3</code> contains </p>\n\n<ol>\n<li>Database query handling</li>\n<li>Data transformation</li>\n<li>Configuration (default values)</li>\n<li>Content parsing</li>\n<li>Template definition</li>\n<li>Template application </li>\n<li>Output</li>\n</ol>\n\n<p>It might be beneficial if some of the responsibilities would be in their own functions and the function <code>f3</code> would just coordinate the process in a higher level of abstraction e.g.</p>\n\n<pre><code>$post_result = find_post($id);\nif(found($post_result)):\n $post = fetch_post($post_result);\n $post_id = id_of($post);\n $post_title = title_of($post);\n $post_content = content_of($post); \n $post_date = format_date_of($post);\n $thumbnail_image = find_first_image_in($post, '/img/default.png');\n echo apply_template($post_id, $post_date, $post_title, $post_content, $thumbnail_image);\n else:\n echo 'Page dont exist';\n endif;\n</code></pre>\n\n<p>In PHP I would be a bit careful with functions that print out to the output stream. The problem is that you may or may not want/need to set header values at some point. If there's output through out the code then you have a higher risk that some output is already sent to the client before the header values are sent. This will cause a warning to be issued and results in an unexpected behaviour. </p>\n\n<p>Generally, you might want to stay clear of magic numbers. For some reason, the title is truncated to the first 150 characters. Where does that number come from and what does it mean?</p>\n\n<p>You are using the mysql set of functions while you should use mysqli (mysql improved extension). That's just PHP for you. </p>\n\n<p>In SQL, I prefer using JOIN syntax as it forces you to define the join conditions in the immediate context e.g. </p>\n\n<pre><code>SELECT \n id,post_title,post_content,post_date,post_status,term_taxonomy_id,object_id \nFROM wp_posts \nJOIN wp_term_relationships on object_id = id\nWHERE term_taxonomy_id = 60 \n AND post_status = \"publish\" \nORDER BY post_date DESC LIMIT 1 OFFSET 2\n</code></pre>\n\n<p>I'd like it even more, if the same name was used for both columns (object_id) and you could use <code>JOIN ... USING (object_id)</code>. </p>\n\n<p>I'm a bit puzzled why you have escaped the <code>$id</code> variable even though you don't use it in the query. Might this be a bug?</p>\n\n<p>I'm not sure why do you want all those columns in the projection if you only use some of them? </p>\n\n<p>When it come to intendation I've come to like that the control statements are on the same level of intendation and blocks are intended one step more e.g. </p>\n\n<pre><code>if (mysql_num_rows($res) !=0):\n ...\nelse:\n ...\nendif;\n</code></pre>\n\n<p>The effect of the intendation you used was that I didn't immediately catch the start of the else block. </p>\n\n<p>I see you use <code>x != 0</code>. In PHP it's almost always better to use <code>!==</code> and <code>===</code> instead as they take the type into account as well. You'll save yourself from accidental bugs in the long run. </p>\n\n<p>Lastly there is the case of 5 000 lines (lines of code are called lines instead of rows) in a single class. The length of the class is code smell that suggests that you might not have modelled the problem and the solution quite far enough. I would also be a bit worried that a class that size may have some duplication in it. I would suggest splitting the class though it may increase the total number of lines in the application. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T10:43:42.583",
"Id": "4524",
"ParentId": "4522",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4523",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T04:14:55.943",
"Id": "4522",
"Score": "-1",
"Tags": [
"php",
"performance"
],
"Title": "Displaying posts"
}
|
4522
|
<p>I have written this PHP function which will flip an image (horizontally, like looking in a mirror). It reads the file, flips it, and writes it to a new filed called filename"_flipped".ext. I would like to refactor this to the smallest possible size, but maintaining human readability. </p>
<p>Here is the function: </p>
<pre><code>function flip_image($filepath)
{
if(file_exists($filepath)):
//Array ( [dirname] => images
// [basename] => pig.png
// [extension] => png
// [filename] => pig
// [filesize] => 72 )
$file = $this->get_file_info($filepath); // Returns above array
// Is it allowed in our extensions array
if(in_array($file['extension'], $this->allowed_exts)):
// Reference our Image for the correct extension
switch ($file['extension']) {
case 'png':
$img = imagecreatefrompng($filepath);
break;
case 'gif':
$img = imagecreatefromgif($filepath);
break;
default: // Has to be JPG, or JPEG
$img = imagecreatefromjpeg($filepath);
break;
}
// Now we have our image...
// Image Width & Height
$size_x = imagesx($img);
$size_y = imagesy($img);
// Create Temp Image
$temp = imagecreatetruecolor($size_x, $size_y);
// Define a colour as transparant, allocate the colour, resample it
imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);
if ($x) {
$img = $temp;
}
else {
die('Unable to flip image');
}
$writepath = $file['dirname'] . "/" . $file['filename'] . "_flipped" . ".";
// Write our file
switch ($file['extension']) {
case 'png':
imagepng($img, $writepath.$file['extension']);
break;
case 'gif':
imagegif($img, $writepath.$file['extension']);
break;
default: // Has to be PNG
imagejpeg($img, $writepath.$file['extension']);
break;
}
$flipped_path = $writepath.$file['extension'];
imagedestroy($img);
return $flipped_path;
else:
echo 'Incorrect File Type, Not an Image, .png .gif, jpeg. jpeg Only.';
return false;
endif;
else:
echo 'No Such file found, Check the file path';
return false;
endif;
}
</code></pre>
|
[] |
[
{
"body": "<p>You could use call_user_func to check the extension only once. Something like this (I haven't got the time even to read the code now) </p>\n\n<pre><code>function flip_image($filepath)\n{\nif(file_exists($filepath)):\n\n //Array ( [dirname] => images \n // [basename] => pig.png \n // [extension] => png \n // [filename] => pig \n // [filesize] => 72 )\n $file = $this->get_file_info($filepath); // Returns above array\n\n // Is it allowed in our extensions array\n if(in_array($file['extension'], $this->allowed_exts)):\n // Reference our Image for the correct extension\n $outfile = $file['dirname'] . \"/\" . $file['filename'] . \"_flipped\" . \".\" . $file['extension'];\n switch ($file['extension']) {\n case 'png':\n return flip_image_in($filepath, $outfile, 'imagecreatefrompng', 'imagepng');\n case 'gif':\n return flip_image_in($filepath, $outfile, 'imagecreatefromgif', 'imagegif');\n default: // Has to be JPG, or JPEG\n return flip_image_in($filepath, $outfile, 'imagecreatefromjpeg', 'imagejpeg');\n }\n else:\n echo 'Incorrect File Type, Not an Image, .png .gif, jpeg. jpeg Only.';\n return false;\n endif;\nelse:\n echo 'No Such file found, Check the file path';\n return false;\nendif;\n\n}\n\nfunction flip_image_in($inpath, $outfile, $create_function, $write_function)\n{\n $img = call_user_func($create_function, $inpath);\n\n // Now we have our image...\n // Image Width & Height\n $size_x = imagesx($img);\n $size_y = imagesy($img);\n\n // Create Temp Image\n $temp = imagecreatetruecolor($size_x, $size_y);\n\n // Define a colour as transparant, allocate the colour, resample it\n imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));\n imagealphablending($temp, false);\n imagesavealpha($temp, true);\n\n $x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $size_y, 0-$size_x, $size_y);\n if ($x) {\n $img = $temp;\n }\n else {\n die('Unable to flip image');\n }\n\n call_user_func($write_function, $img, $outfile);\n imagedestroy($img);\n return $outfile;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T13:01:44.463",
"Id": "4527",
"ParentId": "4526",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4527",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T12:43:03.917",
"Id": "4526",
"Score": "0",
"Tags": [
"php"
],
"Title": "Help to Refactor PHP Flip Image Code to smallest size as possible"
}
|
4526
|
<p>I have this code:</p>
<pre><code>private void numWidth_ValueChanged(object sender, EventArgs e)
{
if (ignoreChange) return; // Sometimes I only want to change the value without the event firing (like when undo-ing)
PushUndoStack();
int width = (int)numWidth.Value;
foreach (Layer layer in doc.TileLayers)
layer.Width = width;
hscDoc.Maximum = doc.WidthInPixels;
ClampScrollbarValue(hscDoc);
}
private void numHeight_ValueChanged(object sender, EventArgs e)
{
if (ignoreChange) return;
PushUndoStack();
int height = (int)numHeight.Value;
foreach (Layer layer in doc.TileLayers)
layer.Height = height;
vscDoc.Maximum = doc.HeightInPixels;
ClampScrollbarValue(vscDoc);
}
</code></pre>
<p>They are both very similar yet I can't really think of a good way to combine the two. This happens several times in my program and the lines of code are really adding up. I <em>suppose</em> I could use reflection but is it overkill? Can anyone think of a better way?</p>
<p>This is just an example. This happens quite a few times in my program where functions are very similar but cannot be easily refactored in to a generic method.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T22:53:10.603",
"Id": "6772",
"Score": "3",
"body": "There is a site for code-reviews on SE, check it out ;) Apart from that, you could in that case (adapt where necessary) create a dimensionChanged method that takes sender, e and a (boolean? string? int? I favor int...) variable indicating direction."
}
] |
[
{
"body": "<p>You can try the idea below. </p>\n\n<pre><code> private void numWidth_ValueChanged(object sender, EventArgs e)\n {\n if (OnValueChanged((layer, value) => layer.Width = value, (int)numWidth.Value))\n {\n // Can be refactored in a similar\n // hscDoc.Maximum = doc.WidthInPixels;\n // ClampScrollbarValue(hscMap);\n }\n }\n\n private void numHeight_ValueChanged(object sender, EventArgs e)\n {\n if (OnValueChanged((layer, value) => layer.Height = value, (int)numHeight.Value));\n {\n // Can be refactored in a similar way\n // vscDoc.Maximum = doc.HeightInPixels;\n // ClampScrollbarValue(vscMap);\n }\n }\n\n private bool OnValueChanged<TValue>(Action<Layer, TValue> setter, TValue value)\n {\n if (ignoreChange) return false;\n\n PushUndoStack();\n\n foreach (Layer layer in doc.TileLayers)\n setter(layer, value);\n\n return true;\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T23:21:03.643",
"Id": "4529",
"ParentId": "4528",
"Score": "2"
}
},
{
"body": "<p>Something along these lines:</p>\n\n<pre><code>private void ValueChangedImp(object sender, EventArgs e, Func<int> get_value, Action<Layer, int> set_value, Func<int> get_pixels)\n{\n if (ignoreChange) return; // Sometimes I only want to change the value without the event firing (like when undo-ing)\n\n PushUndoStack();\n\n int value = get_value();\n\n foreach (Layer layer in doc.TileLayers)\n set_value(laywe, value);\n\n hscDoc.Maximum = get_pixels();\n ClampScrollbarValue(hscDoc);\n}\n\nprivate void numWidth_ValueChanged(object sender, EventArgs e)\n{\n ValueChangedImp(sender, e, () => (int)numWidth.Value, (layer, value) => layer.Width = value, () => doc.WidthInPixels);\n}\n\nprivate void numHeight_ValueChanged(object sender, EventArgs e)\n{\n ValueChangedImp(sender, e, () => (int)numHeight.Value, (layer, value) => layer.Height = value, () => doc.HeightInPixels);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T23:47:45.210",
"Id": "6773",
"Score": "0",
"body": "The scrollbar is not always hscDoc but I get the idea. Forgot all about these features in C#"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T23:21:40.563",
"Id": "4530",
"ParentId": "4528",
"Score": "5"
}
},
{
"body": "<p>while the other solutions show ways of injecting code into a templated function...which is useful. But can lead to 'coincidental coupling'. Its a good approach in some situations.</p>\n\n<p>But potentially I'd opt for...</p>\n\n<p>I'd also probably work to move UpdateDimensions to a view model and for it to take the height and width as a parameter.</p>\n\n<pre><code>private void numWidth_ValueChanged(object sender, EventArgs e)\n{\n UpdateDimensions();\n}\nprivate void numHeight_ValueChanged(object sender, EventArgs e)\n{\n UpdateDimensions();\n}\n\nprivate void UpdateDimensions()\n{\n if (ignoreChange) return; \n PushUndoStack();\n\n int width = (int)numWidth.Value;\n int height = (int)numHeight.Value;\n\n foreach (Layer layer in doc.TileLayers)\n {\n layer.Width = width;\n layer.Height = height;\n }\n hscDoc.Maximum = doc.WidthInPixels;\n ClampScrollbarValue(hscDoc);\n vscDoc.Maximum = doc.HeightInPixels;\n ClampScrollbarValue(vscDoc);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T22:46:29.837",
"Id": "4537",
"ParentId": "4528",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4530",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-08-31T22:50:03.123",
"Id": "4528",
"Score": "5",
"Tags": [
"c#"
],
"Title": "How to shorten two methods with the same theme?"
}
|
4528
|
<p>Example code:</p>
<pre><code><?php
class MyClass {
public $bar = array('a', 'b', 'c');
public function getBar() {return $this->bar;}
public function execute(array $fooArray) {
foreach ($fooArray as $foo) {
echo $foo.":".$this->checkBar($foo, $this->getBar())." ";// PASSED IN//
//echo $foo.":".$this->checkBar($foo)." ";// RETRIEVED //
}
}
// PASSED IN //
public function checkBar($foo, array $fooCheck) {
return in_array($foo, $fooCheck);
}
// RETRIEVED //
/*public function checkBar($foo) {
$fooCheck = $this->getBar();
return in_array($foo, $fooCheck);
}*/
}
$someClass = new MyClass();
$someClass->execute(array('a','f','c','g'));
?>
</code></pre>
<p>Are there any performance considerations to passing <code>$fooCheck</code> in as a variable into <code>checkBar</code> vs having <code>MyClass::checkBar()</code> handle calling the function itself?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-11-12T03:47:59.777",
"Id": "9208",
"Score": "0",
"body": "Nope, it's all good."
}
] |
[
{
"body": "<p>Having (1)</p>\n\n<pre><code>public function execute(array $fooArray)\n{\n foreach ($fooArray as $foo) {\n echo $foo . \":\" . $this->checkBar($foo, $this->getBar()) . \" \";\n }\n}\n\npublic function checkBar($foo, array $fooCheck)\n{\n return in_array($foo, $fooCheck);\n}\n</code></pre>\n\n<p>is <strong>the exact same thing</strong> (performance wise) as (2)</p>\n\n<pre><code>public function execute(array $fooArray)\n{\n foreach ($fooArray as $foo) {\n echo $foo . \":\" . $this->checkBar($foo) . \" \";\n }\n}\n\npublic function checkBar($foo)\n{\n return in_array($foo, $this->getBar());\n}\n</code></pre>\n\n<p>In example (1), if you needed <code>checkBar()</code> to handle several different array inputs, then you would be able to differentiate them in <code>execute()</code>. Whereas example (2) would be better if you knew you would only be checking against a single array.</p>\n\n<p>It's easier to expand code that's written like example (1).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-06-15T04:21:38.820",
"Id": "54284",
"ParentId": "4532",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T15:36:46.053",
"Id": "4532",
"Score": "2",
"Tags": [
"php",
"performance"
],
"Title": "PHP performance considerations of passing variable into a function"
}
|
4532
|
<p><code>BudgetCode</code> is in the format <code>'xxxx-yyyyy-zzzzz'</code>. This splits it correctly but I think that there has to be a more efficient way.</p>
<pre><code>Select
substring(pc.BudgetCode,1, CHARINDEX('-',pc.BudgetCode)-1) as Cost_Center,
substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),1, CHARINDEX('-',Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))-1) as Account_Code,
Substring(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)),Charindex('-',Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))+1,len(Substring(pc.BudgetCode,Charindex('-',pc.BudgetCode)+1,len(pc.BudgetCode)))) as Slid_Code
from pc
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T17:19:10.293",
"Id": "6774",
"Score": "1",
"body": "What RDBMS are you on? Some 'better' solutions don't work on all products. Also, I recommend storing the code separated, if at all possible, so you don't have to do the split; if 90% of the time you are using the split code for joins, store it that way. Of course, if this is just for display, you should probably be using your application layer to perform the split."
}
] |
[
{
"body": "<p>Hmm... Not sure how much <em>faster</em> this will be, but it may be easier to wrap your head around.<br>\nYou can use a recursive CTE: </p>\n\n<pre><code>WITH Splitter (id, start, e, section, original, num) as (\n SELECT id, 1, CHARINDEX('-', budgetCode), CAST('' AS VARCHAR(20)), budgetCode, 0\n FROM PC\n UNION ALL\n SELECT id, e + 1, \n CASE WHEN CHARINDEX('-', original, e + 1) > 0\n THEN CHARINDEX('-', original, e + 1)\n ELSE LEN(original) + 1 END,\n SUBSTRING(original, start, e - start), \n original, num + 1\n FROM Splitter\n WHERE e > start) \n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>SELECT * \nFROM splitter\n</code></pre>\n\n<p>Makes a table that looks like this: </p>\n\n<pre><code>Id BudgetCode\n=====================\n1 xxxx-yyyyy-zzzzz\n</code></pre>\n\n<p>Into this: </p>\n\n<pre><code>Id Start End Section Original Num\n1 1 5 xxxx-yyyyy-zzzzz 0\n1 6 11 xxxx xxxx-yyyyy-zzzzz 1\n1 12 17 yyyyy xxxx-yyyyy-zzzzz 2\n1 18 17 zzzzz xxxx-yyyyy-zzzzz 3\n</code></pre>\n\n<p><kbd><a href=\"http://sqlfiddle.com/#!3/788cb/4/0\" rel=\"nofollow\">SQL Fiddle Example</a></kbd></p>\n\n<p>You can then join to the result set multiple times based on <code>Num</code> or something to get the particular index you need. It'll automatically handle any additional 'subfields' (to the limit of the recursion, of course).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-23T22:55:49.240",
"Id": "193267",
"Score": "0",
"body": "Sweet I got this to work I added where length(section) > 0 to get rid of all the empty rows."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-24T17:00:43.573",
"Id": "193418",
"Score": "0",
"body": "I had to a a space because it couldn't parse when the last character was non blank. budgetcode || ' '"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-24T23:18:12.683",
"Id": "193480",
"Score": "0",
"body": "@danny117 - not sure what you mean? The example is handling non-space-terminated data just fine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-25T14:12:42.760",
"Id": "193568",
"Score": "0",
"body": "It failed on IBM Iseries DB2. Which doesn't have charindex substituted the locate function It failed on that implementation if a fixed length column didn't have a trailing blank so I just append a trailing blank. It probably works on other DB just fine."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T22:26:32.523",
"Id": "4536",
"ParentId": "4533",
"Score": "4"
}
},
{
"body": "<p>First, if you have any influence at all in the database design, you may do better by storing the strings separately. It is a lot easier to glue strings together when needed than to split them apart when needed.</p>\n\n<p>Second, if you are guaranteed to always have the same number of digits in each budget code, you could just use the absolute character positions, such as <code>substring(pc.BudgetCode,6,5)</code> </p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/630907/mssql-split-a-field-into-3-fields\">this similar SO question</a> and <a href=\"https://stackoverflow.com/questions/697519/split-function-equivalent-in-tsql\">this more general SO question</a>, which links to \n<a href=\"http://www.sommarskog.se/arrays-in-sql.html\" rel=\"nofollow noreferrer\">this authoritative page of many ways to split strings</a>, many of which seem unnecessarily complex for your purpose.</p>\n\n<p>You might also try writing really simple functions. One advantage is that MSSQL seems to cache the results of functions, so a query with functions can run a lot faster the second time:</p>\n\n<pre><code>create function getslidcode (@budgetcode nvarchar(100))\n returns @slidcode nvarchar(100) as\nbegin\n declare @pos int\n select @pos = charindex('-', @budgetcode)\n select @pos = charindex('-', @budgetcode, @pos + 1)\n select @slidcode = substring(@budgetcode, @pos + 1, 100)\nend\n\nselect budgetcode, getslidcode(budgetcode) as slidcode from pc\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T12:51:14.053",
"Id": "6920",
"Score": "0",
"body": "This is for a report that will get run 10 times (once a week for the next 10 weeks then go away) I Have no influence on the design of the db and if it was this isnt even close the the first thing i would tackle. I really am trying to avoid adding more function to this already programatically bloated db (With unused and unmaintained sps and functions not tomention tempo tables that have become part of the standard process this whole db belongs on thedailywtf.com) for what is essentially a 1 off report that will probably never be read."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T14:34:45.643",
"Id": "6921",
"Score": "0",
"body": "Splitting strings at db level is relatively hard, as you are seeing. If it's for a one-off (or 10-off), you should just do the splitting in another language after extracting the result from the db."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T15:18:44.160",
"Id": "6922",
"Score": "0",
"body": "that would be far to easy... They want a query they can run themselves... of course i will be assinged the task to run it everytime."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T16:01:12.163",
"Id": "6923",
"Score": "0",
"body": "In this situation, I normally provide a single Excel file containing the instructions 1. copy and run the SQL at right, 2. paste the SQL results here, 3. the desired report is below."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T14:09:15.263",
"Id": "4583",
"ParentId": "4533",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T16:43:38.603",
"Id": "4533",
"Score": "3",
"Tags": [
"sql",
"strings",
"sql-server"
],
"Title": "Splitting a string in an SQL query"
}
|
4533
|
<p>I have recently become annoyed enough with something about the linux command line experience to take action.</p>
<p>I welcome all comments, but specific things I'd like input on are:</p>
<ul>
<li>Is there something already available that does this?</li>
<li>How would you do the same thing in Perl or Python?</li>
<li>How would you go about reducing code duplication here? (The file-types hash looks similar enough in both places that it feels like I should be able to abstract it)</li>
<li>In <code>unpack</code>, is there a better way of determining file-type?</li>
<li>Can you think of any situations that would cause <code>pack</code> to blow up (and any ways of solving those situations)? Just failing to do anything wouldn't be <em>too</em> bad, but (for example) compressing random other files is something I'd like to avoid.
<hr></li>
</ul>
<p>Take 4:</p>
<p><code>unpack</code>:</p>
<pre><code>#!/usr/bin/ruby
archive_types = {
"tar" => ["tar", "-xvf"],
"tar.gz" => ["tar", "-zxvf"],
"tgz" => ["tar", "-zxvf"],
"tar.bz2" => ["tar", "-jxvf"],
"rar" => ["unrar", "x"],
"zip" => ["unzip"]
}
ARGV.each do |target|
file_type = target.match(/\.([^\W0-9]{3}?(\.\w+)?)$/)[1]
if archive_types[file_type]
args = archive_types[file_type].push target
system(*args)
else
puts "Dunno how to deal with '#{file_type}' files"
end
end
</code></pre>
<p><code>pack</code> (with added <code>--exclude</code> options for my ease of use):</p>
<pre><code>#!/usr/bin/ruby
require 'optparse'
require 'pp'
require 'fileutils'
archive_types = {
"tar" => ["tar", "-cvf"],
"tar.gz" => ["tar", "-zcvf"],
"tgz" => ["tar", "-zcvf"],
"tar.bz2" => ["tar", "-jcvf"],
"zip" => ["zip"]
}
########## parsing inputs
options = { :type => "tar", :excluded => [".git", ".gitignore", "*~"] }
optparse = OptionParser.new do|opts|
opts.on("-e", "--exclude a,b,c", Array,
"Specify things to ignore. Defaults to [#{options[:excluded].join ", "}]") do |e|
options[:excluded] = e
end
opts.on("-t", "--type FILE-TYPE",
"Specify archive type to make. Defaults to '#{options[:type]}'. Supported types: #{archive_types.keys.join ", "}") do |t|
options[:type] = t
end
end
optparse.parse!
##########
ARGV.each do |target|
if not archive_types[options[:type]]
puts "Supported types are #{archive_types.keys.join ", "}"
exit
elsif options[:type] == "zip"
exclude = options[:excluded].map{|d| ["-x", d]}.flatten
else
exclude = options[:excluded].map{|d| ["--exclude", d]}.flatten
end
args = archive_types[options[:type]] +
[target + "." + options[:type], target] +
exclude
system(*args)
end
</code></pre>
|
[] |
[
{
"body": "<p>\"Take 2\" looks much nicer than the initial version.\nOne bug seems to be <code>\"unrar\" => \"unrar\"</code>, which should be <code>\"rar\" => \"unrar\"</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T03:16:33.180",
"Id": "6823",
"Score": "0",
"body": "Yup, caught that earlier; fixed above."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T18:28:06.680",
"Id": "4562",
"ParentId": "4534",
"Score": "3"
}
},
{
"body": "<p>I find take two (for unpack) to be harder to read, actually. It's less extensible, for sure, but for a shell script, it's nice to be very explicit about what you're doing.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T04:43:26.100",
"Id": "4573",
"ParentId": "4534",
"Score": "0"
}
},
{
"body": "<p>Both your <code>pack</code> and <code>unpack</code> scripts will fail if any of the targets contain spaces (or other shell meta-characters) in their name. Generally it's almost always a bad idea to insert arguments into commands using string interpolation.</p>\n\n<p>I assume you're using backticks rather than <code>system</code> because you don't want the output of the invoked commands to go to the screen. In that case you can use <code>IO.popen</code>, which since ruby 1.9 can take an array as its first argument.</p>\n\n<p>As a trivial sidenote: There doesn't seem to be any point in passing the <code>-v</code> flag to <code>tar</code> if you're not going to print its output, so I'd remove it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-21T18:12:51.037",
"Id": "7390",
"Score": "0",
"body": "Nope, just being an idiot. Now that I've had time to play, new versions using `system` instead of backticks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T09:20:11.707",
"Id": "4575",
"ParentId": "4534",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "4575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T20:19:37.783",
"Id": "4534",
"Score": "2",
"Tags": [
"ruby"
],
"Title": "Fixing Archive Annoyances with Ruby"
}
|
4534
|
<p>The following code is a quick implementation since I only needed 3 random images sorted by category (a random eyes image, a random nose image and a random mouth image and then combine them):</p>
<pre><code> fileinfos = FileInfo.all().filter("category =", "eyes")
fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
url = images.get_serving_url(str(fileinfo.blob.key()), size=420)
fileinfos = FileInfo.all().filter("category =", "nose")
fileinfo2 = fileinfos[random.randint(0, fileinfos.count()-1)]
url2 = images.get_serving_url(str(fileinfo2.blob.key()), size=420)
fileinfos = FileInfo.all().filter("category =", "mouth")
fileinfo3 = fileinfos[random.randint(0, fileinfos.count()-1)]
url3 = images.get_serving_url(str(fileinfo3.blob.key()), size=420)
</code></pre>
<p>This case is somewhat specific since the number of selection are fixed to 3. Surely iteration or a function to do this is preferred and <code>memcache</code> would also increase response time since there are not many files and the same file gets chosen sometimes then I'd like to use <code>memcache</code> and it seems <code>memcache</code> can cache the results from <code>get_serving_url</code> so I could cache the <code>fileinfos</code> or the results from <code>get_serving_url</code>. I know <code>memcache</code> is limited in memory.</p>
<pre><code> def get_memcached_serving_url(fileinfo):
from google.appengine.api import memcache
memcache_key = "blob_%d" % fileinfo.blob.key()
data = memcache.get(memcache_key)
if data is not None:
return data
</code></pre>
<p>And I think I can't cache the blob itself and only the result from <code>get_serving_url</code> while it is the trip to the datastore that supposedly takes time.</p>
<p>Please tell me any thoughts or opinions about this quick prototyping how to get random elements while hoping to cache elements since the number of elements is still not very large (<100 elements and if the same is chosen twice then I'd like a fast and preferably cached response)</p>
<p>If you want you can have a look at the actual application here.</p>
|
[] |
[
{
"body": "<p>Regarding image caching, <a href=\"https://stackoverflow.com/questions/1380431/caching-images-in-memcached\">this seems relevant</a>.</p>\n\n<p>Secondly, <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> this code up, it'll make your code more maintainable: </p>\n\n<pre><code>fileinfos = FileInfo.all().filter(\"category =\", \"eyes\")\nfileinfo = fileinfos[random.randint(0, fileinfos.count()-1)] \nurl = images.get_serving_url(str(fileinfo.blob.key()), size=420)\n</code></pre>\n\n<p>Should have it's own function (forgive my py):</p>\n\n<pre><code>def get_random_image_url(category)\n fileinfos = FileInfo.all().filter(\"category =\", category)\n fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)] \n return images.get_serving_url(str(fileinfo.blob.key()), size=420)\n\neyes_url = get_random_image_url(\"eyes\")\nnose_url = get_random_image_url(\"nose\")\nmouth_url = get_random_image_url(\"mouth\")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T23:24:17.500",
"Id": "6807",
"Score": "1",
"body": "Thank you for the important help with structuring it to a function. Thank you also for the link with the important insight when not to use memcache."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T01:31:58.200",
"Id": "4540",
"ParentId": "4538",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4540",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-01T23:09:04.013",
"Id": "4538",
"Score": "0",
"Tags": [
"python",
"image",
"cache",
"google-app-engine"
],
"Title": "Iteration and memcache for selected categorized random elements"
}
|
4538
|
<p>I have been working on a maze generator in C++ in an effort to learn the language and brush up on some long lost knowledge. I want to ensure that I am using best practices, and really doing things the way that they should be done. </p>
<p>My code is safely tucked into a GitHub repository. I would like to have two specific classes reviewed: <a href="https://github.com/matt-y/I-Hope-You-Like-Mazes/blob/master/Maze.h" rel="nofollow">Maze.h</a> (154 lines) (and MazeConstants.h if possible), as well as <a href="https://github.com/matt-y/I-Hope-You-Like-Mazes/blob/master/MazePosition.h" rel="nofollow">MazePosition.h</a> (45 lines).</p>
<p>I also had a couple questions. Is it advisable to overload operator!= in addition to <code>operator==</code>? I overload <code>operator==</code> in the <code>MazePosition</code> class, but not <code>operator!=</code>. Is it good practice to provide copy constructors and overloaded assignment operators as well? I am mostly confused about best practices in these areas, and the info I have found online has been sparse and mostly just pages with illustrated examples. I plan on disabling any sort of copying ability in the Maze.h class by doing something like this: (boost.org/doc/libs/1_47_0/boost/noncopyable.hpp) because it does not make sense to copy that object for any reason (too slow anyway, right?).</p>
<p><strong>File: MazePosition.h (45 Lines)</strong></p>
<pre><code>/*
* File: MazePosition.h
* Author: mattosaurus
*
* Created on August 6, 2011, 4:26 PM
*/
#ifndef MAZEPOSITION_H
#define MAZEPOSITION_H
class MazePosition{
public:
MazePosition(int row, int col) : _row(row), _col(col){}
int getRow() const{
return _row;
}
int getCol() const{
return _col;
}
MazePosition operator+(MazePosition & p2) const{
int newX = _row + p2.getRow();
int newY = _col + p2.getCol();
MazePosition local(newX, newY);
return local;
}
friend bool operator==(MazePosition const&p1, MazePosition const&p2);
private:
int _row;
int _col;
};
bool operator==(MazePosition const&p1, MazePosition const&p2) {
if(p1.getRow() == p2.getRow()){
return (p1.getCol() == p2.getCol());
}
return false;
}
#endif /* MAZEPOSITION_H */
</code></pre>
<p><strong>File: Maze.h (145 Lines)</strong></p>
<pre><code>/*
* File: Maze.h
* Author: mattosaurus
*
* Created on August 5, 2011, 3:34 PM
*/
#ifndef MAZE_H
#define MAZE_H
#include <iostream>
#include <exception>
#include <time.h>
#include <vector>
#include <stack>
#include <algorithm>
#include <stdexcept>
#include "MazePosition.h"
#include "MazeConstants.h"
using std::vector;
using std::stack;
typedef vector< vector<int> > IntMaze;
class Maze {
public:
Maze(int width, int height) : _width(width+2), _height(height+2), _maze(_height, vector<int>(_width))
{
MazeInit(_maze, MazeConstants::UNVISITED);
MazeCarve(_maze, _exitList);
}
int getHeight(){
return _height;
}
int getWidth(){
return _width;
}
void MazeInit( IntMaze & maze, int init){
//initialize all cells to 0 (unvisited)
//surround with a border of out of bounds cells (-1)
for(int i = 0; i < maze.capacity(); i++){
for(int j = 0; j < maze.at(i).capacity(); j++){
if(i == 0 || i == maze.capacity() -1 ){
maze.at(i).at(j) = MazeConstants::INVALID;
}
else if(j == 0 || j == maze.at(i).capacity() -1 ){
maze.at(i).at(j) = MazeConstants::INVALID;
}
else{
maze.at(i).at(j) = init;
}
}
}//end initial initialization
}
void MazeCarve(IntMaze & maze, vector<MazePosition> & exitList){
//Pick a starting location (pick something along the height(x) and width(0).
int row = (rand() % (_height));
int col = (rand() % (_width));
MazePosition start(row, col);
//mark start as visited (non-zero)
maze.at(start.getRow()).at(start.getCol()) = MazeConstants::START;
//begin the grunt work
CarveFrom(maze, start, exitList);
}
void CarveFrom(IntMaze & maze, MazePosition & start, vector<MazePosition> & exitList){
vector<MazePosition> dirCopy = MazeConstants::directions;
std::random_shuffle(dirCopy.begin(), dirCopy.end());
for(int i = 0; i < dirCopy.size(); i++){
MazePosition temp = dirCopy.at(i);
MazePosition newPos = start + temp;
//is position valid
int tile;
try{
tile = maze.at(newPos.getRow()).at(newPos.getCol());
}
catch(std::out_of_range e){
continue;
}
if(tile == MazeConstants::INVALID){
exitList.push_back(temp);
continue;
}
if(tile == MazeConstants::UNVISITED){
maze.at(newPos.getRow()).at(newPos.getCol()) = MazeConstants::FLOOR;
//since we jump multiple tiles, set the prev one to FLOOR
//we came from the south
if(MazeConstants::N == temp){
maze.at(newPos.getRow() -1).at(newPos.getCol()) = MazeConstants::FLOOR;
}
//came from north
if( temp == MazeConstants::S ){
maze.at(newPos.getRow()+1).at(newPos.getCol()) = MazeConstants::FLOOR;
}
//came from west
if(MazeConstants::E ==temp){
maze.at(newPos.getRow()).at(newPos.getCol()-1) = MazeConstants::FLOOR;
}
//came from east
if(MazeConstants::W == temp){
maze.at(newPos.getRow()).at(newPos.getCol()+1) = MazeConstants::FLOOR;
}
//start looking at the new spot.
CarveFrom(maze, newPos, exitList);
}
}
}
friend std::ostream& operator<<(std::ostream& stream, const Maze& m);
private:
const int _height;
const int _width;
IntMaze _maze;
vector<MazePosition> _exitList;
};
std::ostream& operator<<(std::ostream& stream, const Maze& m) {
for(int i = 0; i < m._maze.capacity(); i++){
for(int j = 0; j < m._maze.at(i).capacity(); j++){
/*
* this was added for the pgm output to make things look
* more uniform on the final image, instead of two shades for out of bounds squares.
* Internally, the maze still uses 1 for unvisited - and 0 for invalid. These are only
* altered artificially when the maze is being sent to cout.
*/
int temp = m._maze.at(i).at(j);
if(temp == MazeConstants::UNVISITED){
stream << (temp-1) << " ";
}
else{
stream << temp << " ";
}
}
stream << std::endl;
}
return stream;
}
#endif /* MAZE_H */
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T17:37:04.147",
"Id": "6788",
"Score": "1",
"body": "Go look up the difference between size() and capacity()!!!"
}
] |
[
{
"body": "<ol>\n<li><p>If you overload an operator, make sure that the corresponding operators behave accordingly - in your case: yes, overload <code>!=</code>. Make sure not to copy paste code but call operator <code>==</code> instead (or its implementation).</p></li>\n<li><p>Always provide copy and assignment operators. If you do not, document why the default operators work. If you do not want to copy / assign objects of this type (may be expensive), make them private and provide no implementation. This way you won't accidentally copy an object that is not copyable.</p></li>\n</ol>\n\n<p>Read good C++ books such as <em>Effective C++</em> and <em>More Effective C++</em> by Scott Meyers. He provides lots of hints about pitfalls in C++.</p>\n\n<hr>\n\n<p>A remark on commenting when the defaults do: yes, there are (simple) objects where the defaults do. Still for maintenance it is important to detect whether the author of a class knows that the defaults works or just forgot to prohibit them. That's why documenting this fact is necessary. You can't distinguish a class where someone deliberately relies on the default mechanism or just forgot to implement or prohibit the copy constructor / assignment operator.</p>\n\n<p>With a comment in place it is easy. A class has 3 possibilities:</p>\n\n<ul>\n<li>custom copy & assignment</li>\n<li>prohibited copy & assignment</li>\n<li>comment that the defaults work</li>\n</ul>\n\n<p>Everything else is an error.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T12:32:37.030",
"Id": "6786",
"Score": "0",
"body": "As a rule of thumb, if find that you need to implement either the assignment operator, the copy constructor or the destructor, you will need to implement all three of them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T19:38:03.527",
"Id": "6791",
"Score": "0",
"body": "Don't agree with point (b) here. `MazePosition` default copy constructor and assignment operator are fine and there is no need to document them as they do what is expected. Same thing for `Maze`. You are taking a good rule of thumb and applying it incorrectly as neither of these class have resources or are expensive to copy. There is no point confusing people with documentation when it is not necessary the code should be self documenting </rant>"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T08:03:27.817",
"Id": "4542",
"ParentId": "4541",
"Score": "6"
}
},
{
"body": "<p>You are misusing std::vector, you should look at the <a href=\"http://www.cplusplus.com/reference/stl/vector/\">reference</a>. </p>\n\n<ul>\n<li>You should be using size() instead of capacity(). </li>\n<li>You could use [x] instead of .at(x).</li>\n</ul>\n\n<p>Are you expecting out_of_range exceptions?</p>\n\n<pre><code> try{\n tile = maze.at(newPos.getRow()).at(newPos.getCol());\n }\n catch(std::out_of_range e){\n continue;\n }\n</code></pre>\n\n<p>Exception handling should not be a part of your usual program logic, it should only happen in \"exceptional situations\".</p>\n\n<p>The friend declaration is not needed.</p>\n\n<pre><code>\"friend bool operator==(MazePosition const&p1, MazePosition const&p2);\"\n</code></pre>\n\n<p>Suggestion for MazeInit:</p>\n\n<pre><code>void MazeInit( IntMaze & maze, int init)\n{\n maze_.clear();\n maze_.resize(_height, vector<int>(_width, init));\n\n // Put the borders to MazeConstants::INVALID\n std::fill(maze_.front().begin(), maze_.front().end(), MazeConstants::INVALID);\n std::fill(maze_.back().begin(), maze_.back().end(), MazeConstants::INVALID);\n std::for_each(maze_.begin(), maze_.end(), [](const std::vector<int>& row)\n {\n row.front() = MazeConstants::INVALID;\n row.back() = MazeConstants::INVALID;\n });\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:21:33.763",
"Id": "6794",
"Score": "0",
"body": "I like your init approach a lot better than mine. When I try this though, I get an undefined reference to MazeConstants::INVALID on the first two fill lines."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:57:48.367",
"Id": "6795",
"Score": "0",
"body": "\"an undefined reference\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T01:18:51.497",
"Id": "6811",
"Score": "0",
"body": "\"undefined reference to MazeConstants::INVALID\", straight from gcc's mouth. (gcc -std=c++0x)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T10:25:11.813",
"Id": "4544",
"ParentId": "4541",
"Score": "5"
}
},
{
"body": "<p>My biggest bugbear:</p>\n\n<p>Why are you exposing internal members via getters!!!<br>\nDo other people need to know what position the MazeLocation points at?</p>\n\n<pre><code>int getRow() const{\n return _row;\n}\nint getCol() const{\n return _col;\n}\n</code></pre>\n\n<p>And</p>\n\n<pre><code>int getHeight(){\n return _height;\n}\nint getWidth(){\n return _width;\n}\n</code></pre>\n\n<p>Exposing them tightly binds your object to anything that uses them. As far as I can tell the only thing that will ever need it to know the maze position is a Maze. Thus you should Make 'Maze' a friend of 'MazePosition' and remove the getters (if you are going to tightly bind stuff together make the number of bindings as small as possible.</p>\n\n<p>As pointed out elsewhere: you only need to use <code>at()</code> if you have unvalidated input and are using it to index the array. Your code is using validated input (as you are looping from start to end), unfortunately you make the mistake of using capacity() rather than size() which is why it was throwing.</p>\n\n<pre><code>for(int j = 0; j < maze[i].size(); j++)\n{ // ^^^^^^\n maze[i][j] = MazeConstants::INVALID;\n // ^^^^^^ guranteed to be good\n</code></pre>\n\n<p>But I would rather user iterators:</p>\n\n<pre><code>for(IntMaze::iterator loop = maze.begin(); loop != maze.end(); ++loop)\n{ // ^^ Prefer pre-increment\n\n for(IntRow::iterator inner = loop->begin(); inner != loop->end(); ++inner)\n {\n</code></pre>\n\n<p>This makes the code easier to translate for the standard algorithms when you learn how to use them.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T18:05:22.650",
"Id": "4548",
"ParentId": "4541",
"Score": "10"
}
},
{
"body": "<p>Some others are mentioning good points. I would like to get a point or two in about general readability.</p>\n\n<p>It's very hard for me to look at this code as an outsider and realize what it's doing. Here is a list of things that I think could improve the overall \"feel\" of the code.</p>\n\n<ul>\n<li><p>Put newlines between your header guard, your <code>#include</code> directives, \"<code>using</code>\", etc. and the class definitions. When I read the header, the former categories should read like boiler-plate and the class definition is what should <strong>stick out</strong>. By not separating them visually, some people might glance over the important details.</p>\n\n<p>Actually, it is ill-advised to put <code>using</code> inside a header, because it may cause name clashes with files that may <code>#include</code> you and want to use those names.</p></li>\n<li><p><code>MazeInit</code> and <code>MazeCarve</code>. Why start these names with <code>Maze</code>? You're already in the <code>Maze</code> class.</p></li>\n<li><p><code>MazeInit</code> seems like a very verbose way to zero out a buffer. Note that <code>std::vector<T>::resize</code> can set array elements to some initial value. I'm thinking something like this:</p>\n\n<pre><code>std::vector&lt;int&gt; initialValues;\n\ninitialValues.resize(width, MazeConstants::INVALID);\nmaze.resize(height, initialValues);</pre></p>\n</code></pre></li>\n<li><p>It's somewhat hard for me to guess what <code>Carve</code> is doing. Variable names like <code>temp</code> don't really help. I would add an overall comment to describe the technique. The existing comments in that function assume you already know the algorithm - eg. \"<code>came from east</code>\" - huh? I'm sure that makes sense in the context of the algorithm but if you're reading this for the first time it's not obvious. (I would also try to make this function a bit less repetitive... Is there some way you can express the various directions east/west/north/south as an array of constants to loop through and perform the repetitive action?)</p>\n\n<p>Also I have some points about data representation and memory layout that I would like to raise... These are nitpicky and I'm not necessarily suggesting you rewrite your code, just asking to think about this as a thought exercise.</p></li>\n<li><p>I may get flamed from C++ people who hate the C style, but you can also imagine a different representation for the matrix. One approach would be to drop the STL containers; a simple integer array might do, and can get you a better memory layout than indirection-laden <code>vector</code>s. (With <code>vector<vector<int>></code>, every access does 2 pointer dereferences and the rows are potentially non-contiguous.) It would also change your initialization to a simple <code>memset</code> and it wouldn't perform any extra allocations. This will probably not make a huge difference for performance and is a bit of a religious matter for some; take this suggestion with a grain of salt.</p></li>\n<li><p>While on the topic of alternate matrix representations, another approach would be to switch from <code>vector<vector<int>></code> to simply 1-dimensional <code>vector<int></code>; accessing a location <code>(x,y)</code> would then become an access of <code>(y * width + x)</code>. Like the C-style approach, this would also give you less indirection while accessing elements (1 pointer dereference instead of 2, contiguous elements), though you may have to adjust some loops so that they're written in a \"line-by-line\" fashion. Be careful about doing this multiplication at every point, because in my experience that can add up.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T18:29:46.703",
"Id": "4600",
"ParentId": "4541",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T05:02:19.110",
"Id": "4541",
"Score": "11",
"Tags": [
"c++",
"pathfinding"
],
"Title": "Maze generation"
}
|
4541
|
<p>Often I find myself setting various fields in a Javabean and then passing that Javabean to some method.</p>
<pre><code>customerEntity.setName("Foo");
customerEntity.setAge(45);
customerEntity.setAddress(address);
em.merge(customerEntity);
</code></pre>
<p>Or </p>
<pre><code>requestPayload.setCustomerId(2343);
requestPayload.setCustomerPreference("green");
//lots more
sendRequest(requestPayload)
</code></pre>
<p>Not liking so much of data-population cluttering, I'd move those to a separate method.. </p>
<pre><code>public void doSomeOperation(Customer customer)
{
em.merge(prepareCustomerEntity(customer));
}
private Customer prepareCustomerEntity(Customer customer)
{ customer.setName("Foo");
customer.setAge(45);
customer.setAddress(address);
return customer;
}
</code></pre>
<p>What would be a good name for such a method ? Maybe something like <code>prepareXXX()</code> or <code>populateXXX()</code>? Naming it as <code>prepareXXX()</code> makes it sound like a void method.. <code>populateXXX()</code> sounds better? Or should I just name it as <code>setCustomerValues()</code>. But <code>setXXX()</code> name makes it sound like a typical Javabean setter, which this is not. </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T01:08:19.093",
"Id": "6810",
"Score": "1",
"body": "I like 'populate' personally"
}
] |
[
{
"body": "<p>I agree you should not use setXXX() as this sounds like a classic setter. I would say go with what you think sounds nice and conveys the meaning well. prepareXXX() sound nice to me. If it is default values you are setting, you could use something along populateWithDefaultValues().</p>\n\n<p>Just make sure you use the same naming strategy throughout your application.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:29:36.720",
"Id": "4554",
"ParentId": "4549",
"Score": "2"
}
},
{
"body": "<p>I'm a big fan of <code>init()</code> and <code>initX()</code> for those methods that should only be called to get an object into a working state.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T19:39:40.103",
"Id": "6899",
"Score": "0",
"body": "But looking more at your example, I see that the method takes a customer rather than initialising `this`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T12:36:36.503",
"Id": "6943",
"Score": "0",
"body": "Yes, its not a completely new object. Rather an existing object passed on to a method. When its a new object, names like init(), initX(), newXXXX(), createXXX() sound good ofcourse."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:24:43.170",
"Id": "4580",
"ParentId": "4549",
"Score": "1"
}
},
{
"body": "<p>If you can't be more specific then I'd go with populate, prepare just doesn't convey any meaning to me. Init or initialise is a more specific, and could be used if that is what you are doing, and I would prefer it to populateWithDefaultValues, which is longer.</p>\n\n<p>Additionally, I personally find it confusing if a method mutates a parameter and then returns it. I understand the convenience of being able to do something like <code>em.merge(prepareCustomerEntity(customer))</code>, but I think it bastardises the method design.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T07:40:00.173",
"Id": "6880",
"Score": "0",
"body": "What if the parametr is immutable?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T08:16:38.077",
"Id": "6913",
"Score": "0",
"body": "Then it makes more sense, and I'd go with something along the lines of `Customer newCustomer = newEntityWithDefaults(customer)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T12:32:43.047",
"Id": "6942",
"Score": "0",
"body": "Yep, it sounds very confusing. Thanks for pointing that out. What would be a better practice then ? considering that its not a completely new object, and only certain unset fields are to be set ? A void method that mutates the parameter ? I'll google on it meanwhile.."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T09:09:58.707",
"Id": "6990",
"Score": "0",
"body": "Yes, in Java that's what you do. The alternative (which depends on your architecture), is to put the method in the JavaBean, so that you call customer.setMissingFields(). And I think it's fine to call it setXX here because it's on the object you want to mutate, and it doesn't have any parameters.\n\nIf it's a not completely new object in which you need to set certain unset fields I'd name it maybe `finishInit(customer)` or, if you think it's appropriate, `finalise(customer)`. Or perhaps `populateMissingFields(customer)` or `populateDerivedFields(customer)`.."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T23:21:36.273",
"Id": "4590",
"ParentId": "4549",
"Score": "2"
}
},
{
"body": "<p>Looking at what you are actually doing here, assuming that your customer is unprepared before you call the method, why not just create it there and call your method <code>createCustomer</code></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T19:38:30.807",
"Id": "4604",
"ParentId": "4549",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T19:30:41.500",
"Id": "4549",
"Score": "0",
"Tags": [
"java"
],
"Title": "How to name a method that sets some values in a javabean?"
}
|
4549
|
<p>I've written a linked-list version of something like <code>shared_ptr</code>, which gets destroyed when the last copy of a pointer is destroyed.</p>
<p>Aside from the thread-unsafety, is it a fine implementation? Anything I could improve?</p>
<p>Also, what's the best way to extend it to make it work with <code>HANDLE</code>s, etc., without repeating (or limiting) myself unnecessarily, while <strong>avoiding excess verbosity</strong> (e.g. <code>auto_<HANDLE, custom_deallocator<HANDLE> ></code> is considered too verbose)?</p>
<pre><code>template<typename T>
class auto_
{
T *pValue;
mutable const auto_<T> *pPrev, *pNext;
public:
auto_() : pValue(new T()), pPrev(NULL), pNext(NULL) { }
auto_(T *pValue) : pValue(pValue), pPrev(NULL), pNext(NULL) { }
auto_(const T &v) : pValue(new T(v)), pPrev(NULL), pNext(NULL) { }
auto_(const auto_<T> &o) : pValue(o.pValue), pPrev(&o), pNext(NULL) { o.pNext = this; }
virtual ~auto_()
{
const auto_<T> *const pPrev = this->pPrev, *const pNext = this->pNext;
if (pPrev != NULL) { pPrev->pNext = pNext; }
if (pNext != NULL) { pNext->pPrev = pPrev; }
if (pPrev == NULL && pNext == NULL) { delete this->pValue; }
this->pPrev = this->pNext = NULL;
this->pValue = NULL;
}
auto_<T>& operator=(const auto_<T>& other)
{
if (this != &other)
{
this->~auto_();
this->pValue = other.pValue;
this->pPrev = &other;
this->pNext = other.pNext;
if (other.pNext != NULL) { other.pNext->pPrev = this; }
other.pNext = this;
}
return *this;
}
operator T&() /*also const version*/ { return *this->pValue; }
operator T*() /*also const version*/ { return this->pValue; }
T* operator->() /*also const version*/ { return this->pValue; }
T& operator *() /*also const version*/ { return *this->pValue; }
};
</code></pre>
<p>Sample usage:</p>
<pre><code>template<typename T>
T recurse(T value, int depth)
{
if (depth > 0) { T result = recurse(value, depth - 1); return result; }
else { return value; }
}
auto_<int> test()
{
printf("Value: %d\n", *recurse(auto_<int>(10), 3));
auto_<int> p1 = recurse<auto_<int> >(5, 3);
printf("Value: %d\n", *p1);
auto_<int> p2 = 3;
p1 = p2;
p2 = p1;
return p2;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:18:59.907",
"Id": "6796",
"Score": "0",
"body": "Why a linked list? Instead of a reference counter which would be more effective and simpler?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:36:00.373",
"Id": "6797",
"Score": "0",
"body": "@ronag: Because this is *purely stack-based*. Using a reference counter would require heap allocation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:41:39.077",
"Id": "6799",
"Score": "0",
"body": "I'm not convinced that a \"purely stack based\" implementation is better. Firstly because if it was better then shared_ptr would probably have used it. Secondly, a reference counter would require a single heap allocation, whereas your stack-based solution requires several extra assignments and checks for every copy."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:47:42.707",
"Id": "6802",
"Score": "0",
"body": "If you want to use this class I would strongly suggest that you write unit tests for this class, as it might be easier to verify its correctness."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T03:50:13.083",
"Id": "6826",
"Score": "0",
"body": "@ronag: Huh? *`If it was better then shared_ptr would probably have used it.`*? I don't follow that, sorry. A \"single heap allocation\" (and deallocation) is not exactly trivial -- I'm pretty darn sure that it can't be cheaper than a simple unlink operation. (Feel free to prove me wrong!) And in terms of storage, I'm pretty sure it's *also* less efficient because heap allocations also require metadata anyway. Do you have any reason to believe a heap allocation is more efficient in any respect?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T09:53:18.803",
"Id": "6827",
"Score": "0",
"body": "heap allocation is not more efficient, however, you will only do a single heap allocation for ALL smart pointers pointing to the SAME resource, and then just a counter inc/dec when creating/destroying smart pointer instances. While in your case you the creation of the first smart pointer might have less overhead, however you will have a higher overhead (6 assignments vs 1 inc/dec) creating/destroying copies if that smart pointer. So it's about having one \"large\" overhead vs many \"medium\" overheads."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T10:08:07.747",
"Id": "6828",
"Score": "0",
"body": "Also, if you use std::make_shared then there is no overhead for allocating the reference counter. Since it is allocated together with the actual resource in a single allocation. Which I believe means that the shared_ptr way is most efficient, unless I missed something?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T10:08:29.040",
"Id": "6829",
"Score": "0",
"body": "@ronag: Ah, but *you don't have to pass my handle by value*! You can still pass `auto_` by reference, and only copy it when necessary. That effectively removes all the link/unlink costs (which is already noise anyway), except in those cases where the scopes are escaped -- which can again be optimized away with RVO. So, really, these handles would have *zero* cost unless they actually *need* to be copied (which is probably to a heap object) -- and if they are, then this still (1) is not really happening more often than ref counting, and (2) has better spatial locality/is faster."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T10:19:26.707",
"Id": "6830",
"Score": "0",
"body": "Actually, if you use std::make_shared then I think shared_ptr is faster than your implementation in all cases. The construction only requires a single allocation + assignment. While yours requires 1 allocation + 2 assignments. Copying/destroying requires only reference inc/dec, while your requires 4 branches and 6 assignments. Also I don't think there is much of a difference in cache locality, since the reference counter is as likely to be in the cache (since its written to the cache in constructor), as your stack allocated variables. Although I might be wrong regarding the cache."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T10:26:42.833",
"Id": "6831",
"Score": "0",
"body": "@ronag: But don't forget that heap management is (1) nondeterministic, and (2) nontrivial. Point (1) means that `shared_ptr` is *amortized* constant-time, whereas `auto_` is *literally* constant-time. Point (2) means that `shared_ptr`'s heap allocation is adding pressure to the heap (and hence evicting more data from the cache which you don't need, regarding other heap blocks), which is going to affect everything you do afterward. But either way, *why would 4 branches and 6 assignments* make any difference in the first place? Shouldn't you pass them **by reference** anyway, if in a tight loop?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T10:42:04.020",
"Id": "6832",
"Score": "0",
"body": "With std::make_shared you will have the same heap management as in your case, you do a new T(), while make_shared will probably do something like new obj_with_ref_count<T>(), e.i the same heap management cost. The only case where your implementation is faster is when the pointer to the resource alrdy exists."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T10:42:14.673",
"Id": "6833",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/1280/discussion-between-ronag-and-mehrdad)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T16:54:58.273",
"Id": "6848",
"Score": "0",
"body": "custom_deallocator<foo>: you could type traits or some (overriden) global function (see Boost.Smart_ptr, intrusive_prt). The problem with HANDLE is that it is already a pointer (you do not want a HANDLE* pointer)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:24:10.010",
"Id": "6855",
"Score": "0",
"body": "@ronag: **[Are you sure](https://www.ideone.com/67NeA)** that my implementation is slower?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:41:53.453",
"Id": "6857",
"Score": "0",
"body": "I'm not familiar with ideone, I don't think its good for benchmarks since it probably doesn't optimize much, and your benchmark seems a bit wierd, it doesn't rly do any \"heap allocation\" test, since 99% of the time is spent in the bintree thing. I rewrote it and compiled it on MSVC 2010, http://pastebin.com/Wtpemseu, results: \"Allocation auto_: 4337ms\" \"Allocation shared_ptr: 4081ms\", \"Copying auto_: 3021ms\" \"Copying shared_ptr: 3160ms. Which means that shared_ptr is as fast or faster to allocate, and slower to copy (probably due to thread-safety, unsure)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:44:56.433",
"Id": "6858",
"Score": "0",
"body": "@ronag: I get the *same results* as I got on IDEone with my VC++ 2008 with full optimizations (I have no idea how you have a Visual Studio 2011, the latest is 2010...). Did you turn on optimizations in your own build?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:46:02.250",
"Id": "6859",
"Score": "0",
"body": "It should say MSVC 2010 ofc. I got the same results as you with your benchmark. However, I thought your benchmark was flawed (for the reasons I mentioned) and wrote another one (which I linked)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:01:13.507",
"Id": "6863",
"Score": "0",
"body": "@ronag: `it doesn't rly do any \"heap allocation\" test, since 99% of the time is spent in the bintree thing` -> I don't understand how that's \"flawed\". Why *should* it do any heap allocation? Isn't the *entire point* of my class to **avoid** heap allocations while copying?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:17:36.420",
"Id": "6869",
"Score": "0",
"body": "You argument as I understood from our previous discussion was, \"auto_\" is faster to create, while it doesn't matter that its slower to copy since you will pass it by reference\". The benchmark show just the opposite, shared_ptr is faster to create and slower to copy. Your benchmark is \"flawed\" since it tests the copying, which you stated previously was not of interest. I'm a bit confused..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:27:12.980",
"Id": "6870",
"Score": "0",
"body": "@ronag: *Sigh.... you *claimed* that it's slower to copy, and I told you it doesn't matter. I assumed you might be correct, and so I said you can pass it by reference, but in my benchmark, I showed you that's in fact not even the case. As for the *creation*, *[mine is also faster](https://www.ideone.com/WxwwL)* -- I have no idea what your benchmark was doing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:29:05.427",
"Id": "6871",
"Score": "0",
"body": "You cannot compare with shared_ptrs' copying since it has thread-safety overhead, which I mentioned above."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:30:26.063",
"Id": "6872",
"Score": "0",
"body": "@ronag: *Copying?* I thought you were talking about *creation*? Your argument is so confusing..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:30:30.527",
"Id": "6873",
"Score": "0",
"body": "I give up, this discussion is not getting much farther. Thanks for an interesting discussion so far. And good luck with your auto_ class."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T04:50:42.333",
"Id": "10726",
"Score": "1",
"body": "@Mehrdad: `shared_ptr` has one big advantage over your class. It is thread safe, which means that more than one thread can share the object being pointed to. Yours cannot do that. Being able to do that incurs significant overhead when fiddling with the reference count."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T07:22:47.860",
"Id": "10732",
"Score": "0",
"body": "@Omnifarious: Did you happen to read the *first sentence* of the second paragraph in my question (excluding the \"Edit\" section)?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T08:05:23.883",
"Id": "10733",
"Score": "0",
"body": "@Mehrdad - _shrug_ It's still a big advantage. Your disclaimer doesn't change that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T08:09:46.007",
"Id": "10734",
"Score": "0",
"body": "@Omnifarious: Yup, it is; I wasn't claiming otherwise. That's why I acknowledged the fact while posting this."
}
] |
[
{
"body": "<p>Implementing your own smart pointer is very hard please don't try.</p>\n\n<p>If it is just to try and learn then fine you may learn something but after practicing go back to one that has been tested and is know to work.</p>\n\n<p>20 seconds into looking Bug 1:</p>\n\n<pre><code>int main()\n{\n auto_<int> x;\n auto_<int> y(x);\n auto_<int> z(x);\n}\n</code></pre>\n\n<p>Problem caused by this line:</p>\n\n<pre><code>auto_(const auto_<T> &o)\n : pValue(o.pValue)\n , pPrev(&o)\n , pNext(NULL)\n{\n o.pNext = this; // Here you are overwriting x.pNext when building z\n} // It may or may not cause a bug but it was definitely\n // not what you intended to do.\n</code></pre>\n\n<p>You now have</p>\n\n<pre><code>pNext List\n[X] -> [Z] -> | Y/Z point at nothing\n [Y] -> | X points at Z\n\npPrev List\n[Y] -> [X] -> | Y/Z point at X\n[Z] ----^ X points at nothing.\n\n One assumes you are trying to create a circular list!\n</code></pre>\n\n<h3>Don't use hungarian notation</h3>\n\n<pre><code>pValue\n</code></pre>\n\n<p>Do you really want to bind your object to always using pointers?<br>\nJust use logical names for the members try not to encode type information into the name of the member it already has that information in its type.</p>\n\n<h3>Style Tip</h3>\n\n<p>Don;t do this:</p>\n\n<pre><code> const auto_<T> *const pPrev = this->pPrev, *const pNext = this->pNext;\n</code></pre>\n\n<p>It really hard to read. You are doing complex enough stuff try and make it easy to read</p>\n\n<pre><code> auto_<T> const* const pPrev = this->pPrev\n auto_<T> const* const pNext = this->pNext;\n</code></pre>\n\n<h3>Don't do pointless work</h3>\n\n<pre><code> this->pPrev = this->pNext = NULL;\n this->pValue = NULL;\n</code></pre>\n\n<p>This does nothing. This object is going to be destroyed. Therefore these variables do not exist after the destructor exists. So little point in playing with their values just before destruction.</p>\n\n<h3>Don't manually call the destructor</h3>\n\n<pre><code> this->~auto_();\n</code></pre>\n\n<p>Nobody expects people to do this. Its just confusing. Move the code in the destructor into another method and call that.</p>\n\n<h3>Broken link</h3>\n\n<p>If sombody inserts a NULL pointer into your smart pointer you are asking for trouble when they de-reference it.</p>\n\n<pre><code>auto_<int> x(NULL); // valid constructor\n</code></pre>\n\n<p>This is going to blow up</p>\n\n<pre><code>operator T&() /*also const version*/ { return *this->pValue; }\n</code></pre>\n\n<p>You either need to check the ptr on construction (to make sure it is never NULL) or if you allow NULL pointers then you need to check when the object is used.</p>\n\n<h3>Specialization</h3>\n\n<p>To avoid repeating yourself allow your code to be specialized by a second template parameter that understands how to reclaim the resources of different types. The default version just calls delete but this allows you to use specialize it for handles etc.</p>\n\n<h3>Circular lists are easier with no NULL pointers.</h3>\n\n<pre><code>template<typename T>\nstruct Deleter\n{\n void operator()(T* ptr) const { delete ptr;}\n};\n\ntemplate<typename T, typename D = Deleter<T> >\nclass my_auto\n{\n T *value;\n mutable const my_auto<T>* prev;\n mutable const my_auto<T>* next;\n\n public:\n // set up the chain to be circular pointing at just itself.\n // This way next/prev will never be NULL and we don't need to test\n my_auto() : value(new T()), prev(this), next(this) { }\n my_auto(T *value) : value(value), prev(this), next(this) { if (value == 0) throw int(1);}\n my_auto(const T &v) : value(new T(v)), prev(this), next(this) { }\n\n // insertInto() will do that appropriate set up.\n // We are currently not in a chain and have no value to release.\n my_auto(const my_auto<T> &o)\n {\n insertInto(o);\n }\n\n my_auto<T>& operator=(const my_auto<T>& other)\n {\n // Check for assignment to self\n if (this != &other)\n {\n testAndDestroy();\n removeFromChain();\n insertInto(other);\n }\n return *this;\n }\n\n ~my_auto()\n {\n testAndDestroy();\n removeFromChain();\n }\n\n private:\n // If next == this then this is the only node in the chain\n // So we destroy the data portion.\n void testAndDestroy()\n {\n if (next == this)\n {\n D deleter;\n deleter(value);\n }\n }\n // Unlink this node from the chain.\n // If we are the only link in the chain it still works\n // we just remain linked to ourselves.\n void removeFromChain()\n {\n // Remove this node from the chain\n prev->next = next;\n next->prev = prev;\n }\n // Insert into another chain.\n // Assumes that we are not part of another chain\n // and that our data has already been released as required.\n void insertInto(const my_auto<T>& other)\n {\n value = other.value;\n\n next = other.next;\n other.next.prev = this;\n\n prev = other;\n other.next = this;\n }\n};\n</code></pre>\n\n<p>If you want to use a non circular list (then you need to fix the constructor)</p>\n\n<pre><code>auto_(const auto_<T> &o)\n : pValue(o.pValue)\n , pPrev(&o)\n , pNext(o.pNext) // Fix this line\n{\n if (o.pNext) { o.pNext.prev = this;} // Add this line\n o.pNext = this;\n}\n// Your code assumes the node is always added to the end of the list\n// You can not guarantee this. So you need to take account of being\n// inserted into the middle.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:44:14.550",
"Id": "6800",
"Score": "3",
"body": "I second \"Implementing your own smart pointer is very hard please don't try.\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:44:33.307",
"Id": "6801",
"Score": "0",
"body": "Ah, I think you're right about `pNext(NULL)` -- I think it should have said `pNext(other.pNext)` instead; thanks for catching that! Regarding Hungarian notation: I don't *normally* use it, but I make an exception for pointers... I feel like it makes more sense, since `pValue` *has* to be a pointer (since my `auto_` is wrapping pointers)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:54:05.787",
"Id": "6803",
"Score": "0",
"body": "@ronag: I feel that's a depressing answer. \"You can't write good code, so don't try.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:55:29.577",
"Id": "6804",
"Score": "0",
"body": "@Mehrdad: Even with that fix your code is wrong. You never update enough pointer to maintain the list correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:59:10.133",
"Id": "6805",
"Score": "0",
"body": "@Mehrdad: That is not what he is saying. smart pointers are very very hard to write correctly. Even when you fix the obvious stuff I have pointed out you are still going to get it wrong (the non obvious stuff is hard and you are not skilled enough to get the obvious stuff). Don't feel bad it took ten years (and thousands of people looking) to get the standard smart pointers to work in all situations. So don't expect to write your own smart pointers and expect them to work in a single try. They will fail when you start to do anything non trivial. **Use it to learn but not in real code**."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T00:41:07.873",
"Id": "6808",
"Score": "0",
"body": "@Tux-D: I'm still confused at what you mean by your statement, *\"You never update enough pointer to maintain the list correctly.\"*... What do you mean by \"enough pointer\"? What exactly am I missing?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T05:52:49.743",
"Id": "6813",
"Score": "0",
"body": "@Mehrdad: You are trying to maintain a list of smart pointers that all point at the same resource. You are not doing this **`incorrectly`**. In both the constructor and the assignment operator you are doing it incorrectly. I have provided an implementation that maintains the list correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T06:02:47.027",
"Id": "6814",
"Score": "0",
"body": "@Tux-D: Thanks for the \"correct\" implementation, but I'm still confused at why *mine* is wrong. Is the only difference in whether or not the pointers can be `NULL`? If so, why is that considered to be a problem? (Isn't dereferencing a pointer undefined *anyway*?) If not, then what is the issue? I feel like I've missed it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T17:01:58.757",
"Id": "6817",
"Score": "0",
"body": "OK. Re-read your code. It now looks fine, sorry I was obviously rushing the review yesterday."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T03:47:16.910",
"Id": "6825",
"Score": "0",
"body": "@Tux-D: Cool, thanks for taking a look at it! If there is no issue with the `NULL`s then I think it might not be a bad idea to remove it from the answer, since it might be misleading for whomever who sees this later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T16:31:10.380",
"Id": "6847",
"Score": "0",
"body": "@Mehrdad: I already did. It was just the assignment operator I made a mistake on. The constructor is still broken. The technique for not using NULL is just a well know better technique for this situation (you want to use a circular list hence no NULL(s)). It makes the code easier to write/read. (You are not the first to implement smart pointers using a list)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:57:06.057",
"Id": "6861",
"Score": "0",
"body": "@Tux-D: Then I *still* don't understand what's \"broken\" about my constructor. I thought changing `pNext(NULL)` to `pNext(other.pNext)` fixes the issue, doesn't it? Which constructor are you referring to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:06:02.683",
"Id": "6865",
"Score": "0",
"body": "@Mehrdad: See new edit to show fix for constructor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:09:06.037",
"Id": "6866",
"Score": "0",
"body": "@Tux-D: Oooooooh of *course*! thanks a lot for pointing it out! +1 :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:12:17.093",
"Id": "6867",
"Score": "0",
"body": "@Mehrdad: Rule of thumb. Doubly linked lists have four pointers that need to be modified to insert an item (always count and make sure you have tried to update four pointers)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:13:29.993",
"Id": "6868",
"Score": "0",
"body": "@Tux-D: Yeah, I \"know\" that but I still mess up the last link every single time. xD"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T00:32:35.593",
"Id": "6930",
"Score": "1",
"body": "@Tux-D Why is the destructor virtual ? Well it helps if someone wants to inherit my_auto, then it is useful. For me, removing the virtual will make people stop inheriting this class w/o any necessity."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T00:58:20.737",
"Id": "6932",
"Score": "0",
"body": "@Jagannath: Bug. It should probably not be there. Thanks. See smart pointers are very hard to write well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T02:02:44.730",
"Id": "7186",
"Score": "0",
"body": "Regarding the manual destructor call, being confusing is not the only problem. An object's lifetime ends when the destructor is called. After that the object is no more and everything you try to do with it is undefined behaviour."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T08:11:03.553",
"Id": "10735",
"Score": "0",
"body": "Just thought I'd mention -- I've been using this extensively (after a few tweaks of course) and it's been working beautifully so far. It's great (and fast) to not have to worry about heap allocations. :)"
}
],
"meta_data": {
"CommentCount": "20",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:33:33.637",
"Id": "4556",
"ParentId": "4550",
"Score": "12"
}
},
{
"body": "<p>You post a link to benchmark results, which are very interesting. They show your pointer class to be significantly faster than the boost <code>shared_ptr</code> class.</p>\n\n<p>There are a few critiques here. Your benchmarking technique is a bit crude, and it's very heavily oriented towards making copies of the pointer. While most pointers are copied a bit more than they're created, the ratio is more like 5 to 1, not 16 million to 1.</p>\n\n<p>But, of course, that makes your benchmark all the more interesting since <code>shared_ptr</code>s big weakness as compared to yours is the requirement of allocating memory when the pointer is first created. Of course, using <code>make_shared</code> gets rid of this overhead and, as a bonus, increases locality of reference since the reference count and data pointed at are close to each other in memory.</p>\n\n<p>I ran this benchmark on a Linux Opteron based system with Boost 1.47 and got nearly identical results to yours.</p>\n\n<p>Then I transformed your program slightly. C++11 has a <code>shared_ptr</code> as part of the standard library. I changed your program to use this instead and compiled for C++11.</p>\n\n<p>After this, the performance of your class was only slightly better than the standard library class. 960ms vs. 800ms.</p>\n\n<p>I then recompiled with the <code>-pthread</code> option and the performance of the standard library <code>shared_ptr</code> dropped drastically. 1660ms vs 820ms.</p>\n\n<p>This confirms my theory that Boost's poor performance is very likely due to thread safety. Changing a reference count in a thread-safe way is much slower because the CPU is force to use atomic memory operations.</p>\n\n<p>Anyway, the difference between your class and the standard library class is so small in a non-threaded context that I wouldn't feel it was worth it to use your special class vs. one that was part of the standard library.</p>\n\n<p>If you want to re-create the benchmark I ran, change these lines in your benchmark:</p>\n\n<pre><code>#include <boost/shared_ptr.hpp>\n#include <boost/make_shared.hpp>\nusing namespace boost;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>#include <memory>\nusing ::std::shared_ptr;\nusing ::std::make_shared;\n</code></pre>\n\n<p>And compile with a compiler that supports C++11. g++ can be made to support C++11 by passing the <code>-std=gnu++0x</code> or <code>-std=c++0x</code> options. By default the GNU compiler will compile in single-threaded mode. In order to get it to compile programs that will run properly with multiple threads, the <code>-pthread</code> option needs to be passed to both the compiler and linker.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T09:33:16.697",
"Id": "10742",
"Score": "0",
"body": "Oh lol, so it really wasn't different. xD I just tried it on MSVC 2010 (it only comes with a multithreaded library -- but that's what I'm using for my projects) and got `610 ms` vs `1595 ms`. So I guess it's a factor of ~3 difference for MSVC projects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T14:51:44.890",
"Id": "10750",
"Score": "0",
"body": "@Mehrdad: _nod_ Apparently so. Do you realize why the multi-threaded implementation is so much slower?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T19:54:51.687",
"Id": "10786",
"Score": "0",
"body": "lol, of course; I knew it before I posted this."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-15T06:07:58.450",
"Id": "6859",
"ParentId": "4550",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4556",
"CommentCount": "27",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T19:54:05.247",
"Id": "4550",
"Score": "6",
"Tags": [
"c++",
"pointers"
],
"Title": "shared_ptr implementation"
}
|
4550
|
<p>I am trying to get a row if it has the desired specific value, otherwise get the first or default:</p>
<pre><code>dr =
(from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value")
where
pavTable.Field<int>("FKI_ProductAttribute") == Value2 &&
avTable.Field<string>("Name") == "Specific Value"
select avTable).FirstOrDefault() ??
(from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value")
where pavTable.Field<int>("FKI_ProductAttribute") == Value2
select avTable).FirstOrDefault();
</code></pre>
<p>This smells. Is there a better way to do this?</p>
<p>I want to do something like this:</p>
<pre><code>var dt =
(from avTable in DAL.DataStore.DSet.Tables["Values1"].AsEnumerable()
join pavTable in DAL.DataStore.DSet.Tables["Values2"].AsEnumerable()
on avTable.Field<int>("PK") equals pavTable.Field<int>("FK_Value")
where
pavTable.Field<int>("FKI_ProductAttribute") == Value2 &&
avTable.Field<string>("Name") == "Specific Value"
select avTable)
DataRow dr = dt.Select("PK = Specified value");
If(dr==null) dr = dt.FirstOrDefault();
</code></pre>
<p>and then do a select based on a specified value. If that is <code>null</code>, then grab the first or default. This seems to be more DRY, but is it more or less efficient?. Also, I have a hard time doing a select on the dt based on the specific value (lack of Linq expertise and Google prowess to find the answer I am looking for).</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T20:50:40.680",
"Id": "6792",
"Score": "0",
"body": "This is the way `FirstOrDefault` is supposed to work ...? I don't see anything that 'smells' ...unless there is some optimization to the query. But nothing I can really see ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:10:12.307",
"Id": "6793",
"Score": "0",
"body": "It just doesn't seem DRY to me, so I clarified what I am looking to do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T23:04:27.720",
"Id": "6806",
"Score": "0",
"body": "*'But nothing I can really see ...'* ...and then I put my glasses on ..."
}
] |
[
{
"body": "<p>Will this work?</p>\n\n<pre><code>var dr= (from avTable in DAL.DataStore.DSet.Tables[\"Values1\"].AsEnumerable()\n join pavTable in DAL.DataStore.DSet.Tables[\"Values2\"].AsEnumerable()\n on avTable.Field<int>(\"PK\") equals pavTable.Field<int>(\"FK_Value\");\n where\n (pavTable.Field<int>(\"FKI_ProductAttribute\") == Value2 &&\n avTable.Field<string>(\"Name\") == \"Specific Value\") ||\n pavTable.Field<int>(\"FKI_ProductAttribute\") == Value2\n select avTable)\n .FirstOrDefault();\n</code></pre>\n\n<p>I don't really have a way to test this, but I believe if the first part of the <code>where</code> clause criteria is met, the part after the <code>||</code> is skipped. If the first part returns no record then the second part is evaluated and will return a result ...or null.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:30:06.853",
"Id": "4555",
"ParentId": "4552",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4555",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T20:13:44.690",
"Id": "4552",
"Score": "3",
"Tags": [
"c#",
".net",
"linq"
],
"Title": "Selecting a specific row with a desired value"
}
|
4552
|
<p>I have been making this FSM today. However, as this is probably the biggest practical program I have ever written in CL, I don't know if there are some things that could be improved, or if using a closure is the best thing here.</p>
<p>Any feedback is appreciated.</p>
<pre><code>;;; States: -- EnterMineAndDigForNugget
;;; -- QuenchThirst
;;; -- GoHomeAndSleepTillRested
;;; -- VisitBankAndDepositGold
(defmacro while (test &rest body)
`(do ()
((not ,test))
,@body))
(defmacro enter (state)
`(setf state ,state))
(defun make-miner ()
(let ((wealth 0)
(thirst 0)
(rested 0)
(state 'EnterMineAndDigForNugget))
(list
(defun EnterMineAndDigForNugget ()
; (setf location 'mine)
(format t "~&Diggin' up gold!")
(incf wealth)
(incf thirst)
(cond ((>= thirst 7) (enter 'QuenchThirst))
(t (enter 'VisitBankAndDepositGold))))
(defun QuenchThirst ()
(format t "~&Drinkin' old good whiskey")
(setf thirst 0)
(enter 'EnterMineAndDigForNugget))
(defun VisitBankAndDepositGold ()
(format t "~&All this gold ought to be stored somewhere!")
(incf wealth)
(cond ((>= wealth 5) (progn
(format t "~&Too much gold for today, let's sleep!")
(enter 'GoHomeAndSleepTillRested)
(setf wealth 0)))
(t (EnterMineAndDigForNugget))))
(defun GoHomeAndSleepTillRested ()
(while (<= rested 3)
(format t "~&Sleepin'")
(incf rested))
(enter 'EnterMineAndDigForNugget)
(setf rested 0))
(defun controller ()
(dotimes (n 30)
(cond ((equal state 'QuenchThirst) (QuenchThirst))
((equal state 'VisitBankAndDepositGold) (VisitBankAndDepositGold))
((equal state 'GoHomeAndSleepTillRested) (GoHomeAndSleepTillRested))
((equal state 'EnterMineAndDigForNugget) (EnterMineAndDigForNugget))))))))
</code></pre>
<p><strong>EDIT</strong></p>
<p>I have applied all the suggested changes but for the flet/labels one. Everything worked fine until I changed the one of "set the state to the next function". Now, the macro <code>enter</code> doesn't seem to be ever called.</p>
<p>This is the current state of the code, with the required code to make it work</p>
<pre><code>;;; States: -- enter-mine-and-dig-for-nugget
;;; -- quench-thirst
;;; -- go-home-and-sleep-till-rested
;;; -- visit-bank-and-deposit-gold
(defmacro enter (state)
`(setf state ,state))
(defun make-miner ()
(let ((wealth 0)
(thirst 0)
(rested 0)
(state #'enter-mine-and-dig-for-nugget))
(list
(defun enter-mine-and-dig-for-nugget ()
(format t "~&Diggin' up gold!")
(incf wealth)
(incf thirst)
(if (>= thirst 7)
(enter #'quench-thirst)
(enter #'visit-bank-and-deposit-gold)))
(defun quench-thirst ()
(format t "~&Drinkin' old good whiskey")
(setf thirst 0)
(enter #'enter-mine-and-dig-for-nugget))
(defun visit-bank-and-deposit-gold ()
(format t "~&All this gold ought to be stored somewhere!")
(incf wealth)
(if (>= wealth 5)
(progn
(format t "~&Too much gold for today, let's sleep!")
(enter #'go-home-and-sleep-till-rested)
(setf wealth 0))
(enter #'enter-mine-and-dig-for-nugget)))
(defun go-home-and-sleep-till-rested ()
(dotimes (i 4)
(format t "~&Sleepin'"))
(enter #'enter-mine-and-dig-for-nugget))
(defun controller ()
(dotimes (n 30)
(funcall state))))))
(let ((a (make-miner)))
(funcall (fifth a)))
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T00:41:41.477",
"Id": "6809",
"Score": "0",
"body": "The code tag doesn't keep all the formatting, but in my real code it is a good one"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T07:49:29.760",
"Id": "6816",
"Score": "0",
"body": "Because there is no code tag. Just indent 4 spaces (the button or Ctrl+K) and text will be formatted as code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T21:36:23.377",
"Id": "6819",
"Score": "0",
"body": "well, by code tag I meant the 4-indentation. But it still shows 4 lines slightly out of place"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-10T01:08:34.667",
"Id": "7054",
"Score": "0",
"body": "THe nested DEFUN is definitely wrong. You need to get rid of that. The indenting also looks wrong. Let the editor indent the code, add four spaces in front of the each line and paste that into the text field."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-10T09:06:49.240",
"Id": "7057",
"Score": "0",
"body": "I want to get rid of the DEFUN, but I need to make sure to change one thing at a time, to make sure everything still works. Also, the indentation is managed by EMACS+SLIME, but somehow I can't make it look right here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-28T22:40:21.547",
"Id": "45876",
"Score": "0",
"body": "I think you mean `(format t \"~&Drinkin' good old whiskey\")` :)"
}
] |
[
{
"body": "<p>Can you comment on what the goal/output of this program is supposed to be? How you're supposed to use it? It looks like <code>make-miner</code> just returns a list of functions, which doesn't sound useful on its own.</p>\n\n<p>Some preliminary comments:</p>\n\n<hr>\n\n<p>You can cut the <code>while</code> macro. CL provides you with many iteration constructs (<code>do</code>, <code>dotimes</code>, <code>dolist</code>, <code>mapcar</code> and friends, and <code>loop</code>). That last one can do what you want here (and <a href=\"http://www.ai.sri.com/pkarp/loop.html\" rel=\"nofollow\">lots</a> more <a href=\"http://www.gigamonkeys.com/book/loop-for-black-belts.html\" rel=\"nofollow\">if you feel</a> like <a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_loop.htm#loop\" rel=\"nofollow\">reading</a>);</p>\n\n<pre><code>(loop while (<= rested 3)\n do (format t \"~&Sleepin'\")\n do (incf rested))\n</code></pre>\n\n<p>Since you reset <code>rested</code> to 0 later in the same block anyway, you could also just do</p>\n\n<pre><code>(loop repeat 4 do (format t \"~&Sleepin'\"))\n</code></pre>\n\n<p>or</p>\n\n<pre><code>(dotimes (i 4) do (format t \"~&Sleepin'\"))\n</code></pre>\n\n<hr>\n\n<p>Common Lisp convention is to use <code>dashed-lower-case-names</code> rather than <code>CamelCaseNames</code>.</p>\n\n<hr>\n\n<p><code>cond</code> clauses don't need an explicit <code>progn</code>, but read on first</p>\n\n<hr>\n\n<p>Wherever you've got <code>(cond ([test] [clause]) (t [clause]))</code>, you can instead write <code>(if [test] [clause] [clause])</code>. For example,</p>\n\n<pre><code>(if (>= wealth 5) \n (progn \n (format t \"~&Too much gold for today, let's sleep!\")\n (enter 'GoHomeAndSleepTillRested)\n (setf wealth 0))\n (EnterMineAndDigForNugget))\n</code></pre>\n\n<p>You do actually need the <code>progn</code> here. In general, you should use <code>cond</code> where you'd normally use <code>if</code>/<code>elseif</code>/<code>else</code> in other languages (<a href=\"http://www.lispworks.com/documentation/HyperSpec/Body/m_case_.htm#case\" rel=\"nofollow\"><code>case</code></a> is actually the <code>switch</code> analogue), and use <code>if</code>/<code>when</code>/<code>unless</code> where you can to signal intent.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T22:56:36.830",
"Id": "6820",
"Score": "0",
"body": "Thanks, I'll read the links you provided and correct the code. Also, I'm aware of the naming convention, and even use it myself, but I was following an AI book (Programming AI by example), so I kept it the way it appeared in the book"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T02:57:51.257",
"Id": "4558",
"ParentId": "4557",
"Score": "3"
}
},
{
"body": "<p><strong>DEFUN</strong></p>\n\n<p>The most basic mistake in your code is that <code>DEFUN</code> is not correct for nested functions. <code>DEFUN</code> is a top-level macro, defining a top-level function and should be used in top-level forms.</p>\n\n<p>Nested functions are defined in Common Lisp with <code>FLET</code> and <code>LABELS</code>. <code>LABELS</code> is used for recursive sub-functions.</p>\n\n<p><strong>Naming</strong></p>\n\n<p>Symbols like <code>FooBarBaz</code> are not use in Common Lisp. By default Common Lisp upcases all names internally, so the case information gets lost.</p>\n\n<p>Usually we write <code>foo-bar-baz</code>.</p>\n\n<p><strong>Checking symbols</strong></p>\n\n<p>Use <code>CASE</code> (or <code>ECASE</code>) instead of <code>(cond ((equal foo 'bar) ...))</code>.</p>\n\n<p><strong>Architecture</strong></p>\n\n<p>Usually I would write that piece of code using CLOS, the Common Lisp Object System.</p>\n\n<p>In a more functional style I would propose the following:</p>\n\n<ul>\n<li><p>use <code>LABELS</code> for the local procedures.</p></li>\n<li><p>set the state to the next function. A function is written as <code>(function my-function)</code> or <code>#'my-function</code>.</p></li>\n<li><p>the controller just calls the next function from the state variable. It is not necessary to list all cases.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T23:09:00.463",
"Id": "7051",
"Score": "0",
"body": "Edited OP, need some help"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-11T22:15:04.313",
"Id": "7097",
"Score": "0",
"body": "Both answers are very good. I chose yours because it was the one I found more helpful"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T01:54:49.650",
"Id": "45878",
"Score": "0",
"body": "What does 'DEFUN is not thought for nested functions' mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-07-29T06:24:28.967",
"Id": "45890",
"Score": "2",
"body": "@James McMahon: DEFUN inside DEFUN is not a useful concept in Lisp. Local functions are defined by FLET or LABELS."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T12:44:44.670",
"Id": "4576",
"ParentId": "4557",
"Score": "5"
}
},
{
"body": "<p>As of your second edit. </p>\n\n<p>Ok, yeah now that you've shown how this is supposed to be called, CLOS is definitely the way to go here. Representing an object as a list of closures is less than optimal, if for no other reason that you then need to resort to <code>(funcall (fifth a-miner))</code> in order to actually start it up (and consequently change that call every time you add a new \"method\" to your miner). There's also the problem that each \"<code>miner</code>\" you instantiate carries around its own independent functions (so good luck changing behavior at runtime or using any kind of inheritance for more complex modeling).</p>\n\n<p>I suggest you take a look at <a href=\"http://cl-cookbook.sourceforge.net/clos-tutorial/index.html\" rel=\"nofollow\">this CLOS tutorial</a> as well as chapters <a href=\"http://www.gigamonkeys.com/book/object-reorientation-generic-functions.html\" rel=\"nofollow\">16</a> and <a href=\"http://www.gigamonkeys.com/book/object-reorientation-classes.html\" rel=\"nofollow\">17</a> of <a href=\"http://www.gigamonkeys.com/book/\" rel=\"nofollow\">Practical Common Lisp</a></p>\n\n<p>Here's a transliteration of your program using CLOS to act as a learning aid:</p>\n\n<pre><code>(defpackage :cl-miner (:use :cl))\n(in-package :cl-miner)\n\n(defclass miner ()\n ((wealth :accessor wealth :initarg :wealth :initform 0)\n (thirst :accessor thirst :initarg :thirst :initform 0)\n (rested :accessor rested :initarg :rested :initform 0)\n (state :accessor state :initarg :state :initform #'enter-mine-and-dig-for-nugget)))\n\n;;;;;;;;;;;;;;; shortcuts\n(defmethod enter ((m miner) a-state)\n (setf (state m) a-state))\n\n(defun make-miner ()\n (make-instance 'miner))\n\n;;;;;;;;;;;;;;; miner methods\n(defmethod enter-mine-and-dig-for-nugget ((m miner))\n (format t \"~&Diggin' up gold!\")\n (incf (wealth m))\n (incf (thirst m))\n (if (>= (thirst m) 7)\n (enter m #'quench-thirst)\n (enter m #'visit-bank-and-deposit-gold)))\n\n(defmethod quench-thirst ((m miner))\n (format t \"~&Drinkin' old good whiskey\")\n (setf (thirst m) 0)\n (enter m #'enter-mine-and-dig-for-nugget))\n\n(defmethod visit-bank-and-deposit-gold ((m miner))\n (format t \"~&All this gold ought to be stored somewhere!\")\n (incf (wealth m))\n (if (>= (wealth m) 5)\n (progn \n (format t \"~&Too much gold for today, let's sleep!\")\n (enter m #'go-home-and-sleep-till-rested)\n (setf (wealth m) 0))\n (enter m #'enter-mine-and-dig-for-nugget)))\n\n(defmethod go-home-and-sleep-till-rested ((m miner))\n (dotimes (i 4)\n (format t \"~&Sleepin'\"))\n (enter m #'enter-mine-and-dig-for-nugget))\n\n(defmethod work ((m miner))\n (dotimes (n 30)\n (funcall (state m) m)))\n\n(let ((a (make-miner)))\n (work a))\n</code></pre>\n\n<p>I was going to compare them for performance, but I couldn't get your revised version to run (it gave me an \"unhandled memory fault\" error which is something I haven't seen before).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-13T16:03:08.533",
"Id": "4798",
"ParentId": "4557",
"Score": "4"
}
},
{
"body": "<p>If your FSM hardly ever changes, and performance is your primary concern, you can't beat this.</p>\n\n<p>Translate it into simple structured code, in a <code>progn</code> or whatever, which you can do with any FSM.\nHere's the \"C-ish\" equivalent:</p>\n\n<pre><code>w = th = 0;\nwhile(T){\n w++; th++;\n // Diggin' up gold!\n if (th >= 7){\n // Drinkin' old good whiskey\n th = 0;\n } else {\n // all this gold ought to be stored somewhere\n if (w >= 5){\n // Too much gold for today, let's sleep!\n w = 0;\n for (r = 0; r <= 3; r++){\n // sleepin'\n }\n }\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T23:59:15.947",
"Id": "4828",
"ParentId": "4557",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4576",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T00:40:30.013",
"Id": "4557",
"Score": "6",
"Tags": [
"lisp",
"common-lisp"
],
"Title": "Finite State Machine code"
}
|
4557
|
<p>I am trying to learn graphs and implement in code. Can you please review my code and give me feedback?</p>
<p><a href="https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/graphs/graph.cpp" rel="nofollow">Source code</a></p>
<pre><code>#include <iostream>
using namespace std;
#include <list>
#include <queue>
#include <map>
</code></pre>
<h3>Class Edge</h3>
<pre><code>class Edge
{
public:
int dest;
int weight;
Edge(int dest) : dest(dest), weight(0) {}
};
</code></pre>
<h3>Class Vertex</h3>
<pre><code>class Vertex
{
public:
int orig;
std::list<Edge> adjList;
bool visited;
int indegree;
Vertex() : orig(-1), visited(false), indegree(0) {}
Vertex(int v) : orig(v), visited(false), indegree(0) {}
friend bool operator==(const Vertex & v, int data);
friend std::ostream & operator<<(std::ostream & os, const Vertex & v);
};
bool operator==(const Vertex & v, int data)
{
if (v.orig == data) return true;
return false;
}
std::ostream & operator<<(std::ostream & os, const Vertex & v)
{
os << v.orig << ":";
std::list<Edge>::const_iterator iter = v.adjList.begin();
for(; iter != v.adjList.end(); ++iter)
{
os << " " << iter->dest;
}
return os;
}
</code></pre>
<h3>Class Graph</h3>
<pre><code>class Graph
{
private:
typedef std::map<int, Vertex> VertexMap;
typedef std::map<int, Vertex>::iterator VertexIterator;
typedef std::map<int, Vertex>::const_iterator VertexConstIterator;
bool visit(int v, std::list<int> & sortedList);
VertexMap vertices;
public:
void addVertex(int v);
void addEdge(int v1, int v2);
void print();
void BreadthFirstTour(int v);
void DepthFirstTour(int v);
void TopologicalSort();
void resetStates();
};
void Graph::addVertex(int v)
{
vertices.insert( std::make_pair(v, Vertex(v)) );
}
void Graph::addEdge(int v1, int v2)
{
VertexIterator iter = vertices.find(v1);
if (iter != vertices.end())
{
Edge edge(v2);
iter->second.adjList.push_back(edge);
}
iter = vertices.find(v2);
iter->second.indegree++;
}
void Graph::print()
{
VertexConstIterator iter = vertices.begin();
for (; iter != vertices.end(); ++iter)
{
cout << iter->second << "\n";
}
}
void Graph::BreadthFirstTour(int v)
{
cout << "BFS BEGIN\n";
std::queue<int> q;
VertexConstIterator iter = vertices.find(v);
if (iter != vertices.end())
{
q.push(iter->first);
}
else
{
cout << "BFS END\n";
return;
}
VertexIterator iter1;
while (!q.empty())
{
int vtx = q.front();
q.pop();
Vertex & v = vertices[vtx];
if (v.visited == false )
{
v.visited = true;
cout << v.orig << " ";
std::list<Edge>::const_iterator iter = v.adjList.begin();
while (iter != v.adjList.end())
{
//cout << "dest " << iter->dest << endl;
VertexConstIterator citer = vertices.find(iter->dest);
if (citer != vertices.end())
{
q.push(citer->first);
//cout << "pushing " << citer->orig << endl;
}
++iter;
}
}
}
cout << "\nBFS END" << endl;
resetStates();
}
void Graph::resetStates()
{
VertexIterator iter = vertices.begin();
for (; iter != vertices.end(); ++iter)
{
iter->second.visited = false;
}
}
void Graph::DepthFirstTour(int v)
{
VertexIterator iter = vertices.find(v);
if (iter != vertices.end())
{
if (iter->second.visited == false)
{
iter->second.visited = true;
std::list<Edge>::iterator liter = iter->second.adjList.begin();
for (; liter != iter->second.adjList.end(); ++liter)
{
DepthFirstTour(liter->dest);
}
cout << iter->second.orig << " ";
}
}
}
void Graph::TopologicalSort()
{
VertexConstIterator iter = vertices.begin();
std::list<int> sortedList;
bool cycle = false;
for (; iter != vertices.end(); ++iter)
{
if (iter->second.indegree == 0)
{
if (!visit(iter->first, sortedList))
{
cycle = true;
break;
}
}
}
if (cycle || sortedList.size() != vertices.size())
{
cout << "CYCLE";
return;
}
std::list<int>::const_iterator liter = sortedList.begin();
for (; liter != sortedList.end(); ++liter)
{
cout << *liter << " ";
}
}
bool Graph::visit(int v, std::list<int> & sortedList)
{
VertexIterator iter = vertices.find(v);
if (iter != vertices.end())
{
if (iter->second.visited == false)
{
iter->second.visited = true;
std::list<Edge>::const_iterator liter = iter->second.adjList.begin();
for (; liter != iter->second.adjList.end(); ++liter)
{
if (!visit(liter->dest, sortedList))
{
return false;
}
}
sortedList.push_front(iter->first);
}
else
{
return false;
}
}
return true;
}
</code></pre>
<h3>main()</h3>
<pre><code>int main()
{
Graph g;
g.addVertex(1);
g.addVertex(2);
g.addVertex(3);
g.addVertex(4);
g.addVertex(5);
g.addVertex(6);
g.addVertex(7);
g.addVertex(8);
g.addEdge(1,2);
g.addEdge(1,3);
g.addEdge(2,4);
g.addEdge(2,5);
g.addEdge(3,6);
g.addEdge(3,7);
//g.addEdge(5,8); //disjoint node 8
//g.addEdge(6,3); //this is forming cycle
g.print();
g.BreadthFirstTour(1);
cout << "DFS START\n";
g.DepthFirstTour(1);
g.resetStates();
cout << "\nDFS END" << endl;
cout << "TOPOLOGICAL SORT START\n";
g.TopologicalSort();
g.resetStates();
cout << "\nTOPOLOGICAL SORT END\n";
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Don't put using namespace std<br>\nbefore including other header files<br>\nIf you must do it then put it after all the includes. But preferably don't use it at all.</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\n#include <list>\n#include <queue>\n#include <map>\n</code></pre>\n\n<p>Do you really want all the members of Vertix to be public?</p>\n\n<pre><code>public:\nint orig;\nstd::list<Edge> adjList;\nbool visited;\nint indegree;\n</code></pre>\n\n<p>Equality test is correct:</p>\n\n<pre><code>if (v.orig == data) return true;\nreturn false;\n</code></pre>\n\n<p>But it is easier to read when written like this:</p>\n\n<pre><code>return v.orig == data;\n</code></pre>\n\n<p>When you have an operator << it is usually a good idea to implement >> (in the long run you probably will). Thus when writing your output stream you want to write it in a way that makes reading it back in easy. So when you class contains things like vectors it is useful to prefix them with a count of elements (not a termination marker). Also any sub elements should be printed with their own stream operator << so you should probably write one for Edge as well.</p>\n\n<p>Typedef the iterators in terms of the container. That way if you change the container you only need to make one change (not a cascade of changes).</p>\n\n<pre><code>typedef std::map<int, Vertex> VertexMap;\ntypedef std::map<int, Vertex>::iterator VertexIterator;\ntypedef std::map<int, Vertex>::const_iterator VertexConstIterator;\n</code></pre>\n\n<p>could be written as:</p>\n\n<pre><code>typedef std::map<int, Vertex> VertexMap;\ntypedef VertexMap::iterator VertexIterator;\ntypedef VertexMap::const_iterator VertexConstIterator;\n // ^^^^^^^^^ Use the container type we just defined.\n</code></pre>\n\n<p>Here is where you public members are going to haunt you.</p>\n\n<pre><code> iter->second.adjList.push_back(edge);\n</code></pre>\n\n<p>You are binding your representation of a vertices to always contain its list of edges in this manor. You should really define a more abstract interface on the class that will allow you to change the internal representations without affecting the implementation of Graph.</p>\n\n<p>When you add edges to a graph.<br>\nYou check that the source is there. But you do not check that a destination node has been created. I would expect this to be more symmetrical.</p>\n\n<p>Is the method 'void resetStates()' really a member of the public interface?</p>\n\n<p>In your BreadthFirstTour/DepthFirstTour traversal of the graph. Its not really a breadth first/Depth first tour (as this implies a breadth or depth) while a graph is bit less symmetric than that (especially since edges have a weight and the graph may not be fully connected).</p>\n\n<p>But as part of the implementation you actually store whether a node (vertex) has been visited as a member of the vertex. You are basically tightly coupling the traversal of the graph to its implementation which may restrict you in future enhancements to the graph (and limiting how the graph can be traversed).</p>\n\n<p>You can de-couple how the graph is traversed from the implementation of the graph by using a visitor pattern. This also conforms to the open/closed principle by making your class open to expansion but closed to change by allowing the traversal mechanism to be specified externally to the graph.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T21:00:35.027",
"Id": "6818",
"Score": "0",
"body": "Excellent critique. Many helpful suggestions. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T18:45:50.150",
"Id": "4563",
"ParentId": "4561",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4563",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T18:05:59.717",
"Id": "4561",
"Score": "3",
"Tags": [
"c++",
"algorithm",
"graph"
],
"Title": "BFT/DFT/Topological graph implementation"
}
|
4561
|
<p>I'm drawing rectangular ROI region by darkening the area outside of it as in this image:</p>
<p><img src="https://i.stack.imgur.com/24OlL.jpg" alt="enter image description here"></p>
<p>But <code>image.MakeTransparent</code> takes too much time. What is the best way to increase drawing speed?</p>
<pre><code>void DrawRoi(Bitmap Image, RectangleF rect)
{
Rectangle roi = new Rectangle();
roi.X = (int)((float)Image.Width * rect.X);
roi.Y = (int)((float)Image.Height * rect.Y);
roi.Width = (int)((float)Image.Width * rect.Width);
roi.Height = (int)((float)Image.Height * rect.Height);
Stopwatch timer = new Stopwatch();
timer.Start();
// graphics manipulation takes about 240ms on 1080p image
using (Bitmap roiMaskImage = CreateRoiMaskImage(ImageWithRoi.Width, ImageWithRoi.Height, roi))
{
using (Graphics g = Graphics.FromImage(ImageWithRoi))
{
g.DrawImage(Image, 0, 0);
g.DrawImage(roiMaskImage, 0, 0);
Pen borderPen = CreateRoiBorderPen(ImageWithRoi);
g.DrawRectangle(borderPen, roi);
}
}
Debug.WriteLine("roi graphics: {0}ms", timer.ElapsedMilliseconds);
this.imagePictureBox.Image = ImageWithRoi;
}
Bitmap CreateRoiMaskImage(int width, int height, Rectangle roi)
{
Bitmap image = new Bitmap(width, height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(image))
{
SolidBrush dimBrush = new SolidBrush(Color.FromArgb(64, 0, 0, 0));
g.FillRectangle(dimBrush, 0, 0, width, height);
SolidBrush roiBrush = new SolidBrush(Color.Red);
g.FillRectangle(roiBrush, roi);
image.MakeTransparent(Color.Red);
return image;
}
}
Pen CreateRoiBorderPen(Bitmap image)
{
float width = ((float)(image.Width + image.Height) * 2.5f) / (float)(640 + 480);
if (width < 1.0f)
width = 1.0f;
Pen pen = new Pen(Color.FromArgb(255, 0, 255, 0), width);
return pen;
}
</code></pre>
|
[] |
[
{
"body": "<p>Well, you could try literally darkening the outside of the image by 25%, not by creating a 25%-opaque black area but just by calculating the pixel color values of the same color 25% darker, without the need to create a new 32bbp bitmap.</p>\n\n<p>This might help: <a href=\"https://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color\">Formula to determine brightness of RGB color (StackOverflow)</a>. Based on this, let's say you choose <code>Y = 0.2126 R + 0.7152 G + 0.0722 B</code> as your luminance formula and <code>0.75</code> and the new brightness of the outside part of the image -- each pixel should be changed to:</p>\n\n<pre><code>Y = 0.75 * (0.2126 * R + 0.7152 * G + 0.0722 * B)\n(R, G, B)' = (R - Y * 0.2126, G - Y * 0.7152, B - Y * 0.0722)\n</code></pre>\n\n<p>(Twice I realized that the formula I put here was quite wrong... this time I'm more confident, but it might be that this makes no sense when painted, I haven't tested it.)</p>\n\n<p>This would require iterating through each individual pixel outside the central square, so not sure if it will be faster in the end... But as will all things performance, only measurements will tell!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T11:44:44.307",
"Id": "6886",
"Score": "0",
"body": "thank you very much for intresting suggestion, I will try the approach"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-12-17T22:57:12.260",
"Id": "10853",
"Score": "0",
"body": "Could this be done with a ColorMatrix?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T19:46:44.820",
"Id": "4567",
"ParentId": "4564",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T19:03:22.100",
"Id": "4564",
"Score": "2",
"Tags": [
"c#",
"performance",
".net",
"image"
],
"Title": "Optimization of region of interest (ROI) drawing in the image"
}
|
4564
|
<p>I started implementing a graph drawing application in javascript and < canvas > element, and i just wanted to hear your thought on the progress so far. I'm very open to suggestions and i'm very interested to hear what you have to say.<br>
So you can see the progress so far in the present code, if you have any questions about it feel free to ask.</p>
<pre><code>var graph = {
init: function(edges) {
graph.vertices = {};
graph.edges = {};
graph.canvas = document.getElementById('platno');
graph.width = graph.canvas.width;
graph.height = graph.canvas.height;
graph.hookes_test = true;
graph.ctx = graph.canvas.getContext('2d');
document.addEventListener("mousedown", graph.klik, false);
document.addEventListener("mouseup", graph.drop, false);
document.addEventListener("dblclick", graph.dblclick, false);
graph.addNodesFromEdgesList(edges);
graph.addEdgesFromEdgesList(edges);
graph.mapEdges(graph.oDuljina);
setInterval(graph.draw, 1024 / 24);
},
addNodesFromEdgesList: function(EdgesList) {
for (var r1 = 0; r1 < EdgesList.length; r1++) {
for (var r2 = 0; r2 < EdgesList[r1].length - 1; r2++) {
if ((typeof graph.vertices[EdgesList[r1][r2]]) === "undefined") {
graph.addNode({
id: EdgesList[r1][r2],
x: Math.floor(graph.width / 2 + 100 * Math.cos(Math.PI * (EdgesList[r1][r2] * 2) / 11)),
y: Math.floor(graph.height / 2 + 100 * Math.sin(Math.PI * (EdgesList[r1][r2] * 2 / 11))),
size: 6,
ostalo: 100
});
}
}
}
},
addEdgesFromEdgesList: function(EdgesList) {
for (var a = 0; a < EdgesList.length; a++) {
graph.addEdge({
from: EdgesList[a][0],
to: EdgesList[a][1],
id: a
});
}
},
node: function(node) {
this.id = node.id;
this.pos = new vektor(node.x, node.y);
this.size = node.size;
this._size = node.size;
this.expanded = false;
},
addNode: function(node) {
(typeof graph.vertices[node.id]) === "undefined" ? graph.vertices[node.id] = new graph.node(node) : console.log("Duplikat cvora! Id:" + node.id);
},
removeNode: function(id) {
if (typeof graph.vertices[id] !== "undefined") {
graph.removeEdgeByNodeId(id);
if (id == graph.info_node.id) graph.info_node = false;
delete graph.vertices[id];
} else {
console.log("Ne postoji node! Id:" + id);
}
},
edge: function(edge) {
this.id = edge.id;
this.from = graph.vertices[edge.from];
this.to = graph.vertices[edge.to];
},
addEdge: function(edge) {
(typeof graph.edges[edge.id]) === "undefined" ? graph.edges[edge.id] = new graph.edge(edge) : console.log("Duplikat brida! Id:" + edge.id);
},
removeEdgeByEdgeId: function(id) {
(typeof graph.edges[id]) !== "undefined" ? delete graph.edges[id] : console.log("Ne postoji brid! Id:" + id);
},
removeEdgeByNodeId: function(id) {
if (typeof graph.vertices[id] !== "undefined") {
for (var edge in graph.edges) {
if (graph.edges.hasOwnProperty(edge) && (graph.edges[edge].from.id == id || graph.edges[edge].to.id == id)) {
delete graph.edges[edge];
}
}
} else {
console.log("Ne postoji cvor! Id:" + id);
}
},
clearGraph: function() {
for (var id in graph.vertices) {
if (graph.vertices.hasOwnProperty(id)) {
graph.removeNode(id)
}
}
},
mapNodes: function(funkcija, obj) {
var res = [],
tmp, id;
for (id in graph.vertices) {
if (graph.vertices.hasOwnProperty(id)) {
tmp = funkcija.apply(graph, [graph.vertices[id], obj || {}]);
if (tmp) res.push(tmp);
}
}
return res;
},
mapEdges: function(funkcija) {
for (var id in graph.edges) {
if (graph.edges.hasOwnProperty(id)) {
funkcija.apply(graph, [graph.edges[id].from, graph.edges[id].to, graph.edges[id].id]);
}
}
},
vuci: function(e) {
if (graph.drag) {
graph.drag.pos.x = (e.pageX - graph.canvas.offsetLeft);
graph.drag.pos.y = (e.pageY - graph.canvas.offsetTop);
if (graph.drag.pos.x > graph.width - 6) graph.drag.pos.x = graph.width - 6;
else if (graph.drag.pos.x < 6) graph.drag.pos.x = 6;
else if (graph.drag.pos.y > graph.height - 6) graph.drag.pos.y = graph.height - 6;
else if (graph.drag.pos.y < 6) graph.drag.pos.y = 6;
}
},
klik: function(e) {
graph.drag = graph.getNodeFromXY(e.pageX - graph.canvas.offsetLeft, e.pageY - graph.canvas.offsetTop)[0];
document.addEventListener("mousemove", graph.vuci, false);
},
drop: function() {
graph.drag = false;
document.removeEventListener("mousemove", graph.vuci, false);
},
getNodeFromXY: function(_x, _y) {
return graph.mapNodes(function(node, obj) {
if ((obj.x > node.pos.x - node.size) && (obj.x < node.pos.x + node.size) && (obj.y > node.pos.y - node.size) && (obj.y < node.pos.y + node.size)) {
return node;
} else {
return false
};
}, {
x: _x,
y: _y
});
},
draw: function() {
graph.ctx.clearRect(0, 0, graph.width, graph.height);
background();
graph.mapEdges(crtaj_v);
graph.mapNodes(crtaj_n);
graph.info();
if (!graph.hookes_test) graph.mapEdges(graph.hookes);
function background() {
var grd = graph.ctx.createRadialGradient(graph.width / 2, graph.height / 2, 30, graph.width / 2, graph.height / 2, graph.height);
grd.addColorStop(0, "#42586d");
grd.addColorStop(0.5, "#36495a");
grd.addColorStop(1, "#26323e");
graph.ctx.fillStyle = grd;
graph.ctx.fillRect(0, 0, graph.width, graph.height);
}
function crtaj_n(v) {
graph.ctx.fillStyle = 'rgba(0,0,0,0.4)';
graph.ctx.beginPath();
graph.ctx.arc(v.pos.x, v.pos.y, v.size, 0, Math.PI * 2, true);
graph.ctx.fill();
graph.ctx.strokeStyle = '#818f9a'
graph.ctx.arc(v.pos.x, v.pos.y, v.size, 0, Math.PI * 2, true);
graph.ctx.stroke();
return false;
}
function crtaj_v(v1, v2) {
graph.ctx.beginPath();
graph.ctx.strokeStyle = 'rga(129,143,154,0.1)';
var duljina = [v1.pos.udaljenost(v2.pos) - v1.size, v1.pos.udaljenost(v2.pos) - v2.size];
var kut = Math.atan2(v2.pos.y - v1.pos.y, v2.pos.x - v1.pos.x);
graph.ctx.moveTo(v2.pos.x - (duljina[0] * Math.cos(kut)), v2.pos.y - (duljina[0] * Math.sin(kut)));
graph.ctx.lineTo(v1.pos.x + (duljina[1] * Math.cos(kut)), v1.pos.y + (duljina[1] * Math.sin(kut)));
graph.ctx.stroke();
}
},
dblclick: function(e) {
var dbl = graph.getNodeFromXY(e.pageX - platno.offsetLeft, e.pageY - platno.offsetTop)[0] || false;
if (dbl.expanded) {
dbl.size = dbl._size;
dbl.expanded = false;
graph.info_node = false;
} else if (dbl) {
graph.mapNodes(function(v1) {
if (v1.expanded) {
v1.size = v1._size;
v1.expanded = false;
graph.info_node = false;
}
})
dbl.size = 30;
dbl.expanded = true;
graph.info_node = dbl;
}
},
info: function() {
if (graph.info_node) {
graph.ctx.font = "10px Verdana";
graph.ctx.textAlign = "center";
graph.ctx.fillStyle = '#ffffff';
graph.ctx.fillText("Node: " + graph.info_node.id, graph.info_node.pos.x, graph.info_node.pos.y + 3, 30);
}
},
hookes: function(v1, v2, id) {
var duljina = v1.pos.oduzmi(v2.pos),
udaljenost = duljina.duljina() - (graph.edges[id].duljina),
HL = 20 * (udaljenost / duljina.duljina()),
kut = Math.atan2(v2.pos.y - v1.pos.y, v2.pos.x - v1.pos.x);
(graph.drag && (graph.drag.id != v1.id)) || !graph.drag ? graph.zbrojiLokacija(v1, kut, HL) : false;
(graph.drag && (graph.drag.id != v2.id)) || !graph.drag ? graph.oduzmiLokacija(v2, kut, HL) : false;
},
oDuljina: function(v1, v2, id) {
graph.hookes_test = false;
graph.edges[id].duljina = v1.pos.oduzmi(v2.pos).duljina();
},
zbrojiLokacija: function(v1, kut, HL) {
var dis = new vektor(HL * Math.cos(kut), HL * Math.sin(kut))
if (v1.pos.x + dis.x > graph.width - v1.size || v1.pos.x + dis.x < 0 + v1.size) {
v1.pos.x += dis.x * (-1);
v1.pos.y += dis.y;
} else if (v1.pos.y + dis.y > graph.height - v1.size || v1.pos.y + dis.y < 0 + v1.size) {
v1.pos.x += dis.x;
v1.pos.y += dis.y * (-1);
} else {
v1.pos = v1.pos.zbroji(dis)
}
},
oduzmiLokacija: function(v1, kut, HL) {
var dis = new vektor(HL * Math.cos(kut), HL * Math.sin(kut))
if (v1.pos.x + dis.x > graph.width - v1.size || v1.pos.x + dis.x < 0 + v1.size) {
v1.pos.x -= dis.x * (-1);
v1.pos.y -= dis.y;
} else if (v1.pos.y + dis.y > graph.height - v1.size || v1.pos.y + dis.y < 0 + v1.size) {
v1.pos.x -= dis.x;
v1.pos.y -= dis.y * (-1);
} else {
v1.pos = v1.pos.oduzmi(dis)
}
}
}
function vektor(x, y) {
this.x = x;
this.y = y;
}
vektor.prototype.zbroji = function(v1) {
return new vektor(this.x + v1.x, this.y + v1.y);
}
vektor.prototype.oduzmi = function(v1) {
return new vektor(this.x - v1.x, this.y - v1.y);
}
vektor.prototype.division = function(x) {
return new vektor(this.x / x, this.y / x);
}
vektor.prototype.multiply = function(x) {
return new vektor(this.x * x, this.y * x);
}
vektor.prototype.udaljenost = function(v1) {
return Math.sqrt(Math.pow(v1.x - this.x, 2) + Math.pow(v1.y - this.y, 2));
}
vektor.prototype.duljina = function() {
return Math.max(20, Math.sqrt(Math.pow(this.x, 2) + Math.pow(this.y, 2)));
}
//////////////////////////////////////
// Test data //
/////////////////////////////////////
var edges = [
[1, 2, 1],
[1, 3, 1],
[2, 3, 1],
[3, 4, 1],
[3, 5, 1],
[3, 6, 1],
[4, 1, 1],
[4, 2, 1],
[5, 6, 1]
];
graph.init(edges);
</code></pre>
<p>UPDATE: added new code, this is just a preview i didn't have time to optimize the code, and also some of function names and varibles are written in my native language.</p>
<p>Also I've added a jsfiddle link so you can see the work so far in action.
<a href="http://jsfiddle.net/nNcHJ/1/" rel="nofollow">http://jsfiddle.net/nNcHJ/1/</a> </p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T18:33:29.187",
"Id": "6850",
"Score": "0",
"body": "Maybe you can provide an example of using it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T18:53:21.060",
"Id": "6854",
"Score": "0",
"body": "@Muha An example would be good. I would also start from the API, how would you expect the user to enter the values of a graph. Say you were to define a Traveling Salesman problem? See https://github.com/ajaxorg/apf/blob/master/CODING_STANDARDS for a good style guide"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:42:08.073",
"Id": "6874",
"Score": "0",
"body": "@Muha Thanks, you will get a better review, if you translate some of the code to English, `klik` and `vektor` are fine but what is `zbrojiLokacija`? (See http://en.wikipedia.org/wiki/Hungarian_notation). In general though it is shaping up and looks interesting. Also you need to change the canvas size in the jsFiddle in order to see it say 300px x 300px."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T21:37:34.223",
"Id": "6875",
"Score": "0",
"body": "thank you very much for your feedback, i'm planning to convert the names but i didn't have plenty of time today. but i will get to it soon."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T13:45:29.833",
"Id": "6887",
"Score": "0",
"body": "I would consider using a library to help abstract out some of the Canvas stuff you are doing. I haven't done anything on Canvas yet, but when I used to do stuff like this I would use http://raphaeljs.com/. (Generates SVG)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T13:53:51.270",
"Id": "6888",
"Score": "0",
"body": "Hello @Travis i'm doing this as a personal project so i can better learn have to use Javasript, so when i get a hang of it i'll definitely use a library, because of the performance that they give."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T13:59:15.007",
"Id": "6889",
"Score": "0",
"body": "@Muha, that makes sense, good luck :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-12T14:10:11.107",
"Id": "52135",
"Score": "0",
"body": "@Muha There's a design issue that got to my attention as soon as I started to look at the code. You should definitely make use of `this` instead of `graph` at multiple places. Also, your object is making too many assumptions, things such as the canvas id shouldn't be hard-coded within the *class*."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-12T14:16:07.247",
"Id": "52136",
"Score": "0",
"body": "Also you have far too many property lookups; they are expensive in JS. Instead of repeating things like `graph.ctx` multiple times, store the value in a variable and use that variable to reference your object. You should as well stick to a single naming convention, you are using *under_score*, *UpperCaseCamel*, *lowerCaseCamel* ... that's too much."
}
] |
[
{
"body": "<p>I like the code on the whole, I could work with this.\nMy 2 cents:</p>\n\n<ul>\n<li><code>graph.hookes_test</code> , please use lowerCaseCamel, so <code>graph.hookTest</code></li>\n<li><code>graph.oDuljina</code> , please use English</li>\n<li><code>document.getElementById('platno');</code> , if you provide an options parameter to <code>init(edges)</code>, then you can write something like <code>document.getElementById( options.canvasID || 'platno');</code></li>\n<li><code>setInterval(graph.draw, 1024 / 24);</code> , put magical numbers together in a section, preferably with a comment as to what the value means, consider to have this overridable by <code>options</code> as well.</li>\n<li>You have <code>this.size = node.size;</code> and also <code>this._size = node.size;</code>, whatever problem you solve with this should probably be addressed differently</li>\n<li><code>typeof graph.vertices[node.id]) === \"undefined\"</code> probably deserves its own one line function, <code>nodeExists()</code>, you use that expression all over the place</li>\n<li><code>clearGraph</code>, why can you not simply either re-<code>init()</code> or set <code>vertices</code> and <code>edges</code> to {} ?</li>\n<li>in <code>vuci</code> , the magical constant 6 should be a <code>var</code></li>\n<li>in <code>draw</code> and <code>info</code> , you should have a <code>var</code> section with all your style info</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-13T14:37:45.753",
"Id": "37308",
"ParentId": "4568",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T21:20:42.640",
"Id": "4568",
"Score": "4",
"Tags": [
"javascript",
"graph"
],
"Title": "Javascript graph skeleton implementation"
}
|
4568
|
<p>I'm learning to implement linked list. I've implemented sorting with merge sort, reversing etc...</p>
<p><a href="https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/ds/LinkedList.cpp" rel="nofollow">LinkedList.cpp</a></p>
<pre><code>#include <iostream>
template <class T>
struct Node
{
T data;
Node * next;
};
template <class T>
class LinkedList
{
public:
LinkedList() : head(NULL), size(0) {};
~LinkedList() { destroyList(); };
bool addNode(T data);
bool deleteNode(T data);
Node<T> * searchNode(T data);
void printList();
void reverseList();
void sortList();
private:
Node<T> * head;
int size;
void destroyList();
Node<T>* mergeSort(Node<T> * head, int total);
Node<T>* Merge(Node<T>* left, int lcount, Node<T>* right, int rcount);
void print(Node<T> * tmp);
};
template <class T>
bool LinkedList<T>::addNode(T data)
{
try
{
Node<T> * tmp = new Node<T>();
tmp->data = data;
tmp->next = head;
head = tmp;
++size;
return true;
}
catch(std::exception & ex)
{
return false;
}
}
template <class T>
bool LinkedList<T>::deleteNode(T data)
{
Node<T> *curr = head, *prev = NULL;
while (curr)
{
if (curr->data == data) break;
prev = curr;
curr = curr->next;
}
if (curr)
{
if (prev)
{
prev->next = curr->next;
}
else
{
head = curr->next;
}
delete(curr);
--size;
return true;
}
else
{
return false;
}
}
template <class T>
Node<T> * LinkedList<T>::searchNode(T data)
{
Node<T> * tmp = head;
while (tmp)
{
if (tmp->data == data)
{
return tmp;
}
tmp = tmp->next;
}
return NULL;
}
template <class T>
void LinkedList<T>::print(Node<T> * tmp)
{
bool printNewLine = (tmp) ? true : false;
while (tmp)
{
std::cout << tmp->data << ",";
tmp = tmp->next;
}
if (printNewLine)
{
std::cout << std::endl;
}
}
template <class T>
void LinkedList<T>::printList()
{
Node<T> * tmp = head;
bool printNewLine = (tmp) ? true : false;
while (tmp)
{
std::cout << tmp->data << "|";
tmp = tmp->next;
}
if (printNewLine)
{
std::cout << std::endl;
}
}
template <class T>
void LinkedList<T>::destroyList()
{
Node<T> * tmp = NULL;
while (head)
{
tmp = head;
head = head->next;
//std::cout << "deleting data " << tmp->data << std::endl;
delete(tmp);
}
}
template <class T>
void LinkedList<T>::reverseList()
{
Node<T> *curr = head, *prev = head, *save = NULL;
while (curr)
{
save = curr->next;
curr->next = prev;
prev = curr;
curr = save;
}
head->next = NULL;
head = prev;
}
//use merge sort
template <class T>
void LinkedList<T>::sortList()
{
head = mergeSort(head, size);
}
template <class T>
Node<T>* LinkedList<T>::mergeSort(Node<T> * first, int total)
{
if (total < 1) { return first; }
if (total < 2) { first->next = NULL; return first;}
Node<T> * curr = first;
int count = total/2;
while (count--)
{
curr = curr->next;
}
count = total/2;
first = mergeSort(first, count);
curr = mergeSort(curr, total-count);
return Merge(first, count, curr, total-count);
}
template <class T>
Node<T>* LinkedList<T>::Merge(Node<T>* left, int lcount, Node<T>* right, int rcount)
{
Node<T> * h = new Node<T>();
h->next = NULL;
Node<T> * tmp = h;
while (lcount > 0 && rcount > 0)
{
if (left->data < right->data)
{
tmp->next = left;
tmp = tmp->next;
left = left->next;
--lcount;
}
else if (right->data < left->data)
{
tmp->next = right;
tmp = tmp->next;
right = right->next;
--rcount;
}
else
{
tmp->next = left;
tmp = tmp->next;
left = left->next;
--lcount;
tmp->next = right;
tmp = tmp->next;
right = right->next;
--rcount;
}
}
while (lcount > 0)
{
tmp->next = left;
tmp = tmp->next;
left = left->next;
--lcount;
}
while (rcount > 0)
{
tmp->next = right;
tmp = tmp->next;
right = right->next;
--rcount;
}
tmp = h;
h = h->next;
delete(tmp);
return h;
}
int main()
{
LinkedList<int> l;
l.addNode(3);
l.addNode(2);
l.addNode(6);
l.addNode(4);
l.addNode(3);
l.printList();
l.reverseList();
l.printList();
l.sortList();
l.printList();
l.deleteNode(3);
l.deleteNode(3);
l.deleteNode(4);
l.printList();
l.reverseList();
l.printList();
l.sortList();
l.printList();
if (l.searchNode(2))
{
std::cout << "2 found \n";
}
if (!l.searchNode(5))
{
std::cout << "5 not found \n";
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T03:32:41.663",
"Id": "6824",
"Score": "6",
"body": "Welcome to code review! Please post the code you want reviewed as part of your post rather then a link to elsewhere."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-22T17:45:46.360",
"Id": "266485",
"Score": "0",
"body": "Your code is asking for memory leaks by allocating a new node on the free store but neglecting to delete the node in the case of an exception. You should avoid this possibility altogether by using standard library smart pointer type such as `std::unique_ptr<T>`"
}
] |
[
{
"body": "<pre><code>#include <iostream>\n\ntemplate <class T>\nstruct Node\n{\n T data;\n Node * next;\n};\n\ntemplate <class T>\nclass LinkedList\n{\npublic:\n LinkedList() : head(NULL), size(0) {};\n ~LinkedList() { destroyList(); };\n</code></pre>\n\n<p>Why did you make destroyList a seperate method? Why not put it in the destructor?</p>\n\n<pre><code> bool addNode(T data);\n bool deleteNode(T data);\n Node<T> * searchNode(T data);\n void printList();\n void reverseList();\n void sortList();\nprivate:\n Node<T> * head;\n int size;\n</code></pre>\n\n<p>I recommend some newlines between the data methods and the utility functions.</p>\n\n<pre><code> void destroyList();\n Node<T>* mergeSort(Node<T> * head, int total);\n Node<T>* Merge(Node<T>* left, int lcount, Node<T>* right, int rcount);\n</code></pre>\n\n<p>I recommend picking a consistent capitalization scheme. This should be merge not Merge.</p>\n\n<pre><code> void print(Node<T> * tmp);\n};\n\ntemplate <class T>\nbool LinkedList<T>::addNode(T data)\n{\ntry\n {\n Node<T> * tmp = new Node<T>();\n tmp->data = data;\n tmp->next = head;\n head = tmp;\n ++size;\n return true;\n }\ncatch(std::exception & ex)\n {\n return false;\n }\n</code></pre>\n\n<p>Don't ever do this. You shouldn't generally catch all exceptions. You should catch only the exception you are interested in. Converting the exception into a return value loses the advantage of an exception. Why did you add this exception logic here? \n }</p>\n\n<pre><code>template <class T>\nbool LinkedList<T>::deleteNode(T data)\n{\n Node<T> *curr = head, *prev = NULL;\n</code></pre>\n\n<p>I recommend typing whole words not abbreviations.</p>\n\n<pre><code> while (curr)\n {\n if (curr->data == data) break;\n</code></pre>\n\n<p>Use <code>while(curr && curr->data != data)</code></p>\n\n<pre><code> prev = curr;\n curr = curr->next;\n }\n\n if (curr)\n {\n</code></pre>\n\n<p>You are making use of inconsistent indentation. Pick a scheme and stick to it.</p>\n\n<pre><code> if (prev)\n {\n prev->next = curr->next;\n }\n else\n {\n head = curr->next;\n }\n delete(curr);\n</code></pre>\n\n<p>Parenthesis not needed</p>\n\n<pre><code> --size;\n return true;\n }\n else\n {\n return false;\n }\n}\n\ntemplate <class T>\nNode<T> * LinkedList<T>::searchNode(T data)\n</code></pre>\n\n<p>You are really finding a node rather then searching it.</p>\n\n<pre><code>{\n Node<T> * tmp = head;\n</code></pre>\n\n<p>tmp should be a banned variable name. all variables are temporary, so pick a better name,</p>\n\n<pre><code> while (tmp)\n {\n</code></pre>\n\n<p>I suggest</p>\n\n<p>for(Node * tmp = head; tmp; tmp = tmp->next)</p>\n\n<p>I think it'll make the code clearer.</p>\n\n<pre><code> if (tmp->data == data)\n {\n return tmp;\n }\n tmp = tmp->next;\n }\n return NULL;\n}\n\ntemplate <class T>\nvoid LinkedList<T>::print(Node<T> * tmp)\n</code></pre>\n\n<p>Printing is a bit of a odd feature for a linked list class. Typically, you'd except external code to handle that.</p>\n\n<pre><code>{\n bool printNewLine = (tmp) ? true : false;\n</code></pre>\n\n<p>Use 'bool printNewLine = bool(tmp)'; </p>\n\n<pre><code> while (tmp)\n {\n std::cout << tmp->data << \",\";\n tmp = tmp->next;\n } \n\n if (printNewLine)\n</code></pre>\n\n<p>Rather then doing this. I suggest keeping a copy of the original parameter and testing it here.\n {\n std::cout << std::endl;\n }\n }</p>\n\n<p>Is the function even used?</p>\n\n<pre><code>template <class T>\nvoid LinkedList<T>::printList()\n{\n Node<T> * tmp = head;\n bool printNewLine = (tmp) ? true : false;\n while (tmp)\n {\n std::cout << tmp->data << \"|\";\n</code></pre>\n\n<p>|? Okay, whatever.</p>\n\n<pre><code> tmp = tmp->next;\n } \n\n if (printNewLine)\n {\n std::cout << std::endl;\n }\n}\n\ntemplate <class T>\nvoid LinkedList<T>::destroyList()\n{\n Node<T> * tmp = NULL;\n while (head)\n {\n tmp = head;\n head = head->next;\n //std::cout << \"deleting data \" << tmp->data << std::endl;\n</code></pre>\n\n<p>Don't leave dead code in your code.</p>\n\n<pre><code> delete(tmp);\n }\n}\n\ntemplate <class T>\nvoid LinkedList<T>::reverseList()\n{\n Node<T> *curr = head, *prev = head, *save = NULL;\n\n\n while (curr)\n {\n save = curr->next;\n</code></pre>\n\n<p>You should declare save inside this loop rather then outside. I also suggest calling it next.</p>\n\n<pre><code> curr->next = prev;\n prev = curr;\n curr = save;\n }\n\n head->next = NULL;\n head = prev;\n}\n\n//use merge sort\ntemplate <class T>\nvoid LinkedList<T>::sortList()\n{\n head = mergeSort(head, size);\n}\n\ntemplate <class T>\nNode<T>* LinkedList<T>::mergeSort(Node<T> * first, int total)\n{\n if (total < 1) { return first; }\n if (total < 2) { first->next = NULL; return first;}\n\n Node<T> * curr = first;\n int count = total/2;\n</code></pre>\n\n<p>Add spaces around operators</p>\n\n<pre><code> while (count--)\n</code></pre>\n\n<p>I suggest counting down via for loop\n {\n curr = curr->next;\n }</p>\n\n<pre><code> count = total/2;\n</code></pre>\n\n<p>Rather then doing this calculation twice, I suggest saving the original version</p>\n\n<pre><code> first = mergeSort(first, count);\n\n curr = mergeSort(curr, total-count);\n\n return Merge(first, count, curr, total-count);\n}\n\ntemplate <class T>\nNode<T>* LinkedList<T>::Merge(Node<T>* left, int lcount, Node<T>* right, int rcount)\n{\n Node<T> * h = new Node<T>();\n h->next = NULL;\n Node<T> * tmp = h;\n</code></pre>\n\n<p>Creating a node during merging seems odd...</p>\n\n<pre><code> while (lcount > 0 && rcount > 0)\n {\n if (left->data < right->data)\n {\n tmp->next = left;\n tmp = tmp->next;\n</code></pre>\n\n<p>use <code>tmp = left</code></p>\n\n<pre><code> left = left->next;\n --lcount;\n }\n else if (right->data < left->data)\n {\n tmp->next = right;\n tmp = tmp->next;\n right = right->next;\n --rcount;\n }\n else\n {\n tmp->next = left;\n tmp = tmp->next;\n left = left->next;\n --lcount;\n\n tmp->next = right;\n tmp = tmp->next;\n right = right->next;\n --rcount;\n</code></pre>\n\n<p>There is no need for this. Just let one of the above cases handle equal as well.\n }\n }</p>\n\n<pre><code> while (lcount > 0)\n {\n tmp->next = left;\n tmp = tmp->next;\n left = left->next;\n --lcount;\n</code></pre>\n\n<p>This pattern is getting common. Think about refactoring this function or writing a function.</p>\n\n<pre><code> }\n\n while (rcount > 0)\n {\n tmp->next = right;\n tmp = tmp->next;\n right = right->next;\n --rcount;\n }\n\n tmp = h;\n h = h->next;\n delete(tmp);\n\n return h;\n}\n</code></pre>\n\n<p><strong>EDIT: My version of merge</strong></p>\n\n<pre><code>template <class T>\nNode<T>* LinkedList<T>::Merge(Node<T>* left, int count_left, Node<T>* right, int count_right)\n{\n Node<T> * head = NULL;\n Node<T> ** current = &head;\n\n while (count_left > 0 || count_right > 0)\n {\n if( count_right == 0 || (count_left > 0 && left->data < right->data))\n {\n *current = left;\n left = left->next;\n --count_left;\n }\n else\n {\n *current = right;\n right = right->next;\n --count_right;\n }\n current = &(*current)->next;\n }\n return head;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T14:08:51.640",
"Id": "6838",
"Score": "0",
"body": "Helpful suggestions. Thanks. \"There is no need for this. Just let one of the above cases handle equal as well.\" I think it is not possible because we have to advance both the lists in this case."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T14:22:34.267",
"Id": "6842",
"Score": "0",
"body": "_Creating a node during merging seems odd..._ \n `while (lcount > 0 && rcount > 0)\n {\n if (left->data < right->data)\n {\n tmp->next = left;\n tmp = tmp->next;` \n_use tmp = left_ If I do tmp=left, how will I be able to advance the tmp correctly in the next iteration"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T15:01:38.720",
"Id": "6845",
"Score": "0",
"body": "@Medicine, you'll be fine if you only advance one of the lists. The other value will still be there and you can advance it next time. I'll add how I'd do the merge."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T15:06:12.043",
"Id": "6846",
"Score": "0",
"body": "right, I also wanted the sort to be stable. So, I should be handling the equality case to the left."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:36:04.873",
"Id": "6856",
"Score": "0",
"body": "@Medicine, ok. easy enough to do just change the < to <="
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T23:45:59.907",
"Id": "6876",
"Score": "0",
"body": "your code is not advancing the left and right pointers. \n `if( count_right == 0 || (count_left > 0 && left->data < right->data))\n {\n *current = left;\n current = &(*current)->next;\n left = left->next;\n --count_left;\n }\n else\n {\n *current = right;\n current = &(*current)->next;\n right = right->next;\n --count_right;\n }`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T23:49:30.857",
"Id": "6877",
"Score": "0",
"body": "@Medicine, opps!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T00:49:01.257",
"Id": "6878",
"Score": "0",
"body": "but your implementation of Merge is much elegant."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:41:48.053",
"Id": "4581",
"ParentId": "4569",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": "4581",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T02:43:47.297",
"Id": "4569",
"Score": "4",
"Tags": [
"c++",
"linked-list"
],
"Title": "Linked List implementation in C++"
}
|
4569
|
<p>I have been solving a set of online Clojure problems. One of them involves the <a href="http://en.wikipedia.org/wiki/Look-and-say_sequence" rel="nofollow">look and say sequence</a>.</p>
<pre><code>(defn look-and-say [s]
(let [las (loop [item (first s) coll s counts [] count 0]
(cond
(nil? (seq coll)) (conj counts count item)
(= item (first coll)) (recur item (rest coll) counts (inc count))
:else (recur (first coll) coll (conj counts count item) 0)))]
(lazy-seq (cons las (look-and-say las)))))
</code></pre>
<p>I would like know what I did right and what I could do better. Any feedback is welcome.</p>
|
[] |
[
{
"body": "<p>one of the great things about Clojure is the ability to seperate code into concerns and then compose them. This really helps spot reusable parts and lets you build code in smaller independently testable parts.</p>\n\n<p>the parts I see are:</p>\n\n<ul>\n<li>given a sequence of number produce the next one \n<ul>\n<li><code>partition-all</code> the seq into groups of consecutive numbers</li>\n<li>for each group of consecutive numbers say how many there are <code>(map say list-o-groups)</code></li>\n<li><code>flatten</code> the result into one list. but really you should use <code>mapcat</code> in the previous step and skip this step.</li>\n</ul></li>\n<li>apply the the result to the same function (the <code>iterate</code> function)</li>\n<li><code>take</code> as many of these as you need</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:57:21.850",
"Id": "6821",
"Score": "1",
"body": "Bluggghhhhh `map` followed by `flatten` is vile, don't recommend it. Just use `mapcat`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-03T00:12:06.973",
"Id": "6822",
"Score": "0",
"body": "yes, mapcat is better. It makes for a less clear explanation of \"separating concerns\". I will edit to note this :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T22:49:41.507",
"Id": "4572",
"ParentId": "4571",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4572",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-02T21:43:21.737",
"Id": "4571",
"Score": "4",
"Tags": [
"homework",
"clojure",
"lazy"
],
"Title": "Lazy look and say sequence"
}
|
4571
|
<p>I've written this small class in Python that wraps bound methods but does not prevent the deletion of self.</p>
<ol>
<li>Do you have any thoughts on my code?</li>
<li>Do you think I handle errors appropriately?</li>
<li>Is it missing anything?</li>
<li>What should be done to make it more robust?</li>
<li>Is the documentation clear enough?</li>
</ol>
<p></p>
<pre><code>import weakref
class WeakBoundMethod:
"""
Wrapper around a method bound to a class instance. As opposed to bare
bound methods, it holds only a weak reference to the `self` object,
allowing it to be deleted.
This can be useful when implementing certain kinds of systems that
manage callback functions, such as an event manager.
"""
def __init__(self, meth):
"""
Initializes the class instance. It should be ensured that methods
passed through the `meth` parameter are always bound methods. Static
methods and free functions will produce an `AssertionError`.
"""
assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
'Object is not a bound method.'
self._self = weakref.ref(meth.__self__)
self._func = meth.__func__
def __call__(self, *args, **kw):
"""
Calls the bound method and returns whatever object the method returns.
Any arguments passed to this will also be forwarded to the method.
In case an exception is raised by the bound method, it will be
caught and thrown again to the caller of this `WeakBoundMethod` object.
Calling this on objects that have been collected will result in
an `AssertionError` being raised.
"""
assert self.alive(), 'Bound method called on deleted object.'
try:
return self._func(self._self(), *args, **kw)
except Exception, e:
raise e
def alive(self):
"""
Checks whether the `self` object the method is bound to has
been collected.
"""
return self._self() is not None
</code></pre>
|
[] |
[
{
"body": "<pre><code>class WeakBoundMethod:\n</code></pre>\n\n<p>I suggest making it a new-style class by inheriting from object.</p>\n\n<pre><code> assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\\\n 'Object is not a bound method.'\n</code></pre>\n\n<p>Don't do this. Just let the invalid parameter types raise attribute errors when you try to fetch the <code>__func__</code> and <code>__self__</code>. You don't gain anything by checking them beforehand.</p>\n\n<pre><code>assert self.alive(), 'Bound method called on deleted object.'\n</code></pre>\n\n<p>Raising an Assertion here is a bad choice. Assertions are for thing that should never happen, but having the underlying self object cleaned up doesn't really count. Raise an exception like weakref.ReferenceError. That way a caller can reasonably catch the error.</p>\n\n<p>The documentation is very clear, well done.</p>\n\n<p><strong>EDIT</strong></p>\n\n<pre><code> try:\n return self._func(self._self(), *args, **kw)\n except Exception as e:\n raise e\n</code></pre>\n\n<p>Why are you catching an exception only to rethrow it? That's really pointless.</p>\n\n<p>I'd write the whole function as:</p>\n\n<pre><code>def __call__(self, *args, **kw):\n _self = self._self()\n if _self is None:\n raise weakref.ReferenceError()\n\n return self._func(_self, *args, **kw)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T13:16:17.097",
"Id": "4579",
"ParentId": "4574",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4579",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T06:32:31.290",
"Id": "4574",
"Score": "4",
"Tags": [
"python",
"classes",
"weak-references"
],
"Title": "Wrapping bound methods"
}
|
4574
|
<p>Implemented
Bubble Sort, Insertion Sort, Selection Sort,
Quick Sort, Merge Sort and
Radix Sort</p>
<p><a href="https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/sorting/SortingAlgorithms.cpp" rel="nofollow">https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/sorting/SortingAlgorithms.cpp</a></p>
<pre><code>#include <iostream>
#include <vector>
#include <queue>
using namespace std;
void swap(std::vector<int> & data, int i, int j)
{
int tmp = data[i];
data[i] = data[j];
data[j] = tmp;
}
void print(std::vector<int> const & data)
{
std::vector<int>::const_iterator iter = data.begin();
for (; iter != data.end(); ++iter)
{
cout << *iter << " ";
}
if (data.size() > 0)
{
cout << endl;
}
}
int generateRandom(int low, int high);
void Shuffle(std::vector<int> & data)
{
int length = data.size();
for (int i = 0; i < length-1; ++i)
{
swap(data, i, generateRandom(i+1, length-1));
}
print(data);
}
int generateRandom(int low, int high)
{
srand(low);
int gen = 0;
gen = rand() % (high - low + 1) + low;
return gen;
}
//useful for small lists, and for large lists where data is
//already sorted
void BubbleSort(std::vector<int> & data)
{
int length = data.size();
for (int i = 0; i < length; ++i)
{
bool swapped = false;
for (int j = 0; j < length - (i+1); ++j)
{
if (data[j] > data[j+1])
{
swap(data, j, j+1);
swapped = true;
}
}
if (!swapped) break;
}
}
//useful for small lists and where swapping is expensive
// does at most n swaps
void SelectionSort(std::vector<int> & data)
{
int length = data.size();
for (int i = 0; i < length; ++i)
{
int min = i;
for (int j = i+1; j < length; ++j)
{
if (data[j] < data[min])
{
min = j;
}
}
if (min != i)
{
swap(data, i, min);
}
}
}
//useful for small and mostly sorted lists
//expensive to move array elements
void InsertionSort(std::vector<int> & data)
{
int length = data.size();
for (int i = 1; i < length; ++i)
{
bool inplace = true;
int j = 0;
for (; j < i; ++j)
{
if (data[i] < data[j])
{
inplace = false;
break;
}
}
if (!inplace)
{
int save = data[i];
for (int k = i; k > j; --k)
{
data[k] = data[k-1];
}
data[j] = save;
}
}
}
void Merge(std::vector<int> & data, int lowl, int highl, int lowr, int highr);
void MergeSort(std::vector<int> & data, int low, int high)
{
if (low >= high)
{
return;
}
int mid = low + (high-low)/2;
MergeSort(data, low, mid);
MergeSort(data, mid+1, high);
Merge(data, low, mid, mid+1, high);
}
void Merge(std::vector<int> & data, int lowl, int highl, int lowr, int highr)
{
int tmp_low = lowl;
std::vector<int> tmp;
while (lowl <= highl && lowr <= highr)
{
if (data[lowl] < data[lowr])
{
tmp.push_back(data[lowl++]);
}
else if (data[lowr] < data[lowl])
{
tmp.push_back(data[lowr++]);
}
else
{
tmp.push_back(data[lowl++]);
tmp.push_back(data[lowr++]);
}
}
while (lowl <= highl)
{
tmp.push_back(data[lowl++]);
}
while (lowr <= highr)
{
tmp.push_back(data[lowr++]);
}
std::vector<int>::const_iterator iter = tmp.begin();
for(; iter != tmp.end(); ++iter)
{
data[tmp_low++] = *iter;
}
}
int Partition(std::vector<int> & data, int low, int high);
void QuickSort(std::vector<int> & data, int low, int high)
{
if (low >= high) return;
int p = Partition(data, low, high);
QuickSort(data, low, p-1);
QuickSort(data, p+1, high);
}
int Partition(std::vector<int> & data, int low, int high)
{
int p = low;
for (int i = p+1; i <= high; ++i)
{
if (data[i] < data[p])
{
swap(data, i, p);
if (i != p+1)
{
swap(data, i, p+1);
}
p = p + 1;
}
}
return p;
}
//O(kN) k is max number of digits
int findMaxDigits(std::vector<int> & data);
void PutInQueues(std::queue<int> q[], int qcount, std::vector<int> & data, int digit);
void GetPartialSorted(std::queue<int> q[], int qcount, std::vector<int> & data);
void RadixSort(std::vector<int> & data)
{
std::queue<int> q[10];
int maxDigits = findMaxDigits(data);
for (int i = 0; i < maxDigits; ++i)
{
PutInQueues(q, 10, data, i+1);
data.clear();
GetPartialSorted(q, 10, data);
}
}
int getDigitAt(int n, int digit);
void PutInQueues(std::queue<int> q[], int qcount, std::vector<int> & data, int digit)
{
std::vector<int>::const_iterator iter = data.begin();
for(; iter != data.end(); ++iter)
{
int qpos = getDigitAt(*iter, digit);
q[qpos].push(*iter);
}
}
int getDigitAt(int n, int digit)
{
int dig = 0;
while (digit--)
{
dig = n % 10;
n = n / 10;
}
return dig;
}
void GetPartialSorted(std::queue<int> q[], int qcount, std::vector<int> & data)
{
for (int i = 0; i < qcount; ++i)
{
if (q[i].size() > 0)
{
int length = q[i].size();
while (length--)
{
data.push_back(q[i].front());
q[i].pop();
}
}
}
}
int numDigits(int n);
int findMaxDigits(std::vector<int> & data)
{
std::vector<int>::const_iterator iter = data.begin();
int max = 0;
for (; iter != data.end(); ++iter)
{
int numd = numDigits(*iter);
if (max < numd)
{
max = numd;
}
}
return max;
}
int numDigits(int n)
{
int count = 0;
while(n != 0)
{
n = n/10;
++count;
}
return count;
}
int main()
{
int a[] = {5, 6, 1, 2, 0, 8, -1, -2, 8, 0};
std::vector<int> data(a, a + sizeof(a)/sizeof(int));
//Bubble sort
BubbleSort(data);
print(data);
//Selection sort
Shuffle(data);
SelectionSort(data);
print(data);
//Insertion sort
Shuffle(data);
InsertionSort(data);
print(data);
//Merge sort
Shuffle(data);
MergeSort(data, 0, data.size()-1);
print(data);
//Quick sort
Shuffle(data);
QuickSort(data, 0, data.size()-1);
print(data);
//Radix Sort
int b[] = {123, 6, 24, 4567, 45, 989834, 98, 23, 8, 0};
std::vector<int> rdata(b, b + sizeof(b)/sizeof(int));
RadixSort(rdata);
print(rdata);
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<h3>Standard functions</h3>\n\n<p>There is already a standard swap.<br>\nNo need o pollute your code with one.</p>\n\n<pre><code>void swap(std::vector<int> & data, int i, int j)\n\ntemplate<typename T>\nvoid std::swap(T& lhs, T& rhs) // Implements optimal swap for T\n</code></pre>\n\n<p>OK your shuffle algorithm is ok (better than most people I see try this). But again there is one in the standard</p>\n\n<pre><code>void Shuffle(std::vector<int> & data)\n\ntemplate<typename Iterator>\nvoid random_shuffle (Iterator first, Iterator last ); // shuffle a container.\n</code></pre>\n\n<h3>Random numbers</h3>\n\n<p>Random nmber generation.<br>\n<strong>NEVER</strong> call srand() more than once in a program.<br>\nCall it on entry to main and never again.</p>\n\n<h3>Don't reinvent the wheel:</h3>\n\n<pre><code>int numDigits(int n)\n</code></pre>\n\n<p>Is this just not implementing </p>\n\n<pre><code>int numDigits(int n) { return int(log10(n) + 1);}\n</code></pre>\n\n<h3>Variable Names</h3>\n\n<p>Make your variables names unique and easy to find.</p>\n\n<pre><code>for (int i = 0; i < length; ++i)\n</code></pre>\n\n<p>Here i is a horrible name.<br>\nImagine the code gets longer over the years and you need to maintain it. Now you need to find all occurences of the variable 'i' to validate that they are being used in the correct array. Think of how many falso positives a search on i is going to give you.</p>\n\n<p>Also it gives no indication as to its use.<br>\nI like <code>loop</code> personally (But a lot of people think this is horrible because it does not expresses intention (I disagree with them)). Alternatives would be <code>index</code>, <code>outerLoop</code> etc.</p>\n\n<p>Yes <code>i</code> and 'j` were standard variable names for integer loop variables in fortran and old lecturers who can not get out of the old practice have carried this forward into their teaching of modern languages. In real life where you have good consistent code reviews this would fail a code review and you would be told go go change it (especially on big code bases). Get into the habit of using expressive names.</p>\n\n<h3>Indent Style</h3>\n\n<p>Your indent style is unique. That is bad. Pick a style that everybody else uses (or one of the big religious groups) but stay consistent (this also helps when tools get involved having a unique style means the some tools may not work as effectively for you).</p>\n\n<pre><code>// Style 1\n if (max < numd)\n {\n max = numd;\n }\n// Style 2\n if (max < numd)\n {\n max = numd;\n }\n// Style 3\n if (max < numd) {\n max = numd;\n }\n// Not a standard style\n if (max < numd)\n {\n max = numd;\n }\n</code></pre>\n\n<p>And it does not match your outer style:</p>\n\n<pre><code>int numDigits(int n)\n{\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T18:06:20.587",
"Id": "6849",
"Score": "1",
"body": "why NEVER call srand() more than once? does it take too much time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T18:41:19.153",
"Id": "6852",
"Score": "0",
"body": "@Medicine: No. You are only supposed to call it once. If you call it more than once you ruin the random numbers (as you are restarting the sequence). Thus if you call it before rand() each time you are **NOT** getting random numbers. It's **NEVER** because all beginners do this and get its irritating to tell them again and again and again and again ...."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T18:48:20.007",
"Id": "6853",
"Score": "0",
"body": "I use style1 at work which is taken care by my .emacs. at home I use Mac and I have Aquamacs whose default indentation is what I am using..the non-standard style."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T16:28:05.453",
"Id": "4584",
"ParentId": "4582",
"Score": "10"
}
},
{
"body": "<p>Starting from (close to) the top, most of your <code>print</code> is basically just a somewhat crippled imitation of <code>std::copy</code> with a <code>std::ostream_iterator</code> as the destination. I'm not excited about its existing at all, but if you're going to have it, I'd use something like this:</p>\n\n<pre><code>void print(std::vector<int> const &data) { \n if (!data.empty())\n copy(data.begin(), data.end(), ostream_iterator<int>(cout, \" \"));\n cout << endl;\n }\n}\n</code></pre>\n\n<p>Although it's rarely a matter of much importance, also note that if you're just checking for empty/non-empty, using <code>x.empty()</code> is usually preferable to <code>x.count()!=0</code>.</p>\n\n<p>Getting to <code>GenerateRandom()</code> and <code>shuffle</code>, @Tux-D has something of a point, but he's stated it incorrectly.</p>\n\n<p>The way you've used <code>srand</code> doesn't seem very sensible, <em>but</em> in some cases (probably including this one) it can/does make sense to call it more than once in a particular program. In this case, it does make at least some sense to start each sort algorithm with exactly the same input sequence. To do that, however, you want to re-seed the random number generator once before you generate each sequence (and use the same value each time). As @Tux-D also pointed out (but correctly, in this case) you usually want to do this with <code>std::random_shuffle</code>. <code>random_shuffle</code> takes a random-number generating object as a parameter, so you'd normally want to write a small class that calls srand, and provides an <code>operator()</code> that provides the random numbers.</p>\n\n<p>Getting to the bubble-sort, there's one point worth mentioning: this is the version with an early-out test. That's worth mentioning, because it's a bit of a gamble: while it improves speed quite a lot if the data is already sorted (or <em>very</em> close to sorted) it makes what's already a slow algorithm even slower in nearly every other case. As such, it's generally a net loss unless the data really is quite close to sorted.</p>\n\n<p>For the selection sort, it's probably worth noting that the standard library already has a <code>min_element</code>, so you can reduce your selection sort to something like:</p>\n\n<pre><code>for (size_t i=0; i<length-1; i++) {\n size_t least = std::min_element(&data[i], &data[length]);\n swap(&data[i], &data[least]);\n}\n</code></pre>\n\n<p>The insertion sort can also be minimized considerably. The basic idea is pretty simple:</p>\n\n<pre><code>for (size_t i=1; i<length; i++)\n int temp = data[i];\n size_t j;\n for (j=i; j>0 && temp < data[j-1]; j--)\n data[j] = data[j-1];\n data[j-1] = temp;\n}\n</code></pre>\n\n<p>Getting to the merge-sort, I notice two things: first, it looks to me like it should be written as a function-object, with <code>merge</code> as a private member function (and note that the same applies in other cases as well, such as <code>partition</code> as a private member function of a quicksort function object). Other than that, I'm still left scratching my head wondering how a merge ended up nearly 40 lines long.</p>\n\n<pre><code>std::vector<int> merge(std::vector<int> &a, std::vector<int> &b) {\n std::vector<int> result;\n size_t i=0, j=0;\n while (i<a.size() && j<b.size())\n if (a[i] <= b[j])\n result.push_back(a[i++]);\n else\n result.push_back(b[j++]);\n // Copy tail. Only one of these loops will execute per invocation\n while (i<a.size())\n result.push_back(a[i++]);\n while (j<b.size())\n result.push_back(b[j++]);\n return result;\n}\n</code></pre>\n\n<p>Other than that, I'd probably start with a base class (sort, or something on that order):</p>\n\n<pre><code>struct sort { \n virtual void operator()(std::vector<int> &) = 0;\n};\n</code></pre>\n\n<p>and have each sort algorithm derive from that:</p>\n\n<pre><code>struct bubblesort : sort {\n void operator()(std::vector<int> &array) {\n // ...\n }\n};\n\nstruct insertionsort : sort { \n void operator()(std::vector<int> &array) {\n // ...\n }\n};\n\n// etc.\n</code></pre>\n\n<p>Then in main, you can have something like:</p>\n\n<pre><code>sort sorts[] = {bubblesort, insertionsort, selectionsort, mergesort, quicksort};\n\nfor (int i=0; i<sizeof(sorts)/sizeof(sorts[0]); i++) {\n std::vector<int> data = fill_random(size);\n\n sorts[i](data);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T18:34:34.593",
"Id": "6896",
"Score": "1",
"body": "DOn't agree that I was wrong about srand(). In the general case you should only be calling it once. If you are doing testing and want to repeatedly get the sane random sequence then fine you can re-use it (with he same seed). But let teach beginners basics first before we start getting them onto advanced techniques."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T03:48:43.390",
"Id": "4595",
"ParentId": "4582",
"Score": "8"
}
},
{
"body": "<p>It might be suitable for something like a homework exercise in a data structures class, but my biggest objection to this is you've tied everything to sorting the entirety of a <code>std::vector</code>. One of the strengths of the STL iterator approach and what you might find in the <code><algorithm></code> header is that you can fairly easily replace the backing data structure. If you specify the data to be sorted as a "begin" and an "end" iterator, you get all this for free:</p>\n<ul>\n<li>Sorting the entirety of a <code>vector</code></li>\n<li>Sorting just a range of a <code>vector</code></li>\n<li>Replacing that <code>vector</code> with a raw C array. Same sorting code works!</li>\n<li>... Or some other data structure you might not have envisioned.</li>\n<li>Most importantly, being able to do all the above while producing binary code that beats what you'd write doing generics in plain C.</li>\n</ul>\n<p>The C++ iterator syntax looks strange and counter-intuitive to many... Many people writing C++ don't really understand the benefits; I myself was writing C++ for a long time without really getting it. I think the turning point for me was reading <a href=\"//www.stroustrup.com/hopl-almost-final.pdf\" rel=\"nofollow noreferrer\">Stroustrup's HOPL-III paper</a>; as a longtime (ab)user of the "C-style" the parts about STL were helpful for me to clearly explain the approach, where it comes from, and the benefits.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2011-09-05T19:12:42.643",
"Id": "4603",
"ParentId": "4582",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4595",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T14:01:21.553",
"Id": "4582",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"sorting"
],
"Title": "Sorting algorithms implemented in C++"
}
|
4582
|
<p>I'm processing about 3.5gb/15minutes, and I was wondering if I could get this down to a better time... </p>
<p>Note that this is for a very specific CSV file, so I am not concerned about generality - only speed of implementation and optimization.</p>
<pre><code>int main(int argc, char *argv[]) {
std::string filename;
std::cout << "Please type the file name: " << std::endl;
std::cin >> filename;
std::string ticker;
std::cout << "Please enter the ticker: " << std::endl;
std::cin >> ticker;
std::ifstream instream(filename.c_str());
std::string ask_filename = ticker + "_ASK.NIT";
std::ofstream askstream(ask_filename.c_str());
std::string bid_filename = ticker + "_BID.NIT";
std::ofstream bidstream(bid_filename.c_str());
std::string line;
std::getline(instream,line);
while(std::getline(instream,line))
{
std::stringstream lineStream(line);
std::string cell;
std::string new_line;
std::vector<std::string> my_str_vec;
while(std::getline(lineStream,cell,','))
{
my_str_vec.push_back(cell);
//new_line.append(cell.append(";"));
}
// works on date
std::string my_date = my_str_vec[0];
std::string::iterator my_iter;
std::string processed_date = "";
for(my_iter = my_date.begin(); my_iter != my_date.end(); ++my_iter) {
if(std::isalnum(*my_iter) || *my_iter == ' ')
processed_date.append(1,(*my_iter));
}
my_str_vec[0] = processed_date;
std::vector<std::string>::iterator my_vec_iter;
for(my_vec_iter = my_str_vec.begin() + 1; my_vec_iter != my_str_vec.end(); ++my_vec_iter) {
std::string my_semicol = ";";
*my_vec_iter = my_semicol.append(*my_vec_iter);
}
askstream << my_str_vec[0] << my_str_vec[1] << my_str_vec[3] << std::endl;
bidstream << my_str_vec[0] << my_str_vec[2] << my_str_vec[4] << std::endl;
}
askstream.close();
bidstream.close();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>First off streams and specifically the stream operators >> and << are designed for robustness not speed. They make the code harder to write incorrectly (and provide some local specific conversions) that make expensive in terms of using (consider changing to C fscanf() if speed is paramount).</p>\n\n<p>So if speed is you objective streams is not the best choice. </p>\n\n<p>Assuming we are staying with streams (Ask another question about how to write this in C for speed): </p>\n\n<h3>Dead Code</h3>\n\n<p>Second delete dead code (it confuses a review) and costs in creation.</p>\n\n<pre><code> std::string new_line;\n</code></pre>\n\n<h3>Small Inefficiencies</h3>\n\n<p>There is no need to create the cell object each time through the loop create it once outside the loop. (Personally I would leave it in the loop, but if you are going for speed then this is an obvious simple save).</p>\n\n<p>When scanning the date you are making a copy of the value:</p>\n\n<pre><code> std::string my_date = my_str_vec[0];\n</code></pre>\n\n<p>No need just make a reference (you can even use a const reference for safety):</p>\n\n<pre><code> std::string const& my_date = my_str_vec[0];\n // ^^^^^^\n</code></pre>\n\n<h3>Use Reserve</h3>\n\n<p>Building the string character by character may not be the most efficient way of getting the date (as the string <code>processed_date</code> may be resized on each insert). </p>\n\n<pre><code> for(my_iter = my_date.begin(); my_iter != my_date.end(); ++my_iter) {\n if(std::isalnum(*my_iter) || *my_iter == ' ')\n processed_date.append(1,(*my_iter));\n }\n</code></pre>\n\n<p>Use reserve so you know that it is not re-sized internally, then use a standard algorithm for optimal looping:</p>\n\n<pre><code>processed_date.reserve(my_date.size()); // Note: not resize()\nstd::remove_copy(my_date.begin(), my_date.end(), \n std::back_inserter(processed_date),\n [](char const& my_char) {return !(std::isalnum(*my_char) || *my_char == ' ');}\n );\n// Note if you don't have C++0x then lamda is easily replaced by a functor.\n</code></pre>\n\n<h3>Standard algorithms.</h3>\n\n<p>Your code will be optimal when you use the standard algorithms. Its worth learning what is available.</p>\n\n<p><a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\">http://www.sgi.com/tech/stl/table_of_contents.html</a><br>\nSee section 5</p>\n\n<p>I showed you how to copy all but the characters you want. But there is one to remove all elements in-place. I'll let you experiment.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T19:40:10.943",
"Id": "4587",
"ParentId": "4585",
"Score": "8"
}
},
{
"body": "<p>Untest version using fscanf()</p>\n\n<pre><code>#include <iostream>\n#include <stdio.h>\n\nstruct ValidDate\n{\n bool operator()(char c) const { return !(std::isalnum(c) || c == ' ');}\n};\n\nint main(int argc, char *argv[])\n{\n std::string filename;\n std::cout << \"Please type the file name: \" << std::endl;\n std::cin >> filename;\n\n std::string ticker;\n std::cout << \"Please enter the ticker: \" << std::endl;\n std::cin >> ticker;\n\n std::string ask_filename = ticker + \"_ASK.NIT\";\n std::string bid_filename = ticker + \"_BID.NIT\";\n\n FILE* instream = fopen(filename.c_str(), \"r\");\n FILE* askstream = fopen(ask_filename.c_str(), \"w\");\n FILE* bidstream = fopen(bid_filename.c_str(), \"w\");\n\n char part[5][1000];\n char term;\n int dateLen;\n while(feof(instream))\n {\n term = '\\n';\n dateLen = 0;\n fscanf(instream, \"%999[^,\\n]%n\", part[0], &dateLen);fscanf(instream,\"%c\", &term);\n // Note you do need two fscanf() in case there is an empty cell with no data\n if (term == ',') {fscanf(instream, \"%999[^,\\n]\", part[1]);fscanf(instream,\"%c\", &term);}\n if (term == ',') {fscanf(instream, \"%999[^,\\n]\", part[2]);fscanf(instream,\"%c\", &term);}\n if (term == ',') {fscanf(instream, \"%999[^,\\n]\", part[3]);fscanf(instream,\"%c\", &term);}\n if (term == ',') {fscanf(instream, \"%999[^,\\n]\", part[4]);fscanf(instream,\"%c\", &term);}\n // Read the remainder of the line\n // Actually need to use two fscans (just in case there is only a '\\n' left)\n if (term == ',') {fscanf(instream, \"%*[^\\n]\"); fscanf(instream, \"%c\", &term);}\n\n if (term != '\\n')\n { abort(); // something very wrong happened\n // like data was too big for a part buffer\n }\n\n // If we have reached the EOF then \n // something went wrong with one of the reads (probably the first)\n // and we should not continue.\n if (feof(instream))\n { break;\n }\n\n char* newLast = std::remove_if(static_cast<char*>(part[0]), static_cast<char*>(part[0]) + dateLen, ValidDate());\n *newLast = '\\0';\n\n fprintf(askstream, \"%s;%s;%s;\\n\", part[0], part[1], part[3]);\n fprintf(bidstream, \"%s;%s;%s;\\n\", part[0], part[2], part[4]);\n }\n\n fclose(askstream);\n fclose(bidstream);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T20:54:49.990",
"Id": "4588",
"ParentId": "4585",
"Score": "0"
}
},
{
"body": "<p>As a rule of thumb, parsing in a compiled language should be I/O bound.\nIn other words, it shouldn't take much longer to parse the file than it takes to just copy it by any method.</p>\n\n<p>Here's how I optimize code.\nI'm not looking for \"slow routines\".\nI want a much finer level of granularity.</p>\n\n<p>I'm looking for individual statements or function call sites, that are on the call stack a substantial fraction of the time,\nbecause any such call, if it could be replaced by some code that did the same action in a lot less time, would reduce total running time by roughly that fraction.</p>\n\n<p>It's extremely easy to find them. All you gotta do is <a href=\"https://stackoverflow.com/questions/375913/what-can-i-use-to-profile-c-code-in-linux/378024#378024\">pause the program</a> a few times, and each time get out your magnifying glass and ask what it's doing and why.</p>\n\n<p>Don't stop after you've found and fixed just one problem.\nSince you've reduced the total time, other problems now take a larger percentage of the time, and are thus easier to find.\nSo, the more you do it, the more you find, and each speedup compounds on the previous ones.\nThat's how you <a href=\"https://stackoverflow.com/questions/926266/performance-optimization-strategies-of-last-resort/927773#927773\">really make it fast</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T01:28:29.343",
"Id": "4594",
"ParentId": "4585",
"Score": "4"
}
},
{
"body": "<p>Remember that std::string is allowed to have embedded NULL chars.\nEliminate all unnecessary copying. e.g.</p>\n\n<pre><code>my_str_vec.push_back(cell);\n\nstd::stringstream lineStream(line);\n\nstd::string my_date = my_str_vec[0];\n</code></pre>\n\n<p>Use iterators everywhere.</p>\n\n<pre><code>typedef std::vector<std::string::iterator> field_positions;\nfield_positions field;\nstd::back_insert_iterator<field_positions> biitfp(field)\nbool found = true;\n\nfor (std::string::iterator it = date; it != line.end(); ++it) {\n if (found) { *biitfp = it; found = false; }\n found = ',' == *it;\n if (found) *it = 0; // overwrite commas with NULL\n}\n*biitfp = it; // save the end point too see field.back() below\n</code></pre>\n\n<p>do everything in place in the copy of the line you already have</p>\n\n<pre><code>std::string::iterator it1 = field[0].begin(), it2 = field[0].begin();\nfor (;0 != *it2; ++it2)\n{\n // overwrite bad char with good char\n if (std::isalnum(*my_iter) || *my_iter == ' ') *it1++ = *it2;\n}\nwhile (it1 != it2) *it1 = 0; // overwrite the left over chars in the field with NULL\n\nint f = 0;\nfor (field_positions::const_iterator fpit = field.begin(), fpend = field.end();\n fpit != fpend; ++fpit, ++f)\n{\n for (std::string::const_iterator it = *fpit; 0 != *it && it != field.back(); ++it)\n {\n switch (f) { // single character stream output is FAST\n case 0: askstream << *it; bidstream << *it; break;\n case 1: case 3: askstream << *it; break;\n case 2: case 4: bidstream << *it; break;\n default: break;\n }\n }\n askstream << ';';\n bidstream << ';';\n}\naskstream << std::endl; bidstream << std::endl;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T04:51:47.563",
"Id": "4627",
"ParentId": "4585",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4587",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T17:00:20.227",
"Id": "4585",
"Score": "4",
"Tags": [
"c++",
"performance",
"parsing",
"csv"
],
"Title": "File parsing code in C++"
}
|
4585
|
<p>I have to use a C++ member function in pthread_create. Also, the member function needs to be able to get the argument.</p>
<p>So, I have implemented a launcher function, which with help of a launcher object which stores the member function's address and the argument, will be able to do the desired.</p>
<p>Is there a better/elegant way to do this?</p>
<pre><code>template <class T>
class Launcher
{
public:
Launcher(T * obj, void * (T::*mfpt) (void *), void * arg) : myobj(obj), fpt(mfpt), myarg(arg) {}
~Launcher() {}
void launch() { (*myobj.*fpt)(myarg);}
private:
T* myobj;
void* myarg;
void * (T::*fpt) (void *); //Member function pointer
};
template <class T>
void * LaunchMemberFunction(void * obj)
{
Launcher<T> * l = reinterpret_cast<Launcher<T>*>(obj);
l->launch();
}
</code></pre>
<p><strong>Complete program and usage below:</strong>
<a href="https://code.google.com/p/medicine-cpp/source/browse/trunk/cpp/mt/ScopedLock.cpp" rel="nofollow">Link to Code</a></p>
<pre><code>#include <iostream>
#include <pthread.h>
class ScopedLock
{
public:
ScopedLock(pthread_mutex_t& mutex);
~ScopedLock();
void lock();
void unlock();
bool isLocked();
private:
pthread_mutex_t& _mutex;
bool _locked;
};
ScopedLock::ScopedLock(pthread_mutex_t& mutex) : _mutex(mutex) // references can only be initialized here
{
//pthread_mutex_init(&_mutex, NULL);
//_mutex = mutex;
pthread_mutex_lock(&_mutex);
std::cout << "acquired mutex\n";
_locked = true;
}
ScopedLock::~ScopedLock()
{
pthread_mutex_unlock(&_mutex);
std::cout << "destroyed mutex\n";
_locked = false;
}
void ScopedLock::lock()
{
if (_locked) return;
pthread_mutex_lock(&_mutex);
_locked = true;
}
void ScopedLock::unlock()
{
if (!_locked) return;
pthread_mutex_unlock(&_mutex);
_locked = false;
}
bool ScopedLock::isLocked()
{
return _locked;
}
int count = 0;
class Test
{
public:
Test() { pthread_mutex_init(&new_mutex, NULL); }
~Test() {}
void * compute(void * data);
private:
pthread_mutex_t new_mutex;
};
void * Test::compute(void * data)
{
int id = (int)data;
std::cout << "my thread id:" << id << "|" << pthread_self() <<
std::endl;
std::cout << "before mutex count = " << count << "|" << id << std::endl;
ScopedLock sl(new_mutex);
sleep(3);
std::cout << "after sleep mutex count = " << count << "|" << id << std::endl;
++count;
std::cout << "after Inc mutex count = " << count << "|" << id << std::endl;
}
template <class T>
class Launcher
{
public:
Launcher(T * obj, void * (T::*mfpt) (void *), void * arg) : myobj(obj), fpt(mfpt), myarg(arg) {}
~Launcher() {}
void launch() { (*myobj.*fpt)(myarg);}
private:
T* myobj;
void* myarg;
void * (T::*fpt) (void *); //Member function pointer
};
template <class T>
void * LaunchMemberFunction(void * obj)
{
Launcher<T> * l = reinterpret_cast<Launcher<T>*>(obj);
l->launch();
}
int main()
{
pthread_t threads[3];
Launcher<Test> * larray[3];
Test t;
for (int i = 0; i < 3; ++i)
{
std::cout << "In main: creating thread " << i << std::endl;
larray[i] = new Launcher<Test>(&t, &Test::compute, (void*)i);
std::cout << "address of l is " << larray[i] << std::endl;
int rc = pthread_create(&threads[i], NULL, LaunchMemberFunction<Test>, larray[i]);
if (rc)
{
std::cout << "Error: return code from pthread_create() is "
<< rc << " i= " << i << "\n";
exit(-1);
}
}
for (int i = 0; i < 3; ++i)
{
pthread_join(threads[i], NULL);
}
std::cout << "main thread count = " << count << std::endl;
//delete [] larray;
for (int i = 0; i < 3; ++i)
{
delete larray[i]; //cannot do delete [] larray here because larray has not been created by new
}
pthread_exit(NULL);
}
</code></pre>
|
[] |
[
{
"body": "<p>Technically pthreads is a C library.<br>\nThus the callback function you pass to pthread_create() must be a C function with C linkage. To do this in C++ code the function must be declared as extern \"C\".</p>\n\n<p>So it may work, but it is non portable and you just happen to be getting lucky that the compiler is using the same calling convention for C functions as for C++ functions. But because the C++ ABI is deliberately not defined this may not hold for all compilers.</p>\n\n<p>Once you are in your function it is perfectly legal to use all the C++ tricks.</p>\n\n<p>I like you personally like to use the <code>reinterpret_cast<>()</code> to convert the pointer back to its original type. But I believe I am in the minority on this one and most people use static_cast<>(). There have been several long discussions on SO about the usage (check there for details).</p>\n\n<p>Some minor modifications to make it legal:</p>\n\n<pre><code>class LauncherBase\n{\n public:\n virtual ~Launcher() {}\n\n virtual void launch() = 0;\n};\n\ntemplate <class T>\nclass Launcher: public LauncherBase\n....\n\nextern \"C\" void* LaunchMemberFunction(void* obj);\n\nvoid* LaunchMemberFunction(void* obj)\n{\n Launcher<T> * l = reinterpret_cast<LauncherBase*>(obj);\n l->launch();\n // should always return something from a non void function\n return NULL; // I would make launch return the result.\n}\n\nint main()\n{\n....\n int rc = pthread_create(&threads[i],\n NULL,\n LaunchMemberFunction,\n dynamic_cast<LauncherBase*>(larray[i])\n );\n....\n}\n</code></pre>\n\n<p>Your Scopped locks are messey.</p>\n\n<p>Why is there a manual lock()/unlock() these are going to lead to problems unless handled correctly. If you needed a way to temporarily unlock a locked mutex then you whould have had a scopped_unlock class that handles the unlocking/locking symetrically.</p>\n\n<p>Here:</p>\n\n<pre><code>void ScopedLock::unlock()\n{\n if (!_locked) return;\n pthread_mutex_unlock(&_mutex);\n _locked = false;\n}\n</code></pre>\n\n<p>You are introducing a potential race condition as _locked is modified outside the scope of beign locked.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T23:40:14.527",
"Id": "4591",
"ParentId": "4589",
"Score": "1"
}
},
{
"body": "<p>A few random points:</p>\n\n<p>I find it a little jarring that <code>Launcher</code> holds a <code>T*</code> as a member. In general when writing/reviewing C or C++ I like to be able to quickly answer questions like \"who releases this object, and when?\" By holding a potentially-dangling <code>T*</code> the way that you're doing, that ownership of resources becomes ambiguous, and handling deleting the objects in a safe way becomes tricky when you might have another thread working with it. I would consider a reference-counted smart pointer like <code>shared_ptr</code>.</p>\n\n<p>It's also a bit weird to me that <code>Launcher</code> is tied to method pointers. For more generality maybe <code>Launcher</code> should just be a template parameter that handles <code>operator ()</code>, then you can provide multiple implementations for this, including one that calls a method pointer. Maybe something like this:</p>\n\n<pre><code>template <class T>\nvoid *thread_creation_routine(void *ptr)\n{\n // This thread now owns deleting the object...\n // See pthread_create call below.\n //\n auto_ptr<T> arg(reinterpret_cast<T*>(ptr));\n return (*arg)();\n}\n</code></pre>\n\n<p>Then you could invoke it with something like:</p>\n\n<pre><code>template <class T>\nclass Launcher\n{\n shared_ptr<T> m_ptr;\n void *(T::*m_func)();\npublic:\n Launcher(shared_ptr<T> &ptr, void *(T::*func)()) : m_ptr(ptr), m_func(func) {}\n\n void *operator ()()\n {\n return (*m_ptr.*m_func)();\n }\n};\n</code></pre>\n\n<p>Note in this usage, <code>Launcher</code> is only one functor that can be passed to <code>thread_creation_routine</code>. You can envision others in the future. (Say, C++0x lambda expressions -- although at that point I'd say maybe you should look into the new thread stuff that's in C++0x.) Then finally you would tie it all together with something like this:</p>\n\n<pre><code>class MyDemo\n{\npublic:\n void *SayHello()\n {\n cout << \"Hello, threaded world!\" << endl;\n\n return 0;\n }\n};\n\nint main()\n{\n shared_ptr<MyDemo> myDemo(new MyDemo());\n Launcher<MyDemo> *myLauncher(new Launcher<MyDemo>(myDemo, &MyDemo::SayHello));\n\n pthread_t t;\n int r;\n\n if ((r=pthread_create(&t,\n NULL,\n thread_creation_routine<Launcher<MyDemo> >,\n myLauncher)))\n {\n // Failed to create the thread...\n // Thread_creation_routine cannot take ownership of the launcher, so\n // we delete it here.\n //\n delete myLauncher;\n\n cerr << \"pthread_create failed with error \" << r <<\n \" (\" << strerror(r) << \")\" << endl;\n return r;\n }\n\n // NB: this could theoretically fail; error checking omitted...\n //\n pthread_join(t, NULL);\n\n return 0;\n}\n</code></pre>\n\n<p>Note the only weird thing here is the ownership of <code>myLauncher</code>'s allocation. If we succeeded in creating the thread, the thread routine deletes it, otherwise <code>main</code> will. To make this sort of thing exception safe it might be advisable to wrap that allocation in RAII, but for this example it is not needed.</p>\n\n<p>Then notice with a quick rewrite of <code>Launcher</code> you can actually avoid the method pointer call entirely while still maintaining a lot of source code flexibility to change or re-use the thread creation routine:</p>\n\n<pre><code>class Launcher2\n{\n shared_ptr<MyDemo> m_ptr;\npublic:\n Launcher2(shared_ptr<MyDemo> &ptr) : m_ptr(ptr) {}\n\n void *operator ()()\n {\n return m_ptr->SayHello();\n }\n};\n</code></pre>\n\n<p>You can imagine a compiler generating better code when using this launcher. (Eg. the method call might be inlined into the thread creation routine. Also, function pointer calls are typically not as efficient on modern CPUs as simply calling a function.) In most cases this won't really make a difference, but if you had very frequent calls to something like this, it's a good thing to be aware of generally, and one of C++'s real strengths. You can also imagine additional launchers which carry parameters for the callee, cleanly releasing any acquired resources they get deleted.</p>\n\n<p>Also: for your scoped locks... It's rare, but <code>pthread_mutex_lock</code> can fail. I'm not sure off the top of my head what those failure conditions may be, but you might want to do something for that case, like throw an error.</p>\n\n<p>Lastly... I would re-iterate the earlier comment that maybe the C++0x thread support is right for you. (To be honest I haven't looked into it all that much, so I don't know much about it myself.) Failing that, maybe Boost.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T23:52:45.577",
"Id": "4592",
"ParentId": "4589",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4592",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-04T22:29:56.303",
"Id": "4589",
"Score": "2",
"Tags": [
"c++",
"multithreading"
],
"Title": "Passing a member function in pthread_create"
}
|
4589
|
<p>Are there any issues with below implementation?<br>
Input: from STDIN, a list of strings<br>
Output: serialize to a file called "out.txt" and then unserialize into a list of strings, and output to STDOUT </p>
<p>Goal is not here too much about code organization, but I would like to know if this code can fail for certain types of inputs </p>
<pre><code>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
using namespace std;
int main()
{
std::vector<std::string> input;
std::string tmp;
while (std::cin >> tmp)
{
input.push_back(tmp);
}
std::ofstream out("out.txt", std::ios::out);
for (std::vector<std::string>::const_iterator iter = input.begin();
iter != input.end();
++iter)
{
out << (*iter).size() << "|" << *iter;
}
out.close();
std::vector<std::string> output;
std::ifstream in("out.txt", std::ios::in);
if (in.is_open())
{
std::string tmp;
if (!in.eof())
{
getline(in, tmp);
size_t pos;
int length = 0;
std::string str;
while (!tmp.empty())
{
pos = tmp.find('|');
if (pos != std::string::npos)
{
length = atoi(tmp.substr(0, pos).c_str());
str = tmp.substr(pos+1, length);
tmp = tmp.substr(pos+str.size() + 1);
output.push_back(str);
}
}
}
in.close();
}
for (std::vector<std::string>::const_iterator iter = output.begin();
iter != output.end();
++iter)
{
std::cout << *iter << "\n";
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Looks like it will work fine.<br>\nYou preserve the string integrity in the file by maintaining its length as a separate entity that you can check independently. So it should work fine.</p>\n\n<p>Not sure why you copy it to intermediate arrays.<br>\nWhy not copy directly from input to file then from file to output?</p>\n\n<p>You implement most of the other loops so precisely. But the main loop to read from the file is a bit a bit bulky and messey. With an extra class you can make it look just like the others.</p>\n\n<pre><code>std::vector<std::string> output;\nstd::ifstream in(\"out.txt\", std::ios::in);\nMyStringReader reader;\n\nwhile(in >> reader)\n{\n output.push_back(reader);\n}\nin.close();\n</code></pre>\n\n<p>So now you just need to define the MyClassReader</p>\n\n<pre><code>struct MyStringReader\n{\n std::string data;\n operator std::string const&() {return data;} // This is used in the line\n}; // output.push_back(reader) and converts\n // the reader object into a string before\n // it is pushed\n\nstd::istream& operator>>(std::istream& stream, MyStringReader& value)\n{\n size_t length;\n char sep = 'X';\n\n // Use the stream operators to get the size (and separator)\n // Much nicer than using tha atoi() function.\n //\n if ((stream >> length >> sep) && (sep == '|'))\n {\n // Resize the string to the correct size and put the word into it.\n value.data.resize(length);\n stream.read(&value.data[0], length);\n }\n return stream;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T19:03:43.180",
"Id": "4602",
"ParentId": "4593",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4602",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T00:47:35.140",
"Id": "4593",
"Score": "1",
"Tags": [
"c++",
"strings"
],
"Title": "Serialization/Unserialization of a list of strings - C++"
}
|
4593
|
<p>I wrote a language in C, dubbed <code>gecho</code>. The code can be found <a href="http://github.com/tekknolagi/gecho/tree/testing" rel="nofollow">here</a>.</p>
<p>I'm writing this for a purely educational reason (not for school at all) and I just hope to make it Turing complete, and to improve the structure. The basic syntax is in the README. Let me know if you happen to do anything super cool with a gecho program.</p>
<p>Just some criticism (harsh, please) would be lovely!</p>
<blockquote>
<p><strong>functions.h:</strong> functions to operate on the stack ->
i have all the commands here, really</p>
<p><strong>gecho.c:</strong> main REPL for interpreter ->
has main() and an eval() function that interprets each 'word'</p>
<p><strong>gechoc.c:</strong> main eval loop for compiler ->
has main() and an eval() function that interprets each 'word' and fprintfs >equivalent
C code</p>
<p><strong>header.h:</strong> template for compilation ->
includes necessary headers and is itself included while writing to a .c file</p>
<p><strong>stack.h:</strong> stack implementation ->
operations with the stack: push, pop, show, that kind of thing</p>
<p><strong>structdef:</strong> definitions for structs (like modes and constants) ->
has the mode struct defined, the constant struct defined</p>
<p><strong>structs.h:</strong> structs ->
holds the mode, constant, variable struct defined</p>
<p><strong>usefunc.h:</strong> gets all necessary headers and #defines some stuff ->
a catch-all for includes and preprocessor directives</p>
</blockquote>
|
[] |
[
{
"body": "<p>It looks like you have some of basics of language development, so well done for a first start.</p>\n\n<p>I'd say that you want to avoid things like your RES_SIZE and VAR_SIZE constants. Where do these numbers come from? Are they designed to be suitable for the system that you're running on? What about someone else's system? What about in five years? What about the system running on someone's phone? It's generally best to allocate resources as you need them, and to not place any arbitrary restrictions of how many of anything you can have. When system resources run out, you will get back error messages from functions like fork or malloc, and then you know you're out of resources.</p>\n\n<p>You may think they're only there until you put a proper allocation system in place, but will you really remember to go back and fix them all? Best to do it right in the first place.</p>\n\n<p>Have you read some books on language development. There are loads of them, and some of them are very good and very readable. If you take a week off programming, and instead read something like the dragon book (http://dragonbook.stanford.edu/), you will come back with a much clearer idea of what you're doing.</p>\n\n<p>Good luck.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T04:50:35.973",
"Id": "6907",
"Score": "0",
"body": "Thank you for the memory allocation tip and Dragon Book tip as well!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T13:24:01.717",
"Id": "4598",
"ParentId": "4596",
"Score": "4"
}
},
{
"body": "<p>Okay, here are some things I noticed after a quick scan through the code:</p>\n\n<p>The first thing that jumped at me that you put your function definitions in your header files. I'm not sure why you chose to do this, but it is almost definitely a bad idea. Please only put the prototypes in the header and put the definitions in c-files (and then adjust the build process accordingly).</p>\n\n<p>Your header files also don't have any <a href=\"http://en.wikipedia.org/wiki/Include_guard\" rel=\"nofollow\">#include guards</a>. You should fix that as well.</p>\n\n<hr>\n\n<p>You should also always compile your code with warnings enabled. Doing so will warn you about the following bugs:</p>\n\n<ul>\n<li>In functions.h there are two functions which call <code>printf</code> with an empty string as its parameter. Since that does nothing at all, this is either a bug (if you meant it to do something other than nothing) or just plain unnecessary code.</li>\n<li>In gecho.c you have a variable <code>tmp</code> that you never use. In gechoc.c you have a variable <code>msg</code> that you also never use.</li>\n<li>In both <code>eval</code> functions you never return a value even though the functions are declared to return an <code>int</code>. Since you never use their return value either, I suppose they should just be <code>void</code>.</li>\n</ul>\n\n<p>You should also be aware that your code does not compile if you enable strict ansi compliance (no matter whether C90 or C99) on account of using several non-standard extensions like for example the <code>bool</code> datatype (I'm not going to list all of them here - you can just try to compile with <code>-ansi</code> and you can see the errors for yourself).</p>\n\n<hr>\n\n<p>Both your <code>eval</code> functions are way too long. They also seem to be quite similar to each other in parts. I'd say this is definitely in need of some refactoring. You should split the functions into multiples shorter functions and move the common stuff out into functions that are shared between both components.</p>\n\n<p>Also the <code>eval</code> function of the compiler should not actually be called <code>eval</code>. It does not actually evaluate anything, it just generates code. Consequently it should be called something along the lines of <code>codegen</code> or <code>generate_code</code>.</p>\n\n<hr>\n\n<p>On a language design note I think the <code>..</code> command is rather badly named as it does not do what one would expect (or what I would expect at least): Given the fact that in most cases <code>opop</code> seems to do the same thing as <code>op</code>, but for the entire stack (e.g. <code>+</code> adds two numbers and <code>++</code> adds the entire stack) and the fact that <code>.</code> (pops and) prints one element, I'd expect <code>..</code> to (pop and) print the entire stack, instead of just popping it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T04:46:20.547",
"Id": "6906",
"Score": "0",
"body": "Thank you for your long feedback. Why is it bad to put functions in headers? Are single-line comments not allowed with `-ansi`? How do you suggest I refactor the eval/codegen functions? Also thank you for the tip - i'll rename `..` to `dels`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T07:01:35.583",
"Id": "6910",
"Score": "0",
"body": "@tekknolagi: Putting definitions into headers is bad because: 1. It will lead to linker errors if you try to link multiple objects that included the same header. 2. It makes modular compilation impossible (if multiple c files include the same header, the code in the header will be compiled each time, whereas if it was in its own .c file, it would be compiled only once). 3. You won't get forward-declarations for your functions for free (which you would if you had the prototypes in a header and included that in the .c file which contains the definitions)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T07:05:00.383",
"Id": "6911",
"Score": "0",
"body": "@tekknolagi: On a related note I've just noticed that you also don't have any `#include` guards in your headers. You should fix that as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T07:08:14.277",
"Id": "6912",
"Score": "0",
"body": "@tekknolagi: Single line comments are allowed by C99, but not by C90. `-ansi` uses C90 by default. If you use `-std=c99`, you won't get complaints about the single line comments anymore (but still about stuff like `bool`, `true` and `false` being undefined)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T00:35:31.013",
"Id": "6931",
"Score": "0",
"body": "sepp2k: i thank you for the word on headers. also, what are #include guards? and i defined true and false as an enum named bool."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T07:12:41.490",
"Id": "6936",
"Score": "0",
"body": "@tekknolagi: [#include guards](http://en.wikipedia.org/wiki/Include_guard) are what people do to prevent a header from accidentally being included more than once. It's common practice in C, as it quickly becomes very cumbersome to make sure each header is only included once otherwise."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T00:40:30.670",
"Id": "6980",
"Score": "0",
"body": "added them and pushed"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T18:46:00.783",
"Id": "4601",
"ParentId": "4596",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4601",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T05:22:14.240",
"Id": "4596",
"Score": "-1",
"Tags": [
"c"
],
"Title": "My language, gecho"
}
|
4596
|
<p>I'm a beginning Scala programmer with a strong background in functional programming (ML, Haskell, Scheme) and I've just written my first Scala program. It is an implementation of a FSA (finite state automaton). Below is a simplified version that has 3 events/actions/labels (E0, E1, E2) and four states (S0, S1, S2, S3).</p>
<pre><code> sealed abstract class Event
case object E0 extends Event
case object E1 extends Event
case object E2 extends Event
abstract class State { def event ( e : Event ) : State }
object S0 extends State {
override def event ( e : Event ) : State = {
e match {
case E0 => { S1 }
case E1 => { S0 }
case E2 => { S2 } } } }
object S1 extends State {
override def event ( e : Event ) : State = {
e match {
case E0 => { S1 }
case E1 => { S2 }
case E2 => { S0 } } } }
object S2 extends State {
override def event ( e : Event ) : State = {
e match {
case E0 => { S2 }
case E1 => { S0 }
case E2 => { S3 } } } }
object S3 extends State {
override def event ( e : Event ) : State = {
e match {
case E0 => { S0 }
case E1 => { S3 }
case E2 => { S3 } } } }
class Fsa {
private var state : State = S0
def event ( e : Event ) : Unit = { state = state.event ( e ) } }
</code></pre>
<p>A typical use of <code>Fsa</code> objects would be like this:</p>
<pre><code>val fsa = new Fsa
while ( true ) {
fsa.event ( ... nextEvent () ) }
</code></pre>
<p>I'd be interested to know if you think this is a good, or at least reasonable way
of implmenting FSAs in Scala, and if not, why. I'm particularly interested in the memory consumption of solutions like this.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T20:15:50.710",
"Id": "6964",
"Score": "1",
"body": "If you look for alternative implementations, Akka has an interesting FSM implementation (with actors, of course, but it is easy to reduce it without them, I did that for a lightweight program)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T10:59:10.100",
"Id": "7036",
"Score": "0",
"body": "Wow, thank you very much, interesting. Akka is one of the reasons why I decided to learn Scala. I shall look at the Akka FSM in detail when mygrasp of Scala is more firm."
}
] |
[
{
"body": "<p>Looks fine to me. You don't need so much parens:</p>\n\n<pre><code>object S0 extends State {\n override def event (e : Event) : State = e match {\n case E0 => S1 \n case E1 => S0 \n case E2 => S2 \n } \n} \n</code></pre>\n\n<p>But in this easy example I would use a <code>Map</code> to encode the transition rules (<strong>corrected</strong>):</p>\n\n<pre><code>sealed abstract class State {\n def m: Map[Event, State]\n def event ( e : Event ) : State = m(e)\n}\n\nobject S0 extends State{ lazy val m = Map[Event, State](E0 -> S1, E1 -> S0, E2 -> S3) }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T10:56:47.577",
"Id": "6916",
"Score": "0",
"body": "Thank you, very interesting, and much simpler than my proposal, but when I compile it, I get \"error: super constructor cannot be passed a self reference unless parameter is declared by-name\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T12:12:51.370",
"Id": "6918",
"Score": "1",
"body": "Sorry, I corrected my example. I overlooked that we have cyclic dependencies when constructing `S0`..`S3`. The easiest way to deal with this is using a `lazy val`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T12:41:31.273",
"Id": "6919",
"Score": "0",
"body": "Thanks, your program compiles now without modification. I wonder why though, as S1, S3, E0, E1 and E2 are undefined. My type-theoretic intuition tells me this should not type-check. Clearly, I still have a lot to learn about Scala."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T20:19:47.697",
"Id": "6926",
"Score": "0",
"body": "Of course you need the rest of the definitions as well. I guess the other class files are still there from your previous build."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T08:02:14.287",
"Id": "6940",
"Score": "0",
"body": "Interesting. So you are saying that whether a Scala program type-checks or not does not just depend on the program but also on what kind of other files are around (without explicit imports)? That's rather surprising to me."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T07:00:23.610",
"Id": "4611",
"ParentId": "4597",
"Score": "3"
}
},
{
"body": "<p>Following suggestions from <a href=\"https://codereview.stackexchange.com/users/3141/landei\">Landei</a> above, and <a href=\"http://www.scala-lang.org/node/2541\" rel=\"nofollow noreferrer\">this</a> article on recursive type declarations in Scala, I've come up with a slightly different solution where states are directly modelled as state transitions.</p>\n\n<pre><code>trait StateFunc [ T ] extends PartialFunction [ T, StateFunc [ T ] ]\n\nsealed abstract class Event\n\ncase object E0 extends Event\ncase object E1 extends Event\ncase object E2 extends Event\n\nclass FSA {\n private type State = StateFunc [ Event ]\n\n private def transitions [ T ] ( pf : PartialFunction [ T, StateFunc [ T ] ] ) = new StateFunc [ T ] {\n def apply( event : T ) = pf ( event )\n def isDefinedAt ( event : T ) = pf.isDefinedAt ( event ) }\n\n private val ( s0 : State ) = transitions { case E0 => s1; case E1 => s2; case E2 => s0 }\n private val ( s1 : State ) = transitions { case E0 => s3; case E1 => s0; case E2 => s1 }\n private val ( s2 : State ) = transitions { case E0 => s2; case E1 => s1; case E2 => s0 }\n private val ( s3 : State ) = transitions { case E0 => s3; case E1 => s3; case E2 => s1 }\n\n private var state = s0\n\n def handle ( e : Event ) { state = state ( e ) } }\n</code></pre>\n\n<p>I'm not saying that this is better than the other solutions proposed, but I wonder about memory usage. Clearly, as this is a highly recursive construct, if the compiler doesn't do tail-call optimisation, this solution will run out of memory eventually. I have no understanding of the Scala compiler, but I would imagine that in this simple case the tail calls are optimised to ensure constant stack space usage. But what if the transition functions do something more complicated (e.g. possibly throwing exceptions)? Can constant space usage still be guaranteed?</p>\n\n<p>As an aside, is it really necessary to go through so many hoops to define a recursive type? Why can I not simply write e.g. <code>type T = Map [ Int, T ]</code>?</p>\n\n<p><b>Edit 9.9.2011:</b> I added @tailrec annotations to the program above with the following results: The compiler accepts @tailrec on s0, ..., s3 just fine. But it balks when I annotate the private definition of transitions, which is not surprising. What that means in practise for stack-space usage of this form of implementing FSAs I don't know.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T13:39:23.580",
"Id": "4615",
"ParentId": "4597",
"Score": "4"
}
},
{
"body": "<p>A better way to implement your FSM is to use our company <a href=\"https://github.com/anduintransaction/scala-fsm\" rel=\"nofollow noreferrer\">open source FSM implementation</a>. It's strongly typed and invalid transitions won't compile. Your code will look some what like this:</p>\n\n<pre><code>// States\ncase object S0 extends State\ncase object S1 extends State\ncase object S2 extends State\ncase object S3 extends State\n\n// Inputs\ncase object E0 extends Input\ncase object E1 extends Input\ncase object E2 extends Input\n\n// Transitions\nimplicit val tS0S1 = Transition[S0.type, E0.type, S1.type]((_, _) => S1)\n// more transitions\n\n// State machine\nFsm(S0).transition(E0) // return Fsm(S1)\nFsm(S0).transition(E0).transition(E1).transition(E2) // return Fsm(S3)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-05-18T05:45:33.627",
"Id": "163618",
"ParentId": "4597",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4611",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T11:09:08.900",
"Id": "4597",
"Score": "6",
"Tags": [
"scala"
],
"Title": "FSA (finite state automaton) in Scala"
}
|
4597
|
<p>I'm trying to get a list of all artists on an iPhone / iPod touch music library. The best way I've found has been to group by artists (the convenience constructor on MPMediaQuery) and to iterate over the collections, being one for each artist. That way I've optimized out having to use an NSSet to ensure uniqueness in the artist list. Still, I need to make each collection into a representative item and get it's artist, which according to Time Profiler takes a very good part of this code snippet.</p>
<pre><code>NSString *artistKey = [MPMediaItem titlePropertyForGroupingType:MPMediaGroupingArtist];
MPMediaQuery *artistsQuery = [MPMediaQuery artistsQuery];
NSMutableArray *artists = [NSMutableArray arrayWithCapacity:artistsQuery.collections.count];
for (MPMediaItemCollection *album in artistsQuery.collections) {
MPMediaItem *albumItem = [album representativeItem];
[artists addObject:[albumItem valueForProperty:artistKey]];
}
</code></pre>
<p>Wrapping it in some timing blocks, such as below, I've gotten it to run in 0.315 seconds on my iPhone 4 with a library of ~2600 songs and 88 artists, but I feel like that long for only 88 items is way too long.</p>
<pre><code>NSTimeInterval start = [[NSDate date] timeIntervalSince1970];
// [snip]
NSTimeInterval finish = [[NSDate date] timeIntervalSince1970];
NSLog(@"Execution took %f seconds.", finish - start]);
</code></pre>
<p>Does anyone know of a way to make this a bit faster?</p>
|
[] |
[
{
"body": "<p>Is it actually necessary to add just the artist to the array? We could simply do this:</p>\n\n<pre><code>NSMutableArray *artists = artistsQuery.collections;\n</code></pre>\n\n<p>Now we don't have to iterate through an entire array. And later, when we need to access the artist at a particular array index, we can still get to that value as such:</p>\n\n<pre><code>[[artists[someIndex] representativeItem] valueForProperty:artistKey];\n</code></pre>\n\n<hr>\n\n<p>Also, this <a href=\"https://stackoverflow.com/a/15125179/2792531\">SO answer</a> seems to suggest that <code>valueForProperty:</code> is just slow in general. Despite only needing the artist, it might be better to enumerate through all the properties:</p>\n\n<pre><code>[artistsQuery.collections enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {\n MPMediaItem *item = (MPMediaItem *)obj;\n [item enumerateValuesForProperties:properties usingBlock:^(NSString *property, id value, BOOL *stop) {\n if ([property isEqualToString:artistKey]) {\n [artists addObject:value];\n }\n }];\n}];\n</code></pre>\n\n<p>At first glance it may seem like this will automatically be slower since you're iterating through every property instead of just accessing the one you need, and in this case, since you only need a single property, this may actually be slower. But if you need multiple properties, this should definitely be faster--enumerations like this (as well as <code>forin</code> loops) are handled in batches so they run quite fast.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-07T02:01:51.333",
"Id": "99082",
"Score": "0",
"body": "You'd think they'd optimize `valueForProperty:` rather than document it's slowness. I'm not working on this code anymore but I'm accepting the answer since it sounds right. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-07T02:02:33.180",
"Id": "99083",
"Score": "0",
"body": "Yeah, I agree. Certainly seems odd. `valueForProperty:` seems significantly less clunky to use, so it's too bad it appears to be documented as inefficient."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-06T01:35:47.610",
"Id": "56242",
"ParentId": "4605",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "56242",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-05T23:04:12.937",
"Id": "4605",
"Score": "7",
"Tags": [
"objective-c",
"ios",
"search"
],
"Title": "Optimizing a search for list of artists in iTunes library"
}
|
4605
|
<p>So I have some Javascript code that resembles the following:</p>
<pre><code>var mylibrary = new (function ()
{
this._getLibraryObj = function ()
{
var newLibraryObj = {};
var libraryData = window.specifiedLibraryData;
// Add head librarian details
// open library
// etc. etc. turn into an object from data
return newLibraryObj ;
};
this.item = function (item)
{
if (this.obj && item in this.obj)
{
return this.obj[item];
}
else
{
this.obj = this._getLibraryObj();
if (item in this.obj)
{
return this.obj[item];
}
return null;
}
};
return this;
})();
</code></pre>
<p>What annoys me is that <code>this.item(item)</code> function repeats the <code>item in this.obj[item]</code> and I find it a little hard to read. I was hoping for it to not have to run <code>_getLibraryObj</code> too often. </p>
<p><strong>Question:</strong> How would you rewrite <code>this.item()</code> to be short and sweet <em>(DRY and readable)</em>?</p>
<p><strong>EDIT:-</strong> From alex's post I realised I left out one constraint: If the item isn't in the library object then it might need to <code>_getLibraryObj()</code> again as the data may have changed</p>
<p><strong>Solution:-</strong> I ended up using <a href="https://codereview.stackexchange.com/users/6301">@Alex Nolan</a>'s fifth example <em>(with <code>||</code> instead of <code>&&</code> I find it easier to read.)</em>:</p>
<pre><code>this.item = function(item)
{
if(!this.obj || !item in this.obj)
{
this.obj = this._getLibraryObj();
}
return this.obj[item] || null;
}
</code></pre>
|
[] |
[
{
"body": "<p>Another downfall of your <code>this.item()</code> function is that if <code>item</code> isn't in <code>this.obj</code>, <code>this._getLibraryObj()</code> will be called every time.</p>\n\n<p>Try</p>\n\n<pre><code>this.item = function(item) {\n if (this.obj) {\n return this.obj[item] || null;\n } else {\n this.obj = this._getLibraryObj();\n return this.item(item);\n }\n};\n</code></pre>\n\n<p>Or if you want it even more minimal:</p>\n\n<pre><code>this.item = function(item) {\n if (this.obj) \n return this.obj[item] || null;\n\n this.obj = this._getLibraryObj();\n return this.item(item);\n};\n</code></pre>\n\n<p>If you switch up the statements a little bit you get the most readable IMHO:</p>\n\n<pre><code>this.item = function(item) {\n if (!this.obj) \n this.obj = this._getLibraryObj();\n\n return this.obj[item] || null;\n};\n</code></pre>\n\n<p>One final way to do it would be to do:</p>\n\n<pre><code>this.item = function(item) {\n this.obj = this.obj || this._getLibraryObj();\n\n return this.obj[item] || null;\n};\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>In light of your comment about needing to re-call getLibraryObj</p>\n\n<pre><code>this.item = function(item) {\n if (!(this.obj && item in this.obj))\n this.obj = this._getLibraryObj();\n\n return this.obj[item] || null;\n};\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>this.item = function(item) {\n this.obj = this.obj && item in this.obj ? this.obj : this._getLibraryObj();\n\n return this.obj[item] || null;\n};\n</code></pre>\n\n<p>or a one-liner:</p>\n\n<pre><code>this.item = function(item) {\n return (this.obj = (this.obj && item in this.obj ? this.obj : this._getLibraryObj()))[item] || null;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T04:09:32.197",
"Id": "6904",
"Score": "0",
"body": "Sorry I left one thing out. If the item isn't in the library object then it might need to `_getLibraryObj()` again as the data may have changed. I do really like that \"final way\" Nice and simple ... how could I have not thought of it!?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T04:23:42.547",
"Id": "6905",
"Score": "0",
"body": "I guess I could put an `if(!item in this.obj){ this.obj = this._getLibraryObj();}` or use the second last example and change the if to `if(!this.obj || !item in this.obj)` *(just thought of a one liner: `return item in (this.obj = this.obj || this._getLibraryObj()) ? this.obj[item] : (this.obj = this._getLibraryObj())[item] || null;`)*"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T03:58:39.360",
"Id": "4609",
"ParentId": "4606",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4609",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T00:52:21.777",
"Id": "4606",
"Score": "1",
"Tags": [
"javascript"
],
"Title": "Javascript get item in object code"
}
|
4606
|
<p>For a site I wrote this JS contact parser. It simply reads contacts and parses links if a known service is identified. Could this be made more compact? How about robustness? (it cannot handle exceptions where the url does not begin with http for instance). What other services should I consider to add?</p>
<p>Here is <a href="http://jsfiddle.net/majidf/96Gk6/" rel="nofollow">jsfiddle</a>. And the code is below:</p>
<p><strong>Markup</strong></p>
<pre><code><div id="contacts"></div>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>span { padding: 10px; }
</code></pre>
<p><strong>JS</strong></p>
<pre><code>var contacts = 'guy@gmail.com, guy@owndomain.com, http://twitter.com/guy, http://www.facebook.com/profile.php?id=100002877203519, http://www.linkedin.com/in/coolguy, http://www.myspace.com/coolguy, skype:cool.guy?call, aim:goim?screenname=cool.guy, http://coolguy.com';
var re = / /gi;
contacts = contacts.replace(re, "");
contacts = contacts.split(',');
var picBase = 'http://jqeedu.tuxfamily.org/images/media/';
jQuery(document).ready(function() {
for (var i = 0; i < contacts.length; i++) {
addContact(contacts[i]);
}
});
function addContact(c) {
cdiv = jQuery("#contacts");
var i = false;
var h = '';
var n = '';
if(c.indexOf('@gmail.com') != -1) {
i = 'gmail.png';
h = 'mailto:'+c;
}
if(!i && c.indexOf('http://www.facebook.com/profile.php?id=') == 0) {
i = 'facebook.png';
h = c;
}
if(!i && c.indexOf('http://www.linkedin.com/in/') == 0) {
i = 'linkedin.png';
h = c;
}
if(!i && c.indexOf('http://www.myspace.com/') == 0) {
i = 'myspace.png';
h = c;
}
if(!i && c.indexOf('skype:') == 0 && c.indexOf('?call') != -1) {
i = 'skype.png';
h = c;
}
if(!i && c.indexOf('aim:goim?screenname=') == 0 ) {
i = 'aim.png';
h = c;
}
if(!i && c.indexOf('http://twitter.com/') == 0) {
i = 'twitter.png';
h = c;
}
if(!i && c.indexOf('http://') == 0) {
i = 'website.png';
h = c;
}
if(!i) {
i = 'email.png';
h = 'mailto:'+c;
}
n = '<span><a href="'+h+'"><img src="'+picBase+i+'"></a></span>';
cdiv.append(n);
}
</code></pre>
|
[] |
[
{
"body": "<p>Firstly I would change all the occurances of </p>\n\n<pre><code>}\n\nif(!i && c.indexOf(...\n</code></pre>\n\n<p>to </p>\n\n<pre><code> } else if(c.indexOf(...\n</code></pre>\n\n<p>To me there doesn't seem to be any difference logically and its cleaner.</p>\n\n<p>Second I would use regexes for the urls <em>(I'm sure someone will comment on how regexes aren't needed/ too slow yadda yadda.)</em></p>\n\n<pre><code>var regexFBprofile = /^(http\\:\\/\\/)?(www\\.)?facebook\\.com\\/profile\\.php\\?id=/;\nvar regexLinkedIn = /^(http\\:\\/\\/)?(www\\.)?linkedin\\.com\\/in\\//;\nvar regexMySpace = /^(http\\:\\/\\/)?(www\\.)?myspace\\.com/;\nvar regexTwitter = /^(http\\:\\/\\/)?(www\\.)?twitter\\.com\\//;\n</code></pre>\n\n<p>another small thing:</p>\n\n<pre><code>re = / /g;\ncontacts = contacts.replace re, \"\");\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>contacts[i].trim();\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/96Gk6/34/\" rel=\"nofollow\">http://jsfiddle.net/96Gk6/34/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T05:37:33.993",
"Id": "6908",
"Score": "0",
"body": "+1 Thanks. Do the regexes cause the script to identify all variants of urls? - `facebook.com`, `http://facebook.com`, `http://www.facebook.com`, `www.facebook.com`, ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T06:03:03.323",
"Id": "6909",
"Score": "0",
"body": "@majid the regexes in english are: `^` start of the string, then optionally contains `http://` and/or optional `www.` plus mandatory domain `domain.com`. **So in short: Yes.**"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T03:36:08.897",
"Id": "4608",
"ParentId": "4607",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4608",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T02:40:00.150",
"Id": "4607",
"Score": "0",
"Tags": [
"javascript"
],
"Title": "Better JS Contact Parser"
}
|
4607
|
<p>I have an array of objects eg.</p>
<p>[
array(
'id' => 1,
'name' => "simon"
),
...
]</p>
<p>and I need to get an array of IDs eg.
[1,2,3,4,5];</p>
<p>Currently I'm doing this:</p>
<pre><code> $entities = $this->works_order_model->get_assigned_entities($id);
$employee_ids = array();
foreach ($entities as $entity) {
array_push($employee_ids, $entity->id);
}
</code></pre>
<p>Is there a best practice way of doing this?</p>
|
[] |
[
{
"body": "<p>I think array_map is what you are looking for:</p>\n\n<pre><code>php > $aa = array (array (\"id\" => 1, \"name\" => 'what'), array('id' => 2));\nphp > function id($i) { return $i['id'];};\nphp > print_r(array_map ('id', $aa));\nArray\n(\n [0] => 1\n [1] => 2\n)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-12T22:08:18.473",
"Id": "7144",
"Score": "0",
"body": "Thanks for this. Is the function id() necessary? \nI don't see it being used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-13T01:23:05.220",
"Id": "7157",
"Score": "1",
"body": "It is used as the first argument to array_map (the first argument is a string that is the name of a function to use)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T14:33:12.953",
"Id": "4616",
"ParentId": "4610",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4616",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T05:27:48.420",
"Id": "4610",
"Score": "3",
"Tags": [
"php",
"array"
],
"Title": "Getting an array from one property of an associative array best practice"
}
|
4610
|
<p>After I made a change to the html structure for a project, I found myself having to change many jquery selectors in many places. To avoid this problem in the future I decided to make a simple function where I pass an element indicating where I am and a string indicating where I want to go. This function should apply whatever logic is necessary to access the given endpoint. I showed this code to someone and he didn't like it, he said I should use multiple functions or an object. I thought that would make the code too much longer for little to no benefit, but I'm not really sure. The code below is for <a href="http://taskranger.com" rel="nofollow">this tool</a>, which is a tree-based time-tracking app, so for example, "node" refers to a node in the tree. The logic is not exhaustive as I only add code to the function on an as-needed basis.</p>
<pre><code>// Access one particular element from another.
function from(start, end) {
start = $(start)
if(start.parent().hasClass('headline')) {
var node = start.parent().parent()
if(end == 'node') return node
else if(end == 'model') return get_model(node.attr('model_id'))
}
if(end == 'headline') return start.children('.headline')
if(end == 'child_list') return start.children('ol')
if(end == 'each_child') return start.find('> ol > .model')
if(end == 'parent') return start.parents('.model')
if(end.indexOf('.') != 0) end = '.' + end
if(start.hasClass('headline')) return $(start.children(end))
return start.find('> .headline > ' + end)
}
</code></pre>
|
[] |
[
{
"body": "<p>The answer depends, for me, on many things. Some are:</p>\n\n<ul>\n<li>is it a prototype or not? Looks like it is</li>\n<li>are you in a rush? If so, do whatever works for you IF it's a prototype.</li>\n<li>how big will the whole project be?</li>\n</ul>\n\n<p>Here's a list of things that bother me:</p>\n\n<ol>\n<li><p>Function name: <code>from</code>? Might make sense to you but it's not a very good name. It's too...generic. I'd take <code>swissArmyKnifeFromElement</code> over <code>from</code> any day - easy to remember, hard to confuse. If this method is somehow part of an object (like your <code>Tree</code>), then it might be OK for a private function.</p></li>\n<li><p>The arguments might mean something else too - <code>start</code> and <code>end</code> suggest a range. It's potentially misleading. <code>end</code> can be many things (two, so far): a rule, like <code>'node'</code> or <code>'child_list'</code> or a class name. Again, misleading - it will only bring pain.</p>\n\n<pre><code>function findTreeElements(root, rule, params)\n{\n //implementation\n}\n\n//you could call it like this\nfindTreeElements(a,'class',{'name':'someClassName'});\nfindTreeElements(a,'headline');\n</code></pre></li>\n<li><p>The more your project grows, the more complex this function will become - in ways that you cannot foresee :) Maybe that's why your friend was talking about objects and multiple functions. jQuery uses objects everywhere and I think that you should do that too:</p>\n\n<ul>\n<li>define a tree/list object</li>\n<li>define a task/node/whatever object</li>\n<li>have the tree keep a list of tasks/nodes/etc</li>\n<li>define the methods for manipulating the tree/node/whatever inside the associated objects</li>\n</ul>\n\n<p>something like (totally random, possibly related, example):</p>\n\n<pre><code>var list = tree.findNode(someNodeNameOrIndex).tasks();\n</code></pre>\n\n<p>It's up to <code>Tree</code> object to manage its list of nodes and implement the <code>findNode</code> method (that parses the DOM whatever way you like).</p>\n\n<p>It's up to the <code>Node</code> object (returned by Tree's findNode) to manage the list of tasks inside that node (or something similar) and implement the tasks function which would work in a similar way to your current <code>find(elem, 'child_list')</code>.</p></li>\n</ol>\n\n<p>Look at the code written by 'better' javascript developers and learn from them. There are many good projects out there that can teach you a lot. Look for decent sized projects, not 'plugins' or basic snippets; browser extensions are also good candidates. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T10:40:45.787",
"Id": "6914",
"Score": "0",
"body": "Nice critique. A lot better than what I was expecting. I somewhat disagree about point 1. I like short function names cuz they're easy to type and take up little space, and I think the comment provides a sufficient explanation. I think your point about the 'end' argument meaning two different things is a good one -- that could get confusing. I also agree about point 3, but I think that since a more sophisticated structure is not immediately needed, building one now would be a form of premature optimization. Thanks for the thoughts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T05:10:39.247",
"Id": "7030",
"Score": "0",
"body": "I don't believe in 'though shall not' type laws so yes, some things might not make sense in your case (I'm not trying to imply that I'm right anyway) and might simply slow you down with no other benefits. However, it sounds like you're working (mostly) alone on this project - introduce a team and priorities will change :) I wrote about the short names with other people in mind, mostly; you want your code to be readable not only by you but by others too - if you can avoid confusion, avoid it early."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T05:18:10.437",
"Id": "7031",
"Score": "0",
"body": "Regarding point 3:I wouldn't call it premature optimization (everyone seems to be afraid of it but it's not that bad, provided you have enough experience and KNOW what you're doing). I might call it over-engineering and it can be bad; in this case, if you want to grow this project beyond the 'prototype' level, I think that you'll need to structure it a bit better and make use of some sort of object oriented approach - otherwise, it can quickly grow into a spaghetti mess that nobody will want to come anywhere near of; separation of concerns / object oriented programming might fix that."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T09:11:06.027",
"Id": "4613",
"ParentId": "4612",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4613",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T07:10:36.670",
"Id": "4612",
"Score": "2",
"Tags": [
"javascript",
"jquery"
],
"Title": "Using one function to go from one element to another"
}
|
4612
|
<p>Is the code below safe from SQL injection?</p>
<pre><code><?
mysql_connect ("localhost", "db","pass") or die (mysql_error());
mysql_select_db ("db");
$term = mysql_real_escape_string($_POST['term']);
$sql = mysql_query("select * from tblListings where category like '%$term%' or title like '%$term%' or postcode like '%$term%' or info like '%$term%' ");
function highlight($needle, $haystack)
{
return preg_replace('/(' . preg_quote($needle, '/') . ')/i', '<mark>$1</mark>', $haystack);
}
while ($row = mysql_fetch_array($sql)){
echo '<br/> Category: ' . highlight($term, $row['category']);
echo '<br/> Title: ' . highlight($term, $row['title']);
echo '<br/> Address: ' . highlight($term, $row['add1']);
echo '<br/> Street: ' . highlight($term, $row['street']);
echo '<br/> City: ' . highlight($term, $row['city']);
echo '<br/> Postcode: ' . highlight($term, $row['postcode']);
echo '<br/> Phone: ' . highlight($term, $row['phone']);
echo '<br/> E-Mail: ' . highlight($term, $row['email']);
echo '<br/> Website: ' . highlight($term, $row['website']);
echo '<br/> Info: ' . highlight($term, $row['info']);
echo '<br/><br/>';
//echo '<br/> E-Mail: '.$row['email']; use this for the fields that you dont want to search
}
?>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-22T16:14:31.120",
"Id": "148007",
"Score": "1",
"body": "As far as I know it is safe from SQL injection, but it is vulnerable to HTML/Javascript injection (xss attacks) unless the details in the database are explicitly stored in HTML form. If they are stored as plain text then you need htmlspecialchars() or similar when outputting them as html."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-06-04T13:00:03.257",
"Id": "168270",
"Score": "0",
"body": "You also should escape `%` and `_` because they're wildcard characters in LIKE expression. You can test this by searching for `%`."
}
] |
[
{
"body": "<p>I <strong>HIGHLY</strong> suggest using PHP PDO with prepared statements ALONG with filtering each field for specific accepted characters. </p>\n\n<p>But to answer your question, your method above is no longer considered safe and can be exploited. </p>\n\n<p>PDO & Tutorial:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow\">http://php.net/manual/en/book.pdo.php</a> </li>\n<li><a href=\"http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/\" rel=\"nofollow\">http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/</a></li>\n</ul>\n\n<p>You can use <a href=\"http://php.net/manual/en/function.preg-match.php\" rel=\"nofollow\"><code>preg_match</code></a> to filter for specific character sequences. </p>\n\n<p>Basic Regex Filter Example: </p>\n\n<pre><code>if (preg_match('/^[0-9-]+$/', $_POST['postcode'])) \n{\n //POSTAL CODE IS GOOD TO GO\n //Filters for charaters \"0-9\" along with \"-\" for longer postal codes\n} \nelse \n{\n //REJECT\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T13:06:59.740",
"Id": "13419",
"Score": "1",
"body": "If he's using Unicode UTF8, then this code is safe. It's better practise to use PDO however. But there's no need to panic people by saying the code can be exploited, when it cannot."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-02-02T14:52:01.663",
"Id": "13424",
"Score": "0",
"body": "@soupagain Interesting.. I've never heard of this UTF8 deal. What makes that secure and how do you force everything to be UTF8? I don't think many people know about that as I've read tons of PHP SQL tutorials/articles/questions without any mention of using specific encoding to make things secure. I could be remembering wrong though. Thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T18:41:47.563",
"Id": "4619",
"ParentId": "4617",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T15:23:40.120",
"Id": "4617",
"Score": "2",
"Tags": [
"php",
"mysql",
"security",
"sql-injection"
],
"Title": "Simultaneously searching listings by attributes such as category, title, postcode"
}
|
4617
|
<p>I'm creating a dispatcher class - which is itself a long running task which can be cancelled at anytime by the user. This Task will poll the database to see if there is any work that needs to be done, and run up to X [5] # of child tasks.</p>
<p>As far as I can tell - it's working great, but I have a few questions/concerns about the code. More or less, since I couldn't find another example of this, am I doing it right? Are there things that I could improve on?</p>
<ol>
<li><p>I'm using a <code>ConcurrentDictionary</code> to keep track of the child tasks that are running. This dictionary stores the <code>RequestKey</code> that's being processed, and the <code>CancellationTokenSource</code> for that task.</p>
<ul>
<li>Is this the best way to do this? In the <code>StartDownloadProcess</code> (this is the child task) I'm creating the <code>CancellationTokenSource</code> and adding it to the dictionary, then starting the task. I've added a <code>Continuation</code> to it which then removes the item from the <code>Dictionary</code> when processing is completed so that it doesn't get called in the <code>Cancel</code> method.</li>
</ul></li>
<li><p>In the child task I'm passing the Cancellation Token to the method that actually does the work. That process will then check to see if it needs to abort by checking that token periodically. Is this correct?</p></li>
<li><p>In the <code>Cancel</code> method, I'm creating a copy of the Keys in the Dictionary, iterating over it and trying to access and remove the item from the dictionary and issuing a <code>Cancel</code> request.</p>
<ul>
<li>Is this the best way to do this? Do I need to wait to see if the task actually cancelled? Can I?</li>
<li>Should I be disposing of the CTS? </li>
</ul></li>
<li><p>I'm doing a <code>Thread.Sleep</code> in the main task. Is this good or bad? Should I use <code>SpinWait</code> instead? Is there another method/better way to have the primary poller go to sleep and re-run at particular intervals?</p></li>
</ol>
<p><strong>Note:</strong> In the <code>StartDownloadProcess</code> I'm using a <code>while(true)</code> to loop until the task completes, or is cancelled to iterate until <code>j > requestKey</code>. In the real code there would be no <code>while</code> loop. It would simply start the new task and run the actual download process.</p>
<pre><code>/// <summary>
/// Primary dispatcher token source
/// </summary>
CancellationTokenSource primaryTokenSource;
/// <summary>
/// A collection of Worker Tokens which can be used to cancel worker tasks and keep track of how many
/// there are.
/// </summary>
ConcurrentDictionary<int, CancellationTokenSource> workerTokens = new ConcurrentDictionary<int, CancellationTokenSource>();
/// <summary>
/// Runs this instance.
/// </summary>
public void Run() {
// Only one dispatcher can be running
if (IsRunning)
return;
// Create a new token source
primaryTokenSource = new CancellationTokenSource();
// Create the cancellation token to pass into the Task
CancellationToken token = primaryTokenSource.Token;
// Set flag on
IsRunning = true;
// Fire off the dispatcher
Task.Factory.StartNew(
() => {
// Loop forever
while (true) {
// If there are more than 5 threads running, don't add a new one
if (workerTokens.Count < 5) {
// Check to see if we've been cancelled
if (token.IsCancellationRequested)
return;
// Check to see if there are pending requests
int? requestKey = null;
// Query database (removed)
requestKey = new Random().Next(1550);
// If we got a request, start processing it
if (requestKey != null) {
// Check to see if we've been cancelled before running the child task
if (token.IsCancellationRequested)
return;
// Start the child downloader task
StartDownloadProcess(requestKey.Value);
}
} else {
// Do nothing, we've exceeded our max tasks
Console.WriteLine("MAX TASKS RUNNING, NOT STARTING NEW");
}
// Sleep for the alloted time
Thread.Sleep(Properties.Settings.Default.PollingInterval);
}
}, token)
// Turn running flag off
.ContinueWith((t) => IsRunning = false)
// Notify that we've finished
.ContinueWith(OnDispatcherStopped);
}
/// <summary>
/// Starts the download process.
/// </summary>
/// <param name="requestKey">The request key.</param>
private void StartDownloadProcess(int requestKey) {
CancellationTokenSource workerTokenSource = new CancellationTokenSource();
CancellationToken token = workerTokenSource.Token;
// Add the token source to the queue
workerTokens.GetOrAdd(requestKey, workerTokenSource);
// Start the child downloader task
Task.Factory.StartNew(
() => {
int j = 0;
while (true) {
if (token.IsCancellationRequested) {
Console.WriteLine("Sub-Task Cancelled {0}", requestKey);
return;
}
// Create a new downloader, pass it the RequestKey and token
//var downloader = new Downloader(requestKey, token);
//downloader.Run();
// Simulate work
Thread.Sleep(250);
Console.WriteLine("SUB-Task {0} is RUNNING! - #{1}", requestKey, j);
// Simulate - automatically end task when j > requestkey
if (j++ > requestKey) {
Console.WriteLine("SUB TASK {0} IS ENDING!", requestKey);
return;
}
}
},
token
).ContinueWith((t) => {
// If we ended naturally, the cancellationtoken will need to be removed from the dictionary
CancellationTokenSource source = null;
workerTokens.TryRemove(requestKey, out source);
});
}
/// <summary>
/// Cancels this instance.
/// </summary>
public void Cancel() {
// Cancel the primary task first so new new child tasks are created
if (primaryTokenSource != null)
primaryTokenSource.Cancel();
// Iterate over running cancellation sources and terminate them
foreach (var item in workerTokens.Keys.ToList()) {
CancellationTokenSource source = null;
if (workerTokens.TryRemove(item, out source)) {
source.Cancel();
}
}
}
</code></pre>
<p>Additionally, not shown in the example above: several events are also able to be raised using within the tasks. Those events all look like the following:</p>
<pre><code>public event EventHandler DispatcherStarted;
private void OnDispatcherStarted() {
EventHandler handler = DispatcherStarted;
if (handler != null)
Task.Factory.StartNew(() => handler(this, EventArgs.Empty), CancellationToken.None, TaskCreationOptions.None, taskScheduler).Wait();
}
</code></pre>
<p>In the <code>Run()</code> method, at various points, it would call <code>OnDispatcher*()</code> to raise the events so the caller could subscribe and be notified. Those tasks that the event creates would run on the primary thread.</p>
<p>I was looking at making the dispatcher generic and passing in the <code>poller</code> object, which checks the database. If successful, it creates a child task and passes in the parameter(s) that it needs. I ran into some issues such as passing data around, which objects to pass in <code>Interfaces/Classes/Func<,,,>/Action<></code> etc. How could I turn this into a generic dispatcher/poller that runs A which returns parameters (I was thinking a Dictionary) which then creates a child task B which uses those parameters and supports cancellation and event notification?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-10-22T04:57:53.563",
"Id": "28342",
"Score": "0",
"body": "Matthew I am writing almost the exactly the same code. :) We should collaborate!"
}
] |
[
{
"body": "<p>Bug in your code: if you have 5 or more tasks running, no task will ever respond to a Cancel() request on the CancellationToken.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-09-29T19:51:48.430",
"Id": "194299",
"Score": "0",
"body": "Reporting a bug is considered an answer since it does review the code in a way, see http://meta.codereview.stackexchange.com/a/2117 . It does not provide much but I think it's a valid answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-13T04:41:13.827",
"Id": "434579",
"Score": "0",
"body": "@david can you please elaborate why cancellation token will not be honoured?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-25T20:43:27.573",
"Id": "12080",
"ParentId": "4620",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T19:55:03.123",
"Id": "4620",
"Score": "1",
"Tags": [
"c#",
"multithreading",
"winforms"
],
"Title": "Properly creating a Task to poll and dispatch child tasks with cancellation for each"
}
|
4620
|
<p>I am developing a class library for processing credit cards. There is a thought in management in the short-term future to look for a new credit card processor. So I want to write once and use everywhere (I should be anyway, right?).</p>
<p>We are currently using First Data's Global Gateway Web Service API. I need a separate web reference setup for live and test.</p>
<p>I am trying to do the following:</p>
<pre><code>//using ProcessCreditCard.WebReference;
using ProcessCreditCard.WebReferenceTest;
public class ProcessCreditCard
{
private FDGGWSApiOrderService oFDGGWSApiOrderService = null;
#region Intialize the object
/// <summary>
/// Initializes a new instance of the <see cref="ProcessCreditCard"/> class.
/// </summary>
public ProcessCreditCard()
{
ServicePointManager.Expect100Continue = false;
// Initialize Service Object
oFDGGWSApiOrderService = new FDGGWSApiOrderService();
// Set the WSDL URL
oFDGGWSApiOrderService.Url = @Properties.Settings.Default.CcApiUrl;
// Configure Client Certificate
oFDGGWSApiOrderService.ClientCertificates.Add(X509Certificate.CreateFromCertFile(Properties.Settings.Default.CertFile));
// Set the Authentication Credentials
NetworkCredential nc = new NetworkCredential(Properties.Settings.Default.CertUser, Properties.Settings.Default.CertPass);
oFDGGWSApiOrderService.Credentials = nc;
}
/// <summary>
/// Initializes a new instance of the test version of the <see cref="ProcessCreditCard"/> class.
/// </summary>
/// <param name="test">if set to <c>true</c> [test].</param>
public ProcessCreditCard(bool test)
{
ServicePointManager.Expect100Continue = false;
// Initialize Service Object
oFDGGWSApiOrderService = new FDGGWSApiOrderService();
// Set the WSDL URL
oFDGGWSApiOrderService.Url = @Properties.Settings.Default.CcApiUrl_Test;
// Configure Client Certificate
oFDGGWSApiOrderService.ClientCertificates.Add(X509Certificate.CreateFromCertFile(Properties.Settings.Default.CertFile_Test));
// Set the Authentication Credentials
NetworkCredential nc = new NetworkCredential(Properties.Settings.Default.CertUser_Test, Properties.Settings.Default.CertPass_Test);
oFDGGWSApiOrderService.Credentials = nc;
}
#endregion
/// <summary>
/// Charges the credit card.
/// </summary>
/// <returns></returns>
public MktoResponse ChargeCreditCard()
{
/// Code here for setting up the transaction
return BuildResponse(oFDGGWSApiOrderService.FDGGWSApiOrder(oOrderRequest));
}
</code></pre>
<p>So in my calling code, I can create the right environment based on the boolean:</p>
<pre><code>ProcessCreditCard.ProcessCreditCard pcc = new ProcessCreditCard.ProcessCreditCard(true);
</code></pre>
<p>How can I get this so that when I reference the <code>oFDGGWSApiOrderService</code> object that I am using the right environment?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-17T23:35:03.573",
"Id": "8193",
"Score": "0",
"body": "Is your objective to support both the test and live processing in a single environment? Usually your live environment goes to a live CC processor, and your test to test. Thus, why wouldn't you have one group of configuration properties, and set those in your config accordingly to the target environment? This does not address your concern of switching out to a completely different payment processor, but keeps configuration of test and live in the configurataion and your code then uses the same logic, driven by your configuration."
}
] |
[
{
"body": "<p>Here's one method. In your settings file, define a \"Mode\" setting. Toggle that for Live/Test. Then create a public property that uses that (I put it in my Settings.cs file).</p>\n\n<pre><code> /// <summary>\n /// Gets the DB connection string\n /// </summary>\n /// <value>The DB connect.</value>\n public string DBConnect {\n get { \n // Determine which database should be connected to\n switch (this.DBConnect_Mode) {\n // Connect to the live database\n case \"Live\": return this.DBConnect_Live; \n // Connect to the dev database\n case \"Dev\": return this.DBConnect_Dev; \n // All other cases, connect to the live database\n default: return this.DBConnect_Live; \n }\n }\n }\n</code></pre>\n\n<p>Then in my calling code I just use this:</p>\n\n<pre><code>var connection = Properties.Settings.Default.DBConnect;\n</code></pre>\n\n<p>This way, you can easily switch and even have it be an optional setting on a configuration screen. You could also use symbols instead of a 3rd setting.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-16T05:22:03.227",
"Id": "7250",
"Score": "1",
"body": "I think the OP is using a web service API for connecting to the c/c processing gateway. I don't see any database connections being used."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-16T16:30:28.103",
"Id": "7268",
"Score": "0",
"body": "Why would you downvote me ? It wasn't that this is a database connection -- it's \"THIS IS HOW YOU CAN DO THIS\"."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T20:18:49.433",
"Id": "4622",
"ParentId": "4621",
"Score": "0"
}
},
{
"body": "<p>First, I hope this question is still relevant in your company. One point that is of great interest to me in the question, is the management's vision to use other 3rd party payment processing providers. This directly implies that the code should accomodate this by abstracting the operation of processing orders and resolving dependecies on external systems. </p>\n\n<p>I will give some simple suggestions intended to decouple the code from a specific implementation (therefore enhancing code re-use and testability)</p>\n\n<h3>Step I, Resolve dependency on 3rd party credit services</h3>\n\n<p>This is acheived by abstracting the functionalities exposed by the service (of course every service will have a different API, but the processing logic will follow more or less the same workflow):</p>\n\n<pre><code>public interface IPaymentGateWayService\n{\n List<X509Certificate> ClientCertificates { get; }\n string Url { set; }\n NetworkCredential Credential { set; }\n}\n</code></pre>\n\n<p>So now your Payment processor is agnostic to which service it is using as such:</p>\n\n<pre><code>class PaymentProessor\n{\n private readonly IPaymentGateWayService _paymentGateWayService;\n\n public PaymentProessor(IPaymentGateWayService paymentGateWayService)\n {\n _paymentGateWayService = paymentGateWayService;\n _propertyProvider = propertyProvider;\n }\n\n public void ProcessCreditCardPayment()\n {\n _paymentGateWayService.Url = /*service url*/;\n _paymentGateWayService.ClientCertificates.Add(/*X509 certificate*/)\n _paymentGateWayService.Credential = new NetworkCredential(/*username and password*/);\n\n }\n}\n</code></pre>\n\n<p>You then create a wrapper for your <code>FDGGWApiOrderService</code> that implements the <code>IPaymentGateEayService</code> interface:</p>\n\n<pre><code>class FDGGWS : IPaymentGateWayService\n{\n private FDGGWSApiOrderService _fdggwsApiOrderService;\n\n public FDGGWS()\n {\n _fdggwsApiOrderService = new FDGGWSApiOrderService();\n }\n\n public List<X509Certificate> ClientCertificates\n {\n /*delegate to _fdggwsApiOrderService*/\n }\n\n public string Url\n {\n /*delegate to _fdggwsApiOrderService*/\n }\n\n public NetworkCredential Credential\n {\n /*delegate to _fdggwsApiOrderService*/\n }\n}\n</code></pre>\n\n<p>So now when you create your payment processor, you pass the instance of the service you want to use.</p>\n\n<pre><code>new PaymentProessor(new FDGGWS());\n</code></pre>\n\n<p>This simply allows you to reuse your code to accomodate different service providers, also, you can support multiple providers at the same time by creating a service factory that returns the desired concrete instance of teh service depending on a configuration setting.</p>\n\n<h3>Step II, Handle environment settings</h3>\n\n<p>There are tons of techniques that allow you to read values from configuration stores, like <code>App.config</code> or a <code>web.config</code>. But for the purpose of my answer I will leverage the dependency injection technique and resolve the dependency on environment properties using constructor injection, similar to what is used to abstract the service interface.</p>\n\n<p>So we create an interface for the configuration settings:</p>\n\n<pre><code>internal interface IPropertyProvider\n{\n string Cert_File { get; }\n string Cer_User { get; }\n string Cer_Password { get; }\n string ServiceUrl { get; }\n}\n</code></pre>\n\n<p>And you can create as many flavours of the interface as there are environments, in your case of for test and one for production, here is an abridged example of either:</p>\n\n<pre><code>class ProductionPropertyProvider : IPropertyProvider\n{\n public string Cert_File\n {\n get { return \"Path to Production file\"; }\n }\n\n /* other properties */\n}\n\nclass TestPropertyProvider : IPropertyProvider\n{\n public string Cert_File\n {\n get { return \"Path to test file\"; }\n }\n\n /* other properties */\n}\n</code></pre>\n\n<p>And here is how you perform the dependency injection:</p>\n\n<pre><code>class PaymentProessor\n{\n private readonly IPaymentGateWayService _paymentGateWayService;\n private readonly IPropertyProvider _propertyProvider;\n\n public PaymentProessor()\n :this(new FDGGWS(), new ProductionPropertyProvider())\n {}\n public PaymentProessor(IPaymentGateWayService paymentGateWayService, IPropertyProvider propertyProvider)\n {\n _paymentGateWayService = paymentGateWayService;\n _propertyProvider = propertyProvider;\n }\n\n public void ProcessCreditCardPayment()\n {\n _paymentGateWayService.Url = _propertyProvider.ServiceUrl;\n _paymentGateWayService.ClientCertificates.Add(X509Certificate.CreateFromCertFile(_propertyProvider.Cert_File));\n _paymentGateWayService.Credential = new NetworkCredential(_propertyProvider.Cer_User, _propertyProvider.Cer_Password);\n\n }\n}\n</code></pre>\n\n<p><strong>Notice the default constructor that creates default service and property provider instances. This is just to demonstrate that you can specify the default dependencies in the default constructor</strong></p>\n\n<p>Lastly, all you need is one configuration key in your app.config that specifies what environment is it.. we use that key to determine the type of the <code>IPropertyProvider</code>.</p>\n\n<h1>Example</h1>\n\n<pre><code>//Read env setting from the application configuration file\nvar environment = ConfigurationManager.AppSettings[\"env\"];\n\n//create appropriate PropertyProvider\nIPropertyProvider propertyProvider;\nif (environment == \"test\")\n propertyProvider = new TestPropertyProvider();\nelse\n propertyProvider = new ProductionPropertyProvider();\n\n//process the payment\nnew PaymentProessor(new FDGGWS(), propertyProvider).ProcessCreditCardPayment();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-21T04:32:39.130",
"Id": "8336",
"Score": "0",
"body": "Wow... I'll have to parse this in the daylight at work. A great looking answer and at least looks like what I was trying to work toward as a wrapper around or processor's API so it would be easier to change in the future."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-20T22:09:26.037",
"Id": "5494",
"ParentId": "4621",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "5494",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T20:05:48.867",
"Id": "4621",
"Score": "3",
"Tags": [
"c#",
"finance"
],
"Title": "Class library for processing credit cards"
}
|
4621
|
<p>I was told that I might get some feed back about the code below. I'm learning and need some criticism.</p>
<p>My initial question was how to save users answers and tally them up to display number correct/wrong.</p>
<pre><code>import random
import os
if __name__=='__main__':
books=['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua',
'Judges', 'Ruth', 'I Samuel', 'II Samuel', 'I Kings', 'II Kings',
'I Chronicles', 'II Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalms',
'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremiah',
'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos', 'Obadiah',
'Jonah', 'Micah', 'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai', 'Zechariah',
'Malachi', 'Matthew', 'Mark', 'Luke', 'John', 'Acts', 'Romans', 'I Corinthians',
'II Corinthians', 'Galatians', 'Ephesians', 'Philippians',
'Colossians', 'I Thessalonians', 'II Thessalonians', 'I Timothy', 'II Timothy',
'Titus', 'Philemon', 'Hebrews', 'James', 'I Peter', 'II Peter', 'I John',
'II John', 'III John', 'Jude', 'Revelation']
Title = "{0:^78}".format("Welcome to the Bible book quiz!\n\n")
seleCtion = raw_input(" The Bible has a number of " + str(len(books)) + " books.\n Select Next to see them below:\n" + "{0:^78}".format("[1]Next [2]Exit\n") )
if seleCtion == '1':
#This section displays the books of the Bible and their indexes.
count = 1
indexMap = {}
for i, bname in enumerate(books):
print '\n{0:3d}. {1}'.format(count, bname)
indexMap[count] = i
count +=1
elif seleCtion == '2':
print Title
print "\n Let's start the quiz:\n\n\n"
else:
print 'You must select 1 or 2'
mydict_book = {'Genesis':1, 'Exodus':2, 'Leviticus':3, 'Numbers':4, 'Deuteronomy':5, 'Joshua':6,
'Judges':7, 'Ruth':8, 'I Samuel':9, 'II Samuel':10, 'I Kings':11, 'II Kings':12,
'I Chronicles':13, 'II Chronicles':14, 'Ezra':15, 'Nehemiah':16, 'Esther':17, 'Job':18, 'Psalms':19,
'Proverbs':20, 'Ecclesiastes':21, 'Song of Solomon':22, 'Isaiah':23, 'Jeremiah':24,
'Lamentations':25, 'Ezekiel':26, 'Daniel':27, 'Hosea':28, 'Joel':29, 'Amos':30, 'Obadiah':31,
'Jonah':32, 'Micah':33, 'Nahum':34, 'Habakkuk':35, 'Zephaniah':36, 'Haggai':37, 'Zechariah':38,
'Malachi':39, 'Matthew':40, 'Mark':41, 'Luke':42, 'John':43, 'Acts':44, 'Romans':45, 'I Corinthians':46,
'II Corinthians':47, 'Galatians':48, 'Ephesians':49, 'Philippians':50,
'Colossians':51, 'I Thessalonians':52, 'II Thessalonians':53, 'I Timothy':54, 'II Timothy':55,
'Titus':56, 'Philemon':57, 'Hebrews':58, 'James':59, 'I Peter':60, 'II Peter':61, 'I John':62,
'II John':63, 'III John':64, 'Jude':65, 'Revelation':66}
#new_dict = dict.fromkeys(books, counter)
#print new_dict
while 1:
try:
#This section starts the random book selection index match
user_sel = []
print '\n\n\n Here are the first 5 books in the quiz: \n'
sampler =random.sample(books, 5)
first = str(sampler[0])
second = str(sampler[1])
third = str(sampler[2])
fourth = str(sampler[3])
fifth = str(sampler[4])
user_sel = mydict_book[first], mydict_book[second], mydict_book[third], mydict_book[fourth], mydict_book[fifth]
num_sampler = random.sample(user_sel, 5)
print sampler
print '\nMatch the correct numeric position below:'
print '\n', num_sampler
samp1 = int(raw_input('\nWhich number is ' + sampler[0] +': '))
samp2 = int(raw_input('Which number is ' + sampler[1] +': '))
samp3 = int(raw_input('Which number is ' + sampler[2] +': '))
samp4 = int(raw_input('Which number is ' + sampler[3] +': '))
samp5 = int(raw_input('Which number is ' + sampler[4] +': '))
# taking the the users answer and finding the resultant book
# need to put an if statement condition for !< 1 and ! < 66
answer1=books[samp1-1]
answer2=books[samp2-1]
answer3=books[samp3-1]
answer4=books[samp4-1]
answer5=books[samp5-1]
# taking the book and finding the numeric value associated with it
right1 = mydict_book[answer1]
right2 = mydict_book[answer2]
right3 = mydict_book[answer3]
right4 = mydict_book[answer4]
right5 = mydict_book[answer5]
#display what my answers yield
print '\nYour Answers yield:\n'
print "1. " + str(answer1)
print "2. " + str(answer2)
print "3. " + str(answer3)
print "4. " + str(answer4)
print "5. " + str(answer5)
#takes the random books converts them to strings
first = str(sampler[0])
second = str(sampler[1])
third = str(sampler[2])
fourth = str(sampler[3])
fifth = str(sampler[4])
# print the numeric value and string value of the correct answers.
print "\nThe Correct Answers are:\n"
print sampler[0] + " - " , mydict_book[first], tstmnt
print sampler[1] + " - " , mydict_book[second], tstmnt
print sampler[2] + " - " , mydict_book[third], tstmnt
print sampler[3] + " - " , mydict_book[fourth], tstmnt
print sampler[4] + " - " , mydict_book[fifth], tstmnt
continue
except ValueError:
break
</code></pre>
|
[] |
[
{
"body": "<pre><code>import random\nimport os\n\nif __name__=='__main__':\n\n books=['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua',\n</code></pre>\n\n<p>The python style guide recommends that global constants be in ALL_CAPS. There is no reason to put such assignments inside <code>if __name__ == '__main__'</code> </p>\n\n<pre><code>Title = \"{0:^78}\".format(\"Welcome to the Bible book quiz!\\n\\n\")\n</code></pre>\n\n<p>Why is this outside of the <code>__main__</code> bit? You should probably put it all in a function.</p>\n\n<pre><code>seleCtion = raw_input(\" The Bible has a number of \" + str(len(books)) + \" books.\\n Select Next to see them below:\\n\" + \"{0:^78}\".format(\"[1]Next [2]Exit\\n\") )\n</code></pre>\n\n<p>What with the capital C in the middle?</p>\n\n<pre><code>if seleCtion == '1':\n\n #This section displays the books of the Bible and their indexes.\n count = 1\n indexMap = {}\n\n for i, bname in enumerate(books):\n print '\\n{0:3d}. {1}'.format(count, bname)\n indexMap[count] = i\n count +=1\n</code></pre>\n\n<p>What are you trying to do here... count always equals i + 1.</p>\n\n<pre><code>elif seleCtion == '2':\n print Title\n print \"\\n Let's start the quiz:\\n\\n\\n\"\n</code></pre>\n\n<p>Doesn't 2 mean exit?</p>\n\n<pre><code>else:\n print 'You must select 1 or 2'\n</code></pre>\n\n<p>Should you go back and make them try again? </p>\n\n<pre><code>mydict_book = {'Genesis':1, 'Exodus':2, 'Leviticus':3, 'Numbers':4, 'Deuteronomy':5, 'Joshua':6,\n 'Judges':7, 'Ruth':8, 'I Samuel':9, 'II Samuel':10, 'I Kings':11, 'II Kings':12,\n 'I Chronicles':13, 'II Chronicles':14, 'Ezra':15, 'Nehemiah':16, 'Esther':17, 'Job':18, 'Psalms':19,\n 'Proverbs':20, 'Ecclesiastes':21, 'Song of Solomon':22, 'Isaiah':23, 'Jeremiah':24,\n 'Lamentations':25, 'Ezekiel':26, 'Daniel':27, 'Hosea':28, 'Joel':29, 'Amos':30, 'Obadiah':31,\n 'Jonah':32, 'Micah':33, 'Nahum':34, 'Habakkuk':35, 'Zephaniah':36, 'Haggai':37, 'Zechariah':38,\n 'Malachi':39, 'Matthew':40, 'Mark':41, 'Luke':42, 'John':43, 'Acts':44, 'Romans':45, 'I Corinthians':46,\n 'II Corinthians':47, 'Galatians':48, 'Ephesians':49, 'Philippians':50,\n 'Colossians':51, 'I Thessalonians':52, 'II Thessalonians':53, 'I Timothy':54, 'II Timothy':55,\n 'Titus':56, 'Philemon':57, 'Hebrews':58, 'James':59, 'I Peter':60, 'II Peter':61, 'I John':62,\n 'II John':63, 'III John':64, 'Jude':65, 'Revelation':66} \n</code></pre>\n\n<p>You shouldn't need to repeat the list of books again. </p>\n\n<pre><code>#new_dict = dict.fromkeys(books, counter)\n#print new_dict\n</code></pre>\n\n<p>Don't leave commented dead code in your code </p>\n\n<pre><code>while 1:\n</code></pre>\n\n<p>use <code>while True</code></p>\n\n<pre><code> try:\n #This section starts the random book selection index match\n user_sel = []\n\n\n print '\\n\\n\\n Here are the first 5 books in the quiz: \\n' \n sampler =random.sample(books, 5)\n first = str(sampler[0])\n second = str(sampler[1])\n third = str(sampler[2])\n fourth = str(sampler[3])\n fifth = str(sampler[4])\n</code></pre>\n\n<p>Don't go around creating variables like first, second, third, fourth. If you have a number of variables like it should virtually always be a list.</p>\n\n<pre><code> user_sel = mydict_book[first], mydict_book[second], mydict_book[third], mydict_book[fourth], mydict_book[fifth]\n num_sampler = random.sample(user_sel, 5)\n</code></pre>\n\n<p>Why are you selecting 5 books at random from a selection of 5 books?</p>\n\n<pre><code> print sampler\n print '\\nMatch the correct numeric position below:'\n print '\\n', num_sampler\n\n samp1 = int(raw_input('\\nWhich number is ' + sampler[0] +': '))\n samp2 = int(raw_input('Which number is ' + sampler[1] +': '))\n samp3 = int(raw_input('Which number is ' + sampler[2] +': '))\n samp4 = int(raw_input('Which number is ' + sampler[3] +': '))\n samp5 = int(raw_input('Which number is ' + sampler[4] +': '))\n</code></pre>\n\n<p>In programming, if you find yourself repeating things like the question above, it means you need a loop or a function.</p>\n\n<pre><code> # taking the the users answer and finding the resultant book\n # need to put an if statement condition for !< 1 and ! < 66\n answer1=books[samp1-1]\n answer2=books[samp2-1]\n answer3=books[samp3-1]\n answer4=books[samp4-1]\n answer5=books[samp5-1]\n\n # taking the book and finding the numeric value associated with it\n\n\n right1 = mydict_book[answer1]\n right2 = mydict_book[answer2]\n right3 = mydict_book[answer3]\n right4 = mydict_book[answer4]\n right5 = mydict_book[answer5]\n</code></pre>\n\n<p>Use books.index(answer1) rather then creating mydict_book dictionary.</p>\n\n<pre><code> #display what my answers yield\n print '\\nYour Answers yield:\\n'\n print \"1. \" + str(answer1) \n print \"2. \" + str(answer2) \n print \"3. \" + str(answer3)\n print \"4. \" + str(answer4)\n print \"5. \" + str(answer5)\n\n #takes the random books converts them to strings\n first = str(sampler[0])\n second = str(sampler[1])\n third = str(sampler[2])\n fourth = str(sampler[3])\n fifth = str(sampler[4])\n\n # print the numeric value and string value of the correct answers. \n print \"\\nThe Correct Answers are:\\n\"\n print sampler[0] + \" - \" , mydict_book[first], tstmnt\n print sampler[1] + \" - \" , mydict_book[second], tstmnt\n print sampler[2] + \" - \" , mydict_book[third], tstmnt\n print sampler[3] + \" - \" , mydict_book[fourth], tstmnt\n print sampler[4] + \" - \" , mydict_book[fifth], tstmnt\n\n\n continue\n</code></pre>\n\n<p>Since this is the end of the loop, it does nothing to say continue here.</p>\n\n<pre><code>except ValueError:\n break\n</code></pre>\n\n<p>If your catching exception like this and its not clear where the exception might come from, add a comment explaining. Or make it clearer where the exception is coming from.</p>\n\n<p>Here is my version of what you did.</p>\n\n<pre><code>import random\nBOOKS = [\n 'Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua', \n 'Judges', 'Ruth', 'I Samuel', 'II Samuel', 'I Kings', 'II Kings', \n 'I Chronicles', 'II Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job',\n 'Psalms', 'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', \n 'Jeremiah', 'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos',\n 'Obadiah', 'Jonah', 'Micah', 'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai',\n 'Zechariah', 'Malachi', 'Matthew', 'Mark', 'Luke', 'John', 'Acts', \n 'Romans', 'I Corinthians', 'II Corinthians', 'Galatians', 'Ephesians',\n 'Philippians', 'Colossians', 'I Thessalonians', 'II Thessalonians', \n 'I Timothy', 'II Timothy', 'Titus', 'Philemon', 'Hebrews', 'James',\n 'I Peter', 'II Peter', 'I John', 'II John', 'III John', 'Jude', \n 'Revelation'\n]\n\ndef print_all_books():\n for count, bname in enumerate(BOOKS):\n print '{0:3d}. {1}'.format(count + 1, bname)\n\ndef get_response(prompt, valid_responses):\n while True:\n text = raw_input(prompt)\n try:\n value = int(text)\n except ValueError:\n print \"Please enter a number\"\n else:\n if value not in valid_responses:\n print \"Please enter one of: {0}\".format(valid_responses)\n else:\n return value\n\n\ndef bible_book_quiz():\n print \"{0:^78}\".format(\"Welcome to the Bible book quiz!\\n\\n\")\n\n while True:\n number_of_questions = get_response('Enter the number of questions you wanna be asked (0 to quit): ', range(10))\n\n if number_of_questions == 0:\n break\n\n\n books_selection = random.sample(BOOKS, number_of_questions)\n positions = sorted([BOOKS.index(book) + 1 for book in books_selection])\n\n print\n print\n print\n print 'Here are the first {0} books in the quiz: '.format(number_of_questions)\n\n #This section starts the random book selection index match\n\n print \"\\t\", books_selection\n print 'Match the correct numeric position below:'\n print \"\\t\", positions\n\n answers = []\n for book in books_selection:\n answers.append( get_response('Which number is {0}: '.format(book), positions) )\n\n #display what my answers yield\n print\n print 'Your Answers yield:'\n for i, answer in enumerate(answers):\n print \"{0}. {1}\".format(i+1, BOOKS[answer-1])\n\n # print the numeric value and string value of the correct answers. \n print \"\\nThe Correct Answers are:\\n\"\n print positions\n for book in books_selection:\n print \"{0} - {1}\".format(book, BOOKS.index(book) + 1)\n\n print\n\ndef main():\n print \"The Bible has a number of {0} books.\".format(len(BOOKS))\n print \"Select a menu option:\"\n print \"[1] Print All Books [2] Start Quiz\"\n option = get_response('', [1,2])\n\n if option == 1:\n print_all_books()\n elif option == 2:\n bible_book_quiz()\n\nif __name__=='__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T23:11:06.690",
"Id": "6929",
"Score": "0",
"body": "Thanks for explaining the why? I really needed that!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T22:10:58.487",
"Id": "4625",
"ParentId": "4623",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "4625",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-06T20:59:00.217",
"Id": "4623",
"Score": "2",
"Tags": [
"python"
],
"Title": "Matching and enumerating the results of a quiz"
}
|
4623
|
<p>I wanted to give Haskell a try, and I started with a simple exercise I found <a href="http://www.cs.brown.edu/courses/cs173/2008/Assignments/04-laziness-prog.html" rel="nofollow">here</a>.</p>
<blockquote>
<ol>
<li>Write <code>isPrime :: Integer -> Bool</code>, which determines whether a given
integer is prime.</li>
<li>Define <code>primes :: [Integer]</code>, the list of all primes.</li>
<li>Revise <code>isPrime</code> so that it only tests divisibility by prime factors.</li>
</ol>
</blockquote>
<h3>My answer to Q1</h3>
<pre><code>isPrime :: Integer -> Bool
isPrime v = let maxDiv = floor(sqrt (fromIntegral v))
in all (\x -> (v `rem` x) /= 0) [2..maxDiv]
</code></pre>
<p>This one was easy, except for the explicit numeric types conversions I had a hard time to get right.</p>
<h3>My answer to Q2</h3>
<pre><code>primes = filter isPrime [0..]
</code></pre>
<p>This one was easy, too.</p>
<h3>My answer to Q3</h3>
<p>It took me several hours to answer this one. I quickly understood that <code>isPrime</code> could leverage the values already computed in the array <code>primes</code>. So, my first attempt was :</p>
<pre><code>isPrime :: Integer -> Bool
isPrime v | v < 2 = False
| otherwise = all (\x -> (v `rem` x) /= 0) (takeWhile (<v) primes)
</code></pre>
<p><code>isPrime</code> works fine for v=0 and v=1, but hangs forever for v>1. Ok, I get it : the mutual recursion creates an infinite loop, due to <code>takeWhile</code> trying to access a <code>primes</code> element which is not yet computed.</p>
<p>One thing I don't understand though, is why <code>primes !! 0</code> and <code>primes !! 1</code> hang forever, too.</p>
<p>I tried many approaches for replacing this <code>(takeWhile (<v) primes)</code> by an expression that would stop before reaching a not-yet-computed value. I came to this solution :</p>
<pre><code>isPrime :: Integer -> Bool
isPrime v | v < 2 = False
| v == 2 = True
| otherwise = all (\x -> (v `rem` x) /= 0) (takeWhile' (\t -> t*t<=v) primes)
takeWhile' :: (a -> Bool) -> [a] -> [a]
takeWhile' p (x:xs) = if p x then x : takeWhile' p xs else [x]
</code></pre>
<p>This solution works. But I had to define a <code>takeWhile'</code> that works just like <code>takeWhile</code>, but also includes the first non-matching element.</p>
<p>Here are my questions to you :</p>
<p><strong>QA</strong> : why do <code>primes !! 0</code> and <code>primes !! 1</code> hangs in my first attempt ?</p>
<p><strong>QB</strong> : is there a magical <code>takeWhileOnlyForAlreadyComputedElements</code> function ? Or a construct that would prevent the infinite loop of this mutual recursion ?</p>
<p><strong>QC</strong> : does <code>takeWhile'</code> already exist in the stdlib ? Or maybe the same effect can be achieved in a simpler way ?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T01:55:53.693",
"Id": "6933",
"Score": "0",
"body": "I realize QA may be a better fit on stackoverflow, but the questions I'm more interrested in are QB and QC, which (I think) belong to codereview."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-03T18:55:59.503",
"Id": "38116",
"Score": "0",
"body": "QC: http://www.haskell.org/hoogle/?hoogle=takeWhile Hoogle is very useful."
}
] |
[
{
"body": "<p>Not an answer to your questions, but a correction for your first, looping attempt for Q3:</p>\n\n<p>Things get much easier if you initially have at least one prime number in your list. You <em>could</em> ensure this by a separate case in <code>isPrime</code>, but why not cheat a little bit, and add it directly?</p>\n\n<pre><code>primes = 2 : filter isPrime [3..]\n</code></pre>\n\n<p>Then you can use your solution for Q1 without much changes (I took the freedom to kill some parens etc):</p>\n\n<pre><code>isPrime :: Integer -> Bool\nisPrime v = let maxDiv = floor $ sqrt $ fromIntegral v\n in all ((/= 0).(v `rem`)) $ takeWhile (<= maxDiv) primes\n</code></pre>\n\n<p>However, this is not the best way to generate a list of primes. Read the excellent paper <a href=\"http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf\" rel=\"nofollow\">http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf</a> for details.</p>\n\n<p><strong>[Edit]</strong> </p>\n\n<p>I forgot to mention <a href=\"http://www.haskell.org/haskellwiki/Prime_numbers\" rel=\"nofollow\">http://www.haskell.org/haskellwiki/Prime_numbers</a> with many interesting techniques.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T09:00:38.047",
"Id": "6941",
"Score": "0",
"body": "Thanks, initializing `primes` with the first value is clearly the way to go. I'll remember the `$` function, too (I saw it in the Prelude, but didn't get its usefulness)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T07:06:47.903",
"Id": "4633",
"ParentId": "4626",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "4633",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T01:51:38.367",
"Id": "4626",
"Score": "1",
"Tags": [
"haskell",
"primes"
],
"Title": "Lazy computation of primes in Haskell"
}
|
4626
|
<p>Please review this:</p>
<pre><code>#include <iostream>
using namespace std;
template <class T>
struct Node
{
T data;
Node * next;
Node(T data) : data(data), next(NULL) {}
};
template <class T>
class CircularLinkedList
{
public:
CircularLinkedList() : head(NULL) {}
~CircularLinkedList();
void addNode(T data);
void deleteNode(T data);
template <class U>
friend std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll);
private:
Node<T> * head;
};
template <class T>
CircularLinkedList<T>::~CircularLinkedList()
{
if (head)
{
Node<T> * tmp = head;
while (tmp->next != head)
{
Node<T> * t = tmp;
tmp = tmp->next;
delete(t);
}
delete tmp;
head = NULL;
}
}
template <class T>
void CircularLinkedList<T>::addNode(T data)
{
Node<T> * t = new Node<T>(data);
if (head == NULL)
{
t->next = t;
head = t;
return;
}
Node<T> * tmp = head;
while (tmp->next != head)
{
tmp = tmp->next;
}
tmp->next = t;
t->next = head;
}
template <class T>
void CircularLinkedList<T>::deleteNode(T data)
{
Node<T> * tmp = head;
Node<T> * prev = NULL;
while (tmp->next != head)
{
if (tmp->data == data) break;
prev = tmp;
tmp = tmp->next;
}
if (tmp == head)
{
while (tmp->next != head)
{
tmp = tmp->next;
}
tmp->next = head->next;
delete head;
head = tmp->next;
}
else
{
prev->next = tmp->next;
delete tmp;
}
}
template <class U>
std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll)
{
Node<U> * head = cll.head;
if (head)
{
Node<U> * tmp = head;
while (tmp->next != head)
{
os << tmp->data << " ";
tmp = tmp->next;
}
os << tmp->data;
}
return os;
}
int main()
{
CircularLinkedList<int> cll;
cll.addNode(1);
cll.addNode(2);
cll.addNode(3);
cll.addNode(4);
cll.addNode(5);
cout << cll << endl;
cll.deleteNode(3);
cll.deleteNode(1);
cll.deleteNode(5);
cout << cll << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T06:33:57.693",
"Id": "6934",
"Score": "0",
"body": "Most of the cases I wrote for your other question are also applicable here: http://codereview.stackexchange.com/questions/4629/doubly-linked-list-c/4630#4630"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-09-06T21:47:36.567",
"Id": "24970",
"Score": "0",
"body": "Use const reference instead of value"
}
] |
[
{
"body": "<p>)</p>\n\n<p>My first comment is you should start looking at smart pointers.<br>\nThey will definitely simplify your code.</p>\n\n<p>The second comment: look at the <a href=\"http://www.sgi.com/tech/stl/Container.html\" rel=\"nofollow noreferrer\">STL containers</a>.<br>\nContainers in C++ follow a specific pattern. The idea is that we want to use algorithms on containers interchangeably and thus containers follow these conventions to make them easy to use with the standard algorithms.</p>\n\n<p>Third comment: you fail to follow the <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">rule of three</a>.<br>\nBasically. If you define one of 'Destructor'/'Copy-Constructor'/'Assignment-Operator' (rather than using the compiler generated defaults) then you probably need to define all three. In this case your code is going to crash if you make a copy of the list. The problem arises from having an owned pointer in your code.</p>\n\n<p>Fourth comment: Prefer to be pass parameters by const reference. For simple objects like integers it will not make any difference. But you have templatised the code and T can be any type. Thus passing by value is going to cause a copy (which may be expensive).</p>\n\n<p>Reviewing the above code:<br>\nThe complexity of adding a node is O(n). By maintaining a head and a tail pointer you can change this to have a complexity of O(1). ie. this loop becomes unnecessary.</p>\n\n<pre><code>Node<T> * tmp = head;\nwhile (tmp->next != head)\n{\n tmp = tmp->next;\n}\n</code></pre>\n\n<p>You have an output operator <code>std::ostream & operator<<(std::ostream & os, const CircularLinkedList<U> & cll)</code> It would be nice if you had a symmetric input operator. In this situation you need to worry about the size of the list (or adding a special terminating character). So the creation of the input operator will affect your design of the output operator.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T03:59:25.560",
"Id": "6981",
"Score": "1",
"body": "I don't really see how smart pointers will help this code. In my mind, the most compelling reasons to use smart pointers are for exception safety and graceful cleanup. Here we have exactly 1 place where allocations happen. It's pretty manageable. I see the use of smart pointers here as a solution in need of a problem. Using smart pointer poorly would also make it worse, i.e. using `shared_ptr` would add gross amounts of overhead."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T14:05:18.080",
"Id": "4640",
"ParentId": "4628",
"Score": "6"
}
},
{
"body": "<p>the code has problem when the list has only one node, and when it is removed, the head is not pointed to NULL.</p>\n\n<p>e.g.,</p>\n\n<pre><code>int main() {\nCircularLinkedList<int> cll;\n\ncll.addNode(5);\ncout << cll << endl;\ncll.deleteNode(5);\ncout << cll << endl;\nreturn 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-31T06:21:16.837",
"Id": "12181",
"ParentId": "4628",
"Score": "1"
}
},
{
"body": "<p>Also, for simplicity I would have kept a reference to the last inserted item (calling it the tail might be wrong as it is circular, but then again is concise with your head). This way, inserting would be O(1) instead of O(n), which makes sense as you know you will add it last in the list, right before head. You could then do:</p>\n\n<pre><code>if (head == NULL) {\n head = t;\n head->next = head;\n return;\n}\n\ntail->next = t;\nt->next = head;\n</code></pre>\n\n<p>in add_node.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-05-31T07:32:21.140",
"Id": "12182",
"ParentId": "4628",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4640",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T05:07:08.233",
"Id": "4628",
"Score": "4",
"Tags": [
"c++",
"linked-list",
"circular-list"
],
"Title": "Circular linked list"
}
|
4628
|
<p>Please, review the code:</p>
<pre><code>#include <iostream>
using namespace std;
template <class T>
struct Node
{
Node(T data) : data(data), next(NULL), prev(NULL) {}
T data;
Node * next;
Node * prev;
};
template <class T>
class DoublyLinkedList
{
public:
DoublyLinkedList() : head(NULL), tail(NULL) {}
DoublyLinkedList(const DoublyLinkedList<T> & dll);
~DoublyLinkedList();
void addNode(T data);
//void insertNodeBefore(int data, int before);
//void insertNodeAfter(int data, int after);
void deleteNode(T data);
template <class U>
friend std::ostream & operator<<(std::ostream & os, const DoublyLinkedList<U> & dll);
private:
Node<T> * head;
Node<T> * tail;
};
template <class U>
std::ostream & operator<<(std::ostream & os, const DoublyLinkedList<U> & dll)
{
Node<U> * tmp = dll.head;
while (tmp)
{
os << tmp->data << " ";
tmp = tmp->next;
}
return os;
}
template <class T>
DoublyLinkedList<T>::~DoublyLinkedList()
{
Node<T> * tmp = NULL;
while (head)
{
tmp = head;
head = head->next;
delete tmp;
}
head = tail = NULL;
}
template <class T>
void DoublyLinkedList<T>::addNode(T data)
{
Node<T> * t = new Node<T>(data);
Node<T> * tmp = head;
if (tmp == NULL)
{
head = tail = t;
}
else
{
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = t;
t->prev = tail;
tail = t;
}
}
template <class T>
void DoublyLinkedList<T>::deleteNode(T data)
{
Node<T> * tmp = head;
while (tmp && tmp->data != data)
{
tmp = tmp->next;
}
if (tmp)
{
if (tmp->prev && tmp->next) // no change to head or tail
{
tmp->prev->next = tmp->next;
tmp->next->prev = tmp->prev;
}
else if (tmp->prev) // change to tail
{
tmp->prev->next = tmp->next;
tail = tmp->prev;
}
else if (tmp->next) // change to head
{
tmp->next->prev = tmp->prev;
head = tmp->next;
}
delete tmp;
}
}
template <class T>
DoublyLinkedList<T>::DoublyLinkedList(const DoublyLinkedList<T> & dll)
{
Node<T> * tmp = dll.head;
while (tmp)
{
this->addNode(tmp->data);
tmp = tmp->next;
}
}
int main()
{
DoublyLinkedList<int> dll;
dll.addNode(1);
dll.addNode(2);
dll.addNode(3);
dll.addNode(4);
dll.addNode(5);
cout << dll << endl;
DoublyLinkedList<int> dll2(dll);
cout << dll2 << endl;
dll.deleteNode(3);
dll.deleteNode(1);
dll.deleteNode(5);
cout << dll << endl;
cout << dll2 << endl;
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-26T09:04:16.073",
"Id": "7476",
"Score": "0",
"body": "never open a namespace declaration in a header file btw. So for instance, don't put in 'using namespace std;'"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-27T18:35:43.953",
"Id": "7509",
"Score": "0",
"body": "C Johnson, why not in .h, but could be in .cpp?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-27T20:09:46.380",
"Id": "7511",
"Score": "0",
"body": "ok got it, it can cause trouble to other header files included which are not in the same namespace."
}
] |
[
{
"body": "<ol>\n<li><p>Consider replacing <code>Node<T></code> with:</p>\n\n<pre><code>typedef Node<T> node_t;\n\n...\n\nnode_t node;\n</code></pre></li>\n<li><p>Consider making your implementation STL-enabled. If I were user of this class, the first thing I'd ask you is \"how do I iterate over this list?\". Doubly-linked lists are great when adding items in the middle, how do I do it? (it's about operations like <code>insertBefore()</code>, <code>insertAfter()</code>). How do I sort it? How do I check if item is on the list? How do I search using predicate?</p></li>\n<li><p>Why do you call the method <code>deleteNode</code> if it's only argument is of type <code>T</code>? It's more to <code>findNodeByValueAndDeleteIt(T)</code>.</p></li>\n<li><p>What about assignment operator? You should either declare it private (if you don't support it), or implement it explicitly depending on semantics you want to support (deep copy (most likely what you want), reference, COW, etc):</p>\n\n<pre><code>YourList<int> a; // do something with a\n\nYourList<int> b; // do something with b\n\na = b; // what is \"a\" here? what if I add nodes to a? will it affect b?\n\n// imagine, scope ends here, dtor for b is called, everything's fine\n\n// dtor for a is called - here you're going to crash, since\n\n// both a and b were using the same memory and this memory is already\n\n// free, since b's dtor has already been called at this point\n</code></pre></li>\n<li><p>For methods like <code>void addNode(T data)</code> - why do you pass data by value? Since you store item values by value, in either case you're going to call their copy-ctor. Copy-ctor requires const-reference, so you should consider replacing <code>addNode</code> with <code>void addNode(T const& data)</code>.</p></li>\n<li><p><code>using namespace std;</code> - is it <em>only</em> for <code>cout</code> instead of <code>std::cout</code> in your <code>main()</code>?</p></li>\n</ol>\n\n<p>Checked nothing from the \"algorithmic\" standpoint, C++ only.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T05:47:27.640",
"Id": "4630",
"ParentId": "4629",
"Score": "10"
}
},
{
"body": "<p>Consider implementing <code>AddNode</code> and <code>RemoveNode</code> to the node themselves so you can unclutter the interface of the linked list, and make it easier for the list to purge the nodes. You should also declare a destructor, as your class presently leaks memory after you are finished (it does not delete all the nodes stored in the list).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-10-17T12:30:30.787",
"Id": "5419",
"ParentId": "4629",
"Score": "1"
}
},
{
"body": "<ul>\n<li><p><code>addNode(T data)</code></p>\n\n<ul>\n<li>This should be called <code>addNodeToTail</code> or <code>pushBack</code> since it specifically adds a node to the tail of the list</li>\n<li>Why are you iterating through the whole list when you already have a pointer to <code>tail</code>? After the while loop, <code>tmp == tail</code>.</li>\n<li>Never do this: <code>head = tail = t;</code>. Everytime a programmer sees this, they have to stop and think if this is undefined behavior. Make this two separate statements.</li>\n</ul></li>\n<li><p><code>~DoublyLinkedList</code></p>\n\n<ul>\n<li>Never do multiple assignments this way: <code>head = tail = NULL;</code>. See similar note above.</li>\n<li>Since the DoublyLinkedList is destructed, there's not point in setting <code>head</code> and <code>tail</code> to <code>NULL</code> since these variables are immediately destructed afterwards.</li>\n</ul></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-02-25T14:47:46.947",
"Id": "82580",
"ParentId": "4629",
"Score": "1"
}
},
{
"body": "<p>It's just an additional advice.</p>\n\n<pre><code>typedef Node<T> node_t;\n</code></pre>\n\n<p>It can't be done. Type definition can't be with template class.</p>\n\n<p>But I heard that we can do over C++11. (not exactly same above code)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-21T13:36:56.667",
"Id": "108273",
"ParentId": "4629",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4630",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T05:13:21.910",
"Id": "4629",
"Score": "8",
"Tags": [
"c++",
"linked-list"
],
"Title": "Doubly linked list in C++"
}
|
4629
|
<p>Please review this:</p>
<pre><code>#include <iostream>
#include <vector>
#include <cassert>
using namespace std;
template <class T>
class Stack
{
public:
Stack() {}
void push(T x);
void pop();
T & top();
size_t size();
bool empty();
private:
std::vector<T> elems;
};
template <class T>
void Stack<T>::push(T x)
{
elems.push_back(x);
}
template <class T>
void Stack<T>::pop()
{
if (elems.size() > 0)
{
elems.erase(elems.end() - 1);
};
}
template <class T>
T & Stack<T>::top()
{
assert(elems.size() > 0);
return elems.at(elems.size()-1);
}
template <class T>
size_t Stack<T>::size()
{
return elems.size();
}
template <class T>
bool Stack<T>::empty()
{
return elems.size() == 0 ? true : false;
}
int main()
{
Stack<int> s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
cout << "size: " << s.size() << endl;
cout << "top element: " << s.top() << endl;
s.pop();
s.pop();
cout << "size: " << s.size() << endl;
cout << "top element: " << s.top() << endl;
cout << "empty: " << s.empty() << endl;
s.pop();
s.pop();
s.pop();
cout << "size: " << s.size() << endl;
//cout << "top element: " << s.top() << endl;
cout << "empty: " << s.empty() << endl;
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>Most of the cases I wrote for <a href=\"https://codereview.stackexchange.com/questions/4629/doubly-linked-list-c/4630#4630\">your other question</a> are also applicable here. Here's an extra thing:</p>\n\n<p><code>return elems.size() == 0 ? true : false;</code></p>\n\n<p>The expression <code>elems.size() == 0</code> <strong>is</strong> of type bool. What you write is like <code>if(true) return true; else return false;</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T07:12:31.763",
"Id": "6935",
"Score": "0",
"body": "While I see no fault in your argument, there are people that I know who _thinks_ that form is easier to follow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T07:16:50.930",
"Id": "6937",
"Score": "0",
"body": "@Jeff Mercado: well, if these people even have problems reading expressions like \"1 == 2\", I'm curious whether they can write code at all."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T07:18:27.057",
"Id": "6938",
"Score": "0",
"body": "I agree with `return elems.size() == 0;` is more readable but it's more of a coding style argument."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T07:23:26.743",
"Id": "6939",
"Score": "1",
"body": "Coding-styling aspects of this kind is often really bad idea. If someone hires me to write C++ code, I'll write C++ code. If they want me to use a sub-set of C++ (like, no templates) or they require me to write stupidities (like `if(a == true)` instead of `if(a)` in case a is `bool`) that's not C++, that's \"let's play the game our teamlead/PM/any-other-idiot-who-is-bored invented\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T16:41:13.277",
"Id": "6949",
"Score": "1",
"body": "@Jeff: Really? You know people who think introducing a ternary operator make the code easier to follow?????"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T18:23:24.787",
"Id": "6957",
"Score": "0",
"body": "@Nathanael: Not necessarily _that_, but `if (condition) return true; else return false;`. Yes, odd I know."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T19:24:20.407",
"Id": "6959",
"Score": "1",
"body": "@Nathanael: it's something with their perception of the world. I'm not a native English speaker, but when I see `x == 0`, I read it as \"x is zero\", and when I see `return x == 0`, I read it as \"tell *them* that x is zero\". Ternary in `return x == 0 ? true : false` is like \"tell *them* **yes** if x is zero and **no** if it's not\". Too many words!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T06:29:02.813",
"Id": "4632",
"ParentId": "4631",
"Score": "3"
}
},
{
"body": "<p>I agree with loki on the size() method.</p>\n\n<p>Maybe assert is not the correct thing here.</p>\n\n<pre><code>template <class T>\nT & Stack<T>::top()\n{\n assert(elems.size() > 0);\n return elems.at(elems.size()-1);\n}\n</code></pre>\n\n<p>Maybe an exception would be a better idea.<br>\nThat way the user has the potential to recover but if they don't specifically check then the application still exits like assert. Also asserts can be turned of. So there is the potential that production code you would get illegal access to the underlying vector.</p>\n\n<p>Why not have the same test on pop() rather than silently failing in this situation?</p>\n\n<pre><code>template <class T>\nvoid Stack<T>::pop()\n{\n if (elems.size() > 0) // This causes a silent fail\n // But is the same kind of programming bug as top\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T15:40:36.530",
"Id": "4643",
"ParentId": "4631",
"Score": "2"
}
},
{
"body": "<ul>\n<li>Methods <code>size()</code> and <code>empty()</code> should be declared <code>const</code>. There also should be overloaded <code>top() const</code> method.</li>\n<li>Instead of <code>elems.at(elems.size()-1)</code> use <code>elems.back()</code>. There is also a method <code>pop_back()</code>.</li>\n<li>Don't use <code>using namespace std</code>, especially in header files.</li>\n<li>Implementation of these methods is really small, so I would recommend definitions inside class declaration.</li>\n<li>It would be nice to have a constructor that takes expected size of the stack and reserve that amount in <code>elems</code>.</li>\n<li>With <code>assert()</code> the prerequisite will be unchecked in Release mode – use exception.</li>\n</ul>\n\n<hr>\n\n<pre><code>#include <vector>\n#include <stdexcept>\n\ntemplate <class T>\nclass Stack {\npublic:\n Stack(size_t size = 0) {\n elems.reserve(size);\n }\n\n void push(T x) {\n elems.push_back(x);\n }\n\n void pop() {\n if (!empty()) {\n elems.pop_back();\n }\n }\n\n T& top() {\n if (empty()) {\n throw std::out_of_range(\"Stack is empty\");\n }\n return elems.back();\n }\n\n T top() const {\n if (empty()) {\n throw std::out_of_range(\"Stack is empty\");\n }\n return elems.back();\n }\n\n size_t size() const {\n return elems.size();\n }\n\n bool empty() const {\n return size() == 0;\n }\n\nprivate:\n std::vector<T> elems;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-04-19T11:02:17.210",
"Id": "25260",
"ParentId": "4631",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "4643",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T06:01:01.607",
"Id": "4631",
"Score": "1",
"Tags": [
"c++",
"stack"
],
"Title": "Stack class in C++"
}
|
4631
|
<p>There is a 1-to-many relationship between the <code>posts</code> table and the <code>votes</code> table, and they join on <code>posts.id = votes.postid</code>. I would like to know how many posts have 1, 2, 3, 5, etc. votes.</p>
<p>Thanks to Waffles' <a href="http://data.stackexchange.com/stackoverflow/s/87/most-controversial-posts-on-the-site" rel="nofollow">most controversial posts query</a>, it was trivial to write <a href="http://data.stackexchange.com/gaming/s/1836/answer-upvote-distribution" rel="nofollow">this</a>:</p>
<pre><code>declare @VoteStats table (PostId int, up int)
set nocount on
insert @VoteStats
select
PostId,
up = sum(case when VoteTypeId = 2 then 1 else 0 end)
from Votes
where VoteTypeId in (2,3)
group by PostId
set nocount off
select up, count(*)
from @VoteStats
group by up;
</code></pre>
<p>However, <a href="http://data.stackexchange.com/mini-profiler-results?id=fb123312-b40c-43cd-a52c-953d85b358c7" rel="nofollow">it runs in a full 22 seconds</a> on the Stack Overflow data dump.</p>
<p>Am I overlooking an obvious way to speed this query up, perhaps avoiding the creation of the VoteStats table?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T17:47:30.610",
"Id": "6954",
"Score": "1",
"body": "Is there some reason you can't restrict your where clause to `where VoteTypeId = 2` and then just `count(*)` the rows? That's essentially what you're currently asking. Or do you also have a `down` column that goes the other way?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T17:51:30.540",
"Id": "6955",
"Score": "0",
"body": "@X-Zero That [only shoved off one second](http://data.stackexchange.com/mini-profiler-results?id=ee272d21-702b-45ca-bb19-ab3d2f17a403), but makes a lot of sense. Plus, it removed a subtle problem with showing a count of posts with \"0 votes\" (they actually aren't all posts with no votes). I should've totally seen that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T17:57:30.203",
"Id": "6956",
"Score": "0",
"body": "Then that's probably as fast as it's going to get..."
}
] |
[
{
"body": "<p>Not creating the VoteStats table makes a big difference. Gets it down to ~5.5 seconds.</p>\n\n<pre><code>set nocount on\n\nselect up, count(*)\nfrom (\n select\n PostId,\n up = sum(case when VoteTypeId = 2 then 1 else 0 end)\n from Votes\n where VoteTypeId in (2,3)\n group by PostId\n) a\ngroup by up\norder by up\n</code></pre>\n\n<p><a href=\"http://data.stackexchange.com/stackoverflow/q/112108/\" rel=\"nofollow\">http://data.stackexchange.com/stackoverflow/q/112108/</a></p>\n\n<p>From the execution plan of the table variable version, it looks like the table scan and the sort on it is pretty expensive.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T22:45:08.673",
"Id": "7027",
"Score": "0",
"body": "...and combining this with the other answer cuts the time down to 2 seconds. Pesky syntax! :D"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T21:31:26.237",
"Id": "4688",
"ParentId": "4635",
"Score": "2"
}
},
{
"body": "<p>I think this should be faster, because instead of summing up 1 for every vote that has a VoteTypeId=2, I counted votes with VoteTypeId=2:</p>\n\n<pre><code>with VoteCountsByPost as\n(\n select \n p.Id as PostId,\n count(v.Id) as up\n from Posts p\n left join Votes v on v.PostId = p.Id and v.VoteTypeId = 2\n group by p.Id\n)\nselect up, count(*) \nfrom VoteCountsByPost\ngroup by up\norder by up\n</code></pre>\n\n<p>Also, please note that the results are a little different: you query does not take into account posts that have no votes. </p>\n\n<p>For instance, if a post has a vote with VoteTypeId != 2, then that post will appear with 0 ups. If it has no votes whatsoever, then that post will be completely excluded from the result set.</p>\n\n<p>I don't know if this is the intended behavior.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T22:41:58.367",
"Id": "7026",
"Score": "0",
"body": "Yeah, this is what X-Zero suggested. See the comments on the question for my follow up. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T22:07:52.947",
"Id": "4689",
"ParentId": "4635",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T09:55:25.783",
"Id": "4635",
"Score": "3",
"Tags": [
"sql",
"stackexchange"
],
"Title": "Upvote distribution SEDE query"
}
|
4635
|
<p>I'm volunteering some time to work on an open-data project, which I've started a repo out here for:</p>
<p><a href="https://github.com/0xdeadcafe/Open-Hamilton/blob/master/whereare.js" rel="nofollow">https://github.com/0xdeadcafe/Open-Hamilton/blob/master/whereare.js</a></p>
<p>The general idea is you'll paste in script tags the same way Google maps does to any third-party site to call the JavaScript.</p>
<p>I'm trying to prevent global namespace abuses (both-ways), and make configuration very simple and straight-forward.</p>
<p>Right now, the plugin configuration looks like (<em>this is before my re-write</em>):</p>
<pre><code><script type="text/javascript">
var Config = { height: 500, width: 500 };
document.write(unescape("%3Cscript src='http://example.com/somecode.js' type='text/javascript'%3E%3C/script%3E"));
</script>
</code></pre>
<p>I've got a few problems with this, first of all, it's using document.write and hopes that script-tags execute in the way I want them to. I'm scared this will break the page, I'd rather use DOM append child methods.</p>
<p>The other problem here is you can't configure this in-site simply without introducing a global variable.</p>
<p>I'd like to do something where I can call such as:</p>
<pre><code><script type="text/javascript">
/*document.createelement script tag... make the
src equal to the javascript, pass config data by function parameter?*/);
</script>
</code></pre>
<p>So my code is mostly a huge closure, and I try to contain the whole thing inside of there.</p>
<pre><code>(function(conf){
/*things happen*/
})({
"conf": "data",
"etc":"etc"
});
</code></pre>
<p>In the code I've linked up above I've made a function <code>confMerge</code> that attempts to do a recursive deep exclusive replace on the defaults being over-ridden by the configure data. I'm somewhat concerned it's over-kill in a few areas, and may break in others. My other concern is that I can't alter behavior based on type (for instance, google maps API can take a string as a <code>center</code> parameter, but I provide two numbers, my configure style can't deal with that.)</p>
<p>I've got a few rules, and that's that this needs to be ie6 friendly, I can't play with the prototype to shim ES5 styles, and I can't blow up someone elses website with my plugin, and it needs to be able to work without letting an average website with globals all-over-the-place blow up my widget.</p>
<p>Thoughts?</p>
|
[] |
[
{
"body": "<p>There's nothing stopping you putting a closure in around the script part so you don't have global variables - all except closures cause memory leaks in IE6 - in fact, Google Analytic does it.</p>\n\n<p>The switch statement does look a bit over-kill in <code>confMerge</code>. I'm not sure typeof will return 'xml'. Most often, all you have to do is <code>options[i] = conf[i] || defaults[i];</code>, basically. With objects and arrays you just recurse down. I've done this numerous times, so as far as I can see, nothing to worry about.</p>\n\n<p>I don't see why you cannot support strings. You can always build a validator for that specific property.</p>\n\n<p><strong>Update</strong>:\nI think I realise my mistake. I assumed that <code>copyMerge</code> did a shallow copy. The way you do it, you enforce the structure of the defaults. I still believe, however, that validation is best solution, but what you should do is a shallow copy, so when you see an object or array you just reference it, rather than calling <code>copyMerge</code>.</p>\n\n<p>Then to validate the data, I feel that creating validation functions for all the properties is the best way. Thus you can handle the property <code>center</code> and make sure if it's a string, or an object with the two properties 1 and 0. If it must be an array you can it by using <code>Object.prototype.toString.apply( obj ) === \"[object Array]\"</code>.</p>\n\n<p>You can put the validation functions in <code>copyMerge</code> by creating an object <code>funcs</code> with the same name as the properties, so <code>object[\"center\"]</code> or in <code>copyMerge</code>, <code>object[ i ]</code> where <code>i === \"center\"</code>. Another way is to have a <code>copyMerge</code> go the copying and have a validator function to validate the data.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-11T23:02:35.130",
"Id": "7099",
"Score": "0",
"body": "The XML is there because that's a possibility in the spec, so I figure'd I account for it somehow. I'm sure I could support strings, my issue is what's an elegant way to actually do that? If my defaults are an array, and I get a string, I don't want to code a one-off setting, I want to design a solution for other things."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-12T10:40:07.193",
"Id": "7108",
"Score": "0",
"body": "I have added more information. A question that cropped up for me is, why do you do a deep copy?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-11T02:49:06.007",
"Id": "4736",
"ParentId": "4639",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T13:54:35.780",
"Id": "4639",
"Score": "-1",
"Tags": [
"javascript"
],
"Title": "Javascript widget patterns and merging configurations"
}
|
4639
|
<p>I am trying to send mail via the <code>mail()</code> method, but I am doing it on my localhost, which does not appear to have a SMTP server running. </p>
<p>I think the code is fine, and the mail method itself is returning <code>true</code>, but could someone tell me if there is anything wrong with the use of the function before I put it onto my production server?</p>
<pre><code>$mail('john@me.com', 'Title', 'John has send you a link to title','From: john@me.com X-Mailer: PHP/5.2.11');
</code></pre>
|
[] |
[
{
"body": "<p>Your email headers need to be seperated by CRLFs.\nFrom php.net:</p>\n\n<blockquote>\n <p>Multiple extra headers should be separated with a CRLF (<code>\\r\\n</code>)</p>\n</blockquote>\n\n<p>so you would need to add in <code>\"\\r\\n\"</code> between header declarations.</p>\n\n<p>Example from php.net ( <a href=\"http://php.net/manual/en/function.mail.php\" rel=\"nofollow\">http://php.net/manual/en/function.mail.php</a> )</p>\n\n<pre><code><?php\n$to = 'nobody@example.com';\n$subject = 'the subject';\n$message = 'hello';\n$headers = 'From: webmaster@example.com' . \"\\r\\n\" .\n 'Reply-To: webmaster@example.com' . \"\\r\\n\" .\n 'X-Mailer: PHP/' . phpversion();\n\nmail($to, $subject, $message, $headers);\n?>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T16:20:14.157",
"Id": "4646",
"ParentId": "4644",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4646",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T15:51:49.487",
"Id": "4644",
"Score": "-1",
"Tags": [
"php"
],
"Title": "Localhost Mail() issues"
}
|
4644
|
<p>I've written a class that makes writing singletons easy. The class is meant to be used as a decorator (example below). I'd like to see your thoughts about the code, the documentation, and everything else that you feel is worth noting.</p>
<pre><code>class Singleton:
"""
Helper class meant to ease the creation of singletons. This
should be used as a decorator -- not a metaclass -- to the class
that should be a singleton.
The decorated class should define only one `__init__` function
that takes only the `self` argument. Other than that, there are
no restrictions that apply to the decorated class.
To get the singleton instance, use the `Instance` method. Trying
to use `__call__` will result in a `SingletonError` being raised.
"""
_singletons = dict()
def __init__(self, decorated):
self._decorated = decorated
def Instance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
key = self._decorated.__name__
try:
return Singleton._singletons[key]
except KeyError:
Singleton._singletons[key] = self._decorated()
return Singleton._singletons[key]
def __call__(self):
"""
Call method that raises an exception in order to prevent creation
of multiple instances of the singleton. The `Instance` method should
be used instead.
"""
raise SingletonError(
'Singletons must be accessed through the `Instance` method.')
class SingletonError(Exception):
pass
</code></pre>
<p>Now to test if the documentation was clear enough think about how you understood this class is meant to be used... Now look at this example and compare:</p>
<pre><code>@Singleton
class Foo:
def __init__(self):
print('Foo created')
def bar(self, obj):
print(obj)
foo = Foo() # Wrong, raises SingletonError
foo = Foo.Instance() # Good; prints 'Foo created'
goo = Foo.Instance() # Already created, prints nothing
print(goo is foo) # True
foo.bar('Hello, world! I\'m a singleton.')
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T20:15:21.153",
"Id": "6963",
"Score": "0",
"body": "Isn't Alex Martelli's \"Borg\" the existing, recommended solution? http://code.activestate.com/recipes/66531-singleton-we-dont-need-no-stinkin-singleton-the-bo/. Why reinvent this and make it more complex at the same time?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T20:48:46.267",
"Id": "6965",
"Score": "0",
"body": "@S.Lott This doesn't require modification of the original class and it is explicit about it being a singleton (you have to use `Instance`). Borg does neither of these."
}
] |
[
{
"body": "<p>Hmmm, if it's called from multiple threads, it may create few instances. So, some locking would be welcome.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T16:57:10.037",
"Id": "6950",
"Score": "1",
"body": "Oh yeah, I forgot to mention. My app is single threaded, so I didn't make it thread safe."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T17:07:28.633",
"Id": "6951",
"Score": "0",
"body": "\"your app\", \"today\" ... those will change :). Better add the functionality now, and never think about it later. It shouldn't be complicated."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T17:10:45.220",
"Id": "6952",
"Score": "0",
"body": "I've never written a single line of multi-threaded code and I'm already busy on other parts of my app. Please, review it for what it is, for now. :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T23:48:54.203",
"Id": "6976",
"Score": "1",
"body": "@Sunny, so many things will break when multithreading is introduced. Why would you think this particular one should be fixed?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T12:35:19.693",
"Id": "7001",
"Score": "0",
"body": "@Winston Ewert: to start with, I'm not a huge fan of singletons. I do not thing there's a need for such implementation in Python as well - just a module will be more than enough. But ... as the OP has put the effort to do it, and asked for \"review\" I pointed out something which looks important."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T16:54:40.197",
"Id": "4649",
"ParentId": "4648",
"Score": "2"
}
},
{
"body": "<ol>\n<li>You can put your example as <a href=\"http://docs.python.org/library/doctest.html\" rel=\"nofollow\">doctest</a>, or you should write a small <a href=\"http://docs.python.org/library/unittest.html\" rel=\"nofollow\">unittest</a> </li>\n<li>What if <code>Foo</code> needs parameters?</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T19:32:38.033",
"Id": "6960",
"Score": "0",
"body": "At your second point: Foo needing parameters beats the whole purpose of it being a singleton. You don't know exactly when a singleton is created, so you don't know when to pass the parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T19:45:58.660",
"Id": "6961",
"Score": "0",
"body": "[cont'd] And not only that. If your singleton needs parameters, then it means it has state, which means it shouldn't be a singleton in the first place."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T19:22:01.113",
"Id": "4650",
"ParentId": "4648",
"Score": "2"
}
},
{
"body": "<p>It might be beneficial to add positional and keyword arguments to the <code>__call__()</code> method. That way you'll get your <code>SingletonError</code> for <em>any</em> call you attempt to make, rather than just the no-argument call.</p>\n\n<p>You may want to add methods to delete or redefine singletons if necessary or restructure your class to address naming conflicts. It breaks if you define one singleton and use it, then later redefine a new singleton using the same name.</p>\n\n<p>Consider making <code>Instance</code> a property rather than a method.</p>\n\n<p>Consider using \"new-style\" class syntax explicitly.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T20:14:25.797",
"Id": "4652",
"ParentId": "4648",
"Score": "3"
}
},
{
"body": "<p>Singletons are evil, don't use them. Singletons are just a complicated version of a global variable. Your best option is to actually avoid global variables, not reinvent them. See <a href=\"http://www.youtube.com/watch?v=-FRm3VPhseI\" rel=\"nofollow\">http://www.youtube.com/watch?v=-FRm3VPhseI</a> for a discussion of how to really avoid global variables.</p>\n\n<p>Why are you storing the items as a dictionary on the class object rather then as an attribute on the local object?</p>\n\n<p>The python style guide says that methods should be lowercase_with_underscores.</p>\n\n<p>The <code>__call__</code> override is dubiously useful. Perhaps just giving the default python no <code>__call__</code> defined would be sufficient. It is not like anybody should be catching SingletonError</p>\n\n<p><em>EDIT</em></p>\n\n<p>Applying paragraph 2, there is no need for class-level dicts.</p>\n\n<pre><code>class Singleton:\n def __init__(self, decorated):\n self._decorated = decorated\n self._value = None\n\n def Instance(self):\n if self._value is None:\n self._value = self._decorated()\n\n return self._value\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T21:51:36.277",
"Id": "6966",
"Score": "0",
"body": "This isn't the place... (If you're using singletons to store state, you're doing it wrong.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:10:45.323",
"Id": "6967",
"Score": "0",
"body": "@second paragraph: as in, store it in the class itself, rather than in the dict inside `Singleton`? Because I don't want to have to modify the class. I wanted this to be possible with a simple decorator."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:14:23.760",
"Id": "6968",
"Score": "0",
"body": "@fourth paragraph: It's not meant to be caught. It's there to make it clear what the problem is (kinda like `NameError`)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:16:52.040",
"Id": "6969",
"Score": "0",
"body": "@second paragraph: Python itself breaks that guideline: http://docs.python.org/library/logging.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:50:52.537",
"Id": "6970",
"Score": "0",
"body": "@Paul 99% of Singletons I've seen were used to hold state. So I tend to assume that's what people do."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:51:57.900",
"Id": "6971",
"Score": "0",
"body": "@Paul, you store a _decorated item on the decorator itself. just add a _object attribute to hold the value. Then you don't need that class-wide dict."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:53:10.333",
"Id": "6972",
"Score": "1",
"body": "@Paul, your mileage may vary but, I think `TypeError: 'Singleton' object is not callable` is sufficiently clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:53:39.990",
"Id": "6973",
"Score": "0",
"body": "@Paul, if there is no state, why isn't it a module?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:54:44.417",
"Id": "6974",
"Score": "0",
"body": "@Paul, This is the place. Ihis is code review, I'm allowed to complain about any aspect of your code I see fit. You are free to ignore my complaints."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:58:17.313",
"Id": "6975",
"Score": "0",
"body": "@Paul, yes python doesn't follow the guideline usually for backwards compatibility reasons. But it is in the official style guide nonetheless."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T05:38:50.200",
"Id": "6982",
"Score": "0",
"body": "Thanks, I followed your suggestions, except the one about the guideline. (I also removed the downvote.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T06:00:39.480",
"Id": "6983",
"Score": "0",
"body": "I intentionally use a different convention for the Instance method (make is a noun and start with capital letter). This is because it's a special method (almost like a constructor, but not quite) and I like to make it stand out."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T21:46:49.693",
"Id": "4655",
"ParentId": "4648",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4652",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T16:45:03.060",
"Id": "4648",
"Score": "4",
"Tags": [
"python",
"singleton"
],
"Title": "Singleton Decorator"
}
|
4648
|
<p>I have a lot of repeatable blocks of code and want to optimize/simplify them:</p>
<pre><code> function animationInit() {
content = $('#content')
.bind('show',function(event, f) {
$(this).animate({right:0}, lag + 200, function() {
if (f) f();
});
})
.bind('hide',function(event, f) {
$(this).animate({right:-700}, lag + 200, function() {
if (f) f();
});
});
hotelnav = $('#hotel')
.bind('show',function(event, f) {
hotelnav.removeClass('small');
$(this).animate({left:0}, lag + 200, function() {
if (f) f();
});
})
.bind('hide',function(event, f) {
$(this).animate({left:isGallery()?-300:-300}, lag + 200, function() {
hotelnav.addClass(isGallery()?'small':'');
if (f) f();
});
});
bottompanel = $('#bottompanel')
.bind('show',function(event, f) {
$(this).animate({bottom:40}, lag + 200, function() {
if (f) f();
});
})
.bind('hide',function(event, f) {
$(this).animate({bottom:-120}, lag + 200, function() {
if (f) f();
});
});
booknow = $('#booknow')
.bind('show',function(event, f) {
$(this).fadeIn(lag + 200, function() {
if (f) f();
});
})
.bind('hide',function(event, f) {
$(this).fadeOut(lag + 200, function() {
if (f) f();
});
});
};
</code></pre>
<p>How i can optimize repeatable parts of code with callbacks?
Im trying to create separate function like this:</p>
<pre><code>function cb(callback) {
if (callback) callback();
};
</code></pre>
<p>... but just have a lot of asynchronous callbacks...</p>
|
[] |
[
{
"body": "<p>I don't understand the need for </p>\n\n<pre><code>function() {\n if (f) f();\n}\n</code></pre>\n\n<p>put <code>f</code> instead of that whole thing. If it is undefined it won't get called.</p>\n\n<p>e.g</p>\n\n<pre><code>.bind('show',function(event, f) {\n $(this).animate({right:0}, lag + 200, f);\n});\n</code></pre>\n\n<p>Another thought came to me. The functions you use could be factored and used like:</p>\n\n<pre><code>function animateRight(event, f, rightValue, delay)\n{\n $(this).animate({right: rightValue}, lag + delay, f);\n}\n</code></pre>\n\n<p>(or if you can't pass that information in:</p>\n\n<pre><code>function animateRight(event, f, rightValue, delay)\n{\n return new function()\n {\n $(this).animate({right: rightValue}, lag + delay, f);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T23:28:31.647",
"Id": "7028",
"Score": "0",
"body": "@350D I've also some other thoughts Read my update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T13:22:20.617",
"Id": "7045",
"Score": "1",
"body": "creating universal function for all kind of animations - good point. Im working on it, thanks!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-08T07:25:25.467",
"Id": "4665",
"ParentId": "4654",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "4665",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T21:40:03.853",
"Id": "4654",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"callback"
],
"Title": "jQuery callbacks optimization"
}
|
4654
|
<p>I'm doing something quite strange. I'm trying to create a tiny system for creating templates inline in PHP, so that I can refactor by creating multiple templates in the original script, and eventually move the templates to separate scripts.</p>
<p>Here's the silly/basic template library that just calls an anonymous function that gets passed in after some HTML header stuff, and then calls a footer:</p>
<pre><code><?php
// System for using simple, native php templates.
// TODO: Put this in a namespace to keep it clean and separate.
function display_page_inline($templates, $options, $data){
$title = @$options['title'];
echo "<html><head><title>".$title."</title></head>";
if(is_array($templates)){
foreach($templates as $template_function){
$template_function($data);
}
} else{
$template($data); // Call & display the template.
}
echo "<div>Footer</div>";
echo "</html>";
}
?>
</code></pre>
<p>Here's where it's going to get strange. In the scripts I'm creating anonymous functions, saved to variables, and then passing them to the template library for outputting. To avoid having to call an array element (and check whether the element exists each time), I'm trying to export the array passed in to get standard variables in the template (e.g. <code>$name</code> instead of <code>$data_array['name']</code>). Is there a way to abstract away this behavior in PHP?</p>
<pre><code><?php
require_once('core.php');
// Inclusion of the template library
require_once('../core/inline_templates.php');
// Initialization Logic
$title = 'Bob';
// Decide what will be able to be output and put it into an array to pass to the template
$template_output_variables = array('name'=>'no name');
// The page gets displayed at the bottom.
// =================== Templates ========================================
// Todo: Potentially namespace the stuff here.
// Define the anonymous template function here, has html and such in native php here.
$contact_us = function ($template_output_variables=null){
extract($template_output_variables); // Pull the variables.
// Leave php in the template function.
?>
<body>
Hello World Body Text, Hello <?php h($name);?>.
</body>
<?php
}; // End of template function declaration.
$killer_section = function ($data=null){
extract($data); // Pull the variables.
?>
Breaking news, There is a killer among us.
<?php
}; // End of killer section anon. function.
// Display the page.
// call & display the template via delayed execution, display it within a pre-set head and footer.
display_page_inline($templates=array($contact_us, $killer_section), $options=array('title'=>$title), $template_output_variables);
?>
</code></pre>
<p>It's very strange, I know, but I'm trying to do a whole new approach to refactoring, and make use of some new PHP 5.3 features while doing it. The goal is to have inline templates that I can put in any script, as many as I want, and move anywhere I want later, or merge the templates, etc.</p>
|
[] |
[
{
"body": "<p>Something like this would get you most of the way there:</p>\n\n<pre><code><?php\nfunction h($val) {\n echo $val;\n}\n\nfunction template_function($template_body) {\n return function(array $template_output_variables = null) use ($template_body) {\n if ($template_output_variables !== null) {\n extract($template_output_variables);\n }\n $contents = eval('?>'.$template_body.'<?php');\n echo $contents;\n };\n}\n\n\n$contact_us = template_function('\n <body>\n Hello World Body Text, Hello <?php h($name);?>.\n </body>'\n);\n\n$contact_us(array('name' => 'Johnny Boy'));\n</code></pre>\n\n<p>But it's evil, and you will likely end up with very odd, very hard-to-debug errors once your templates are of reasonable size/complexity. It's an interesting idea though -- if you pursue it, make sure you have a thorough set of test cases ;)</p>\n\n<p>The easiest way to clean it up, IMO, would be to do away with allowing raw php in the templates. I'm pretty partial to <a href=\"http://twig.sensiolabs.org/\" rel=\"nofollow\">Twig</a>, you may be able to find some inspiration there.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-19T19:33:12.000",
"Id": "16166",
"Score": "0",
"body": "Yeah, I'm definitely not doing this for the security, obviously (since the templates make all of php available). If I had to share low security templates with untrusted developers, then I'd move to a templating engine altogether.\n\nAnyway, I like the idea of a function that returns an anonymous function. Less so the eval part, though. I'd much prefer to perform that part via an existing php file being included."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-19T23:08:48.087",
"Id": "16178",
"Score": "0",
"body": "Ahh, indeed. You can use `include` or `require` easily -- and cleanly as well using the `ob_*` functions. And you should definitely prefer them over `eval`. I didn't use that as my example as I was trying to keep as close to exactly-in-line with the existing code in the comment as possible."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2012-03-19T09:30:12.227",
"Id": "10144",
"ParentId": "4656",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "10144",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:08:34.437",
"Id": "4656",
"Score": "3",
"Tags": [
"php",
"template"
],
"Title": "Passing anonymous functions and getting variables from an outer scope"
}
|
4656
|
<p>I have a table that contains the <code>UserAgent</code> string and a <code>Count</code> of how many times its seen. The T-SQL below is used to give a breakdown of what browsers are seen and how often then are seen.</p>
<p>I'm looking for comments (good or bad) and suggestions (good only).</p>
<pre><code>SELECT
Browser,
LEFT(Version, CHARINDEX('.', Version + '.', CHARINDEX('.', Version + '.0') + 1) - 1) AS Version,
SUM(Count) AS Count
FROM
(
SELECT
CASE
WHEN UserAgent LIKE '%Firefox/%' THEN 'Firefox'
WHEN UserAgent LIKE '%Chrome/%' THEN 'Chrome'
WHEN UserAgent LIKE '%MSIE %' THEN 'IE'
WHEN UserAgent LIKE '%MSIE+%' THEN 'IE'
WHEN UserAgent LIKE '%iPhone%' THEN 'iPhone Safari'
WHEN UserAgent LIKE '%iPad%' THEN 'iPad Safari'
WHEN UserAgent LIKE '%Opera%' THEN 'Opera'
WHEN UserAgent LIKE '%BlackBerry%' AND UserAgent LIKE '%Version/%' THEN 'BlackBerry WebKit'
WHEN UserAgent LIKE '%BlackBerry%' THEN 'BlackBerry'
WHEN UserAgent LIKE '%Android%' THEN 'Android'
WHEN UserAgent LIKE '%Safari%' THEN 'Safari'
WHEN UserAgent LIKE '%bot%' THEN 'Bot'
WHEN UserAgent LIKE '%http://%' THEN 'Bot'
WHEN UserAgent LIKE '%www.%' THEN 'Bot'
WHEN UserAgent LIKE '%Wget%' THEN 'Bot'
WHEN UserAgent LIKE '%curl%' THEN 'Bot'
WHEN UserAgent LIKE '%urllib%' THEN 'Bot'
ELSE 'Unknown'
END AS Browser,
CASE
WHEN UserAgent LIKE '%Firefox/%' THEN LEFT(RIGHT(UserAgent + ' ', LEN(UserAgent + ' ') - CHARINDEX('Firefox/', UserAgent + ' ') - 6), CHARINDEX(' ', RIGHT(UserAgent + ' ', LEN(UserAgent + ' ') - CHARINDEX('Firefox/', UserAgent + ' ') - 6)) - 1)
WHEN UserAgent LIKE '%Chrome/%' THEN LEFT(RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Chrome/', UserAgent) - 6), CHARINDEX(' ', RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Chrome/', UserAgent) - 6)) - 1)
WHEN UserAgent LIKE '%MSIE %' THEN LEFT(RIGHT(UserAgent + ';', LEN(UserAgent + ';') - CHARINDEX('MSIE ', UserAgent + ';') - 4), CHARINDEX(';', RIGHT(UserAgent + ';', LEN(UserAgent + ';') - CHARINDEX('MSIE ', UserAgent + ';') - 4)) - 1)
WHEN UserAgent LIKE '%MSIE+%' THEN LEFT(RIGHT(UserAgent + ';', LEN(UserAgent + ';') - CHARINDEX('MSIE+', UserAgent + ';') - 4), CHARINDEX(';', RIGHT(UserAgent + ';', LEN(UserAgent + ';') - CHARINDEX('MSIE+', UserAgent + ';') - 4)) - 1)
WHEN UserAgent LIKE '%iPhone%' AND UserAgent LIKE '%Version/%' THEN LEFT(RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7), CHARINDEX(' ', RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7)) - 1)
WHEN UserAgent LIKE '%iPad%' AND UserAgent LIKE '%Version/%' THEN LEFT(RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7), CHARINDEX(' ', RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7)) - 1)
WHEN UserAgent LIKE '%Opera%' THEN LEFT(RIGHT(UserAgent + ' ', LEN(UserAgent + ' ') - CHARINDEX('Opera/', UserAgent + ' ') - 4), CHARINDEX(' ', RIGHT(UserAgent + ' ', LEN(UserAgent + ' ') - CHARINDEX('Opera/', UserAgent + ' ') - 4)) - 1)
WHEN UserAgent LIKE '%BlackBerry%' AND UserAgent LIKE '%Version/%' THEN LEFT(RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7), CHARINDEX(' ', RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7)) - 1)
WHEN UserAgent LIKE '%BlackBerry%' THEN RIGHT(LEFT(UserAgent + ' ', CHARINDEX(' ', UserAgent + ' ') - 1), LEN(LEFT(UserAgent + ' ', CHARINDEX(' ', UserAgent + ' ') - 1)) - CHARINDEX('/', LEFT(UserAgent + ' ', CHARINDEX(' ', UserAgent + ' ') - 1)))
WHEN UserAgent LIKE '%Android%' THEN LEFT(RIGHT(UserAgent + ';', LEN(UserAgent + ';') - CHARINDEX('Android ', UserAgent + ';') - 7), CHARINDEX(';', RIGHT(UserAgent + ';', LEN(UserAgent + ';') - CHARINDEX('Android ', UserAgent + ';') - 7)) - 1)
WHEN UserAgent LIKE '%Safari%' AND UserAgent LIKE '%Version/%' THEN LEFT(RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7), CHARINDEX(' ', RIGHT(UserAgent, LEN(UserAgent) - CHARINDEX('Version/', UserAgent) - 7)) - 1)
WHEN UserAgent LIKE '%bot%' THEN '0.0'
WHEN UserAgent LIKE '%http://%' THEN '0.0'
WHEN UserAgent LIKE '%www.%' THEN '0.0'
WHEN UserAgent LIKE '%Wget%' THEN '0.0'
WHEN UserAgent LIKE '%curl%' THEN '0.0'
WHEN UserAgent LIKE '%urllib%' THEN '0.0'
ELSE '0.0'
END AS Version,
Count
FROM AnalyticsBrowsers
) as Browsers
WHERE
Browser NOT LIKE 'Bot'
GROUP BY
Browser, LEFT(Version, CHARINDEX('.', Version + '.', CHARINDEX('.', Version + '.0') + 1) - 1)
ORDER BY Count DESC
</code></pre>
<p>Output from a live website data collected 8/25/2011 to 9/7/2011:</p>
<blockquote>
<pre><code>Browser Version Count
IE 8.0 1495
IE 7.0 659
IE 6.0 470
Chrome 13.0 354
Firefox 6.0 345
IE 9.0 252
Firefox 3.6 213
Firefox 5.0 156
iPhone Safari 5.0 110
Safari 5.0 98
Safari 5.1 77
Unknown 0.0 47
iPad Safari 5.0 41
Firefox 4.0 34
Android 2.2 31
Firefox 3.5 16
Firefox 3.0 15
Chrome 14.0 11
Opera 9.80 11
Chrome 11.0 10
iPhone Safari 4.0 10
Android 2.3 8
iPhone Safari 0.0 7
Safari 4.0 7
Firefox 2.0 5
Android 2.1-update1 4
Firefox 1.5 4
Chrome 10.0 4
BlackBerry 4.5 4
BlackBerry 5.0 4
IE 5.5 4
Opera 9.24 4
Firefox 7.0 4
Chrome 9.0 3
BlackBerry 4.7 3
Safari 4.1 3
iPad Safari 4.0 3
Chrome 15.0 3
Safari 3.0 2
Safari 0.0 2
BlackBerry WebKit 6.0 2
iPhone Safari 5.1 2
Firefox 8.0a2 2
IE 5.01 1
Chrome 5.0 1
Android 1.5 1
Chrome 12.0 1
Safari 3.2 1
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Not a full answer but I would personally try to store all the mapping you use in the \"case\" statement in table.\nSo you could replace your sub query with all these cases by a join.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T17:28:29.123",
"Id": "4713",
"ParentId": "4657",
"Score": "5"
}
},
{
"body": "<p>You can eliminate a few of the conditions by combining them. Your two checks for IE in the \"Browser\" section can be combined into one <code>WHEN UserAgent LIKE '%MSIE%'</code> since you don't actually report those as different entities. Also, your \"Version\" section doesn't need explicit checks for all of the bot agents since you just report <code>0.0</code> for all of them. You can just let that fall to the <code>ELSE</code> clause.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-09T18:48:25.280",
"Id": "4714",
"ParentId": "4657",
"Score": "4"
}
},
{
"body": "<p>Keep in mind that the <code>LEN</code> function <a href=\"https://stackoverflow.com/questions/2025585/len-function-not-including-trailing-spaces-in-sql-server\">doesn't count trailing spaces</a>. That means that <code>LEN(UserAgent + ' ')</code> is actually equal to <code>LEN(UserAgent)</code>. The linked SO question/answer suggests using <code>DATALENGTH</code> instead (or <code>DATALENGTH(x)/2</code> for unicode strings). This will help future developers who have to maintain your code and may not be familiar with the specific behavior of the <code>LEN</code> function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-10T17:28:42.197",
"Id": "4727",
"ParentId": "4657",
"Score": "1"
}
},
{
"body": "<p>Just first impression...not to criticize...</p>\n\n<p>Personally, I'd recommend normalizing your AnalyticBrowsers table just a bit more... Separate columns for browser and version at a minimum. </p>\n\n<p>This will not only make your function-heavy / complex sql easier to write and process...</p>\n\n<pre><code>SELECT\n Browser,\n Version,\n SUM(Count) AS Count\nFROM\n AnalyticsBrowsers\nWHERE\n Browser NOT LIKE 'Bot'\nGROUP BY\n Browser,\n Version\nORDER BY \n Count DESC\n</code></pre>\n\n<p>But it will also make your data more scalable, in case you ever in the future want to keep data in new tables that is relatable to 'firefox', etc.</p>\n\n<p>As for content...data from this kind of query doesn't mean much without a date context. I guess you commented about that, but it wasn't in your SQL, so FWIW.</p>\n\n<p>Parse the useragent value before inserting into your AnalyticBrowsers table. Your web page could do this, or a stored procedure in your database, build it into your INSERT syntax, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T17:52:23.230",
"Id": "7215",
"Score": "0",
"body": "Hi, thanks for the comments. I do have date information, just left if off this sql :) I do have a browser and version columns as well but am not using them as the data is not of value. The information in the columns is provided by c# HttpContext.Current.Request.Browser and that data is way out of date."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-14T16:35:44.073",
"Id": "4821",
"ParentId": "4657",
"Score": "2"
}
},
{
"body": "<p>Thanks for that list of the cases, I was getting many Unknowns results, after investigation it turns out that IE11 was not detected as IE, so please consider to add one additional CASE statement:</p>\n\n<pre><code> WHEN UserAgent LIKE '%Windows NT%Trident%rv:%' THEN 'IE'\n</code></pre>\n\n<p>it's based according the specification you can find here: <a href=\"https://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-10T14:28:50.217",
"Id": "155018",
"ParentId": "4657",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "4714",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2011-09-07T22:25:12.547",
"Id": "4657",
"Score": "11",
"Tags": [
"performance",
"sql",
"sql-server"
],
"Title": "T-SQL statement to breakdown UserAgent information"
}
|
4657
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.