question_id int64 4 6.31M | answer_id int64 7 6.31M | title stringlengths 9 150 | question_body stringlengths 0 28.8k | answer_body stringlengths 60 27.2k | question_text stringlengths 40 28.9k | combined_text stringlengths 124 39.6k | tags listlengths 1 6 | question_score int64 0 26.3k | answer_score int64 0 28.8k | view_count int64 15 14M | answer_count int64 0 182 | favorite_count int64 0 32 | question_creation_date stringdate 2008-07-31 21:42:52 2011-06-10 18:12:18 | answer_creation_date stringdate 2008-07-31 22:17:57 2011-06-10 18:14:17 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,284 | 7,320 | What is Turing Complete? | What does the expression "Turing Complete" mean? Can you give a simple explanation, without going into too many theoretical details? | Here's the briefest explanation: A Turing Complete system means a system in which a program can be written that will find an answer (although with no guarantees regarding runtime or memory). So, if somebody says "my new thing is Turing Complete" that means in principle (although often not in practice) it could be used to solve any computation problem. Sometimes it's a joke... a guy wrote a Turing Machine simulator in vi, so it's possible to say that vi is the only computational engine ever needed in the world. | What is Turing Complete? What does the expression "Turing Complete" mean? Can you give a simple explanation, without going into too many theoretical details? | TITLE:
What is Turing Complete?
QUESTION:
What does the expression "Turing Complete" mean? Can you give a simple explanation, without going into too many theoretical details?
ANSWER:
Here's the briefest explanation: A Turing Complete system means a system in which a program can be written that will find an answer (although with no guarantees regarding runtime or memory). So, if somebody says "my new thing is Turing Complete" that means in principle (although often not in practice) it could be used to solve any computation problem. Sometimes it's a joke... a guy wrote a Turing Machine simulator in vi, so it's possible to say that vi is the only computational engine ever needed in the world. | [
"language-agnostic",
"theory",
"turing-machines",
"turing-complete"
] | 703 | 524 | 307,423 | 14 | 0 | 2008-08-10T18:41:02.300000 | 2008-08-10T20:10:48.687000 |
7,287 | 7,296 | How do you test/change untested and untestable code? | Lately I had to change some code on older systems where not all of the code has unit tests. Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard. Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it. Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed? | First of all, here's a great article with tips on unit testing. Secondly, I found a great way to avoid making tons of changes in old code is to just refactor it a little until you can test it. One easy way to do this is to make private members protected, and then override the protected field. For example, let's say you have a class that loads some stuff from the database during the constructor. In this case, you can't just override a protected method, but you can extract the DB logic to a protected field and then override it in the test. public class MyClass { public MyClass() { // undesirable DB logic } } becomes public class MyClass { public MyClass() { loadFromDB(); }
protected void loadFromDB() { // undesirable DB logic } } and then your test looks something like this: public class MyClassTest { public void testSomething() { MyClass myClass = new MyClassWrapper(); // test it }
private static class MyClassWrapper extends MyClass { @Override protected void loadFromDB() { // some mock logic } } } This is somewhat of a bad example, because you could use DBUnit in this case, but I actually did this in a similar case recently because I wanted to test some functionality totally unrelated to the data being loaded, so it was very effective. I've also found such exposing of members to be useful in other similar cases where I need to get rid of some dependency that has been in a class for a long time. I would recommend against this solution if you are writing a framework though, unless you really don't mind exposing the members to users of your framework. It's a bit of a hack, but I've found it quite useful. | How do you test/change untested and untestable code? Lately I had to change some code on older systems where not all of the code has unit tests. Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard. Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it. Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed? | TITLE:
How do you test/change untested and untestable code?
QUESTION:
Lately I had to change some code on older systems where not all of the code has unit tests. Before making the changes I want to write tests, but each class created a lot of dependencies and other anti-patterns which made testing quite hard. Obviously, I wanted to refactor the code to make it easier to test, write the tests and then change it. Is this the way you'd do it? Or would you spend a lot of time writing the hard-to-write tests that would be mostly removed after the refactoring will be completed?
ANSWER:
First of all, here's a great article with tips on unit testing. Secondly, I found a great way to avoid making tons of changes in old code is to just refactor it a little until you can test it. One easy way to do this is to make private members protected, and then override the protected field. For example, let's say you have a class that loads some stuff from the database during the constructor. In this case, you can't just override a protected method, but you can extract the DB logic to a protected field and then override it in the test. public class MyClass { public MyClass() { // undesirable DB logic } } becomes public class MyClass { public MyClass() { loadFromDB(); }
protected void loadFromDB() { // undesirable DB logic } } and then your test looks something like this: public class MyClassTest { public void testSomething() { MyClass myClass = new MyClassWrapper(); // test it }
private static class MyClassWrapper extends MyClass { @Override protected void loadFromDB() { // some mock logic } } } This is somewhat of a bad example, because you could use DBUnit in this case, but I actually did this in a similar case recently because I wanted to test some functionality totally unrelated to the data being loaded, so it was very effective. I've also found such exposing of members to be useful in other similar cases where I need to get rid of some dependency that has been in a class for a long time. I would recommend against this solution if you are writing a framework though, unless you really don't mind exposing the members to users of your framework. It's a bit of a hack, but I've found it quite useful. | [
"unit-testing",
"refactoring",
"legacy"
] | 9 | 6 | 2,052 | 5 | 0 | 2008-08-10T18:49:53.920000 | 2008-08-10T19:22:36.943000 |
7,348 | 7,351 | Zip library options for the Compact Framework? | My requirements: Support.NET Compact Framework 2.0 and Windows Mobile 6.0 devices. Only need to unzip the contents to a directory on a storage card. Creation of zip files is not required. Must be able to use in corporate/commercial software. Can be open source, but not have GPL or other viral license. I've seen the Xceed Zip for CF library. What other options are there? | Have a look at #ziplib (www.icsharpcode.com). It's GPL, but you can use it in closed-source, commercial applications. They don't say anything specifically on their page about using it with the Compact Framework, so you'd have to give it a test yourself (that said, it's pure C# without any external dependencies, so the chances are somewhat good that it will work). | Zip library options for the Compact Framework? My requirements: Support.NET Compact Framework 2.0 and Windows Mobile 6.0 devices. Only need to unzip the contents to a directory on a storage card. Creation of zip files is not required. Must be able to use in corporate/commercial software. Can be open source, but not have GPL or other viral license. I've seen the Xceed Zip for CF library. What other options are there? | TITLE:
Zip library options for the Compact Framework?
QUESTION:
My requirements: Support.NET Compact Framework 2.0 and Windows Mobile 6.0 devices. Only need to unzip the contents to a directory on a storage card. Creation of zip files is not required. Must be able to use in corporate/commercial software. Can be open source, but not have GPL or other viral license. I've seen the Xceed Zip for CF library. What other options are there?
ANSWER:
Have a look at #ziplib (www.icsharpcode.com). It's GPL, but you can use it in closed-source, commercial applications. They don't say anything specifically on their page about using it with the Compact Framework, so you'd have to give it a test yourself (that said, it's pure C# without any external dependencies, so the chances are somewhat good that it will work). | [
"windows-mobile",
"compact-framework",
"zip",
"components"
] | 9 | 3 | 7,849 | 5 | 0 | 2008-08-10T21:00:14.173000 | 2008-08-10T21:04:56.690000 |
7,364 | 7,455 | Edit PDF in PHP? | Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods.:) I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF? On the front-end | If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework: pages[0]; $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA); $page->setFont($font, 12); $page->drawText('Hello world!', 72, 720); $pdf->save('zend.pdf'); If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page. A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives. | Edit PDF in PHP? Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods.:) I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF? On the front-end | TITLE:
Edit PDF in PHP?
QUESTION:
Does anyone know of a good method for editing PDFs in PHP? Preferably open-source/zero-license cost methods.:) I am thinking along the lines of opening a PDF file, replacing text in the PDF and then writing out the modified version of the PDF? On the front-end
ANSWER:
If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework: pages[0]; $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA); $page->setFont($font, 12); $page->drawText('Hello world!', 72, 720); $pdf->save('zend.pdf'); If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page. A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives. | [
"php",
"pdf"
] | 93 | 73 | 151,987 | 9 | 0 | 2008-08-10T21:58:24.913000 | 2008-08-11T00:49:58.077000 |
7,367 | 7,399 | Visual Studio - new "default" property values for inherited controls | I'm looking for help setting a new default property value for an inherited control in Visual Studio: class NewCombo: System.Windows.Forms.ComboBox { public NewCombo() { DropDownItems = 50; } } The problem is that the base class property DropDownItems has a 'default' attribute set on it that is a different value (not 50). As a result, when I drag the control onto a form, the designer file gets an explicit mycontrol.DropDownItems = 50; line. At first, this doesn't matter. But if later I change my inherited class to DropDownItems = 45; in the constructor, this does not affect any of the controls on any form since all those designer files still have the value 50 hard-coded in them. And the whole point was to have the value set in one place so I can deal with the customer changing his mind. Obviously, if I were creating my own custom property in the subclass, I could give it its own designer default attribute of whatever I wanted. But here I'm wanting to change the default values of properties in the base. Is there any way to apply Visual Studio attributes to a base class member? Or is there some other workaround to get the result I want? | In your derived class you need to either override (or shadow using new ) the property in question and then re-apply the default value attribute. | Visual Studio - new "default" property values for inherited controls I'm looking for help setting a new default property value for an inherited control in Visual Studio: class NewCombo: System.Windows.Forms.ComboBox { public NewCombo() { DropDownItems = 50; } } The problem is that the base class property DropDownItems has a 'default' attribute set on it that is a different value (not 50). As a result, when I drag the control onto a form, the designer file gets an explicit mycontrol.DropDownItems = 50; line. At first, this doesn't matter. But if later I change my inherited class to DropDownItems = 45; in the constructor, this does not affect any of the controls on any form since all those designer files still have the value 50 hard-coded in them. And the whole point was to have the value set in one place so I can deal with the customer changing his mind. Obviously, if I were creating my own custom property in the subclass, I could give it its own designer default attribute of whatever I wanted. But here I'm wanting to change the default values of properties in the base. Is there any way to apply Visual Studio attributes to a base class member? Or is there some other workaround to get the result I want? | TITLE:
Visual Studio - new "default" property values for inherited controls
QUESTION:
I'm looking for help setting a new default property value for an inherited control in Visual Studio: class NewCombo: System.Windows.Forms.ComboBox { public NewCombo() { DropDownItems = 50; } } The problem is that the base class property DropDownItems has a 'default' attribute set on it that is a different value (not 50). As a result, when I drag the control onto a form, the designer file gets an explicit mycontrol.DropDownItems = 50; line. At first, this doesn't matter. But if later I change my inherited class to DropDownItems = 45; in the constructor, this does not affect any of the controls on any form since all those designer files still have the value 50 hard-coded in them. And the whole point was to have the value set in one place so I can deal with the customer changing his mind. Obviously, if I were creating my own custom property in the subclass, I could give it its own designer default attribute of whatever I wanted. But here I'm wanting to change the default values of properties in the base. Is there any way to apply Visual Studio attributes to a base class member? Or is there some other workaround to get the result I want?
ANSWER:
In your derived class you need to either override (or shadow using new ) the property in question and then re-apply the default value attribute. | [
"c#",
".net",
"vb.net",
"visual-studio"
] | 11 | 5 | 4,116 | 1 | 0 | 2008-08-10T22:06:49.670000 | 2008-08-10T23:11:39.133000 |
7,398 | 26,994 | How to avoid redefining VERSION, PACKAGE, etc | I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes: I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly straightforward, but in this case there is a tiny snag: each project generates its own config.h file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:... warning: "VERSION" redefined... warning: this is the location of the previous definition... warning: "PACKAGE" redefined... warning: this is the location of the previous definition These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is this thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas? | Some notes: you didn't mention how config.h was included - with quotes or angle brackets. See this other question for more information on the difference. In short, config.h is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the config.h from the project's own directory (which is usually what you want) You say that a subproject should be including the enclosing project's config.h Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is). It is usually a big mistake to have config.h be included from public headers. config.h is always private to your project or the subproject, and should only be included from.c files. So, if your vendor's documentation says to include their "vendor.h" and that public header includes config.h somehow, then that is a no-no. Similarly, if your project is a library, don't include config.h anywhere from your publically installed headers. | How to avoid redefining VERSION, PACKAGE, etc I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes: I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly straightforward, but in this case there is a tiny snag: each project generates its own config.h file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:... warning: "VERSION" redefined... warning: this is the location of the previous definition... warning: "PACKAGE" redefined... warning: this is the location of the previous definition These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is this thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas? | TITLE:
How to avoid redefining VERSION, PACKAGE, etc
QUESTION:
I haven't seen any questions relating to GNU autoconf/automake builds, but I'm hoping at least some of you out there are familiar with it. Here goes: I have a project (I'll call it myproject) that includes another project (vendor). The vendor project is a standalone project maintained by someone else. Including a project like this is fairly straightforward, but in this case there is a tiny snag: each project generates its own config.h file, each of which defines standard macros such as PACKAGE, VERSION, etc. This means that, during the build, when vendor is being built, I get lots of errors like this:... warning: "VERSION" redefined... warning: this is the location of the previous definition... warning: "PACKAGE" redefined... warning: this is the location of the previous definition These are just warnings, for the time being at least, but I would like to get rid of them. The only relevant information I've been able to turn up with a Google search is this thread on the automake mailing list, which isn't a whole lot of help. Does anybody else have any better ideas?
ANSWER:
Some notes: you didn't mention how config.h was included - with quotes or angle brackets. See this other question for more information on the difference. In short, config.h is typically included with quotes, not angle brackets, and this should make the preprocessor prefer the config.h from the project's own directory (which is usually what you want) You say that a subproject should be including the enclosing project's config.h Normally this is not at all what you want. The subproject is standalone, and its PACKAGE and VERSION should be the one of that subproject, not yours. If you include libxml in your xmlreader project for example, you would still want the libxml code to be compiled with PACKAGE libxml and VERSION (whatever the libxml version is). It is usually a big mistake to have config.h be included from public headers. config.h is always private to your project or the subproject, and should only be included from.c files. So, if your vendor's documentation says to include their "vendor.h" and that public header includes config.h somehow, then that is a no-no. Similarly, if your project is a library, don't include config.h anywhere from your publically installed headers. | [
"c",
"linux",
"unix",
"autoconf",
"automake"
] | 9 | 5 | 1,782 | 3 | 0 | 2008-08-10T23:10:53.190000 | 2008-08-25T21:52:23.997000 |
7,440 | 20,754 | What do you use to Unit-Test your Web UI? | The company I'm currently working for is using Selenium for Uniting-Testing our User Interface. What do you use to Unit-Test your Web UI and how effective do you find it? | We use Watin at my place of employment, we are a.net shop so this solution made a lot of sense. We actually started with Watir (the original ruby implementation) and switched after. It's been a pretty good solution for us so far | What do you use to Unit-Test your Web UI? The company I'm currently working for is using Selenium for Uniting-Testing our User Interface. What do you use to Unit-Test your Web UI and how effective do you find it? | TITLE:
What do you use to Unit-Test your Web UI?
QUESTION:
The company I'm currently working for is using Selenium for Uniting-Testing our User Interface. What do you use to Unit-Test your Web UI and how effective do you find it?
ANSWER:
We use Watin at my place of employment, we are a.net shop so this solution made a lot of sense. We actually started with Watir (the original ruby implementation) and switched after. It's been a pretty good solution for us so far | [
"unit-testing",
"user-interface",
"selenium"
] | 35 | 10 | 11,955 | 15 | 0 | 2008-08-11T00:05:36.590000 | 2008-08-21T18:46:18.563000 |
7,472 | 7,479 | WPF Databinding | Can anyone point me to a good resource (or throw me a clue) to show me how to do DataBinding to controls (ComboBox, ListBox, etc.) in WPF? I'm at a bit of a loss when all my WinForms niceities are taken away from me, and I'm not all that bright to start with... | I find the tutorial videos at Windows Client.Net equally awesome. Dot Net Rocks TV has also covered it some time ago. | WPF Databinding Can anyone point me to a good resource (or throw me a clue) to show me how to do DataBinding to controls (ComboBox, ListBox, etc.) in WPF? I'm at a bit of a loss when all my WinForms niceities are taken away from me, and I'm not all that bright to start with... | TITLE:
WPF Databinding
QUESTION:
Can anyone point me to a good resource (or throw me a clue) to show me how to do DataBinding to controls (ComboBox, ListBox, etc.) in WPF? I'm at a bit of a loss when all my WinForms niceities are taken away from me, and I'm not all that bright to start with...
ANSWER:
I find the tutorial videos at Windows Client.Net equally awesome. Dot Net Rocks TV has also covered it some time ago. | [
"wpf",
"data-binding"
] | 11 | 3 | 3,869 | 6 | 0 | 2008-08-11T01:34:34.773000 | 2008-08-11T01:45:45.297000 |
7,477 | 7,523 | How to autosize a textarea using Prototype? | I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address. Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed. Here's a screenshot of it currently. Any ideas? @Chris A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space. I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no. I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot). It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it. Though if someone comes up with another way to approach the problem I'm open to that too. I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed. resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0;
$A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines })
$('iso_address').rows = linecount; }; | Facebook does it, when you write on people's walls, but only resizes vertically. Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice. None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'. Some JavaScript code to do it, using Prototype (because that's what I'm familiar with): PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea. | How to autosize a textarea using Prototype? I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address. Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed. Here's a screenshot of it currently. Any ideas? @Chris A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space. I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no. I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot). It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it. Though if someone comes up with another way to approach the problem I'm open to that too. I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed. resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0;
$A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines })
$('iso_address').rows = linecount; }; | TITLE:
How to autosize a textarea using Prototype?
QUESTION:
I'm currently working on an internal sales application for the company I work for, and I've got a form that allows the user to change the delivery address. Now I think it would look much nicer, if the textarea I'm using for the main address details would just take up the area of the text in it, and automatically resize if the text was changed. Here's a screenshot of it currently. Any ideas? @Chris A good point, but there are reasons I want it to resize. I want the area it takes up to be the area of the information contained in it. As you can see in the screen shot, if I have a fixed textarea, it takes up a fair wack of vertical space. I can reduce the font, but I need address to be large and readable. Now I can reduce the size of the text area, but then I have problems with people who have an address line that takes 3 or 4 (one takes 5) lines. Needing to have the user use a scrollbar is a major no-no. I guess I should be a bit more specific. I'm after vertical resizing, and the width doesn't matter as much. The only problem that happens with that, is the ISO number (the large "1") gets pushed under the address when the window width is too small (as you can see on the screenshot). It's not about having a gimick; it's about having a text field the user can edit that won't take up unnecessary space, but will show all the text in it. Though if someone comes up with another way to approach the problem I'm open to that too. I've modified the code a little because it was acting a little odd. I changed it to activate on keyup, because it wouldn't take into consideration the character that was just typed. resizeIt = function() { var str = $('iso_address').value; var cols = $('iso_address').cols; var linecount = 0;
$A(str.split("\n")).each(function(l) { linecount += 1 + Math.floor(l.length / cols); // Take into account long lines })
$('iso_address').rows = linecount; };
ANSWER:
Facebook does it, when you write on people's walls, but only resizes vertically. Horizontal resize strikes me as being a mess, due to word-wrap, long lines, and so on, but vertical resize seems to be pretty safe and nice. None of the Facebook-using-newbies I know have ever mentioned anything about it or been confused. I'd use this as anecdotal evidence to say 'go ahead, implement it'. Some JavaScript code to do it, using Prototype (because that's what I'm familiar with): PS: Obviously this JavaScript code is very naive and not well tested, and you probably don't want to use it on textboxes with novels in them, but you get the general idea. | [
"javascript",
"html",
"css",
"textarea",
"prototypejs"
] | 132 | 80 | 170,377 | 18 | 0 | 2008-08-11T01:43:13.493000 | 2008-08-11T04:49:33.930000 |
7,489 | 13,384 | How do I make a GUI? | I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class? Here's one way I thought of but it doesn't seem right: Edit: I'm using C++. class Gui { public: void update_all(); void draw_all() const; int add_button(Button *button); // Returns button id void remove_button(int button_id); private: Button *buttons[10]; int num_buttons; } This code has a few problems, but I just wanted to give you an idea of what I want. | This question is very similar to one I was going to post, only mine is for Sony PSP programming. I've been toying with something for a while, I've consulted some books and VTMs, and so far this is a rough idea of a simple ui systems. class uiElement() {... virtual void Update() = 0; virtual void Draw() = 0;... }
class uiButton() public: uiElement {... virtual void Update(); virtual void Draw();... }
class uiTextbox() public: uiElement {... virtual void Update(); virtual void Draw();... }... // Other ui Elements
class uiWindow() {... void Update(); void Draw();
void AddElement(uiElement *Element); void RemoveElement(uiElement *Element);
std::list Elements;... }
void uiWindow::Update() {... for (list::iterator it = Elements.begin(); it!= Elements.end(); it++ ) it->Update();... }
void uiWindow::Draw() {... for (list::iterator it = Elements.begin(); it!= Elements.end(); it++ ) it->Draw();... } The princple is to create a window and attact ui Elements to it, and call the draw and update methods from the respective main functions. I don't have anything working yet, as I have issues with drawing code. With different APIs on the PC and PSP, I'm looking at some wrapper code for OpenGL and psp gu. Hope this helps. thing2k | How do I make a GUI? I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class? Here's one way I thought of but it doesn't seem right: Edit: I'm using C++. class Gui { public: void update_all(); void draw_all() const; int add_button(Button *button); // Returns button id void remove_button(int button_id); private: Button *buttons[10]; int num_buttons; } This code has a few problems, but I just wanted to give you an idea of what I want. | TITLE:
How do I make a GUI?
QUESTION:
I've made many different seperate parts of a GUI system for the Nintendo DS, like buttons and textboxes and select boxes, but I need a way of containing these classes in one Gui class, so that I can draw everything to the screen all at once, and check all the buttons at once to check if any are being pressed. My question is what is the best way organize all the classes (such as buttons and textboxes) into one GUI class? Here's one way I thought of but it doesn't seem right: Edit: I'm using C++. class Gui { public: void update_all(); void draw_all() const; int add_button(Button *button); // Returns button id void remove_button(int button_id); private: Button *buttons[10]; int num_buttons; } This code has a few problems, but I just wanted to give you an idea of what I want.
ANSWER:
This question is very similar to one I was going to post, only mine is for Sony PSP programming. I've been toying with something for a while, I've consulted some books and VTMs, and so far this is a rough idea of a simple ui systems. class uiElement() {... virtual void Update() = 0; virtual void Draw() = 0;... }
class uiButton() public: uiElement {... virtual void Update(); virtual void Draw();... }
class uiTextbox() public: uiElement {... virtual void Update(); virtual void Draw();... }... // Other ui Elements
class uiWindow() {... void Update(); void Draw();
void AddElement(uiElement *Element); void RemoveElement(uiElement *Element);
std::list Elements;... }
void uiWindow::Update() {... for (list::iterator it = Elements.begin(); it!= Elements.end(); it++ ) it->Update();... }
void uiWindow::Draw() {... for (list::iterator it = Elements.begin(); it!= Elements.end(); it++ ) it->Draw();... } The princple is to create a window and attact ui Elements to it, and call the draw and update methods from the respective main functions. I don't have anything working yet, as I have issues with drawing code. With different APIs on the PC and PSP, I'm looking at some wrapper code for OpenGL and psp gu. Hope this helps. thing2k | [
"c++",
"user-interface"
] | 8 | 3 | 2,528 | 5 | 0 | 2008-08-11T02:50:09.113000 | 2008-08-16T22:05:03.323000 |
7,503 | 7,512 | Linq to objects - select first object | I know almost nothing about linq. I'm doing this: var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select app; Which gets me all the running processes which match that criteria. But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select app).First(); which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way? UPDATE I'm actually trying to find the first matching item, and call SetForegroundWindow on it I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas? var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess | @FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want: var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle!= IntPtr.Zero);
if (app == null) return;
SetForegroundWindow(app.MainWindowHandle); | Linq to objects - select first object I know almost nothing about linq. I'm doing this: var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select app; Which gets me all the running processes which match that criteria. But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select app).First(); which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way? UPDATE I'm actually trying to find the first matching item, and call SetForegroundWindow on it I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas? var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess | TITLE:
Linq to objects - select first object
QUESTION:
I know almost nothing about linq. I'm doing this: var apps = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select app; Which gets me all the running processes which match that criteria. But I don't know how to get the first one. The examples I can find on the net seem to imply I have to do this var matchedApp = (from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select app).First(); which strikes me as somewhat ugly, and also throws an exception if there are no matching processes. Is there a better way? UPDATE I'm actually trying to find the first matching item, and call SetForegroundWindow on it I've come up with this solution, which also strikes me as ugly and awful, but better than above. Any ideas? var unused = from app in Process.GetProcesses() where app.ProcessName.Contains( "MyAppName" ) && app.MainWindowHandle!= IntPtr.Zero select SetForegroundWindow( app.MainWindowHandle ); // side-effects in linq-query is technically bad I guess
ANSWER:
@FryHard FirstOrDefault will work but remember that it returns null if none are found. This code isn't tested but should be close to what you want: var app = Process.GetProcesses().FirstOrDefault(p => p.ProcessName.Contains("MyAppName") && p.MainWindowHandle!= IntPtr.Zero);
if (app == null) return;
SetForegroundWindow(app.MainWindowHandle); | [
"c#",
"linq",
"linq-to-objects"
] | 12 | 20 | 43,847 | 3 | 0 | 2008-08-11T03:54:43.947000 | 2008-08-11T04:25:07.333000 |
7,517 | 25,741 | Dropping a group of tables in SQL Server | Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process. | At the risk of sounding stupid, I don't believe SQL Server supports the delete / cascade syntax. I think you can configure a delete rule to do cascading deletes ( http://msdn.microsoft.com/en-us/library/ms152507.aspx ), but as far as I know the trick with SQL Server is to just to run your drop query once for each table you're dropping, then check it worked. | Dropping a group of tables in SQL Server Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process. | TITLE:
Dropping a group of tables in SQL Server
QUESTION:
Is there a simple way to drop a group of interrelated tables in SQL Server? Ideally I'd like to avoid having to worry about what order they're being dropped in since I know the entire group will be gone by the end of the process.
ANSWER:
At the risk of sounding stupid, I don't believe SQL Server supports the delete / cascade syntax. I think you can configure a delete rule to do cascading deletes ( http://msdn.microsoft.com/en-us/library/ms152507.aspx ), but as far as I know the trick with SQL Server is to just to run your drop query once for each table you're dropping, then check it worked. | [
"sql",
"sql-server",
"database"
] | 8 | 4 | 3,650 | 7 | 0 | 2008-08-11T04:32:01 | 2008-08-25T07:40:42.033000 |
7,525 | 7,695 | Of Memory Management, Heap Corruption, and C++ | So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an std::string to a class and assigning it a value from another std::string: std::string hello = "Hello, world.\n"; /* exampleString = "Hello, world.\n" would work fine. */ exampleString = hello; crashes on my system with a stack dump. So basically I need to stop and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with valgrind, and while not knowing completely what I'm doing, it did report that the std::string 's destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well. (In before rm -rf ProjectDir, do again in C#:D) EDIT: I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were. | These are relatively cheap mechanisms for possibly solving the problem: Keep an eye on my heap corruption question - I'm updating with the answers as they shake out. The first was balancing new[] and delete[], but you're already doing that. Give valgrind more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents. Think about using the Google Performance Tools as a replacement malloc/new. Have you cleaned out all your object files and started over? Perhaps your make file is... "suboptimal" You're not assert() ing enough in your code. How do I know that without having seen it? Like flossing, no-one assert() s enough in their code. Add in a validation function for your objects and call that on method start and method end. Are you compiling -wall? If not, do so. Find yourself a lint tool like PC-Lint. A small app like yours might fit in the PC-lint demo page, meaning no purchase for you! Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers. Stop using arrays. Use a vector instead. Don't use raw pointers. Use a smart pointer. Don't use auto_ptr! That thing is... surprising; its semantics are very odd. Instead, choose one of the Boost smart pointers, or something out of the Loki library. | Of Memory Management, Heap Corruption, and C++ So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an std::string to a class and assigning it a value from another std::string: std::string hello = "Hello, world.\n"; /* exampleString = "Hello, world.\n" would work fine. */ exampleString = hello; crashes on my system with a stack dump. So basically I need to stop and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with valgrind, and while not knowing completely what I'm doing, it did report that the std::string 's destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well. (In before rm -rf ProjectDir, do again in C#:D) EDIT: I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were. | TITLE:
Of Memory Management, Heap Corruption, and C++
QUESTION:
So, I need some help. I am working on a project in C++. However, I think I have somehow managed to corrupt my heap. This is based on the fact that I added an std::string to a class and assigning it a value from another std::string: std::string hello = "Hello, world.\n"; /* exampleString = "Hello, world.\n" would work fine. */ exampleString = hello; crashes on my system with a stack dump. So basically I need to stop and go through all my code and memory management stuff and find out where I've screwed up. The codebase is still small (about 1000 lines), so this is easily do-able. Still, I'm over my head with this kind of stuff, so I thought I'd throw it out there. I'm on a Linux system and have poked around with valgrind, and while not knowing completely what I'm doing, it did report that the std::string 's destructor was an invalid free. I have to admit to getting the term 'Heap Corruption' from a Google search; any general purpose articles on this sort of stuff would be appreciated as well. (In before rm -rf ProjectDir, do again in C#:D) EDIT: I haven't made it clear, but what I'm asking for are ways an advice of diagnosing these sort of memory problems. I know the std::string stuff is right, so it's something I've done (or a bug, but there's Not A Problem With Select). I'm sure I could check the code I've written up and you very smart folks would see the problem in no time, but I want to add this kind of code analysis to my 'toolbox', as it were.
ANSWER:
These are relatively cheap mechanisms for possibly solving the problem: Keep an eye on my heap corruption question - I'm updating with the answers as they shake out. The first was balancing new[] and delete[], but you're already doing that. Give valgrind more of a go; it's an excellent tool, and I only wish it was available under Windows. I only slows your program down by about half, which is pretty good compared to the Windows equivalents. Think about using the Google Performance Tools as a replacement malloc/new. Have you cleaned out all your object files and started over? Perhaps your make file is... "suboptimal" You're not assert() ing enough in your code. How do I know that without having seen it? Like flossing, no-one assert() s enough in their code. Add in a validation function for your objects and call that on method start and method end. Are you compiling -wall? If not, do so. Find yourself a lint tool like PC-Lint. A small app like yours might fit in the PC-lint demo page, meaning no purchase for you! Check you're NULLing out pointers after deleteing them. Nobody likes a dangling pointer. Same gig with declared but unallocated pointers. Stop using arrays. Use a vector instead. Don't use raw pointers. Use a smart pointer. Don't use auto_ptr! That thing is... surprising; its semantics are very odd. Instead, choose one of the Boost smart pointers, or something out of the Loki library. | [
"c++",
"memory",
"stack",
"heap-memory"
] | 20 | 24 | 16,404 | 12 | 0 | 2008-08-11T04:52:50.800000 | 2008-08-11T11:59:25.777000 |
7,535 | 7,547 | SQL Server 2008 compatibility with SQL Server 2005 | What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005? | This can be done via SQL Enterprise Manager or like this: ALTER DATABASE SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 } Use 90 for 2005 compatibility. This replaces the functionality used for previous releases, the stored procedure sp_dbcmptlevel. | SQL Server 2008 compatibility with SQL Server 2005 What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005? | TITLE:
SQL Server 2008 compatibility with SQL Server 2005
QUESTION:
What is the best way to use SQL Server 2008 as a development database, but ensure that the database is compatible with SQL Server 2005?
ANSWER:
This can be done via SQL Enterprise Manager or like this: ALTER DATABASE SET COMPATIBILITY_LEVEL = { 80 | 90 | 100 } Use 90 for 2005 compatibility. This replaces the functionality used for previous releases, the stored procedure sp_dbcmptlevel. | [
"sql-server",
"sql-server-2008",
"sql-server-2005"
] | 15 | 19 | 11,273 | 3 | 0 | 2008-08-11T05:16:13.047000 | 2008-08-11T05:35:06.177000 |
7,539 | 7,561 | Use of java.math.MathContext | Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part. From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online. Please let me know if you have any idea on this. | @jatan Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method. There's nothing special about BigDecimal.round() vs. any other BigDecimal method. In all cases, the MathContext specifies the number of significant digits and the rounding technique. Basically, there are two parts of every MathContext. There's a precision, and there's also a RoundingMode. The precision again specifies the number of significant digits. So if you specify 123 as a number, and ask for 2 significant digits, you're going to get 120. It might be clearer if you think in terms of scientific notation. 123 would be 1.23e2 in scientific notation. If you only keep 2 significant digits, then you get 1.2e2, or 120. By reducing the number of significant digits, we reduce the precision with which we can specify a number. The RoundingMode part specifies how we should handle the loss of precision. To reuse the example, if you use 123 as the number, and ask for 2 significant digits, you've reduced your precision. With a RoundingMode of HALF_UP (the default mode), 123 will become 120. With a RoundingMode of CEILING, you'll get 130. For example: System.out.println(new BigDecimal("123.4", new MathContext(4,RoundingMode.HALF_UP))); System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.HALF_UP))); System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.CEILING))); System.out.println(new BigDecimal("123.4", new MathContext(1,RoundingMode.CEILING))); Outputs: 123.4 1.2E+2 1.3E+2 2E+2 You can see that both the precision and the rounding mode affect the output. | Use of java.math.MathContext Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part. From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online. Please let me know if you have any idea on this. | TITLE:
Use of java.math.MathContext
QUESTION:
Recently I tried understanding the use of java.math.MathContext but failed to understand properly. Is it used for rounding in java.math.BigDecimal. If yes why does not it round the decimal digits but even mantissa part. From API docs, I came to know that it follows the standard specified in ANSI X3.274-1996 and ANSI X3.274-1996/AM 1-2000 specifications but I did not get them to read online. Please let me know if you have any idea on this.
ANSWER:
@jatan Thanks for you answer. It makes sense. Can you please explain me MathContext in the context of BigDecimal#round method. There's nothing special about BigDecimal.round() vs. any other BigDecimal method. In all cases, the MathContext specifies the number of significant digits and the rounding technique. Basically, there are two parts of every MathContext. There's a precision, and there's also a RoundingMode. The precision again specifies the number of significant digits. So if you specify 123 as a number, and ask for 2 significant digits, you're going to get 120. It might be clearer if you think in terms of scientific notation. 123 would be 1.23e2 in scientific notation. If you only keep 2 significant digits, then you get 1.2e2, or 120. By reducing the number of significant digits, we reduce the precision with which we can specify a number. The RoundingMode part specifies how we should handle the loss of precision. To reuse the example, if you use 123 as the number, and ask for 2 significant digits, you've reduced your precision. With a RoundingMode of HALF_UP (the default mode), 123 will become 120. With a RoundingMode of CEILING, you'll get 130. For example: System.out.println(new BigDecimal("123.4", new MathContext(4,RoundingMode.HALF_UP))); System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.HALF_UP))); System.out.println(new BigDecimal("123.4", new MathContext(2,RoundingMode.CEILING))); System.out.println(new BigDecimal("123.4", new MathContext(1,RoundingMode.CEILING))); Outputs: 123.4 1.2E+2 1.3E+2 2E+2 You can see that both the precision and the rounding mode affect the output. | [
"java",
"math",
"bigdecimal",
"mathcontext"
] | 64 | 56 | 93,899 | 5 | 0 | 2008-08-11T05:23:02.427000 | 2008-08-11T06:06:48.483000 |
7,540 | 7,570 | Some kind of task manager for JavaScript in Firefox 3? | Recently I have been having issues with Firefox 3 on Ubuntu Hardy Heron. I will click on a link and it will hang for a while. I don't know if its a bug in Firefox 3 or a page running too much client side JavaScript, but I would like to try and debug it a bit. So, my question is "is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3?" I would like to be able to see what tabs are using what percent of my processor via the JavaScript on that page (or anything in the page that is causing CPU/memory usage). Does anybody know of a plugin that does this, or something similar? Has anyone else done this kind of inspection another way? I know about FireBug, but I can't imagine how I would use it to finger which tab is using a lot of resources. Any suggestions or insights? | It's probably the awesome firefox3 fsync "bug", which is a giant pile of fail. In summary Firefox3 saves its bookmarks and history in an SQLite database Every time you load a page it writes to this database several times SQLite cares deeply that you don't lose your bookmarks, so each time it writes, instructs the kernel to flush it's database file to disk and ensure that it's fully written Many variants of linux, when told to flush like that, flush EVERY FILE. This may take up to a minute or more if you have background tasks doing any kind of disk intensive stuff. The kernel makes firefox wait while this flush happens, which locks up the UI. | Some kind of task manager for JavaScript in Firefox 3? Recently I have been having issues with Firefox 3 on Ubuntu Hardy Heron. I will click on a link and it will hang for a while. I don't know if its a bug in Firefox 3 or a page running too much client side JavaScript, but I would like to try and debug it a bit. So, my question is "is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3?" I would like to be able to see what tabs are using what percent of my processor via the JavaScript on that page (or anything in the page that is causing CPU/memory usage). Does anybody know of a plugin that does this, or something similar? Has anyone else done this kind of inspection another way? I know about FireBug, but I can't imagine how I would use it to finger which tab is using a lot of resources. Any suggestions or insights? | TITLE:
Some kind of task manager for JavaScript in Firefox 3?
QUESTION:
Recently I have been having issues with Firefox 3 on Ubuntu Hardy Heron. I will click on a link and it will hang for a while. I don't know if its a bug in Firefox 3 or a page running too much client side JavaScript, but I would like to try and debug it a bit. So, my question is "is there a way to have some kind of process explorer, or task manager sort of thing for Firefox 3?" I would like to be able to see what tabs are using what percent of my processor via the JavaScript on that page (or anything in the page that is causing CPU/memory usage). Does anybody know of a plugin that does this, or something similar? Has anyone else done this kind of inspection another way? I know about FireBug, but I can't imagine how I would use it to finger which tab is using a lot of resources. Any suggestions or insights?
ANSWER:
It's probably the awesome firefox3 fsync "bug", which is a giant pile of fail. In summary Firefox3 saves its bookmarks and history in an SQLite database Every time you load a page it writes to this database several times SQLite cares deeply that you don't lose your bookmarks, so each time it writes, instructs the kernel to flush it's database file to disk and ensure that it's fully written Many variants of linux, when told to flush like that, flush EVERY FILE. This may take up to a minute or more if you have background tasks doing any kind of disk intensive stuff. The kernel makes firefox wait while this flush happens, which locks up the UI. | [
"javascript",
"firefox",
"memory",
"cpu"
] | 11 | 9 | 2,626 | 5 | 0 | 2008-08-11T05:24:33.593000 | 2008-08-11T06:35:58.160000 |
7,551 | 7,618 | Best Practices for securing a REST API / web service | When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management)? When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints. While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged. Any discussion or links to relevant documents would be very much appreciated. If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the.NET Framework. | As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying. The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time. Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed. | Best Practices for securing a REST API / web service When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management)? When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints. While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged. Any discussion or links to relevant documents would be very much appreciated. If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the.NET Framework. | TITLE:
Best Practices for securing a REST API / web service
QUESTION:
When designing a REST API or service are there any established best practices for dealing with security (Authentication, Authorization, Identity Management)? When building a SOAP API you have WS-Security as a guide and much literature exists on the topic. I have found less information about securing REST endpoints. While I understand REST intentionally does not have specifications analogous to WS-* I am hoping best practices or recommended patterns have emerged. Any discussion or links to relevant documents would be very much appreciated. If it matters, we would be using WCF with POX/JSON serialized messages for our REST API's/Services built using v3.5 of the.NET Framework.
ANSWER:
As tweakt said, Amazon S3 is a good model to work with. Their request signatures do have some features (such as incorporating a timestamp) that help guard against both accidental and malicious request replaying. The nice thing about HTTP Basic is that virtually all HTTP libraries support it. You will, of course, need to require SSL in this case because sending plaintext passwords over the net is almost universally a bad thing. Basic is preferable to Digest when using SSL because even if the caller already knows that credentials are required, Digest requires an extra roundtrip to exchange the nonce value. With Basic, the callers simply sends the credentials the first time. Once the identity of the client is established, authorization is really just an implementation problem. However, you could delegate the authorization to some other component with an existing authorization model. Again the nice thing about Basic here is your server ends up with a plaintext copy of the client's password that you can simply pass on to another component within your infrastructure as needed. | [
"wcf",
"security",
"rest",
"authorization",
"rest-security"
] | 840 | 303 | 317,485 | 18 | 0 | 2008-08-11T05:44:42.803000 | 2008-08-11T08:45:13.343000 |
7,586 | 7,590 | How do I generate WPF controls through code | I was trying to get my head around XAML and thought that I would try writing some code. Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition. XAML: C#: private void Page_Loaded(object sender, RoutedEventArgs e) { //create the structure Grid g = new Grid(); g.ShowGridLines = true; g.Visibility = Visibility.Visible;
//add columns for (int i = 0; i < 6; ++i) { ColumnDefinition cd = new ColumnDefinition(); cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd); } //add rows for (int i = 0; i < 6; ++i) { RowDefinition rd = new RowDefinition(); rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd); } TextBlock tb = new TextBlock(); tb.Text = "Hello World";
g.Children.Add(tb); } Update Here is the spooky bit: Using VS2008 Pro on XP WPFbrowser Project Template (3.5 verified) I don't get the methods in autocomplete. | WPF makes use of a funky thing called attached properties. So in your XAML you might write this: And this will effectively move the TextBlock into cell (0,0) of your grid. In code this looks a little strange. I believe it'd be something like: g.Children.Add(tb); Grid.SetRow(tb, 0); Grid.SetColumn(tb, 0); Have a look at that link above - attached properties make things really easy to do in XAML perhaps at the expense of intuitive-looking code. | How do I generate WPF controls through code I was trying to get my head around XAML and thought that I would try writing some code. Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition. XAML: C#: private void Page_Loaded(object sender, RoutedEventArgs e) { //create the structure Grid g = new Grid(); g.ShowGridLines = true; g.Visibility = Visibility.Visible;
//add columns for (int i = 0; i < 6; ++i) { ColumnDefinition cd = new ColumnDefinition(); cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd); } //add rows for (int i = 0; i < 6; ++i) { RowDefinition rd = new RowDefinition(); rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd); } TextBlock tb = new TextBlock(); tb.Text = "Hello World";
g.Children.Add(tb); } Update Here is the spooky bit: Using VS2008 Pro on XP WPFbrowser Project Template (3.5 verified) I don't get the methods in autocomplete. | TITLE:
How do I generate WPF controls through code
QUESTION:
I was trying to get my head around XAML and thought that I would try writing some code. Trying to add a grid with 6 by 6 column definitions then add a text block into one of the grid cells. I don't seem to be able to reference the cell that I want. There is no method on the grid that I can add the text block too. There is only grid.children.add(object), no Cell definition. XAML: C#: private void Page_Loaded(object sender, RoutedEventArgs e) { //create the structure Grid g = new Grid(); g.ShowGridLines = true; g.Visibility = Visibility.Visible;
//add columns for (int i = 0; i < 6; ++i) { ColumnDefinition cd = new ColumnDefinition(); cd.Name = "Column" + i.ToString();
g.ColumnDefinitions.Add(cd); } //add rows for (int i = 0; i < 6; ++i) { RowDefinition rd = new RowDefinition(); rd.Name = "Row" + i.ToString();
g.RowDefinitions.Add(rd); } TextBlock tb = new TextBlock(); tb.Text = "Hello World";
g.Children.Add(tb); } Update Here is the spooky bit: Using VS2008 Pro on XP WPFbrowser Project Template (3.5 verified) I don't get the methods in autocomplete.
ANSWER:
WPF makes use of a funky thing called attached properties. So in your XAML you might write this: And this will effectively move the TextBlock into cell (0,0) of your grid. In code this looks a little strange. I believe it'd be something like: g.Children.Add(tb); Grid.SetRow(tb, 0); Grid.SetColumn(tb, 0); Have a look at that link above - attached properties make things really easy to do in XAML perhaps at the expense of intuitive-looking code. | [
"c#",
".net",
"wpf",
"xaml"
] | 8 | 7 | 4,144 | 4 | 0 | 2008-08-11T07:26:46.903000 | 2008-08-11T07:37:24.713000 |
7,592 | 7,643 | Can I use JavaScript to create a client side email? | I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much. The mail created by the mailto action has the syntax: subject: undefined subject body: param1=value1 param2=value2... paramn=valuen Can I use JavaScript to format the mail like this? Subject:XXXXX Body: Value1;Value2;Value3...ValueN | What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used). var addresses = "";//between the speech mark goes the receptient. Seperate addresses with a; var body = ""//write the message text between the speech marks or put a variable in the place of the speech marks var subject = ""//between the speech marks goes the subject of the message var href = "mailto:" + addresses + "?" + "subject=" + subject + "&" + "body=" + body; var wndMail; wndMail = window.open(href, "_blank", "scrollbars=yes,resizable=yes,width=10,height=10"); if(wndMail) { wndMail.close(); } | Can I use JavaScript to create a client side email? I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much. The mail created by the mailto action has the syntax: subject: undefined subject body: param1=value1 param2=value2... paramn=valuen Can I use JavaScript to format the mail like this? Subject:XXXXX Body: Value1;Value2;Value3...ValueN | TITLE:
Can I use JavaScript to create a client side email?
QUESTION:
I want to create a client side mail creator web page. I know the problems of using the mailto action in an html form (not standard, no default mail appication set on the client). But the web page isn't very important, and they don't care very much. The mail created by the mailto action has the syntax: subject: undefined subject body: param1=value1 param2=value2... paramn=valuen Can I use JavaScript to format the mail like this? Subject:XXXXX Body: Value1;Value2;Value3...ValueN
ANSWER:
What we used in a projet is a popup window that opens a mailto: link, it is the only way we found to compose a mail within the default mail client that works with all mail clients (at least all our clients used). var addresses = "";//between the speech mark goes the receptient. Seperate addresses with a; var body = ""//write the message text between the speech marks or put a variable in the place of the speech marks var subject = ""//between the speech marks goes the subject of the message var href = "mailto:" + addresses + "?" + "subject=" + subject + "&" + "body=" + body; var wndMail; wndMail = window.open(href, "_blank", "scrollbars=yes,resizable=yes,width=10,height=10"); if(wndMail) { wndMail.close(); } | [
"javascript",
"email"
] | 19 | 18 | 36,072 | 5 | 0 | 2008-08-11T07:39:51.433000 | 2008-08-11T09:45:17.873000 |
7,596 | 13,283 | How should I structure a Java application, where do I put my classes? | First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier. I myself have always had problems with naming, placing So, Where do you put your domain specific constants (and what is the best name for such a class)? Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)? Where to put Exceptions? Are there any standards to which I can refer? | I've really come to like Maven's Standard Directory Layout. One of the key ideas for me is to have two source roots - one for production code and one for test code like so: MyProject/src/main/java/com/acme/Widget.java MyProject/src/test/java/com/acme/WidgetTest.java (here, both src/main/java and src/test/java are source roots). Advantages: Your tests have package (or "default") level access to your classes under test. You can easily package only your production sources into a JAR by dropping src/test/java as a source root. One rule of thumb about class placement and packages: Generally speaking, well structured projects will be free of circular dependencies. Learn when they are bad (and when they are not ), and consider a tool like JDepend or SonarJ that will help you eliminate them. | How should I structure a Java application, where do I put my classes? First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier. I myself have always had problems with naming, placing So, Where do you put your domain specific constants (and what is the best name for such a class)? Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)? Where to put Exceptions? Are there any standards to which I can refer? | TITLE:
How should I structure a Java application, where do I put my classes?
QUESTION:
First of all, I know how to build a Java application. But I have always been puzzled about where to put my classes. There are proponents for organizing the packages in a strictly domain oriented fashion, others separate by tier. I myself have always had problems with naming, placing So, Where do you put your domain specific constants (and what is the best name for such a class)? Where do you put classes for stuff which is both infrastructural and domain specific (for instance I have a FileStorageStrategy class, which stores the files either in the database, or alternatively in database)? Where to put Exceptions? Are there any standards to which I can refer?
ANSWER:
I've really come to like Maven's Standard Directory Layout. One of the key ideas for me is to have two source roots - one for production code and one for test code like so: MyProject/src/main/java/com/acme/Widget.java MyProject/src/test/java/com/acme/WidgetTest.java (here, both src/main/java and src/test/java are source roots). Advantages: Your tests have package (or "default") level access to your classes under test. You can easily package only your production sources into a JAR by dropping src/test/java as a source root. One rule of thumb about class placement and packages: Generally speaking, well structured projects will be free of circular dependencies. Learn when they are bad (and when they are not ), and consider a tool like JDepend or SonarJ that will help you eliminate them. | [
"java",
"architecture"
] | 43 | 29 | 26,099 | 10 | 0 | 2008-08-11T07:45:20.050000 | 2008-08-16T19:06:10.267000 |
7,622 | 7,636 | Are the shift operators (<<, >>) arithmetic or logical in C? | In C, are the shift operators ( <<, >> ) arithmetic or logical? | According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values. Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values. Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift. | Are the shift operators (<<, >>) arithmetic or logical in C? In C, are the shift operators ( <<, >> ) arithmetic or logical? | TITLE:
Are the shift operators (<<, >>) arithmetic or logical in C?
QUESTION:
In C, are the shift operators ( <<, >> ) arithmetic or logical?
ANSWER:
According to K&R 2nd edition the results are implementation-dependent for right shifts of signed values. Wikipedia says that C/C++ 'usually' implements an arithmetic shift on signed values. Basically you need to either test your compiler or not rely on it. My VS2008 help for the current MS C++ compiler says that their compiler does an arithmetic shift. | [
"c",
"binary",
"bit-manipulation",
"bit-shift"
] | 178 | 119 | 310,131 | 11 | 0 | 2008-08-11T08:55:13.277000 | 2008-08-11T09:18:29.533000 |
7,642 | 7,644 | Naming convention for VB.NET private fields | Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the Offical Guidelines: "Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields." In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions? | I still use the _ prefix in VB for private fields, so I'll have _foo as the private field and Foo as the property. I do this for c# as well and pretty much any code I write. Generally I wouldn't get too caught up in "what is the right way to do it" because there isn't really a "right" way (altho there are some very bad ways) but rather be concerned with doing it consistently. At the end of the day, being consistent will make your code much more readable and maintainable than using any set of "right" conventions. | Naming convention for VB.NET private fields Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the Offical Guidelines: "Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields." In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions? | TITLE:
Naming convention for VB.NET private fields
QUESTION:
Is there an official convention for naming private fields in VB.NET? For example, if I have a property called 'Foo', I normally call the private field '_Foo'. This seems to be frowned upon in the Offical Guidelines: "Do not use a prefix for field names. For example, do not use g_ or s_ to distinguish static versus non-static fields." In C#, you could call the private field 'foo', the property 'Foo', and refer to the private field as 'this.foo' in the constructor. As VB.NET is case insensitive you can't do this - any suggestions?
ANSWER:
I still use the _ prefix in VB for private fields, so I'll have _foo as the private field and Foo as the property. I do this for c# as well and pretty much any code I write. Generally I wouldn't get too caught up in "what is the right way to do it" because there isn't really a "right" way (altho there are some very bad ways) but rather be concerned with doing it consistently. At the end of the day, being consistent will make your code much more readable and maintainable than using any set of "right" conventions. | [
"vb.net",
"convention"
] | 24 | 21 | 13,900 | 10 | 0 | 2008-08-11T09:41:11.373000 | 2008-08-11T09:45:27.967000 |
7,651 | 7,657 | How do I remove duplicate items from an array in Perl? | I have an array in Perl: my @my_array = ("one","two","three","two","three"); How do I remove the duplicates from the array? | You can do something like this as demonstrated in perlfaq4: sub uniq { my %seen; grep!$seen{$_}++, @_; }
my @array = qw(one two three two three); my @filtered = uniq(@array);
print "@filtered\n"; Outputs: one two three If you are aiming for universality, you should take a look at the uniq function. It is included in the core module List::Util as of Perl v5.26.0 (for older versions, use List::MoreUtils ). This function differs from the above sketch in that it treats undef as a separate value, different from '', and does not issue a warning. | How do I remove duplicate items from an array in Perl? I have an array in Perl: my @my_array = ("one","two","three","two","three"); How do I remove the duplicates from the array? | TITLE:
How do I remove duplicate items from an array in Perl?
QUESTION:
I have an array in Perl: my @my_array = ("one","two","three","two","three"); How do I remove the duplicates from the array?
ANSWER:
You can do something like this as demonstrated in perlfaq4: sub uniq { my %seen; grep!$seen{$_}++, @_; }
my @array = qw(one two three two three); my @filtered = uniq(@array);
print "@filtered\n"; Outputs: one two three If you are aiming for universality, you should take a look at the uniq function. It is included in the core module List::Util as of Perl v5.26.0 (for older versions, use List::MoreUtils ). This function differs from the above sketch in that it treats undef as a separate value, different from '', and does not issue a warning. | [
"perl",
"arrays",
"unique",
"duplicates"
] | 175 | 181 | 242,614 | 11 | 0 | 2008-08-11T10:04:32.093000 | 2008-08-11T10:16:22.770000 |
7,652 | 7,710 | Querying like Linq when you don't have Linq | I have a project that I'm currently working on but it currently only supports the.net framework 2.0. I love linq, but because of the framework version I can't use it. What I want isn't so much the ORM side of things, but the "queryability" (is that even a word?) of Linq. So far the closest is llblgen but if there was something even lighter weight that could just do the querying for me that would be even better. I've also looked at NHibernate which looks like it could go close to doing what I want, but it has a pretty steep learning curve and the mapping files don't get me overly excited. If anyone is aware of something that will give me a similar query interface to Linq (or even better, how to get Linq to work on the.net 2.0 framework) I'd really like to hear about it. | Have a look at this: http://www.albahari.com/nutshell/linqbridge.html Linq is several different things, and I'm not 100% sure which bits you want, but the above might be useful in some way. If you don't already have a book on Linq (I guess you don't), then I found "Linq In Action" to be be good. | Querying like Linq when you don't have Linq I have a project that I'm currently working on but it currently only supports the.net framework 2.0. I love linq, but because of the framework version I can't use it. What I want isn't so much the ORM side of things, but the "queryability" (is that even a word?) of Linq. So far the closest is llblgen but if there was something even lighter weight that could just do the querying for me that would be even better. I've also looked at NHibernate which looks like it could go close to doing what I want, but it has a pretty steep learning curve and the mapping files don't get me overly excited. If anyone is aware of something that will give me a similar query interface to Linq (or even better, how to get Linq to work on the.net 2.0 framework) I'd really like to hear about it. | TITLE:
Querying like Linq when you don't have Linq
QUESTION:
I have a project that I'm currently working on but it currently only supports the.net framework 2.0. I love linq, but because of the framework version I can't use it. What I want isn't so much the ORM side of things, but the "queryability" (is that even a word?) of Linq. So far the closest is llblgen but if there was something even lighter weight that could just do the querying for me that would be even better. I've also looked at NHibernate which looks like it could go close to doing what I want, but it has a pretty steep learning curve and the mapping files don't get me overly excited. If anyone is aware of something that will give me a similar query interface to Linq (or even better, how to get Linq to work on the.net 2.0 framework) I'd really like to hear about it.
ANSWER:
Have a look at this: http://www.albahari.com/nutshell/linqbridge.html Linq is several different things, and I'm not 100% sure which bits you want, but the above might be useful in some way. If you don't already have a book on Linq (I guess you don't), then I found "Linq In Action" to be be good. | [
"database",
"linq",
"orm"
] | 3 | 5 | 1,657 | 7 | 0 | 2008-08-11T10:04:50.483000 | 2008-08-11T12:20:36.327000 |
7,661 | 32,551 | Java code for WGS84 to Google map position and back | Searching for some sample code for converting a point in WGS84 coordinate system to a map position in Google Maps (pixel position), also supporting zoom levels. If the codes is well commented, then it can also be in some other language. You can also point me to a open source Java project:) Some resources found: OpenLayer implementation. JOSM project Excellent Java Map Projection Library from JH LABS. This is a pure java PROJ.4 port. Does projection from WGS84 to meters. From there it's quite straightforward to convert meters to tile pixels. | Tile utility code in Java on mapki.com (great resource for google map developers) | Java code for WGS84 to Google map position and back Searching for some sample code for converting a point in WGS84 coordinate system to a map position in Google Maps (pixel position), also supporting zoom levels. If the codes is well commented, then it can also be in some other language. You can also point me to a open source Java project:) Some resources found: OpenLayer implementation. JOSM project Excellent Java Map Projection Library from JH LABS. This is a pure java PROJ.4 port. Does projection from WGS84 to meters. From there it's quite straightforward to convert meters to tile pixels. | TITLE:
Java code for WGS84 to Google map position and back
QUESTION:
Searching for some sample code for converting a point in WGS84 coordinate system to a map position in Google Maps (pixel position), also supporting zoom levels. If the codes is well commented, then it can also be in some other language. You can also point me to a open source Java project:) Some resources found: OpenLayer implementation. JOSM project Excellent Java Map Projection Library from JH LABS. This is a pure java PROJ.4 port. Does projection from WGS84 to meters. From there it's quite straightforward to convert meters to tile pixels.
ANSWER:
Tile utility code in Java on mapki.com (great resource for google map developers) | [
"java",
"google-maps",
"mapping",
"wgs84"
] | 10 | 5 | 23,567 | 6 | 0 | 2008-08-11T10:23:48.763000 | 2008-08-28T15:17:00.740000 |
7,662 | 7,724 | Database, Table and Column Naming Conventions? | Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions: Should table names be plural? Should column names be singular? Should I prefix tables or columns? Should I use any case in naming items? Are there any recommended guidelines out there for naming items in a database? | I recommend checking out Microsoft's SQL Server sample databases: https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects. Singular names for tables Singular names for columns Schema name for tables prefix (E.g.: SchemeName.TableName) Pascal casing (a.k.a. upper camel case) | Database, Table and Column Naming Conventions? Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions: Should table names be plural? Should column names be singular? Should I prefix tables or columns? Should I use any case in naming items? Are there any recommended guidelines out there for naming items in a database? | TITLE:
Database, Table and Column Naming Conventions?
QUESTION:
Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions: Should table names be plural? Should column names be singular? Should I prefix tables or columns? Should I use any case in naming items? Are there any recommended guidelines out there for naming items in a database?
ANSWER:
I recommend checking out Microsoft's SQL Server sample databases: https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects. Singular names for tables Singular names for columns Schema name for tables prefix (E.g.: SchemeName.TableName) Pascal casing (a.k.a. upper camel case) | [
"database",
"database-design",
"language-agnostic",
"naming-conventions"
] | 918 | 382 | 717,584 | 23 | 0 | 2008-08-11T10:27:22.780000 | 2008-08-11T12:39:37.817000 |
7,664 | 7,669 | Windows C++: How can I redirect stderr for calls to fprintf? | I am wrapping existing C++ code from a BSD project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses fprintf to print to stderr in order to log / report errors. I want to redirect this to an alternative place within the same process. On Unix I have done this with a socketpair and a thread: one end of the socket is where I send stderr (via a call to dup2 ) and the other end is monitored in a thread, where I can then process the output. This does not work on Windows though because a socket is not the same as a file handle. All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect stderr within the same process getting a callback of some sort when output is written? (and before you say so, I've tried SetStdHandle but cannot find any way to make this work)... | You can use a similar technique on Windows, you just need to use different words for the same concepts.:) This article: http://msdn.microsoft.com/en-us/library/ms682499.aspx uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in your case all output to stderr from anywhere in the process will be redirected to your consumer. Actually, other pieces of the puzzle you may need are _fdopen and _open_osfhandle. In fact, here's a related example from some code I released years ago: DWORD CALLBACK DoDebugThread(void *) { AllocConsole(); SetConsoleTitle("Copilot Debugger"); // The following is a really disgusting hack to make stdin and stdout attach // to the newly created console using the MSVC++ libraries. I hope other // operating systems don't need this kind of kludge..:) stdout->_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT); stdin->_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT); debug(); stdout->_file = -1; stdin->_file = -1; FreeConsole(); CPU_run(); return 0; } In this case, the main process was a GUI process which doesn't start with stdio handles at all. It opens a console, then shoves the right handles into stdout and stdin so the debug() function (which was designed as a stdio interactive function) can interact with the newly created console. You should be able to open some pipes and do the same sort of thing to redirect stderr. | Windows C++: How can I redirect stderr for calls to fprintf? I am wrapping existing C++ code from a BSD project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses fprintf to print to stderr in order to log / report errors. I want to redirect this to an alternative place within the same process. On Unix I have done this with a socketpair and a thread: one end of the socket is where I send stderr (via a call to dup2 ) and the other end is monitored in a thread, where I can then process the output. This does not work on Windows though because a socket is not the same as a file handle. All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect stderr within the same process getting a callback of some sort when output is written? (and before you say so, I've tried SetStdHandle but cannot find any way to make this work)... | TITLE:
Windows C++: How can I redirect stderr for calls to fprintf?
QUESTION:
I am wrapping existing C++ code from a BSD project in our own custom wrapper and I want to integrate it to our code with as few changes as possible. This code uses fprintf to print to stderr in order to log / report errors. I want to redirect this to an alternative place within the same process. On Unix I have done this with a socketpair and a thread: one end of the socket is where I send stderr (via a call to dup2 ) and the other end is monitored in a thread, where I can then process the output. This does not work on Windows though because a socket is not the same as a file handle. All documents I have found on the web show how to redirect output from a child process, which is not what I want. How can I redirect stderr within the same process getting a callback of some sort when output is written? (and before you say so, I've tried SetStdHandle but cannot find any way to make this work)...
ANSWER:
You can use a similar technique on Windows, you just need to use different words for the same concepts.:) This article: http://msdn.microsoft.com/en-us/library/ms682499.aspx uses a win32 pipe to handle I/O from another process, you just have to do the same thing with threads within the same process. Of course, in your case all output to stderr from anywhere in the process will be redirected to your consumer. Actually, other pieces of the puzzle you may need are _fdopen and _open_osfhandle. In fact, here's a related example from some code I released years ago: DWORD CALLBACK DoDebugThread(void *) { AllocConsole(); SetConsoleTitle("Copilot Debugger"); // The following is a really disgusting hack to make stdin and stdout attach // to the newly created console using the MSVC++ libraries. I hope other // operating systems don't need this kind of kludge..:) stdout->_file = _open_osfhandle((long)GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT); stdin->_file = _open_osfhandle((long)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT); debug(); stdout->_file = -1; stdin->_file = -1; FreeConsole(); CPU_run(); return 0; } In this case, the main process was a GUI process which doesn't start with stdio handles at all. It opens a console, then shoves the right handles into stdout and stdin so the debug() function (which was designed as a stdio interactive function) can interact with the newly created console. You should be able to open some pipes and do the same sort of thing to redirect stderr. | [
"c++",
"windows",
"redirect"
] | 6 | 6 | 11,922 | 3 | 0 | 2008-08-11T10:38:51.570000 | 2008-08-11T11:05:37.820000 |
7,665 | 7,666 | How to resolve symbolic links in a shell script | Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time. If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X): $ ls -ld foo bar drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar $ cd foo $ pwd /Users/greg/tmp/foo $ What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar". | According to the standards, pwd -P should return the path with symlinks resolved. C function char *getcwd(char *buf, size_t size) from unistd.h should have the same behaviour. getcwd pwd | How to resolve symbolic links in a shell script Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time. If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X): $ ls -ld foo bar drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar $ cd foo $ pwd /Users/greg/tmp/foo $ What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar". | TITLE:
How to resolve symbolic links in a shell script
QUESTION:
Given an absolute or relative path (in a Unix-like system), I would like to determine the full path of the target after resolving any intermediate symlinks. Bonus points for also resolving ~username notation at the same time. If the target is a directory, it might be possible to chdir() into the directory and then call getcwd(), but I really want to do this from a shell script rather than writing a C helper. Unfortunately, shells have a tendency to try to hide the existence of symlinks from the user (this is bash on OS X): $ ls -ld foo bar drwxr-xr-x 2 greg greg 68 Aug 11 22:36 bar lrwxr-xr-x 1 greg greg 3 Aug 11 22:36 foo -> bar $ cd foo $ pwd /Users/greg/tmp/foo $ What I want is a function resolve() such that when executed from the tmp directory in the above example, resolve("foo") == "/Users/greg/tmp/bar".
ANSWER:
According to the standards, pwd -P should return the path with symlinks resolved. C function char *getcwd(char *buf, size_t size) from unistd.h should have the same behaviour. getcwd pwd | [
"bash",
"shell",
"scripting",
"symlink"
] | 267 | 102 | 222,917 | 21 | 0 | 2008-08-11T10:40:41.363000 | 2008-08-11T10:48:19.260000 |
7,674 | 8,982 | Best practices for building Flash video player | We have a custom-built Flash-based video player that I maintain, and it needs to support preroll ads and ideally both progressive video playback and streaming depending on a server switch. I've been working with the flvPlayback component but am finding myself a little out of my depth. Are there any good tutorials or resources for understanding the difference between netstream and flvPlayback? Or is one part of the other? Have googled without success. For the preroll ads we'll probably use DART In-Stream, which is part of the reason I feel I'm losing a grip on the best way to structure this thing. Any help with best practices or links most appreciated - ta! EDIT - Update: I wrote a player by hand and got it more or less working with everything it needed to do, but we did migrate to JW Player across all the web properties in the end, about six months later. It's very reliable and well-supported, it integrated with the DART system well, and the designers found it easy to skin. | I would definitely have a look at the JW Flash Media Player: http://www.jeroenwijering.com/?item=JW_FLV_Player It's Open Source, and I found the Source quite clean and easy to understand, it also supports playlists. I don't know the DART In-Stream stuff, but maybe you could "creatively use" the playlist feature to achieve that? Source Code is available here: http://code.jeroenwijering.com/trac/ | Best practices for building Flash video player We have a custom-built Flash-based video player that I maintain, and it needs to support preroll ads and ideally both progressive video playback and streaming depending on a server switch. I've been working with the flvPlayback component but am finding myself a little out of my depth. Are there any good tutorials or resources for understanding the difference between netstream and flvPlayback? Or is one part of the other? Have googled without success. For the preroll ads we'll probably use DART In-Stream, which is part of the reason I feel I'm losing a grip on the best way to structure this thing. Any help with best practices or links most appreciated - ta! EDIT - Update: I wrote a player by hand and got it more or less working with everything it needed to do, but we did migrate to JW Player across all the web properties in the end, about six months later. It's very reliable and well-supported, it integrated with the DART system well, and the designers found it easy to skin. | TITLE:
Best practices for building Flash video player
QUESTION:
We have a custom-built Flash-based video player that I maintain, and it needs to support preroll ads and ideally both progressive video playback and streaming depending on a server switch. I've been working with the flvPlayback component but am finding myself a little out of my depth. Are there any good tutorials or resources for understanding the difference between netstream and flvPlayback? Or is one part of the other? Have googled without success. For the preroll ads we'll probably use DART In-Stream, which is part of the reason I feel I'm losing a grip on the best way to structure this thing. Any help with best practices or links most appreciated - ta! EDIT - Update: I wrote a player by hand and got it more or less working with everything it needed to do, but we did migrate to JW Player across all the web properties in the end, about six months later. It's very reliable and well-supported, it integrated with the DART system well, and the designers found it easy to skin.
ANSWER:
I would definitely have a look at the JW Flash Media Player: http://www.jeroenwijering.com/?item=JW_FLV_Player It's Open Source, and I found the Source quite clean and easy to understand, it also supports playlists. I don't know the DART In-Stream stuff, but maybe you could "creatively use" the playlist feature to achieve that? Source Code is available here: http://code.jeroenwijering.com/trac/ | [
"flash",
"video"
] | 5 | 4 | 2,218 | 4 | 0 | 2008-08-11T11:17:36.547000 | 2008-08-12T15:44:27.193000 |
7,681 | 7,688 | Test serialization encoding | What is the best way to verify/test that a text string is serialized to a byte array with a certain encoding? In my case, I want to verify that an XML structure is serialized to a byte array with the UTF-8 encoding which is of variable character length. As an example, my current ugly procedure is to inject a character known to require two bytes into the structure before serializing, then replacing the two-byte character with an ASCII character and comparing the serialized array lengths. This should yield two serialized arrays where the array containing the two-byte characters should have length +1. Plus if the solution is elegant for Java. I can't think of any elegant way to seek for a byte sequence in a byte array. (Could be used to seek for a known byte sequence representing the desired character representation in UTF-8.) | Perhaps you could deserialise the byte array using a known encoding and ensure that (a) it doesn't throw any exceptions, and (b) deserialises to the original string. It seems that from your description of the scenario, you may not have the original string readily available. Might there be a way to create it? | Test serialization encoding What is the best way to verify/test that a text string is serialized to a byte array with a certain encoding? In my case, I want to verify that an XML structure is serialized to a byte array with the UTF-8 encoding which is of variable character length. As an example, my current ugly procedure is to inject a character known to require two bytes into the structure before serializing, then replacing the two-byte character with an ASCII character and comparing the serialized array lengths. This should yield two serialized arrays where the array containing the two-byte characters should have length +1. Plus if the solution is elegant for Java. I can't think of any elegant way to seek for a byte sequence in a byte array. (Could be used to seek for a known byte sequence representing the desired character representation in UTF-8.) | TITLE:
Test serialization encoding
QUESTION:
What is the best way to verify/test that a text string is serialized to a byte array with a certain encoding? In my case, I want to verify that an XML structure is serialized to a byte array with the UTF-8 encoding which is of variable character length. As an example, my current ugly procedure is to inject a character known to require two bytes into the structure before serializing, then replacing the two-byte character with an ASCII character and comparing the serialized array lengths. This should yield two serialized arrays where the array containing the two-byte characters should have length +1. Plus if the solution is elegant for Java. I can't think of any elegant way to seek for a byte sequence in a byte array. (Could be used to seek for a known byte sequence representing the desired character representation in UTF-8.)
ANSWER:
Perhaps you could deserialise the byte array using a known encoding and ensure that (a) it doesn't throw any exceptions, and (b) deserialises to the original string. It seems that from your description of the scenario, you may not have the original string readily available. Might there be a way to create it? | [
"java",
"xml",
"string",
"serialization",
"encoding"
] | 10 | 2 | 2,452 | 2 | 0 | 2008-08-11T11:33:01.930000 | 2008-08-11T11:46:40.030000 |
7,707 | 881,597 | IE8 overflow:auto with max-height | I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set max-height: 100px and overflow:auto, hoping for scrollbars to appear when the content does not fit. It all works fine in Firefox and IE7, but IE8 behaves as if overflow:hidden was present instead of overflow:auto. I tried overflow:scroll, still does not help, IE8 simply truncates the content without showing scrollbars. Changing max-height declaration to height makes overflow work OK, it's the combination of max-height and overflow:auto that breaks things. This is also logged as an official bug in the final, release version of IE8 Is there a workaround? For now I resorted to using height instead of max-height, but it leaves plenty of empty space in case there isn't much data. | This is a really nasty bug as it affects us heavily on Stack Overflow with code blocks, which have max-height:600 and width:auto. It is logged as a bug in the final version of IE8 with no fix. http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759 There is a really, really hacky CSS workaround: http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode /* SUPER nasty IE8 hack to deal with this bug */ pre { max-height: none\9 } and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request. | IE8 overflow:auto with max-height I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set max-height: 100px and overflow:auto, hoping for scrollbars to appear when the content does not fit. It all works fine in Firefox and IE7, but IE8 behaves as if overflow:hidden was present instead of overflow:auto. I tried overflow:scroll, still does not help, IE8 simply truncates the content without showing scrollbars. Changing max-height declaration to height makes overflow work OK, it's the combination of max-height and overflow:auto that breaks things. This is also logged as an official bug in the final, release version of IE8 Is there a workaround? For now I resorted to using height instead of max-height, but it leaves plenty of empty space in case there isn't much data. | TITLE:
IE8 overflow:auto with max-height
QUESTION:
I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set max-height: 100px and overflow:auto, hoping for scrollbars to appear when the content does not fit. It all works fine in Firefox and IE7, but IE8 behaves as if overflow:hidden was present instead of overflow:auto. I tried overflow:scroll, still does not help, IE8 simply truncates the content without showing scrollbars. Changing max-height declaration to height makes overflow work OK, it's the combination of max-height and overflow:auto that breaks things. This is also logged as an official bug in the final, release version of IE8 Is there a workaround? For now I resorted to using height instead of max-height, but it leaves plenty of empty space in case there isn't much data.
ANSWER:
This is a really nasty bug as it affects us heavily on Stack Overflow with code blocks, which have max-height:600 and width:auto. It is logged as a bug in the final version of IE8 with no fix. http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759 There is a really, really hacky CSS workaround: http://my.opera.com/dbloom/blog/2009/03/11/css-hack-for-ie8-standards-mode /* SUPER nasty IE8 hack to deal with this bug */ pre { max-height: none\9 } and of course conditional CSS as others have mentioned, but I dislike that because it means you're serving up extra HTML cruft in every page request. | [
"internet-explorer-8",
"overflow",
"css"
] | 56 | 72 | 68,906 | 8 | 0 | 2008-08-11T12:18:02.150000 | 2009-05-19T08:34:12.627000 |
7,719 | 7,840 | Capture MouseDown event for .NET TextBox | Is there any way to capture the MouseDown even from the.NET 2.0 TextBox control? I know the inherited Control class has the event, but it's not exposed in TextBox. Is there a way to override the event handler? I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler. Any suggestions? What kind of crazy mobile device do you have that has a mouse?:) Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile.NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case. Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in. According to the.Net Framework, the MouseDown Event Handler on a TextBox is supported. What happens when you try to run the code? Actually, that's only there because it inherits it from "Control", as does every other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio. However, you actually can write the code: textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown); and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event. | Looks like you're right. Bummer. No MouseOver event. One of the fallbacks that always works with.NET, though, is P/Invoke. Someone already took the time to do this for the.NET CF TextBox. I found this on CodeProject: http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx Hope this helps | Capture MouseDown event for .NET TextBox Is there any way to capture the MouseDown even from the.NET 2.0 TextBox control? I know the inherited Control class has the event, but it's not exposed in TextBox. Is there a way to override the event handler? I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler. Any suggestions? What kind of crazy mobile device do you have that has a mouse?:) Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile.NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case. Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in. According to the.Net Framework, the MouseDown Event Handler on a TextBox is supported. What happens when you try to run the code? Actually, that's only there because it inherits it from "Control", as does every other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio. However, you actually can write the code: textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown); and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event. | TITLE:
Capture MouseDown event for .NET TextBox
QUESTION:
Is there any way to capture the MouseDown even from the.NET 2.0 TextBox control? I know the inherited Control class has the event, but it's not exposed in TextBox. Is there a way to override the event handler? I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler. Any suggestions? What kind of crazy mobile device do you have that has a mouse?:) Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile.NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case. Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in. According to the.Net Framework, the MouseDown Event Handler on a TextBox is supported. What happens when you try to run the code? Actually, that's only there because it inherits it from "Control", as does every other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio. However, you actually can write the code: textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown); and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.
ANSWER:
Looks like you're right. Bummer. No MouseOver event. One of the fallbacks that always works with.NET, though, is P/Invoke. Someone already took the time to do this for the.NET CF TextBox. I found this on CodeProject: http://www.codeproject.com/KB/cs/TextBox_subclassing.aspx Hope this helps | [
"c#",
".net",
"events",
"windows-mobile"
] | 2 | 0 | 12,745 | 5 | 0 | 2008-08-11T12:36:20.350000 | 2008-08-11T14:45:05.957000 |
7,720 | 149,971 | Packaging Java apps for the Windows/Linux desktop | I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a.jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular.exe for him/her to run. Has anyone had any experience with any of the.exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own? Edit: I should perhaps mention that I am unable to spend a lot of money on a commercial solution. | To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating.app and.dmg for Mac, but haven't figured out what to do for Linux yet. Project Copies of launch4j and NSIS In my project I have a "vendor" directory and underneath it I have a directory for "launch4j" and "nsis". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each. Script Files I also have a "scripts" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file: true gui rpgam.jar rpgam.exe. normal http://www.rpgaudiomixer.com/ false false 1.5.0 preferJre..\images\splash.bmp true 60 true And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file.; The name of the installer Name "RPG Audio Mixer"!ifndef VERSION!define VERSION A.B.C!endif; The file to write outfile "..\dist\installers\windows\rpgam-${VERSION}.exe"; The default installation directory InstallDir "$PROGRAMFILES\RPG Audio Mixer"; Registry key to check for directory (so if you install again, it will; overwrite the old one automatically) InstallDirRegKey HKLM "Software\RPG_Audio_Mixer" "Install_Dir"
# create a default section. section "RPG Audio Mixer"
SectionIn RO; Set output path to the installation directory. SetOutPath $INSTDIR File /r "..\dist\layout\windows\"; Write the installation path into the registry WriteRegStr HKLM SOFTWARE\RPG_Audio_Mixer "Install_Dir" "$INSTDIR"; Write the uninstall keys for Windows WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "DisplayName" "RPG Audio Mixer" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "UninstallString" '"$INSTDIR\uninstall.exe"' WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoModify" 1 WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoRepair" 1 WriteUninstaller "uninstall.exe"; read the value from the registry into the $0 register;readRegStr $0 HKLM "SOFTWARE\JavaSoft\Java Runtime Environment" CurrentVersion; print the results in a popup message box;messageBox MB_OK "version: $0"
sectionEnd
Section "Start Menu Shortcuts" CreateDirectory "$SMPROGRAMS\RPG Audio Mixer" CreateShortCut "$SMPROGRAMS\RPG Audio Mixer\Uninstall.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0 CreateShortCut "$SMPROGRAMS\RPG AUdio Mixer\RPG Audio Mixer.lnk" "$INSTDIR\rpgam.exe" "" "$INSTDIR\rpgam.exe" 0 SectionEnd
Section "Uninstall"; Remove registry keys DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" DeleteRegKey HKLM SOFTWARE\RPG_Audio_Mixer; Remove files and uninstaller Delete $INSTDIR\rpgam.exe Delete $INSTDIR\uninstall.exe; Remove shortcuts, if any Delete "$SMPROGRAMS\RPG Audio Mixer\*.*"; Remove directories used RMDir "$SMPROGRAMS\RPG Audio Mixer" RMDir "$INSTDIR"
SectionEnd Ant Integration I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks: I then have a simple target for creating the wrapper executable: And another target for making the installer: The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer. | Packaging Java apps for the Windows/Linux desktop I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a.jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular.exe for him/her to run. Has anyone had any experience with any of the.exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own? Edit: I should perhaps mention that I am unable to spend a lot of money on a commercial solution. | TITLE:
Packaging Java apps for the Windows/Linux desktop
QUESTION:
I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a.jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular.exe for him/her to run. Has anyone had any experience with any of the.exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own? Edit: I should perhaps mention that I am unable to spend a lot of money on a commercial solution.
ANSWER:
To follow up on pauxu's answer, I'm using launch4j and NSIS on a project of mine and thought it would be helpful to show just how I'm using them. Here's what I'm doing for Windows. BTW, I'm creating.app and.dmg for Mac, but haven't figured out what to do for Linux yet. Project Copies of launch4j and NSIS In my project I have a "vendor" directory and underneath it I have a directory for "launch4j" and "nsis". Within each is a copy of the install for each application. I find it easier to have a copy local to the project rather than forcing others to install both products and set up some kind of environment variable to point to each. Script Files I also have a "scripts" directory in my project that holds various configuration/script files for my project. First there is the launch4j.xml file: true gui rpgam.jar rpgam.exe. normal http://www.rpgaudiomixer.com/ false false 1.5.0 preferJre..\images\splash.bmp true 60 true And then there's the NSIS script rpgam-setup.nsis. It can take a VERSION argument to help name the file.; The name of the installer Name "RPG Audio Mixer"!ifndef VERSION!define VERSION A.B.C!endif; The file to write outfile "..\dist\installers\windows\rpgam-${VERSION}.exe"; The default installation directory InstallDir "$PROGRAMFILES\RPG Audio Mixer"; Registry key to check for directory (so if you install again, it will; overwrite the old one automatically) InstallDirRegKey HKLM "Software\RPG_Audio_Mixer" "Install_Dir"
# create a default section. section "RPG Audio Mixer"
SectionIn RO; Set output path to the installation directory. SetOutPath $INSTDIR File /r "..\dist\layout\windows\"; Write the installation path into the registry WriteRegStr HKLM SOFTWARE\RPG_Audio_Mixer "Install_Dir" "$INSTDIR"; Write the uninstall keys for Windows WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "DisplayName" "RPG Audio Mixer" WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "UninstallString" '"$INSTDIR\uninstall.exe"' WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoModify" 1 WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" "NoRepair" 1 WriteUninstaller "uninstall.exe"; read the value from the registry into the $0 register;readRegStr $0 HKLM "SOFTWARE\JavaSoft\Java Runtime Environment" CurrentVersion; print the results in a popup message box;messageBox MB_OK "version: $0"
sectionEnd
Section "Start Menu Shortcuts" CreateDirectory "$SMPROGRAMS\RPG Audio Mixer" CreateShortCut "$SMPROGRAMS\RPG Audio Mixer\Uninstall.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0 CreateShortCut "$SMPROGRAMS\RPG AUdio Mixer\RPG Audio Mixer.lnk" "$INSTDIR\rpgam.exe" "" "$INSTDIR\rpgam.exe" 0 SectionEnd
Section "Uninstall"; Remove registry keys DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\RPGAudioMixer" DeleteRegKey HKLM SOFTWARE\RPG_Audio_Mixer; Remove files and uninstaller Delete $INSTDIR\rpgam.exe Delete $INSTDIR\uninstall.exe; Remove shortcuts, if any Delete "$SMPROGRAMS\RPG Audio Mixer\*.*"; Remove directories used RMDir "$SMPROGRAMS\RPG Audio Mixer" RMDir "$INSTDIR"
SectionEnd Ant Integration I have some targets in my Ant buildfile (build.xml) to handle the above. First I tel Ant to import launch4j's Ant tasks: I then have a simple target for creating the wrapper executable: And another target for making the installer: The top portion of that just copies the necessary files for the installer to a temporary location and the second half executes the script that uses all of it to make the installer. | [
"java",
"windows",
"swt",
"executable",
"software-distribution"
] | 40 | 32 | 15,642 | 18 | 0 | 2008-08-11T12:37:50.503000 | 2008-09-29T18:16:22.020000 |
7,737 | 7,950 | How to display unicode text in OpenGL? | Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like #define FONTLISTRANGE 128 GLuint list; list = glGenLists(FONTLISTRANGE); wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list); just won't do because you can't create enough lists for all unicode characters. | You could also group the characters by language. Load each language table as needed, and when you need to switch languages, unload the previous language table and load the new one. | How to display unicode text in OpenGL? Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like #define FONTLISTRANGE 128 GLuint list; list = glGenLists(FONTLISTRANGE); wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list); just won't do because you can't create enough lists for all unicode characters. | TITLE:
How to display unicode text in OpenGL?
QUESTION:
Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like #define FONTLISTRANGE 128 GLuint list; list = glGenLists(FONTLISTRANGE); wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list); just won't do because you can't create enough lists for all unicode characters.
ANSWER:
You could also group the characters by language. Load each language table as needed, and when you need to switch languages, unload the previous language table and load the new one. | [
"windows",
"opengl",
"unicode"
] | 7 | 0 | 18,947 | 8 | 0 | 2008-08-11T12:50:43.787000 | 2008-08-11T16:54:04.997000 |
7,758 | 8,461 | What is the value-binding syntax in xaml? | I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece?: It's the databinding that breaks. I get an InvalidAttributeValue exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless. Changing the ElementName didn't help. There must me something else I'm not getting. I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is: XamlParseException: Invalid attribute value for property Height. This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts. | The ElementName property on a Binding is not supported in Silverlight. You will notice, if you go into the code behind or inspect the Binding object in class explorer, it doesn't have a property named ElementName. | What is the value-binding syntax in xaml? I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece?: It's the databinding that breaks. I get an InvalidAttributeValue exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless. Changing the ElementName didn't help. There must me something else I'm not getting. I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is: XamlParseException: Invalid attribute value for property Height. This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts. | TITLE:
What is the value-binding syntax in xaml?
QUESTION:
I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece?: It's the databinding that breaks. I get an InvalidAttributeValue exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless. Changing the ElementName didn't help. There must me something else I'm not getting. I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is: XamlParseException: Invalid attribute value for property Height. This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts.
ANSWER:
The ElementName property on a Binding is not supported in Silverlight. You will notice, if you go into the code behind or inspect the Binding object in class explorer, it doesn't have a property named ElementName. | [
".net",
"wpf",
"silverlight",
"xaml",
"binding"
] | 2 | 2 | 4,490 | 7 | 0 | 2008-08-11T13:09:08.693000 | 2008-08-12T04:33:00.357000 |
7,773 | 7,777 | Change visibility of ASP.NET label with JavaScript | I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page. What can I do to resolve this? | If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example: Then, you could make it visible on the client side with: document.getElementById('Label1').style.display = 'inherit'; You could make it hidden again with: document.getElementById('Label1').style.display = 'none'; Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ. | Change visibility of ASP.NET label with JavaScript I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page. What can I do to resolve this? | TITLE:
Change visibility of ASP.NET label with JavaScript
QUESTION:
I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page. What can I do to resolve this?
ANSWER:
If you need to manipulate it on the client side, you can't use the Visible property on the server side. Instead, set its CSS display style to "none". For example: Then, you could make it visible on the client side with: document.getElementById('Label1').style.display = 'inherit'; You could make it hidden again with: document.getElementById('Label1').style.display = 'none'; Keep in mind that there may be issues with the ClientID being more complex than "Label1" in practice. You'll need to use the ClientID with getElementById, not the server side ID, if they differ. | [
"asp.net",
"javascript"
] | 34 | 43 | 128,913 | 7 | 0 | 2008-08-11T13:24:19.037000 | 2008-08-11T13:28:55.470000 |
7,779 | 28,154 | I would like a recommendation for a book on Eclipse's Rich Client Platform (RCP) | I have read through several reviews on Amazon and some books seem outdated. I am currently using MyEclipse 6.5 which is using Eclipse 3.3. I'm interested in hearing from people that have experience learning RCP and what reference material they used to get started. | I've been doing Eclipse RCP development for almost 2 years now. When I first started, I wanted a book for help and many people told me, with Eclipse you're better off using the Eclipsepedia and Google. However, I started with " The Java Developer's Guide to Eclipse " by D'Anjou et al, and I still reference it when I need a better starting point or a good reference. It's probably a little outdated now, but is very thorough and really explains how the Eclipse framework works. Like just about anything, RCP isn't too hard to pick up if you've figured out how the framework supporting it works and you'll get a lot more mileage out of your code. | I would like a recommendation for a book on Eclipse's Rich Client Platform (RCP) I have read through several reviews on Amazon and some books seem outdated. I am currently using MyEclipse 6.5 which is using Eclipse 3.3. I'm interested in hearing from people that have experience learning RCP and what reference material they used to get started. | TITLE:
I would like a recommendation for a book on Eclipse's Rich Client Platform (RCP)
QUESTION:
I have read through several reviews on Amazon and some books seem outdated. I am currently using MyEclipse 6.5 which is using Eclipse 3.3. I'm interested in hearing from people that have experience learning RCP and what reference material they used to get started.
ANSWER:
I've been doing Eclipse RCP development for almost 2 years now. When I first started, I wanted a book for help and many people told me, with Eclipse you're better off using the Eclipsepedia and Google. However, I started with " The Java Developer's Guide to Eclipse " by D'Anjou et al, and I still reference it when I need a better starting point or a good reference. It's probably a little outdated now, but is very thorough and really explains how the Eclipse framework works. Like just about anything, RCP isn't too hard to pick up if you've figured out how the framework supporting it works and you'll get a lot more mileage out of your code. | [
"java",
"eclipse",
"rcp",
"myeclipse"
] | 11 | 3 | 3,752 | 6 | 0 | 2008-08-11T13:30:21.850000 | 2008-08-26T14:17:10.447000 |
7,846 | 7,853 | How can I split an XML document into thirds (or, even better, n pieces)? | I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome. What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good. | Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In C#, you'd use the XmlDocument class. For example, if your XML file looked something like this: Some text Some other text then you'd use code like this to extract all of the Pieces: XmlDocument doc = new XmlDocument(); doc.Load(" "); XmlNodeList nl = doc.GetElementsByTagName("Piece"); foreach (XmlNode n in nl) { // Do something with each Piece node } Once you've got the nodes, you can do something with them in your code, or you can transfer the entire text of the node to its own XML document and act on that as if it were an independent piece of XML (including saving it back to disk, etc). | How can I split an XML document into thirds (or, even better, n pieces)? I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome. What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good. | TITLE:
How can I split an XML document into thirds (or, even better, n pieces)?
QUESTION:
I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome. What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good.
ANSWER:
Well of course you can always extract the top-level elements (whether this is the granularity you want is up to you). In C#, you'd use the XmlDocument class. For example, if your XML file looked something like this: Some text Some other text then you'd use code like this to extract all of the Pieces: XmlDocument doc = new XmlDocument(); doc.Load(" "); XmlNodeList nl = doc.GetElementsByTagName("Piece"); foreach (XmlNode n in nl) { // Do something with each Piece node } Once you've got the nodes, you can do something with them in your code, or you can transfer the entire text of the node to its own XML document and act on that as if it were an independent piece of XML (including saving it back to disk, etc). | [
"xml"
] | 8 | 3 | 12,727 | 10 | 0 | 2008-08-11T15:04:21.363000 | 2008-08-11T15:13:14.107000 |
7,864 | 8,215 | Why all the Active Record hate? | As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on Active Record. Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains why it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?) Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record. If it doesn't scale well, why not? What other problems does it have? | There's ActiveRecord the Design Pattern and ActiveRecord the Rails ORM Library, and there's also a ton of knock-offs for.NET, and other languages. These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?" I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it. @BlaM The problem that I see with Active Records is, that it's always just about one table Code: class Person belongs_to:company end people = Person.find(:all,:include =>:company ) This generates SQL with LEFT JOIN companies on companies.id = person.company_id, and automatically generates associated Company objects so you can do people.first.company and it doesn't need to hit the database because the data is already present. @pix0r The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records Code: person = Person.find_by_sql("giant complicated sql query") This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done. @Tim Sullivan...and you select several instances of the model, you're basically doing a "select * from..." Code: people = Person.find(:all,:select=>'name, id') This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on. | Why all the Active Record hate? As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on Active Record. Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains why it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?) Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record. If it doesn't scale well, why not? What other problems does it have? | TITLE:
Why all the Active Record hate?
QUESTION:
As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on Active Record. Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains why it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?) Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record. If it doesn't scale well, why not? What other problems does it have?
ANSWER:
There's ActiveRecord the Design Pattern and ActiveRecord the Rails ORM Library, and there's also a ton of knock-offs for.NET, and other languages. These are all different things. They mostly follow that design pattern, but extend and modify it in many different ways, so before anyone says "ActiveRecord Sucks" it needs to be qualified by saying "which ActiveRecord, there's heaps?" I'm only familiar with Rails' ActiveRecord, I'll try address all the complaints which have been raised in context of using it. @BlaM The problem that I see with Active Records is, that it's always just about one table Code: class Person belongs_to:company end people = Person.find(:all,:include =>:company ) This generates SQL with LEFT JOIN companies on companies.id = person.company_id, and automatically generates associated Company objects so you can do people.first.company and it doesn't need to hit the database because the data is already present. @pix0r The inherent problem with Active Record is that database queries are automatically generated and executed to populate objects and modify database records Code: person = Person.find_by_sql("giant complicated sql query") This is discouraged as it's ugly, but for the cases where you just plain and simply need to write raw SQL, it's easily done. @Tim Sullivan...and you select several instances of the model, you're basically doing a "select * from..." Code: people = Person.find(:all,:select=>'name, id') This will only select the name and ID columns from the database, all the other 'attributes' in the mapped objects will just be nil, unless you manually reload that object, and so on. | [
"ruby-on-rails",
"design-patterns",
"oop",
"activerecord"
] | 102 | 91 | 20,798 | 14 | 0 | 2008-08-11T15:30:30.313000 | 2008-08-11T21:02:03.870000 |
7,880 | 7,886 | How do you open a file in C++? | I want to open a file for reading, the C++ way. I need to be able to do it for: text files, which would involve some sort of read line function. binary files, which would provide a way to read raw data into a char* buffer. | There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen / fread / fclose, or you could use the C++ fstream facilities ( ifstream / ofstream ), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations. All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text: int nsize = 10; std::vector somedata(nsize); ifstream myfile; myfile.open(" "); myfile.read(somedata.data(), nsize); myfile.close(); Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing). | How do you open a file in C++? I want to open a file for reading, the C++ way. I need to be able to do it for: text files, which would involve some sort of read line function. binary files, which would provide a way to read raw data into a char* buffer. | TITLE:
How do you open a file in C++?
QUESTION:
I want to open a file for reading, the C++ way. I need to be able to do it for: text files, which would involve some sort of read line function. binary files, which would provide a way to read raw data into a char* buffer.
ANSWER:
There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen / fread / fclose, or you could use the C++ fstream facilities ( ifstream / ofstream ), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations. All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text: int nsize = 10; std::vector somedata(nsize); ifstream myfile; myfile.open(" "); myfile.read(somedata.data(), nsize); myfile.close(); Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing). | [
"c++",
"file",
"io"
] | 57 | 17 | 215,989 | 9 | 0 | 2008-08-11T15:50:51.660000 | 2008-08-11T15:58:06.980000 |
7,884 | 7,892 | Testing for inequality in T-SQL | I've just come across this in a WHERE clause: AND NOT (t.id = @id) How does this compare with: AND t.id!= @id Or with: AND t.id <> @id I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <> or!= is going to bust any hopes for using an index that I might have had, but surely the first approach above will suffer the same problem? | These 3 will get the same exact execution plan declare @id varchar(40) select @id = '172-32-1176'
select * from authors where au_id <> @id
select * from authors where au_id!= @id
select * from authors where not (au_id = @id) It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself | Testing for inequality in T-SQL I've just come across this in a WHERE clause: AND NOT (t.id = @id) How does this compare with: AND t.id!= @id Or with: AND t.id <> @id I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <> or!= is going to bust any hopes for using an index that I might have had, but surely the first approach above will suffer the same problem? | TITLE:
Testing for inequality in T-SQL
QUESTION:
I've just come across this in a WHERE clause: AND NOT (t.id = @id) How does this compare with: AND t.id!= @id Or with: AND t.id <> @id I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <> or!= is going to bust any hopes for using an index that I might have had, but surely the first approach above will suffer the same problem?
ANSWER:
These 3 will get the same exact execution plan declare @id varchar(40) select @id = '172-32-1176'
select * from authors where au_id <> @id
select * from authors where au_id!= @id
select * from authors where not (au_id = @id) It will also depend on the selectivity of the index itself of course. I always use au_id <> @id myself | [
"t-sql",
"indexing",
"inequality"
] | 48 | 44 | 23,048 | 4 | 0 | 2008-08-11T15:56:42.973000 | 2008-08-11T16:02:43.710000 |
7,885 | 8,668 | How do you create objects in Perl? | Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties? | You should definitely take a look at Moose. package Point; use Moose; # automatically turns on strict and warnings
has 'x' => (is => 'rw', isa => 'Int'); has 'y' => (is => 'rw', isa => 'Int');
sub clear { my $self = shift; $self->x(0); $self->y(0); } Moose gives you (among other things) a constructor, accessor methods, and type checking for free! So in your code you can: my $p = Point->new({x=>10, y=>20}); # Free constructor $p->x(15); # Free setter print $p->x(); # Free getter $p->clear(); $p->x(15.5); # FAILS! Free type check. A good starting point is Moose::Manual and Moose::Cookbook If you just need the basic stuff you can also use Mouse which is not as complete, but without most of the compile time penalty. | How do you create objects in Perl? Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties? | TITLE:
How do you create objects in Perl?
QUESTION:
Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?
ANSWER:
You should definitely take a look at Moose. package Point; use Moose; # automatically turns on strict and warnings
has 'x' => (is => 'rw', isa => 'Int'); has 'y' => (is => 'rw', isa => 'Int');
sub clear { my $self = shift; $self->x(0); $self->y(0); } Moose gives you (among other things) a constructor, accessor methods, and type checking for free! So in your code you can: my $p = Point->new({x=>10, y=>20}); # Free constructor $p->x(15); # Free setter print $p->x(); # Free getter $p->clear(); $p->x(15.5); # FAILS! Free type check. A good starting point is Moose::Manual and Moose::Cookbook If you just need the basic stuff you can also use Mouse which is not as complete, but without most of the compile time penalty. | [
"perl",
"oop",
"syntax"
] | 13 | 23 | 6,766 | 7 | 0 | 2008-08-11T15:57:35.047000 | 2008-08-12T10:54:25.360000 |
7,913 | 7,924 | How do I make Subversion (SVN) send email on checkins? | I've always found checkin (commit) mails to be very useful for keeping track of what work other people are doing in the codebase / repository. How do I set up SVN to email a distribution list on each commit? I'm running clients on Windows and the Apache Subversion server on Linux. The answers below for various platforms will likely be useful to other people though. | You use the post-commit hooks. Here's a sample Ruby script that sends an email after each commit: commit-email.rb | How do I make Subversion (SVN) send email on checkins? I've always found checkin (commit) mails to be very useful for keeping track of what work other people are doing in the codebase / repository. How do I set up SVN to email a distribution list on each commit? I'm running clients on Windows and the Apache Subversion server on Linux. The answers below for various platforms will likely be useful to other people though. | TITLE:
How do I make Subversion (SVN) send email on checkins?
QUESTION:
I've always found checkin (commit) mails to be very useful for keeping track of what work other people are doing in the codebase / repository. How do I set up SVN to email a distribution list on each commit? I'm running clients on Windows and the Apache Subversion server on Linux. The answers below for various platforms will likely be useful to other people though.
ANSWER:
You use the post-commit hooks. Here's a sample Ruby script that sends an email after each commit: commit-email.rb | [
"svn",
"hook",
"post-commit",
"post-commit-hook"
] | 52 | 31 | 79,401 | 16 | 0 | 2008-08-11T16:27:55.703000 | 2008-08-11T16:35:18.887000 |
7,917 | 8,113 | Remove Quotes and Commas from a String in MySQL | I'm importing some data from a CSV file, and numbers that are larger than 1000 get turned into 1,100 etc. What's a good way to remove both the quotes and the comma from this so I can put it into an int field? Edit: The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup. | Here is a good case for regular expressions. You can run a find and replace on the data either before you import (easier) or later on if the SQL import accepted those characters (not nearly as easy). But in either case, you have any number of methods to do a find and replace, be it editors, scripting languages, GUI programs, etc. Remember that you're going to want to find and replace all of the bad characters. A typical regular expression to find the comma and quotes (assuming just double quotes) is: (Blacklist) /[,"]/ Or, if you find something might change in the future, this regular expression, matches anything except a number or decimal point. (Whitelist) /[^0-9\.]/ What has been discussed by the people above is that we don't know all of the data in your CSV file. It sounds like you want to remove the commas and quotes from all of the numbers in the CSV file. But because we don't know what else is in the CSV file we want to make sure that we don't corrupt other data. Just blindly doing a find/replace could affect other portions of the file. | Remove Quotes and Commas from a String in MySQL I'm importing some data from a CSV file, and numbers that are larger than 1000 get turned into 1,100 etc. What's a good way to remove both the quotes and the comma from this so I can put it into an int field? Edit: The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup. | TITLE:
Remove Quotes and Commas from a String in MySQL
QUESTION:
I'm importing some data from a CSV file, and numbers that are larger than 1000 get turned into 1,100 etc. What's a good way to remove both the quotes and the comma from this so I can put it into an int field? Edit: The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup.
ANSWER:
Here is a good case for regular expressions. You can run a find and replace on the data either before you import (easier) or later on if the SQL import accepted those characters (not nearly as easy). But in either case, you have any number of methods to do a find and replace, be it editors, scripting languages, GUI programs, etc. Remember that you're going to want to find and replace all of the bad characters. A typical regular expression to find the comma and quotes (assuming just double quotes) is: (Blacklist) /[,"]/ Or, if you find something might change in the future, this regular expression, matches anything except a number or decimal point. (Whitelist) /[^0-9\.]/ What has been discussed by the people above is that we don't know all of the data in your CSV file. It sounds like you want to remove the commas and quotes from all of the numbers in the CSV file. But because we don't know what else is in the CSV file we want to make sure that we don't corrupt other data. Just blindly doing a find/replace could affect other portions of the file. | [
"mysql",
"regex",
"string"
] | 16 | 2 | 57,017 | 8 | 0 | 2008-08-11T16:28:57.683000 | 2008-08-11T19:21:10.113000 |
7,933 | 7,936 | interrogating table lock schemes in T-SQL | Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in sysobjects but nothing jumped out. | aargh, just being an idiot: SELECT name, lockscheme(name) FROM sysobjects WHERE type="U" ORDER BY name | interrogating table lock schemes in T-SQL Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in sysobjects but nothing jumped out. | TITLE:
interrogating table lock schemes in T-SQL
QUESTION:
Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in sysobjects but nothing jumped out.
ANSWER:
aargh, just being an idiot: SELECT name, lockscheme(name) FROM sysobjects WHERE type="U" ORDER BY name | [
"t-sql",
"sysobjects"
] | 3 | 1 | 1,800 | 2 | 0 | 2008-08-11T16:41:47.487000 | 2008-08-11T16:44:54.483000 |
7,937 | 13,197 | How to solve the select overlap bug in IE6? | When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page. I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing. FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect. Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere. Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible inside the and styling it with: #MyDiv iframe { position: absolute; z-index: -1; filter: mask(); border: 0; margin: 0; padding: 0; top: 0; left: 0; width: 9999px; height: 9999px; overflow: hidden; } Does anyone have an even better solution than this one? EDIT: The purpose of this question is as much informative as it is a real question. I find the trick to be a good solution, but I am still looking for improvement like removing this ugly useless tag that degrades accessibility. | I don't know anything better than an Iframe But it does occur to me that this could be added in JS by looking for a couple of variables IE 6 A high Z-Index (you tend to have to set a z-index if you are floating a div over) A box element Then a script that looks for these items and just add an iframe layer would be a neat solution Paul | How to solve the select overlap bug in IE6? When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page. I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing. FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect. Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere. Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible inside the and styling it with: #MyDiv iframe { position: absolute; z-index: -1; filter: mask(); border: 0; margin: 0; padding: 0; top: 0; left: 0; width: 9999px; height: 9999px; overflow: hidden; } Does anyone have an even better solution than this one? EDIT: The purpose of this question is as much informative as it is a real question. I find the trick to be a good solution, but I am still looking for improvement like removing this ugly useless tag that degrades accessibility. | TITLE:
How to solve the select overlap bug in IE6?
QUESTION:
When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page. I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing. FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect. Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere. Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible inside the and styling it with: #MyDiv iframe { position: absolute; z-index: -1; filter: mask(); border: 0; margin: 0; padding: 0; top: 0; left: 0; width: 9999px; height: 9999px; overflow: hidden; } Does anyone have an even better solution than this one? EDIT: The purpose of this question is as much informative as it is a real question. I find the trick to be a good solution, but I am still looking for improvement like removing this ugly useless tag that degrades accessibility.
ANSWER:
I don't know anything better than an Iframe But it does occur to me that this could be added in JS by looking for a couple of variables IE 6 A high Z-Index (you tend to have to set a z-index if you are floating a div over) A box element Then a script that looks for these items and just add an iframe layer would be a neat solution Paul | [
"html",
"css",
"internet-explorer-6",
"html-select"
] | 28 | 8 | 19,700 | 10 | 0 | 2008-08-11T16:45:10.363000 | 2008-08-16T16:06:35.840000 |
7,940 | 7,945 | How important is W3C XHTML/CSS validation when finalizing work? | Even though I always strive for complete validation these days, I often wonder if it's a waste of time. If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal? What level do you hold your code to when you create it for: a) yourself b) your clients P.S. Jeff and company, why doesn't stack overflow validate?:) EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems" I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going | a) Must look the same b) As standards-compliant as possible, but not so anal that it blocks finishing work In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up. | How important is W3C XHTML/CSS validation when finalizing work? Even though I always strive for complete validation these days, I often wonder if it's a waste of time. If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal? What level do you hold your code to when you create it for: a) yourself b) your clients P.S. Jeff and company, why doesn't stack overflow validate?:) EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems" I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going | TITLE:
How important is W3C XHTML/CSS validation when finalizing work?
QUESTION:
Even though I always strive for complete validation these days, I often wonder if it's a waste of time. If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal? What level do you hold your code to when you create it for: a) yourself b) your clients P.S. Jeff and company, why doesn't stack overflow validate?:) EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems" I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going
ANSWER:
a) Must look the same b) As standards-compliant as possible, but not so anal that it blocks finishing work In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up. | [
"css",
"validation",
"xhtml",
"cross-browser",
"w3c"
] | 15 | 12 | 3,414 | 9 | 0 | 2008-08-11T16:46:28.567000 | 2008-08-11T16:50:32.867000 |
7,954 | 8,034 | SQL Server Recovery States | When restoring a SQL Server Database, I notice that there are 3 different Recovery States to choose from: Restore with Recovery Restore with No Recovery Restore with Standby I've always left it at it's default value, but what do they all mean? (Preferably in layman's terms) | GateKiller, In simple terms (and not a copy-paste out of the SQLBOL) so you can understand the concepts: RESTORE WITH RECOVERY uses the backup media file (eg. fulldata.bak) to restore the database to back to the time that backup file was created. This is great if you want to go back in time to restore the database to an earlier state - like when developing a system. If you want to restore the database TO THE VERY LATEST DATA, (i.e. like if your doing a system Disaster Recovery and you cannot lose any data) then you want to restore that backup AND THEN all the transaction logs created since that backup. This is when you use RESTORE NORECOVERY. It will allow you to restore the later transaction logs right up to the point of failure (as long as you have them). RECOVERY WITH STANDBY is the ability to restore the database up to a parital date (like NORECOVERY above) but to allow the database still to be used READONLY. New transaction logs can still be applied to the database to keep it up to date (a standby server). Use this when it would take too long to restore a full database in order to Return To Operations the system. (ie. if you have a multi TB database that would take 16 hours to restore, but could receive transaction log updates every 15 minutes). This is a bit like a mirror server - but without having "every single transaction" send to the backup server in real time. | SQL Server Recovery States When restoring a SQL Server Database, I notice that there are 3 different Recovery States to choose from: Restore with Recovery Restore with No Recovery Restore with Standby I've always left it at it's default value, but what do they all mean? (Preferably in layman's terms) | TITLE:
SQL Server Recovery States
QUESTION:
When restoring a SQL Server Database, I notice that there are 3 different Recovery States to choose from: Restore with Recovery Restore with No Recovery Restore with Standby I've always left it at it's default value, but what do they all mean? (Preferably in layman's terms)
ANSWER:
GateKiller, In simple terms (and not a copy-paste out of the SQLBOL) so you can understand the concepts: RESTORE WITH RECOVERY uses the backup media file (eg. fulldata.bak) to restore the database to back to the time that backup file was created. This is great if you want to go back in time to restore the database to an earlier state - like when developing a system. If you want to restore the database TO THE VERY LATEST DATA, (i.e. like if your doing a system Disaster Recovery and you cannot lose any data) then you want to restore that backup AND THEN all the transaction logs created since that backup. This is when you use RESTORE NORECOVERY. It will allow you to restore the later transaction logs right up to the point of failure (as long as you have them). RECOVERY WITH STANDBY is the ability to restore the database up to a parital date (like NORECOVERY above) but to allow the database still to be used READONLY. New transaction logs can still be applied to the database to keep it up to date (a standby server). Use this when it would take too long to restore a full database in order to Return To Operations the system. (ie. if you have a multi TB database that would take 16 hours to restore, but could receive transaction log updates every 15 minutes). This is a bit like a mirror server - but without having "every single transaction" send to the backup server in real time. | [
"sql-server",
"backup"
] | 7 | 9 | 14,168 | 3 | 0 | 2008-08-11T16:59:35.047000 | 2008-08-11T18:10:27.133000 |
7,981 | 8,035 | Decoding printf statements in C (Printf Primer) | I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to QString variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little 'printf primer' for Stackoverflow. In the code, I came across this little gem, printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g); How will the variables a, b, c, d, e, f, g be formatted? | Danny is mostly right. a. unsigned decimal, minimum 4 characters, space padded b. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal c. hex, minimum 4 characters, 0 padded, letters are printed in upper case d. same as above, but minimum 2 characters e. e is assumed to be an int, converted to an unsigned char and printed f. same as e g. This is likely a typo, the 4 has no effect. If it were "%.4s", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated. Edit: jj33 points out 2 errors in b and g above here. | Decoding printf statements in C (Printf Primer) I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to QString variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little 'printf primer' for Stackoverflow. In the code, I came across this little gem, printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g); How will the variables a, b, c, d, e, f, g be formatted? | TITLE:
Decoding printf statements in C (Printf Primer)
QUESTION:
I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to QString variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little 'printf primer' for Stackoverflow. In the code, I came across this little gem, printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g); How will the variables a, b, c, d, e, f, g be formatted?
ANSWER:
Danny is mostly right. a. unsigned decimal, minimum 4 characters, space padded b. floating point, minimum 16 digits before the decimal (0 padded), 1 digit after the decimal c. hex, minimum 4 characters, 0 padded, letters are printed in upper case d. same as above, but minimum 2 characters e. e is assumed to be an int, converted to an unsigned char and printed f. same as e g. This is likely a typo, the 4 has no effect. If it were "%.4s", then a maximum of 4 characters from the string would be printed. It is interesting to note that in this case, the string does not need to be null terminated. Edit: jj33 points out 2 errors in b and g above here. | [
"c",
"qt",
"printf",
"qstring"
] | 4 | 5 | 4,566 | 6 | 0 | 2008-08-11T17:28:56.610000 | 2008-08-11T18:11:45.697000 |
7,990 | 8,112 | Printing from a .NET Service | I am working on a project right now that involves receiving a message from another application, formatting the contents of that message, and sending it to a printer. The technology of choice is C# windows service. The output could be called a report, I suppose, but a reporting engine is not necessary. A simple templating engine, like StringTemplate, or even XSLT outputting HTML would be fine. The problem I'm having is finding a free way to print this kind of output from a service. Since it seems that it will work, I'm working on a prototype using Microsoft's RDLC, populating a local report and then rendering it as an image to a memory stream, which I will then print. Issues with that are: Multi-page printing will be a big headache. Still have to use PrintDocument to print the memory stream, which is unsupported in a Windows Service (though it may work - haven't gotten that far with the prototype yet) If the data coming across changes, I have to change the dataset and the class that the data is being deserialized into. bad bad bad. Has anyone had to do anything remotely like this? Any advice? I already posted a question about printing HTML without user input, and after wasting about 3 days on that, I have come to the conclusion that it cannot be done, at least not with any freely available tool. All help is appreciated. EDIT: We are on version 2.0 of the.NET framework. | Trust me, you will spend more money trying to search/develop a solution for this as compared to buying a third party component. Do not reinvent the wheel and go for the paid solution. Printing is a complex problem and I would love to see the day when better framework support is added for this. | Printing from a .NET Service I am working on a project right now that involves receiving a message from another application, formatting the contents of that message, and sending it to a printer. The technology of choice is C# windows service. The output could be called a report, I suppose, but a reporting engine is not necessary. A simple templating engine, like StringTemplate, or even XSLT outputting HTML would be fine. The problem I'm having is finding a free way to print this kind of output from a service. Since it seems that it will work, I'm working on a prototype using Microsoft's RDLC, populating a local report and then rendering it as an image to a memory stream, which I will then print. Issues with that are: Multi-page printing will be a big headache. Still have to use PrintDocument to print the memory stream, which is unsupported in a Windows Service (though it may work - haven't gotten that far with the prototype yet) If the data coming across changes, I have to change the dataset and the class that the data is being deserialized into. bad bad bad. Has anyone had to do anything remotely like this? Any advice? I already posted a question about printing HTML without user input, and after wasting about 3 days on that, I have come to the conclusion that it cannot be done, at least not with any freely available tool. All help is appreciated. EDIT: We are on version 2.0 of the.NET framework. | TITLE:
Printing from a .NET Service
QUESTION:
I am working on a project right now that involves receiving a message from another application, formatting the contents of that message, and sending it to a printer. The technology of choice is C# windows service. The output could be called a report, I suppose, but a reporting engine is not necessary. A simple templating engine, like StringTemplate, or even XSLT outputting HTML would be fine. The problem I'm having is finding a free way to print this kind of output from a service. Since it seems that it will work, I'm working on a prototype using Microsoft's RDLC, populating a local report and then rendering it as an image to a memory stream, which I will then print. Issues with that are: Multi-page printing will be a big headache. Still have to use PrintDocument to print the memory stream, which is unsupported in a Windows Service (though it may work - haven't gotten that far with the prototype yet) If the data coming across changes, I have to change the dataset and the class that the data is being deserialized into. bad bad bad. Has anyone had to do anything remotely like this? Any advice? I already posted a question about printing HTML without user input, and after wasting about 3 days on that, I have come to the conclusion that it cannot be done, at least not with any freely available tool. All help is appreciated. EDIT: We are on version 2.0 of the.NET framework.
ANSWER:
Trust me, you will spend more money trying to search/develop a solution for this as compared to buying a third party component. Do not reinvent the wheel and go for the paid solution. Printing is a complex problem and I would love to see the day when better framework support is added for this. | [
"c#",
".net",
"windows-services",
"printing"
] | 23 | 16 | 19,627 | 11 | 0 | 2008-08-11T17:37:27.310000 | 2008-08-11T19:20:29.707000 |
7,991 | 8,097 | Center text output from Graphics.DrawString() | I'm using the.NETCF (Windows Mobile) Graphics class and the DrawString() method to render a single character to the screen. The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset. For example, at text size 12, the offset is about 4, but at 32 the offset is about 10. I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. this is referencing the user control it's being drawn in. Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F); float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx; float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular), new SolidBrush(Color.Black), padx, pady); Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the Graphics class. | Through a combination of the suggestions I got, I came up with this: private void DrawLetter() { Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width); float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font); g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize) { // Compute actual size, shrink if needed while (true) { SizeF size = g.MeasureString(text, font);
// It fits, back out if (size.Height <= proposedSize.Height && size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size) Font oldFont = font; font = new Font(font.Name, (float)(font.Size *.9), font.Style); oldFont.Dispose(); } } So far, this works flawlessly. The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness. | Center text output from Graphics.DrawString() I'm using the.NETCF (Windows Mobile) Graphics class and the DrawString() method to render a single character to the screen. The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset. For example, at text size 12, the offset is about 4, but at 32 the offset is about 10. I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. this is referencing the user control it's being drawn in. Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F); float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx; float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular), new SolidBrush(Color.Black), padx, pady); Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the Graphics class. | TITLE:
Center text output from Graphics.DrawString()
QUESTION:
I'm using the.NETCF (Windows Mobile) Graphics class and the DrawString() method to render a single character to the screen. The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset. For example, at text size 12, the offset is about 4, but at 32 the offset is about 10. I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. this is referencing the user control it's being drawn in. Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F); float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx; float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular), new SolidBrush(Color.Black), padx, pady); Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the Graphics class.
ANSWER:
Through a combination of the suggestions I got, I came up with this: private void DrawLetter() { Graphics g = this.CreateGraphics();
float width = ((float)this.ClientRectangle.Width); float height = ((float)this.ClientRectangle.Width);
float emSize = height;
Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);
font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);
SizeF size = g.MeasureString(letter.ToString(), font); g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);
}
private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize) { // Compute actual size, shrink if needed while (true) { SizeF size = g.MeasureString(text, font);
// It fits, back out if (size.Height <= proposedSize.Height && size.Width <= proposedSize.Width) { return font; }
// Try a smaller font (90% of old size) Font oldFont = font; font = new Font(font.Name, (float)(font.Size *.9), font.Style); oldFont.Dispose(); } } So far, this works flawlessly. The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness. | [
"c#",
"graphics",
"compact-framework"
] | 73 | 24 | 146,121 | 6 | 0 | 2008-08-11T17:37:57.107000 | 2008-08-11T19:03:59.803000 |
8,004 | 8,090 | Best way to wrap rsync progress in a gui? | I use rsync to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar? I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix tail (3) Watch rsync console output in memory. Which one is best/preferred? | For this type of tasks, I use my own AutoIt script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen). I use AutoIt because it's free, very easy to use, and can compile quickly into an.EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only. $sCmd = "DIR E:\*.AU3 /S"; Test command $nAutoTimeout = 10; Time in seconds to close window after finish
$nDeskPct = 60; % of desktop size (if percent); $nHeight = 480; height/width of the main window (if fixed); $nWidth = 480
$sTitRun = "Executing process. Wait...."; $sTitDone = "Process done";
$sSound = @WindowsDir & "\Media\Ding.wav"; End Sound
$sButRun = "Cancel"; Caption of "Exec" button $sButDone = "Close"; Caption of "Close" button
#include #include #Include Opt("GUIOnEventMode", 1)
if $nDeskPct > 0 Then $nHeight = @DesktopHeight * ($nDeskPct / 100) $nWidth = @DesktopWidth * ($nDeskPct / 100) EndIf
If $CmdLine[0] > 0 Then $sCmd = "" For $nCmd = 1 To $CmdLine[0] $sCmd = $sCmd & " " & $CmdLine[$nCmd] Next; MsgBox (1,"",$sCmd) EndIf; AutoItSetOption("GUIDataSeparatorChar", Chr(13)+Chr(10))
$nForm = GUICreate($sTitRun, $nWidth, $nHeight) GUISetOnEvent($GUI_EVENT_CLOSE, "CloseForm")
$nList = GUICtrlCreateList ("", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL) GUICtrlSetFont (-1, 9, 0, 0, "Courier New")
$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30) GUICtrlSetOnEvent (-1, "CloseForm")
GUISetState(@SW_SHOW);, $nForm)
$nPID = Run(@ComSpec & " /C " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD); $nPID = Run(@ComSpec & " /C _RunErrl.bat " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD); # Con ésto devuelve el errorlevel en _ERRL.TMP
While 1 $sLine = StdoutRead($nPID) If @error Then ExitLoop
If StringLen ($sLine) > 0 then $sLine = StringReplace ($sLine, Chr(13), "|") $sLine = StringReplace ($sLine, Chr(10), "") if StringLeft($sLine, 1)="|" Then $sLine = " " & $sLine endif
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1) EndIf Wend
$sLine = " ||" GUICtrlSetData ($nList, $sLine) _GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
GUICtrlSetData ($nClose, $sButDone)
WinSetTitle ($sTitRun, "", $sTitDone) If $sSound <> "" Then SoundPlay ($sSound) EndIf
$rInfo = DllStructCreate("uint;dword"); # LASTINPUTINFO DllStructSetData($rInfo, 1, DllStructGetSize($rInfo));
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo)) $nLastInput = DllStructGetData($rInfo, 2)
$nTime = TimerInit()
While 1 If $nAutoTimeout > 0 Then DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo)) If DllStructGetData($rInfo, 2) <> $nLastInput Then; Tocó una tecla $nAutoTimeout = 0 EndIf EndIf
If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then ExitLoop EndIf
Sleep (100) Wend
Func CloseForm() Exit EndFunc | Best way to wrap rsync progress in a gui? I use rsync to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar? I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix tail (3) Watch rsync console output in memory. Which one is best/preferred? | TITLE:
Best way to wrap rsync progress in a gui?
QUESTION:
I use rsync to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar? I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix tail (3) Watch rsync console output in memory. Which one is best/preferred?
ANSWER:
For this type of tasks, I use my own AutoIt script (freeware, Windows only). The script redirects the standard output into a graphical window, displaying it with the ability to scroll back, etc (very useful in long processes like XCOPYs / PKZIPs to check if any error did happen). I use AutoIt because it's free, very easy to use, and can compile quickly into an.EXE. I think it's an excellent alternative to a complete programming language for this type of tasks. The downside is that it's for Windows only. $sCmd = "DIR E:\*.AU3 /S"; Test command $nAutoTimeout = 10; Time in seconds to close window after finish
$nDeskPct = 60; % of desktop size (if percent); $nHeight = 480; height/width of the main window (if fixed); $nWidth = 480
$sTitRun = "Executing process. Wait...."; $sTitDone = "Process done";
$sSound = @WindowsDir & "\Media\Ding.wav"; End Sound
$sButRun = "Cancel"; Caption of "Exec" button $sButDone = "Close"; Caption of "Close" button
#include #include #Include Opt("GUIOnEventMode", 1)
if $nDeskPct > 0 Then $nHeight = @DesktopHeight * ($nDeskPct / 100) $nWidth = @DesktopWidth * ($nDeskPct / 100) EndIf
If $CmdLine[0] > 0 Then $sCmd = "" For $nCmd = 1 To $CmdLine[0] $sCmd = $sCmd & " " & $CmdLine[$nCmd] Next; MsgBox (1,"",$sCmd) EndIf; AutoItSetOption("GUIDataSeparatorChar", Chr(13)+Chr(10))
$nForm = GUICreate($sTitRun, $nWidth, $nHeight) GUISetOnEvent($GUI_EVENT_CLOSE, "CloseForm")
$nList = GUICtrlCreateList ("", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL) GUICtrlSetFont (-1, 9, 0, 0, "Courier New")
$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30) GUICtrlSetOnEvent (-1, "CloseForm")
GUISetState(@SW_SHOW);, $nForm)
$nPID = Run(@ComSpec & " /C " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD); $nPID = Run(@ComSpec & " /C _RunErrl.bat " & $sCmd, ".", @SW_HIDE, $STDOUT_CHILD); # Con ésto devuelve el errorlevel en _ERRL.TMP
While 1 $sLine = StdoutRead($nPID) If @error Then ExitLoop
If StringLen ($sLine) > 0 then $sLine = StringReplace ($sLine, Chr(13), "|") $sLine = StringReplace ($sLine, Chr(10), "") if StringLeft($sLine, 1)="|" Then $sLine = " " & $sLine endif
GUICtrlSetData ($nList, $sLine)
_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1) EndIf Wend
$sLine = " ||" GUICtrlSetData ($nList, $sLine) _GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)
GUICtrlSetData ($nClose, $sButDone)
WinSetTitle ($sTitRun, "", $sTitDone) If $sSound <> "" Then SoundPlay ($sSound) EndIf
$rInfo = DllStructCreate("uint;dword"); # LASTINPUTINFO DllStructSetData($rInfo, 1, DllStructGetSize($rInfo));
DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo)) $nLastInput = DllStructGetData($rInfo, 2)
$nTime = TimerInit()
While 1 If $nAutoTimeout > 0 Then DllCall("user32.dll", "int", "GetLastInputInfo", "ptr", DllStructGetPtr($rInfo)) If DllStructGetData($rInfo, 2) <> $nLastInput Then; Tocó una tecla $nAutoTimeout = 0 EndIf EndIf
If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then ExitLoop EndIf
Sleep (100) Wend
Func CloseForm() Exit EndFunc | [
"windows",
"user-interface",
"rsync"
] | 5 | 2 | 6,125 | 5 | 0 | 2008-08-11T17:43:50.277000 | 2008-08-11T18:55:33.753000 |
8,042 | 38,494 | Extension interface patterns | The new extensions in.Net 3.5 allow functionality to be split out from interfaces. For instance in.Net 2.0 public interface IHaveChildren { string ParentType { get; } int ParentId { get; }
List GetChildren() } Can (in 3.5) become: public interface IHaveChildren { string ParentType { get; } int ParentId { get; } }
public static class HaveChildrenExtension { public static List GetChildren( this IHaveChildren ) { //logic to get children by parent type and id //shared for all classes implementing IHaveChildren } } This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test. The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?) Any other reasons not to regularly use this pattern? Clarification: Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on.Net value types without a great deal of peer review (I think the only one we have on a string is a.SplitToDictionary() - similar to.Split() but taking a key-value delimiter too) I think there's a whole best practice debate there;-) (Incidentally: DannySmurf, your PM sounds scary.) I'm specifically asking here about using extension methods where previously we had interface methods. I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies. Is this what MS has done to IEnumerable and IQueryable for Linq? | I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes. Versioning. One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface. As a concrete example, the first version of a library might define an interface like so: public interface INode { INode Root { get; } List GetChildren( ); } Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty: public interface IChildNode: INode { INode Parent { get; } } However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely: public static class NodeExtensions { public INode GetParent( this INode node ) { // If the node implements the new interface, call it directly. var childNode = node as IChildNode; if(!object.ReferenceEquals( childNode, null ) ) return childNode.Parent;
// Otherwise, fall back on a default implementation. return FindParent( node, node.Root ); } } Now all users of the new library can treat both legacy and modern implementations identically. Overloads. Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method. Instead extension methods can be used to provide the trivial overload implementations: public interface ILongMethod { public bool LongMethod( string s, double d, int i, object o,... ); }... public static LongMethodExtensions { public bool LongMethod( this ILongMethod lm, string s, double d ) { lm.LongMethod( s, d, 0, null ); }... } Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack:) Edit: A related post by Joe Duffy: Extension methods as default interface method implementations | Extension interface patterns The new extensions in.Net 3.5 allow functionality to be split out from interfaces. For instance in.Net 2.0 public interface IHaveChildren { string ParentType { get; } int ParentId { get; }
List GetChildren() } Can (in 3.5) become: public interface IHaveChildren { string ParentType { get; } int ParentId { get; } }
public static class HaveChildrenExtension { public static List GetChildren( this IHaveChildren ) { //logic to get children by parent type and id //shared for all classes implementing IHaveChildren } } This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test. The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?) Any other reasons not to regularly use this pattern? Clarification: Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on.Net value types without a great deal of peer review (I think the only one we have on a string is a.SplitToDictionary() - similar to.Split() but taking a key-value delimiter too) I think there's a whole best practice debate there;-) (Incidentally: DannySmurf, your PM sounds scary.) I'm specifically asking here about using extension methods where previously we had interface methods. I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies. Is this what MS has done to IEnumerable and IQueryable for Linq? | TITLE:
Extension interface patterns
QUESTION:
The new extensions in.Net 3.5 allow functionality to be split out from interfaces. For instance in.Net 2.0 public interface IHaveChildren { string ParentType { get; } int ParentId { get; }
List GetChildren() } Can (in 3.5) become: public interface IHaveChildren { string ParentType { get; } int ParentId { get; } }
public static class HaveChildrenExtension { public static List GetChildren( this IHaveChildren ) { //logic to get children by parent type and id //shared for all classes implementing IHaveChildren } } This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test. The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?) Any other reasons not to regularly use this pattern? Clarification: Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on.Net value types without a great deal of peer review (I think the only one we have on a string is a.SplitToDictionary() - similar to.Split() but taking a key-value delimiter too) I think there's a whole best practice debate there;-) (Incidentally: DannySmurf, your PM sounds scary.) I'm specifically asking here about using extension methods where previously we had interface methods. I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies. Is this what MS has done to IEnumerable and IQueryable for Linq?
ANSWER:
I think the judicious use of extension methods put interfaces on a more equatable position with (abstract) base classes. Versioning. One advantage base classes have over interfaces is that you can easily add new virtual members in a later version, whereas adding members to an interface will break implementers built against the old version of the library. Instead, a new version of the interface with the new members needs to be created, and the library will have to work around or limit access to legacy objects only implementing the original interface. As a concrete example, the first version of a library might define an interface like so: public interface INode { INode Root { get; } List GetChildren( ); } Once the library has released, we cannot modify the interface without breaking current users. Instead, in the next release we would need to define a new interface to add additional functionalty: public interface IChildNode: INode { INode Parent { get; } } However, only users of the new library will be able to implement the new interface. In order to work with legacy code, we need to adapt the old implementation, which an extension method can handle nicely: public static class NodeExtensions { public INode GetParent( this INode node ) { // If the node implements the new interface, call it directly. var childNode = node as IChildNode; if(!object.ReferenceEquals( childNode, null ) ) return childNode.Parent;
// Otherwise, fall back on a default implementation. return FindParent( node, node.Root ); } } Now all users of the new library can treat both legacy and modern implementations identically. Overloads. Another area where extension methods can be useful is in providing overloads for interface methods. You might have a method with several parameters to control its action, of which only the first one or two are important in the 90% case. Since C# does not allow setting default values for parameters, users either have to call the fully parameterized method every time, or every implementation must implement the trivial overloads for the core method. Instead extension methods can be used to provide the trivial overload implementations: public interface ILongMethod { public bool LongMethod( string s, double d, int i, object o,... ); }... public static LongMethodExtensions { public bool LongMethod( this ILongMethod lm, string s, double d ) { lm.LongMethod( s, d, 0, null ); }... } Please note that both of these cases are written in terms of the operations provided by the interfaces, and involve trivial or well-known default implementations. That said, you can only inherit from a class once, and the targeted use of extension methods can provide a valuable way to deal with some of the niceties provided by base classes that interfaces lack:) Edit: A related post by Joe Duffy: Extension methods as default interface method implementations | [
"c#",
".net-3.5",
"extension-methods"
] | 25 | 9 | 15,866 | 11 | 0 | 2008-08-11T18:13:44.197000 | 2008-09-01T21:52:48.700000 |
8,066 | 8,086 | .NET Interfaces | Over the past few years I've changed from having a long flowing page of controls that I hid/showed to using a lot of user controls. I've always had a bit of a discussion between co-workers on best practices. Should you have properties that you populate, or use paramterized sub's to load the information in your controls? Part of my fear of using paramteter's is the fact that I cannot make sure that everything will be populated. What is the basic rule's for using interfaces? I've never created one. And should I try this, or stay with a 'sub load'? | I'm not sure if interfaces are going to help you a lot here. My understanding is that you are breaking a page down into set of "composite" user controls that contain other controls, and you want to decide whether to use properties for setting values. I guess this really depends on how the user controls are designed and whether they are being dynamically added to a page etc (one possible scenario). I have a personal preference for specifying stuff in a constructor or using a factory method to create controls. I assume responsibility at creation for making sure that everything is set. My experience with properties is that I'll sometimes forget to set something and not realize my mistake. Your point about setting properties or using a sub, and everything being populated doesn't make a lot of sense to me. If you have some sort of dependency and need something else to be loaded then this could happen irrespective of whether it's a property or sub. I would refer to any book on VB.NET/C#/OOP to see the syntax for interfaces. Interfaces basically describe a contract for a class. If you have class A and B and both implement an interface called ITime then both will provide all of the methods defined on ITime. They can still add their own methods but they must at minimum include an implementation of ITime's methods (eg. we might have GetDate(), GetCurrentTime() as methods on ITime). An interface doesn't tell class A or B how those methods should work - just their name, parameters and return type. Lookup inheritance in an OOP book for more information on how interfaces inheritance is different from implementation inheritance. | .NET Interfaces Over the past few years I've changed from having a long flowing page of controls that I hid/showed to using a lot of user controls. I've always had a bit of a discussion between co-workers on best practices. Should you have properties that you populate, or use paramterized sub's to load the information in your controls? Part of my fear of using paramteter's is the fact that I cannot make sure that everything will be populated. What is the basic rule's for using interfaces? I've never created one. And should I try this, or stay with a 'sub load'? | TITLE:
.NET Interfaces
QUESTION:
Over the past few years I've changed from having a long flowing page of controls that I hid/showed to using a lot of user controls. I've always had a bit of a discussion between co-workers on best practices. Should you have properties that you populate, or use paramterized sub's to load the information in your controls? Part of my fear of using paramteter's is the fact that I cannot make sure that everything will be populated. What is the basic rule's for using interfaces? I've never created one. And should I try this, or stay with a 'sub load'?
ANSWER:
I'm not sure if interfaces are going to help you a lot here. My understanding is that you are breaking a page down into set of "composite" user controls that contain other controls, and you want to decide whether to use properties for setting values. I guess this really depends on how the user controls are designed and whether they are being dynamically added to a page etc (one possible scenario). I have a personal preference for specifying stuff in a constructor or using a factory method to create controls. I assume responsibility at creation for making sure that everything is set. My experience with properties is that I'll sometimes forget to set something and not realize my mistake. Your point about setting properties or using a sub, and everything being populated doesn't make a lot of sense to me. If you have some sort of dependency and need something else to be loaded then this could happen irrespective of whether it's a property or sub. I would refer to any book on VB.NET/C#/OOP to see the syntax for interfaces. Interfaces basically describe a contract for a class. If you have class A and B and both implement an interface called ITime then both will provide all of the methods defined on ITime. They can still add their own methods but they must at minimum include an implementation of ITime's methods (eg. we might have GetDate(), GetCurrentTime() as methods on ITime). An interface doesn't tell class A or B how those methods should work - just their name, parameters and return type. Lookup inheritance in an OOP book for more information on how interfaces inheritance is different from implementation inheritance. | [
".net",
"user-controls",
"interface"
] | 0 | 1 | 826 | 1 | 0 | 2008-08-11T18:30:44.893000 | 2008-08-11T18:50:28.770000 |
8,107 | 8,115 | MySQL replication for fallback scenario | When I have two mysql servers that have different jobs (holding different databases) but want to be able to use one of them to slip in when the other one fails, what would you suggest how I keep the data on both of them equal "close to realtime"? Obviously it's not possible to make a full database dump every x minutes. I've read about the Binary Log, is that the way that I need to go? Will that not slow down the fallback server a lot? Is there a way to not include some tables in the binary log - where it doesn't matter that the data has changed? | Binary log is definitely the way to go. However, you should be aware that with MySQL you can't just flip back and forth between servers like that. One server will be the master and the other will be the slave. You write/read to the master, but can only read from the slave server. If you ever write to the slave, they'll be out of sync and there's no easy way to get them to sync up again (basically, you have to swap them so the master is the new slave, but this is a tedious manual process). If you need true hot-swappable backup databases you might have to go to a system other than MySQL. If all you want is a read-only live backup that you can use instantly in the worst-case scenario (master is permanently destroyed), Binary Log will suit you just fine. | MySQL replication for fallback scenario When I have two mysql servers that have different jobs (holding different databases) but want to be able to use one of them to slip in when the other one fails, what would you suggest how I keep the data on both of them equal "close to realtime"? Obviously it's not possible to make a full database dump every x minutes. I've read about the Binary Log, is that the way that I need to go? Will that not slow down the fallback server a lot? Is there a way to not include some tables in the binary log - where it doesn't matter that the data has changed? | TITLE:
MySQL replication for fallback scenario
QUESTION:
When I have two mysql servers that have different jobs (holding different databases) but want to be able to use one of them to slip in when the other one fails, what would you suggest how I keep the data on both of them equal "close to realtime"? Obviously it's not possible to make a full database dump every x minutes. I've read about the Binary Log, is that the way that I need to go? Will that not slow down the fallback server a lot? Is there a way to not include some tables in the binary log - where it doesn't matter that the data has changed?
ANSWER:
Binary log is definitely the way to go. However, you should be aware that with MySQL you can't just flip back and forth between servers like that. One server will be the master and the other will be the slave. You write/read to the master, but can only read from the slave server. If you ever write to the slave, they'll be out of sync and there's no easy way to get them to sync up again (basically, you have to swap them so the master is the new slave, but this is a tedious manual process). If you need true hot-swappable backup databases you might have to go to a system other than MySQL. If all you want is a read-only live backup that you can use instantly in the worst-case scenario (master is permanently destroyed), Binary Log will suit you just fine. | [
"mysql",
"replication",
"fallback",
"binary-log"
] | 10 | 2 | 3,149 | 2 | 0 | 2008-08-11T19:12:33.920000 | 2008-08-11T19:22:13.060000 |
8,127 | 8,189 | Pre-build task - deleting the working copy in CruiseControl.NET | I'm currently in the process of setting up a continuous integration environment at work. We are using VisualSVN Server and CrusieControl.NET. Occasionally a build will fail and a symptom is that there are conflicts in the CruiseControl.NET working copy. I believe this is due to the way I've setup the Visual Studio solutions. Hopefully the more projects we run in this environment the better our understanding of how to set them up will be so I'm not questioning why the conflicts happen at this stage. To fix the builds I delete the working copy and force a new build - this works every time (currently). So my questions are: is deleting the working copy a valid part of a continuous integration build process, and how do I go about it? I've tried solutions including MSTask and calling delete from the command line but I'm not having any luck. Sorry for being so wordy - good job this is a beta:) | Doing a full delete before or after your build is good practice. This means that there is no chance of your build environment picking up an out of date file. Your building exactly against what is in the repository. Deleting the working copy is possible as I have done it with Nant. In Nant I would have a clean script in its own folder outwith the one I want to delete and would then invoke it from CC.net. I assume this should also be possible with a batch file. Take a look at the rmdir command http://www.computerhope.com/rmdirhlp.htm @pauldoo I prefer my CI server to do a full delete as I don't want any surprise when I go to do a release build, which should always be done from a clean state. But it should be able to handle both, no reason why not | Pre-build task - deleting the working copy in CruiseControl.NET I'm currently in the process of setting up a continuous integration environment at work. We are using VisualSVN Server and CrusieControl.NET. Occasionally a build will fail and a symptom is that there are conflicts in the CruiseControl.NET working copy. I believe this is due to the way I've setup the Visual Studio solutions. Hopefully the more projects we run in this environment the better our understanding of how to set them up will be so I'm not questioning why the conflicts happen at this stage. To fix the builds I delete the working copy and force a new build - this works every time (currently). So my questions are: is deleting the working copy a valid part of a continuous integration build process, and how do I go about it? I've tried solutions including MSTask and calling delete from the command line but I'm not having any luck. Sorry for being so wordy - good job this is a beta:) | TITLE:
Pre-build task - deleting the working copy in CruiseControl.NET
QUESTION:
I'm currently in the process of setting up a continuous integration environment at work. We are using VisualSVN Server and CrusieControl.NET. Occasionally a build will fail and a symptom is that there are conflicts in the CruiseControl.NET working copy. I believe this is due to the way I've setup the Visual Studio solutions. Hopefully the more projects we run in this environment the better our understanding of how to set them up will be so I'm not questioning why the conflicts happen at this stage. To fix the builds I delete the working copy and force a new build - this works every time (currently). So my questions are: is deleting the working copy a valid part of a continuous integration build process, and how do I go about it? I've tried solutions including MSTask and calling delete from the command line but I'm not having any luck. Sorry for being so wordy - good job this is a beta:)
ANSWER:
Doing a full delete before or after your build is good practice. This means that there is no chance of your build environment picking up an out of date file. Your building exactly against what is in the repository. Deleting the working copy is possible as I have done it with Nant. In Nant I would have a clean script in its own folder outwith the one I want to delete and would then invoke it from CC.net. I assume this should also be possible with a batch file. Take a look at the rmdir command http://www.computerhope.com/rmdirhlp.htm @pauldoo I prefer my CI server to do a full delete as I don't want any surprise when I go to do a release build, which should always be done from a clean state. But it should be able to handle both, no reason why not | [
"visual-studio",
"continuous-integration",
"cruisecontrol.net",
"visualsvn-server"
] | 8 | 10 | 6,094 | 5 | 0 | 2008-08-11T19:36:47.630000 | 2008-08-11T20:27:11.603000 |
8,128 | 8,130 | How do I calculate CRC32 of a string | How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in.NET? | This guy seems to have your answer. https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net And in case the blog ever goes away or breaks the url, here's the github link: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs Usage of the Crc32 class from the blog post: Crc32 crc32 = new Crc32(); String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open)) foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash); | How do I calculate CRC32 of a string How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in.NET? | TITLE:
How do I calculate CRC32 of a string
QUESTION:
How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in.NET?
ANSWER:
This guy seems to have your answer. https://damieng.com/blog/2006/08/08/calculating_crc32_in_c_and_net And in case the blog ever goes away or breaks the url, here's the github link: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/Security/Cryptography/Crc32.cs Usage of the Crc32 class from the blog post: Crc32 crc32 = new Crc32(); String hash = String.Empty;
using (FileStream fs = File.Open("c:\\myfile.txt", FileMode.Open)) foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString("x2").ToLower();
Console.WriteLine("CRC-32 is {0}", hash); | [
".net",
"crc32"
] | 53 | 43 | 115,804 | 4 | 0 | 2008-08-11T19:41:20.320000 | 2008-08-11T19:43:31.003000 |
8,140 | 8,157 | Suggestions for Adding Plugin Capability? | Is there a general procedure for programming extensibility capability into your code? I am wondering what the general procedure is for adding extension-type capability to a system you are writing so that functionality can be extended through some kind of plugin API rather than having to modify the core code of a system. Do such things tend to be dependent on the language the system was written in, or is there a general method for allowing for this? | This is generally something that you'll have to expose yourself, so yes, it will be dependent on the language your system is written in (though often it's possible to write wrappers for other languages as well). If, for example, you had a program written in C, for Windows, plugins would be written for your program as DLLs. At runtime, you would manually load these DLLs, and expose some interface to them. For example, the DLLs might expose a gimme_the_interface() function which could accept a structure filled with function pointers. These function pointers would allow the DLL to make calls, register callbacks, etc. If you were in C++, you would use the DLL system, except you would probably pass an object pointer instead of a struct, and the object would implement an interface which provided functionality (accomplishing the same thing as the struct, but less ugly). For Java, you would load class files on-demand instead of DLLs, but the basic idea would be the same. In all cases, you'll need to define a standard interface between your code and the plugins, so that you can initialize the plugins, and so the plugins can interact with you. P.S. If you'd like to see a good example of a C++ plugin system, check out the foobar2000 SDK. I haven't used it in quite a while, but it used to be really well done. I assume it still is. | Suggestions for Adding Plugin Capability? Is there a general procedure for programming extensibility capability into your code? I am wondering what the general procedure is for adding extension-type capability to a system you are writing so that functionality can be extended through some kind of plugin API rather than having to modify the core code of a system. Do such things tend to be dependent on the language the system was written in, or is there a general method for allowing for this? | TITLE:
Suggestions for Adding Plugin Capability?
QUESTION:
Is there a general procedure for programming extensibility capability into your code? I am wondering what the general procedure is for adding extension-type capability to a system you are writing so that functionality can be extended through some kind of plugin API rather than having to modify the core code of a system. Do such things tend to be dependent on the language the system was written in, or is there a general method for allowing for this?
ANSWER:
This is generally something that you'll have to expose yourself, so yes, it will be dependent on the language your system is written in (though often it's possible to write wrappers for other languages as well). If, for example, you had a program written in C, for Windows, plugins would be written for your program as DLLs. At runtime, you would manually load these DLLs, and expose some interface to them. For example, the DLLs might expose a gimme_the_interface() function which could accept a structure filled with function pointers. These function pointers would allow the DLL to make calls, register callbacks, etc. If you were in C++, you would use the DLL system, except you would probably pass an object pointer instead of a struct, and the object would implement an interface which provided functionality (accomplishing the same thing as the struct, but less ugly). For Java, you would load class files on-demand instead of DLLs, but the basic idea would be the same. In all cases, you'll need to define a standard interface between your code and the plugins, so that you can initialize the plugins, and so the plugins can interact with you. P.S. If you'd like to see a good example of a C++ plugin system, check out the foobar2000 SDK. I haven't used it in quite a while, but it used to be really well done. I assume it still is. | [
"plugins",
"extensibility"
] | 16 | 3 | 3,289 | 6 | 0 | 2008-08-11T19:48:52.053000 | 2008-08-11T20:00:09.627000 |
8,142 | 8,152 | When should I use Compiled LINQ vs Normal LINQ | I just read up on a performance of LINQ, and there is a HUGE amount to be gained by using Compiled LINQ. Now, why won't I always use compiled LINQ? | Short answer: when it's only going to happen once in a long time. Long Answer. | When should I use Compiled LINQ vs Normal LINQ I just read up on a performance of LINQ, and there is a HUGE amount to be gained by using Compiled LINQ. Now, why won't I always use compiled LINQ? | TITLE:
When should I use Compiled LINQ vs Normal LINQ
QUESTION:
I just read up on a performance of LINQ, and there is a HUGE amount to be gained by using Compiled LINQ. Now, why won't I always use compiled LINQ?
ANSWER:
Short answer: when it's only going to happen once in a long time. Long Answer. | [
".net",
"linq-to-sql"
] | 5 | 4 | 1,649 | 2 | 0 | 2008-08-11T19:50:31.393000 | 2008-08-11T19:57:30.990000 |
8,145 | 8,161 | How do I find the high water mark (for sessions) on Oracle 9i | How can I find the high water mark (the historical maximum number of concurrent users) in an oracle database (9i). | This should do the trick: SELECT sessions_highwater FROM v$license; | How do I find the high water mark (for sessions) on Oracle 9i How can I find the high water mark (the historical maximum number of concurrent users) in an oracle database (9i). | TITLE:
How do I find the high water mark (for sessions) on Oracle 9i
QUESTION:
How can I find the high water mark (the historical maximum number of concurrent users) in an oracle database (9i).
ANSWER:
This should do the trick: SELECT sessions_highwater FROM v$license; | [
"sql",
"oracle",
"session",
"oracle9i"
] | 7 | 5 | 11,362 | 2 | 0 | 2008-08-11T19:53:16.443000 | 2008-08-11T20:05:44.377000 |
8,147 | 8,289 | How do you get a custom id to render using HtmlHelper in MVC | Using preview 4 of ASP.NET MVC Code like: <%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %> only outputs: There is a name there for the form post back but no id for javascript or labels:-( I was hoping that changing it to: Html.CheckBox( "myCheckBox", "Click Here", "True", false, new { id="myCheckBox" } ) would work - but instead I get an exception: System.ArgumentException: An item with the same key has already been added. As if there was already an id somewhere in a collection somewhere - I'm stumped! The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here): System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Web.Routing.RouteValueDictionary.Add(String key, Object value) at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes) at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108 | Try this: <%= Html.CheckBox("myCheckbox", "Click here", "True", false, new {_id ="test" })%> For any keyword you can use an underscore before the name of the attribute. Instead of class you use _class. Since class is a keyword in C#, and also the name of the attribute in HTML. Now, "id" isn't a keyword in C#, but perhaps it is in another.NET language that they want to support. From what I can tell, it's not a keyword in VB.NET, F#, or Ruby so maybe it is a mistake that they force you to use an underscore with it. | How do you get a custom id to render using HtmlHelper in MVC Using preview 4 of ASP.NET MVC Code like: <%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %> only outputs: There is a name there for the form post back but no id for javascript or labels:-( I was hoping that changing it to: Html.CheckBox( "myCheckBox", "Click Here", "True", false, new { id="myCheckBox" } ) would work - but instead I get an exception: System.ArgumentException: An item with the same key has already been added. As if there was already an id somewhere in a collection somewhere - I'm stumped! The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here): System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Web.Routing.RouteValueDictionary.Add(String key, Object value) at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes) at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108 | TITLE:
How do you get a custom id to render using HtmlHelper in MVC
QUESTION:
Using preview 4 of ASP.NET MVC Code like: <%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %> only outputs: There is a name there for the form post back but no id for javascript or labels:-( I was hoping that changing it to: Html.CheckBox( "myCheckBox", "Click Here", "True", false, new { id="myCheckBox" } ) would work - but instead I get an exception: System.ArgumentException: An item with the same key has already been added. As if there was already an id somewhere in a collection somewhere - I'm stumped! The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here): System.ArgumentException: An item with the same key has already been added. at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource) at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add) at System.Web.Routing.RouteValueDictionary.Add(String key, Object value) at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes) at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes) at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108
ANSWER:
Try this: <%= Html.CheckBox("myCheckbox", "Click here", "True", false, new {_id ="test" })%> For any keyword you can use an underscore before the name of the attribute. Instead of class you use _class. Since class is a keyword in C#, and also the name of the attribute in HTML. Now, "id" isn't a keyword in C#, but perhaps it is in another.NET language that they want to support. From what I can tell, it's not a keyword in VB.NET, F#, or Ruby so maybe it is a mistake that they force you to use an underscore with it. | [
"asp.net-mvc",
"html-helper"
] | 6 | 5 | 3,405 | 2 | 0 | 2008-08-11T19:54:20.687000 | 2008-08-11T22:26:29.177000 |
8,154 | 46,442 | Pylons error - 'MySQL server has gone away' | I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: (2006, 'MySQL server has gone away') I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the sqlalchemy.pool_recycle in the config file should automatically keep it alive. The default was 3600, but I dialed it back to 1800 because of this problem. It helped a bit, but 3600 should be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database:). Maybe something in my MySQL config is goofy? Not sure where to look exactly. Other relevant details: Python 2.5 Pylons: 0.9.6.2 (w/ sql_alchemy) MySQL: 5.0.51 | I think I fixed it. It's turns out I had a simple config error. My ini file read: sqlalchemy.default.url = [connection string here] sqlalchemy.pool_recycle = 1800 The problem is that my environment.py file declared that the engine would only map keys with the prefix: sqlalchemy.default so pool_recycle was ignored. The solution is to simply change the second line in the ini to: sqlalchemy.default.pool_recycle = 1800 | Pylons error - 'MySQL server has gone away' I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: (2006, 'MySQL server has gone away') I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the sqlalchemy.pool_recycle in the config file should automatically keep it alive. The default was 3600, but I dialed it back to 1800 because of this problem. It helped a bit, but 3600 should be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database:). Maybe something in my MySQL config is goofy? Not sure where to look exactly. Other relevant details: Python 2.5 Pylons: 0.9.6.2 (w/ sql_alchemy) MySQL: 5.0.51 | TITLE:
Pylons error - 'MySQL server has gone away'
QUESTION:
I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: (2006, 'MySQL server has gone away') I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the sqlalchemy.pool_recycle in the config file should automatically keep it alive. The default was 3600, but I dialed it back to 1800 because of this problem. It helped a bit, but 3600 should be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database:). Maybe something in my MySQL config is goofy? Not sure where to look exactly. Other relevant details: Python 2.5 Pylons: 0.9.6.2 (w/ sql_alchemy) MySQL: 5.0.51
ANSWER:
I think I fixed it. It's turns out I had a simple config error. My ini file read: sqlalchemy.default.url = [connection string here] sqlalchemy.pool_recycle = 1800 The problem is that my environment.py file declared that the engine would only map keys with the prefix: sqlalchemy.default so pool_recycle was ignored. The solution is to simply change the second line in the ini to: sqlalchemy.default.pool_recycle = 1800 | [
"python",
"mysql",
"pylons"
] | 16 | 8 | 3,760 | 2 | 0 | 2008-08-11T19:59:32.670000 | 2008-09-05T18:07:50.310000 |
8,166 | 8,184 | MySQL replication: if I don't specify any databases, will log_bin log EVERYTHING? | I'm setting up replication for a server which runs a bunch of databases (one per client) and plan on adding more all the time, on my.cnf, Instead of having: binlog-do-db = databasename 1 binlog-do-db = databasename 2 binlog-do-db = databasename 3... binlog-do-db = databasename n can I rather just have binlog-ignore-db = mysql binlog-ignore-db = informationschema (and no database to log specified) and assume that everything else is logged? EDIT: actually if I remove all my binlog-do-db entries, it seemingly logs everything (as you see the binary log file change position when you move the database), but on the slave server, nothing gets picked up! (perhaps, this is the case to use replicate-do-db? this would kill the idea; i guess I cant have MySQL automagically detect which databases to replicate). | That looks correct: http://dev.mysql.com/doc/refman/5.0/en/binary-log.html#option_mysqld_binlog-ignore-db. According to that reference: There are some --binlog-ignore-db rules. Does the default database match any of the --binlog-ignore-db rules? Yes: Do not write the statement, and exit. No: Write the query and exit. Since you only have ignore commands, all queries will be written to the log as long as the default (active) database doesn't match one of the ignored databases. | MySQL replication: if I don't specify any databases, will log_bin log EVERYTHING? I'm setting up replication for a server which runs a bunch of databases (one per client) and plan on adding more all the time, on my.cnf, Instead of having: binlog-do-db = databasename 1 binlog-do-db = databasename 2 binlog-do-db = databasename 3... binlog-do-db = databasename n can I rather just have binlog-ignore-db = mysql binlog-ignore-db = informationschema (and no database to log specified) and assume that everything else is logged? EDIT: actually if I remove all my binlog-do-db entries, it seemingly logs everything (as you see the binary log file change position when you move the database), but on the slave server, nothing gets picked up! (perhaps, this is the case to use replicate-do-db? this would kill the idea; i guess I cant have MySQL automagically detect which databases to replicate). | TITLE:
MySQL replication: if I don't specify any databases, will log_bin log EVERYTHING?
QUESTION:
I'm setting up replication for a server which runs a bunch of databases (one per client) and plan on adding more all the time, on my.cnf, Instead of having: binlog-do-db = databasename 1 binlog-do-db = databasename 2 binlog-do-db = databasename 3... binlog-do-db = databasename n can I rather just have binlog-ignore-db = mysql binlog-ignore-db = informationschema (and no database to log specified) and assume that everything else is logged? EDIT: actually if I remove all my binlog-do-db entries, it seemingly logs everything (as you see the binary log file change position when you move the database), but on the slave server, nothing gets picked up! (perhaps, this is the case to use replicate-do-db? this would kill the idea; i guess I cant have MySQL automagically detect which databases to replicate).
ANSWER:
That looks correct: http://dev.mysql.com/doc/refman/5.0/en/binary-log.html#option_mysqld_binlog-ignore-db. According to that reference: There are some --binlog-ignore-db rules. Does the default database match any of the --binlog-ignore-db rules? Yes: Do not write the statement, and exit. No: Write the query and exit. Since you only have ignore commands, all queries will be written to the log as long as the default (active) database doesn't match one of the ignored databases. | [
"mysql",
"replication"
] | 21 | 12 | 17,119 | 1 | 0 | 2008-08-11T20:08:03.310000 | 2008-08-11T20:22:24.730000 |
8,213 | 8,220 | Generate insert SQL statements from a CSV file | I need to import a csv file into Firebird and I've spent a couple of hours trying out some tools and none fit my needs. The main problem is that all the tools I've been trying like EMS Data Import and Firebird Data Wizard expect that my CSV file contains all the information needed by my Table. I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS. My insert statement would be something like this: INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID),:NAME, (SELECT CITY_ID FROM CITY WHERE NAME =:CITY_NAME) How can I approach this? | It's a bit crude - but for one off jobs, I sometimes use Excel. If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like... ="INSERT INTO MyTable (Col1, Col2, Col3) VALUES (" & A1 & ", " & B1 & ", " & C1 & ")" Then you can replicate the formula down all of your rows, and copy, and paste the answer into a text file to run against your database. Like I say - it's crude - but it can be quite a 'quick and dirty' way of getting a job done! | Generate insert SQL statements from a CSV file I need to import a csv file into Firebird and I've spent a couple of hours trying out some tools and none fit my needs. The main problem is that all the tools I've been trying like EMS Data Import and Firebird Data Wizard expect that my CSV file contains all the information needed by my Table. I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS. My insert statement would be something like this: INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID),:NAME, (SELECT CITY_ID FROM CITY WHERE NAME =:CITY_NAME) How can I approach this? | TITLE:
Generate insert SQL statements from a CSV file
QUESTION:
I need to import a csv file into Firebird and I've spent a couple of hours trying out some tools and none fit my needs. The main problem is that all the tools I've been trying like EMS Data Import and Firebird Data Wizard expect that my CSV file contains all the information needed by my Table. I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS. My insert statement would be something like this: INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID),:NAME, (SELECT CITY_ID FROM CITY WHERE NAME =:CITY_NAME) How can I approach this?
ANSWER:
It's a bit crude - but for one off jobs, I sometimes use Excel. If you import the CSV file into Excel, you can create a formula which creates an INSERT statement by using string concatenation in the formula. So - if your CSV file has 3 columns that appear in columns A, B, and C in Excel, you could write a formula like... ="INSERT INTO MyTable (Col1, Col2, Col3) VALUES (" & A1 & ", " & B1 & ", " & C1 & ")" Then you can replicate the formula down all of your rows, and copy, and paste the answer into a text file to run against your database. Like I say - it's crude - but it can be quite a 'quick and dirty' way of getting a job done! | [
"sql",
"csv",
"insert",
"firebird"
] | 64 | 130 | 124,433 | 12 | 0 | 2008-08-11T20:59:11.973000 | 2008-08-11T21:07:51.287000 |
8,214 | 31,514 | Instrumenting a UI | How are you instrumenting your UI's? In the past I've read that people have instrumented their user interfaces, but what I haven't found is examples or tips on how to instrument a UI. By instrumenting, I mean collecting data regarding usage and performance of the system. A MSDN article on Instrumentation is http://msdn.microsoft.com/en-us/library/x5952w0c.aspx. I would like to capture which buttons users click on, what keyboard shortucts they use, what terms they use to search, etc. How are you instrumenting your UI? What format are you storing the instrumentation? How are you processing the instrumented data? How are you keeping your UI code clean with this instrumentation logic? Specifically, I am implementing my UI in WPF, so this will provide extra challenges compared to instrumenting a web-based application. (i.e. need to transfer the instrumented data back to a central location, etc). That said, I feel the technology may provide an easier implementation of instrumentation via concepts like attached properties. Have you instrumented a WPF application? Do you have any tips on how this can be achieved? Edit: The following blog post presents an interesting solution: Pixel-In-Gene Blog: Techniques for UI Auditing on WPF apps | The following blog post gives quite a few good ideas for instrumenting a WPF application: Techniques for UI Auditing on WPF apps. | Instrumenting a UI How are you instrumenting your UI's? In the past I've read that people have instrumented their user interfaces, but what I haven't found is examples or tips on how to instrument a UI. By instrumenting, I mean collecting data regarding usage and performance of the system. A MSDN article on Instrumentation is http://msdn.microsoft.com/en-us/library/x5952w0c.aspx. I would like to capture which buttons users click on, what keyboard shortucts they use, what terms they use to search, etc. How are you instrumenting your UI? What format are you storing the instrumentation? How are you processing the instrumented data? How are you keeping your UI code clean with this instrumentation logic? Specifically, I am implementing my UI in WPF, so this will provide extra challenges compared to instrumenting a web-based application. (i.e. need to transfer the instrumented data back to a central location, etc). That said, I feel the technology may provide an easier implementation of instrumentation via concepts like attached properties. Have you instrumented a WPF application? Do you have any tips on how this can be achieved? Edit: The following blog post presents an interesting solution: Pixel-In-Gene Blog: Techniques for UI Auditing on WPF apps | TITLE:
Instrumenting a UI
QUESTION:
How are you instrumenting your UI's? In the past I've read that people have instrumented their user interfaces, but what I haven't found is examples or tips on how to instrument a UI. By instrumenting, I mean collecting data regarding usage and performance of the system. A MSDN article on Instrumentation is http://msdn.microsoft.com/en-us/library/x5952w0c.aspx. I would like to capture which buttons users click on, what keyboard shortucts they use, what terms they use to search, etc. How are you instrumenting your UI? What format are you storing the instrumentation? How are you processing the instrumented data? How are you keeping your UI code clean with this instrumentation logic? Specifically, I am implementing my UI in WPF, so this will provide extra challenges compared to instrumenting a web-based application. (i.e. need to transfer the instrumented data back to a central location, etc). That said, I feel the technology may provide an easier implementation of instrumentation via concepts like attached properties. Have you instrumented a WPF application? Do you have any tips on how this can be achieved? Edit: The following blog post presents an interesting solution: Pixel-In-Gene Blog: Techniques for UI Auditing on WPF apps
ANSWER:
The following blog post gives quite a few good ideas for instrumenting a WPF application: Techniques for UI Auditing on WPF apps. | [
"wpf",
"user-interface",
"instrumentation"
] | 8 | 3 | 2,821 | 7 | 0 | 2008-08-11T21:00:40.520000 | 2008-08-28T02:08:26.253000 |
8,219 | 8,226 | Test Distribution | At my work we are running a group of tests that consist of about 3,000 separate test cases. Previously we were running this entire test suite on one machine, which took about 24-72 hours to complete the entire test run. We now have created our own system for grouping and distributing the tests among about three separate machines and the tests are prioritized so that the core tests get run first for more immediate results and the extra tests run when there is an available machine. I am curious if anyone has found a good way to distribute their tests among several machines to reduce total test time for a complete run and what tools were used to achieve that. I've done some research and it looks like TestNG is moving in this direction, but it looks like it is still under quite a bit of development. We don't plan on rewriting any of our tests, but as we add new tests and test new products or add-ons I'd like to be able to deal with the fact that we are working with very large numbers of tests. On the other hand, if we can find a tool that would help distribute our Junit 3.x tests even in a very basic fashion, that would be helpful since we wouldn't have to maintain our own tooling to do that. | I've seen some people having a play with distributed JUnit. I can't particularly vouch for how effective it is, but the other teams I've seen seemed to think it was straight forward enough. Hope that helps. | Test Distribution At my work we are running a group of tests that consist of about 3,000 separate test cases. Previously we were running this entire test suite on one machine, which took about 24-72 hours to complete the entire test run. We now have created our own system for grouping and distributing the tests among about three separate machines and the tests are prioritized so that the core tests get run first for more immediate results and the extra tests run when there is an available machine. I am curious if anyone has found a good way to distribute their tests among several machines to reduce total test time for a complete run and what tools were used to achieve that. I've done some research and it looks like TestNG is moving in this direction, but it looks like it is still under quite a bit of development. We don't plan on rewriting any of our tests, but as we add new tests and test new products or add-ons I'd like to be able to deal with the fact that we are working with very large numbers of tests. On the other hand, if we can find a tool that would help distribute our Junit 3.x tests even in a very basic fashion, that would be helpful since we wouldn't have to maintain our own tooling to do that. | TITLE:
Test Distribution
QUESTION:
At my work we are running a group of tests that consist of about 3,000 separate test cases. Previously we were running this entire test suite on one machine, which took about 24-72 hours to complete the entire test run. We now have created our own system for grouping and distributing the tests among about three separate machines and the tests are prioritized so that the core tests get run first for more immediate results and the extra tests run when there is an available machine. I am curious if anyone has found a good way to distribute their tests among several machines to reduce total test time for a complete run and what tools were used to achieve that. I've done some research and it looks like TestNG is moving in this direction, but it looks like it is still under quite a bit of development. We don't plan on rewriting any of our tests, but as we add new tests and test new products or add-ons I'd like to be able to deal with the fact that we are working with very large numbers of tests. On the other hand, if we can find a tool that would help distribute our Junit 3.x tests even in a very basic fashion, that would be helpful since we wouldn't have to maintain our own tooling to do that.
ANSWER:
I've seen some people having a play with distributed JUnit. I can't particularly vouch for how effective it is, but the other teams I've seen seemed to think it was straight forward enough. Hope that helps. | [
"java",
"testing",
"enterprise"
] | 10 | 3 | 879 | 3 | 0 | 2008-08-11T21:07:44.687000 | 2008-08-11T21:13:06.813000 |
8,223 | 8,232 | Connection Pooling in .NET/SQL Server? | Is it necessary or advantageous to write custom connection pooling code when developing applications in.NET with an SQL Server database? I know that ADO.NET gives you the option to enable/disable connection pooling -- does that mean that it's built into the framework and I don't need to worry about it? Why do people talk about writing their own connection pooling software and how is this different than what's built into ADO.NET? | The connection pooling built-in to ADO.Net is robust and mature. I would recommend against attempting to write your own version. | Connection Pooling in .NET/SQL Server? Is it necessary or advantageous to write custom connection pooling code when developing applications in.NET with an SQL Server database? I know that ADO.NET gives you the option to enable/disable connection pooling -- does that mean that it's built into the framework and I don't need to worry about it? Why do people talk about writing their own connection pooling software and how is this different than what's built into ADO.NET? | TITLE:
Connection Pooling in .NET/SQL Server?
QUESTION:
Is it necessary or advantageous to write custom connection pooling code when developing applications in.NET with an SQL Server database? I know that ADO.NET gives you the option to enable/disable connection pooling -- does that mean that it's built into the framework and I don't need to worry about it? Why do people talk about writing their own connection pooling software and how is this different than what's built into ADO.NET?
ANSWER:
The connection pooling built-in to ADO.Net is robust and mature. I would recommend against attempting to write your own version. | [
"c#",
".net",
"sql-server",
"connection-pooling"
] | 11 | 15 | 4,174 | 5 | 0 | 2008-08-11T21:10:32.903000 | 2008-08-11T21:14:40.303000 |
8,228 | 8,900 | Why won't Entourage work with Exchange 2007? | So this is IT more than programming but Google found nothing, and you guys are just the right kind of geniuses. My Exchange Server 2007 and Entourage clients don't play nice. Right now the big issue is that the entourage client will not connect to Exchange 2007 ( Entourage 2004 or 2008) The account settings are correct and use the proper format of https://exchange2007.mydomain.com/exchange/user@domain.com The issue is with a dll called davex.dll when it is where it belongs, the OWA application pool crashes a whole bunch of nasty things happen. When it isn’t there, I can connect to everything fine - and the OWA app pool doesn’t crash - but Entourage never propogates the folders in the mailbox and doesn't send or receive. Any help or ideas would be appreciated: Microsoft support is silent on the issue, and Google doesn't turn up much. | Try it without using the /exchange in the server properties field. Here's a link with relevant info. | Why won't Entourage work with Exchange 2007? So this is IT more than programming but Google found nothing, and you guys are just the right kind of geniuses. My Exchange Server 2007 and Entourage clients don't play nice. Right now the big issue is that the entourage client will not connect to Exchange 2007 ( Entourage 2004 or 2008) The account settings are correct and use the proper format of https://exchange2007.mydomain.com/exchange/user@domain.com The issue is with a dll called davex.dll when it is where it belongs, the OWA application pool crashes a whole bunch of nasty things happen. When it isn’t there, I can connect to everything fine - and the OWA app pool doesn’t crash - but Entourage never propogates the folders in the mailbox and doesn't send or receive. Any help or ideas would be appreciated: Microsoft support is silent on the issue, and Google doesn't turn up much. | TITLE:
Why won't Entourage work with Exchange 2007?
QUESTION:
So this is IT more than programming but Google found nothing, and you guys are just the right kind of geniuses. My Exchange Server 2007 and Entourage clients don't play nice. Right now the big issue is that the entourage client will not connect to Exchange 2007 ( Entourage 2004 or 2008) The account settings are correct and use the proper format of https://exchange2007.mydomain.com/exchange/user@domain.com The issue is with a dll called davex.dll when it is where it belongs, the OWA application pool crashes a whole bunch of nasty things happen. When it isn’t there, I can connect to everything fine - and the OWA app pool doesn’t crash - but Entourage never propogates the folders in the mailbox and doesn't send or receive. Any help or ideas would be appreciated: Microsoft support is silent on the issue, and Google doesn't turn up much.
ANSWER:
Try it without using the /exchange in the server properties field. Here's a link with relevant info. | [
"email",
"dll",
"exchange-server",
"entourage"
] | 4 | 2 | 1,456 | 2 | 0 | 2008-08-11T21:13:59.340000 | 2008-08-12T14:40:45.060000 |
8,236 | 8,384 | How do you determine the size of a file in C? | How can I figure out the size of a file, in bytes? #include unsigned int fsize(char* file){ //what goes here? } | On Unix-like systems, you can use POSIX system calls: stat on a path, or fstat on an already-open file descriptor (POSIX man page, Linux man page ). (Get a file descriptor from open(2), or fileno(FILE*) on a stdio stream). Based on NilObject's code: #include #include off_t fsize(const char *filename) { struct stat st;
if (stat(filename, &st) == 0) return st.st_size;
return -1; } Changes: Made the filename argument a const char. Corrected the struct stat definition, which was missing the variable name. Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible. If you want fsize() to print a message on error, you can use this: #include #include #include #include #include off_t fsize(const char *filename) { struct stat st;
if (stat(filename, &st) == 0) return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n", filename, strerror(errno));
return -1; } On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details. | How do you determine the size of a file in C? How can I figure out the size of a file, in bytes? #include unsigned int fsize(char* file){ //what goes here? } | TITLE:
How do you determine the size of a file in C?
QUESTION:
How can I figure out the size of a file, in bytes? #include unsigned int fsize(char* file){ //what goes here? }
ANSWER:
On Unix-like systems, you can use POSIX system calls: stat on a path, or fstat on an already-open file descriptor (POSIX man page, Linux man page ). (Get a file descriptor from open(2), or fileno(FILE*) on a stdio stream). Based on NilObject's code: #include #include off_t fsize(const char *filename) { struct stat st;
if (stat(filename, &st) == 0) return st.st_size;
return -1; } Changes: Made the filename argument a const char. Corrected the struct stat definition, which was missing the variable name. Returns -1 on error instead of 0, which would be ambiguous for an empty file. off_t is a signed type so this is possible. If you want fsize() to print a message on error, you can use this: #include #include #include #include #include off_t fsize(const char *filename) { struct stat st;
if (stat(filename, &st) == 0) return st.st_size;
fprintf(stderr, "Cannot determine size of %s: %s\n", filename, strerror(errno));
return -1; } On 32-bit systems you should compile this with the option -D_FILE_OFFSET_BITS=64, otherwise off_t will only hold values up to 2 GB. See the "Using LFS" section of Large File Support in Linux for details. | [
"c",
"file",
"io",
"filesize"
] | 170 | 177 | 156,929 | 12 | 0 | 2008-08-11T21:16:30.147000 | 2008-08-12T00:55:48.313000 |
8,263 | 8,347 | I can't get my debugger to stop breaking on first-chance exceptions | I'm using Visual C++ 2003 to debug a program remotely via TCP/IP. I had set the Win32 exception c00000005, "Access violation," to break into the debugger when thrown. Then, I set it back to "Use parent setting." The setting for the parent, Win32 Exceptions, is to continue when the exception is thrown. Now, when I debug the program, it breaks each time that exception is thrown, forcing me to click Continue to let it keep debugging. How do I get it to stop breaking like this? | I'd like to support Will Dean's answer An access violation sounds like an actual bug in your code. It's not something I'd expect the underlying C/++ Runtime to be throwing and catching internally. The 'first-chance-exceptions' feature is so you can intercept things which get 'caught' in code, using the debugger, and have a look. If there's nothing 'catching' that exception (which makes sense, why on earth would you catch and ignore access violations?), then it will trigger the debugger regardless of what options you may have set. | I can't get my debugger to stop breaking on first-chance exceptions I'm using Visual C++ 2003 to debug a program remotely via TCP/IP. I had set the Win32 exception c00000005, "Access violation," to break into the debugger when thrown. Then, I set it back to "Use parent setting." The setting for the parent, Win32 Exceptions, is to continue when the exception is thrown. Now, when I debug the program, it breaks each time that exception is thrown, forcing me to click Continue to let it keep debugging. How do I get it to stop breaking like this? | TITLE:
I can't get my debugger to stop breaking on first-chance exceptions
QUESTION:
I'm using Visual C++ 2003 to debug a program remotely via TCP/IP. I had set the Win32 exception c00000005, "Access violation," to break into the debugger when thrown. Then, I set it back to "Use parent setting." The setting for the parent, Win32 Exceptions, is to continue when the exception is thrown. Now, when I debug the program, it breaks each time that exception is thrown, forcing me to click Continue to let it keep debugging. How do I get it to stop breaking like this?
ANSWER:
I'd like to support Will Dean's answer An access violation sounds like an actual bug in your code. It's not something I'd expect the underlying C/++ Runtime to be throwing and catching internally. The 'first-chance-exceptions' feature is so you can intercept things which get 'caught' in code, using the debugger, and have a look. If there's nothing 'catching' that exception (which makes sense, why on earth would you catch and ignore access violations?), then it will trigger the debugger regardless of what options you may have set. | [
"c++",
"visual-studio",
"debugging",
"visual-studio-2003",
"first-chance-exception"
] | 4 | 5 | 2,869 | 3 | 0 | 2008-08-11T21:51:06.813000 | 2008-08-11T23:48:33.927000 |
8,276 | 8,310 | Class::DBI-like library for php? | I have inherited an old crusty PHP application, and I'd like to refactor it into something a little nicer to deal with, but in a gradual manner. In perl's CPAN, there is a series of classes around Class::DBI that allow you to use database rows as the basis for objects in your code, with the library generating accessor methods etc as appropriate, but also allowing you to add additional methods. Does anyone know of something like this for PHP? Especially something that doesn't require wholesale adoption of a "framework"... bonus points if it works in PHP4 too, but to be honest, I'd love to have another reason to ditch that.:-) | It's now defunct but phpdbi is possibly worth a look. If you're willing to let go of some of your caveats (the framework one), I've found that Doctrine is a pretty neat way of accessing DBs in PHP. Worth investigating anyway. | Class::DBI-like library for php? I have inherited an old crusty PHP application, and I'd like to refactor it into something a little nicer to deal with, but in a gradual manner. In perl's CPAN, there is a series of classes around Class::DBI that allow you to use database rows as the basis for objects in your code, with the library generating accessor methods etc as appropriate, but also allowing you to add additional methods. Does anyone know of something like this for PHP? Especially something that doesn't require wholesale adoption of a "framework"... bonus points if it works in PHP4 too, but to be honest, I'd love to have another reason to ditch that.:-) | TITLE:
Class::DBI-like library for php?
QUESTION:
I have inherited an old crusty PHP application, and I'd like to refactor it into something a little nicer to deal with, but in a gradual manner. In perl's CPAN, there is a series of classes around Class::DBI that allow you to use database rows as the basis for objects in your code, with the library generating accessor methods etc as appropriate, but also allowing you to add additional methods. Does anyone know of something like this for PHP? Especially something that doesn't require wholesale adoption of a "framework"... bonus points if it works in PHP4 too, but to be honest, I'd love to have another reason to ditch that.:-)
ANSWER:
It's now defunct but phpdbi is possibly worth a look. If you're willing to let go of some of your caveats (the framework one), I've found that Doctrine is a pretty neat way of accessing DBs in PHP. Worth investigating anyway. | [
"php",
"perl",
"orm"
] | 13 | 4 | 2,191 | 5 | 0 | 2008-08-11T22:12:04.527000 | 2008-08-11T22:40:02.893000 |
8,284 | 8,299 | Generating Icon Files | I'm looking for an online solution for generating.ICO files. I'd like the ICO files to have the ability to have transparency as well. What software or web site do you use to create them? [Update] To clarify, I have an existing image in PNG format, 32 x 32 pixels. I want to generate the icon from this existing file, not create a brand new one online. Sorry for the confusion. | I have found the application IcoFx useful, you can import pretty much any image type to use for icon creation, including PNG's. | Generating Icon Files I'm looking for an online solution for generating.ICO files. I'd like the ICO files to have the ability to have transparency as well. What software or web site do you use to create them? [Update] To clarify, I have an existing image in PNG format, 32 x 32 pixels. I want to generate the icon from this existing file, not create a brand new one online. Sorry for the confusion. | TITLE:
Generating Icon Files
QUESTION:
I'm looking for an online solution for generating.ICO files. I'd like the ICO files to have the ability to have transparency as well. What software or web site do you use to create them? [Update] To clarify, I have an existing image in PNG format, 32 x 32 pixels. I want to generate the icon from this existing file, not create a brand new one online. Sorry for the confusion.
ANSWER:
I have found the application IcoFx useful, you can import pretty much any image type to use for icon creation, including PNG's. | [
"icons",
"favicon"
] | 12 | 12 | 2,860 | 17 | 0 | 2008-08-11T22:20:04.697000 | 2008-08-11T22:33:41.613000 |
8,306 | 8,315 | Creating Redundancy for a Subversion Repository? | What is the best way to create redundant subversion repositories? I have a subversion repository (linked through apache2 and WebDAV) and would like to create a mirror repository on a different server in the event of outages, but I am not certain of the best way to proceed. I am thinking that post-commit scripts could be used to propagate changes, but I am not sure if this is the best way to go, anyone have any input | Sounds like what you are looking for is basically federated (synced) servers... I asked the same question recently...and while I didn't find the exact solution I was looking for it came close. See here: | Creating Redundancy for a Subversion Repository? What is the best way to create redundant subversion repositories? I have a subversion repository (linked through apache2 and WebDAV) and would like to create a mirror repository on a different server in the event of outages, but I am not certain of the best way to proceed. I am thinking that post-commit scripts could be used to propagate changes, but I am not sure if this is the best way to go, anyone have any input | TITLE:
Creating Redundancy for a Subversion Repository?
QUESTION:
What is the best way to create redundant subversion repositories? I have a subversion repository (linked through apache2 and WebDAV) and would like to create a mirror repository on a different server in the event of outages, but I am not certain of the best way to proceed. I am thinking that post-commit scripts could be used to propagate changes, but I am not sure if this is the best way to go, anyone have any input
ANSWER:
Sounds like what you are looking for is basically federated (synced) servers... I asked the same question recently...and while I didn't find the exact solution I was looking for it came close. See here: | [
"svn",
"repository",
"redundancy"
] | 4 | 4 | 3,408 | 3 | 0 | 2008-08-11T22:37:47.983000 | 2008-08-11T22:49:02.610000 |
8,318 | 8,322 | Resolving Session Fixation in JBoss | I need to prevent Session Fixation, a particular type of session hijacking, in a Java web application running in JBoss. However, it appears that the standard idiom doesn't work in JBoss. Can this be worked around? | This defect (found here ) points the way to the solution. The Tomcat instance that runs in JBoss is configured with emptySessionPath="true", rather than "false", which is the default. This can be modified in.../deploy/jboss-web.deployer/server.xml; both the HTTP and AJP connectors have this option. The feature itself is used to eliminate the context path (eg. "foo" in http://example.com/foo ) from being included in the JSESSIONID cookie. Setting it to false will break applications that rely on cross-application authentication, which includes stuff built using some portal frameworks. It didn't negatively affect the application in question, however. | Resolving Session Fixation in JBoss I need to prevent Session Fixation, a particular type of session hijacking, in a Java web application running in JBoss. However, it appears that the standard idiom doesn't work in JBoss. Can this be worked around? | TITLE:
Resolving Session Fixation in JBoss
QUESTION:
I need to prevent Session Fixation, a particular type of session hijacking, in a Java web application running in JBoss. However, it appears that the standard idiom doesn't work in JBoss. Can this be worked around?
ANSWER:
This defect (found here ) points the way to the solution. The Tomcat instance that runs in JBoss is configured with emptySessionPath="true", rather than "false", which is the default. This can be modified in.../deploy/jboss-web.deployer/server.xml; both the HTTP and AJP connectors have this option. The feature itself is used to eliminate the context path (eg. "foo" in http://example.com/foo ) from being included in the JSESSIONID cookie. Setting it to false will break applications that rely on cross-application authentication, which includes stuff built using some portal frameworks. It didn't negatively affect the application in question, however. | [
"java",
"security",
"jboss"
] | 11 | 9 | 10,695 | 4 | 0 | 2008-08-11T22:53:50.883000 | 2008-08-11T23:00:58.467000 |
8,348 | 8,366 | Using unhandled exceptions instead of Contains()? | Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a Contains() method. There are several ways of dealing with this. Implement your own Contains() method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach. I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows: try { Object aObject = myCollection[myObject]; } catch(Exception e) { //if this is thrown, then the object doesn't exist in the collection } My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection? | I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable. My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result. For example, an exception could be thrown because the object doesn't exist in the collection, or because the collection itself is null or because you can't cast myCollect[myObject] to aObject. All of these exceptions will get handled in the same way, which may not be your intention. These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions: Foundations of Programming Throwing exceptions in c# I particularly like this quote from the second article: It is important that exceptions are thrown only when an unexpected or invalid activity occurs that prevents a method from completing its normal function. Exception handling introduces a small overhead and lowers performance so should not be used for normal program flow instead of conditional processing. It can also be difficult to maintain code that misuses exception handling in this way. | Using unhandled exceptions instead of Contains()? Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a Contains() method. There are several ways of dealing with this. Implement your own Contains() method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach. I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows: try { Object aObject = myCollection[myObject]; } catch(Exception e) { //if this is thrown, then the object doesn't exist in the collection } My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection? | TITLE:
Using unhandled exceptions instead of Contains()?
QUESTION:
Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a Contains() method. There are several ways of dealing with this. Implement your own Contains() method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach. I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows: try { Object aObject = myCollection[myObject]; } catch(Exception e) { //if this is thrown, then the object doesn't exist in the collection } My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?
ANSWER:
I would have to say that this is pretty bad practice. Whilst some people might be happy to say that looping through the collection is less efficient to throwing an exception, there is an overhead to throwing an exception. I would also question why you are using a collection to access an item by key when you would be better suited to using a dictionary or hashtable. My main problem with this code however, is that regardless of the type of exception thrown, you are always going to be left with the same result. For example, an exception could be thrown because the object doesn't exist in the collection, or because the collection itself is null or because you can't cast myCollect[myObject] to aObject. All of these exceptions will get handled in the same way, which may not be your intention. These are a couple of nice articles on when and where it is usally considered acceptable to throw exceptions: Foundations of Programming Throwing exceptions in c# I particularly like this quote from the second article: It is important that exceptions are thrown only when an unexpected or invalid activity occurs that prevents a method from completing its normal function. Exception handling introduces a small overhead and lowers performance so should not be used for normal program flow instead of conditional processing. It can also be difficult to maintain code that misuses exception handling in this way. | [
"c#",
".net",
"error-handling"
] | 8 | 3 | 1,201 | 8 | 0 | 2008-08-11T23:49:32.503000 | 2008-08-12T00:26:37.577000 |
8,351 | 8,360 | Is there something like "Firebug for IE" (for debugging JavaScript)? | I'm trying to fix some JavaScript bugs. Firebug makes debugging these issues a lot easier when working in Firefox, but what do you do when the code works fine on Firefox but IE is complaining? | you can also check out the IE Developer Toolbar which isn't a debugger but will help you analyze the contents of your code. Visual Studio will help with the debugging Fiddler should help analyse the traffic travelling to and from your browser | Is there something like "Firebug for IE" (for debugging JavaScript)? I'm trying to fix some JavaScript bugs. Firebug makes debugging these issues a lot easier when working in Firefox, but what do you do when the code works fine on Firefox but IE is complaining? | TITLE:
Is there something like "Firebug for IE" (for debugging JavaScript)?
QUESTION:
I'm trying to fix some JavaScript bugs. Firebug makes debugging these issues a lot easier when working in Firefox, but what do you do when the code works fine on Firefox but IE is complaining?
ANSWER:
you can also check out the IE Developer Toolbar which isn't a debugger but will help you analyze the contents of your code. Visual Studio will help with the debugging Fiddler should help analyse the traffic travelling to and from your browser | [
"javascript",
"debugging",
"internet-explorer",
"firebug",
"javascript-debugger"
] | 44 | 23 | 44,845 | 16 | 0 | 2008-08-12T00:02:42.417000 | 2008-08-12T00:11:03.303000 |
8,355 | 12,069 | Using mod_rewrite to Mimic SSL Virtual Hosts? | What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2? Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this: I have set up the server so that the sites can be accessed by https://secure.example.com/dbadmin but I would like to have this as https://dbadmin.example.com How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https? | Configure a single VirtualHost to serve both secure.example.com and dbadmin.example.com (making it the only *:443 VirtualHost achieves this). You can then use mod_rewrite to adjust the URI for requests to dbadmin.example.com: ServerName secure.example.com ServerAlias dbadmin.example.com
RewriteEngine on RewriteCond %{SERVER_NAME} dbadmin.example.com RewriteRule!/dbadmin(.*)$ /dbadmin$1 Your SSL certificate will need to be valid for both secure.example.com and dbadmin.example.com. It can be a wildcard certificate as mentioned by Terry Lorber, or you can use the subjectAltName field to add additional host names. If you're having trouble, first set it up on and check that it works without SSL. The SSL connection and certificate is a separate layer of complexity that you can set up after the URI rewriting is working. | Using mod_rewrite to Mimic SSL Virtual Hosts? What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2? Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this: I have set up the server so that the sites can be accessed by https://secure.example.com/dbadmin but I would like to have this as https://dbadmin.example.com How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https? | TITLE:
Using mod_rewrite to Mimic SSL Virtual Hosts?
QUESTION:
What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2? Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this: I have set up the server so that the sites can be accessed by https://secure.example.com/dbadmin but I would like to have this as https://dbadmin.example.com How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https?
ANSWER:
Configure a single VirtualHost to serve both secure.example.com and dbadmin.example.com (making it the only *:443 VirtualHost achieves this). You can then use mod_rewrite to adjust the URI for requests to dbadmin.example.com: ServerName secure.example.com ServerAlias dbadmin.example.com
RewriteEngine on RewriteCond %{SERVER_NAME} dbadmin.example.com RewriteRule!/dbadmin(.*)$ /dbadmin$1 Your SSL certificate will need to be valid for both secure.example.com and dbadmin.example.com. It can be a wildcard certificate as mentioned by Terry Lorber, or you can use the subjectAltName field to add additional host names. If you're having trouble, first set it up on and check that it works without SSL. The SSL connection and certificate is a separate layer of complexity that you can set up after the URI rewriting is working. | [
"apache",
"mod-rewrite",
"https"
] | 7 | 3 | 2,271 | 3 | 0 | 2008-08-12T00:06:36.073000 | 2008-08-15T08:21:28.300000 |
8,365 | 23,804 | MySQL Administrator Backups: "Compatibility Mode", What Exactly is this doing? | In Mysql Administrator, when doing backups, what exactly is "Compatibility Mode"? I'm trying to bridge backups generated by webmin with the upload tool available inside mysql administrator. My data already has a couple of inconsistencies (ticks, commas, etc, I think) I just wont try to kink out (they might just reappear in the future anyways). These kinks generate errors when I try to restore out of my backups. Now, if I generate backups from webmin, and then use MySQL administrator to restore them, they fail. But if I generate the backups using MySQL Administrator AND tick "Compatibility Mode", then head over to MySQL administrator (another instance) and restore... it works! According to MySQL, "Compatibility Mode" is; Compatibility mode creates backup files that are compatible with older versions of MySQL Administrator. Webmin, on the other hand, gives me the following options for compatibility: ANSI MySQL 3.2.3 MySQL 4.0 PostgreSQL Oracle Microsoft SQL DB2 MaxDB Which would you say is a best fit? My data set is very large, so it would take quite some time to experiment one by one (specially whence thinking might beat brute-forcing it). Edit: seems like it's doing ANSI, but i'm not 100% on it. | Compatibility mode - the mode that helps you create exports compabible with different versions of MYSQL or other databases. You see, some versions of MySQL had different commands that were used in various versions. So what compatibility mode allows you to do is take a database and export the SQL to be compatible with another version of MySQL. Thus, you may want to upgrade your MySQL 3 server to 4 - this compatibility mode allows for the export your database or individual tables to create a SQL file that can import into a MySQL 4 version server (should work in 5 also). I use webmin, also, and run MySQL 5. I use compatibility mode for MySQL 4.... I steer clear of any of the other ones, because I'm not running those other databases. As far as the MySQL commands that were different between MySQL 3.x and 4.x, I believe there were changes in regards to how CURRENT_TIMESTAMP is translated from MySQL 3 to 4, and also MySQL 3 doesn't support charsets, according to this forum post here: http://www.phpbuilder.com/board/showthread.php?t=10330692 | MySQL Administrator Backups: "Compatibility Mode", What Exactly is this doing? In Mysql Administrator, when doing backups, what exactly is "Compatibility Mode"? I'm trying to bridge backups generated by webmin with the upload tool available inside mysql administrator. My data already has a couple of inconsistencies (ticks, commas, etc, I think) I just wont try to kink out (they might just reappear in the future anyways). These kinks generate errors when I try to restore out of my backups. Now, if I generate backups from webmin, and then use MySQL administrator to restore them, they fail. But if I generate the backups using MySQL Administrator AND tick "Compatibility Mode", then head over to MySQL administrator (another instance) and restore... it works! According to MySQL, "Compatibility Mode" is; Compatibility mode creates backup files that are compatible with older versions of MySQL Administrator. Webmin, on the other hand, gives me the following options for compatibility: ANSI MySQL 3.2.3 MySQL 4.0 PostgreSQL Oracle Microsoft SQL DB2 MaxDB Which would you say is a best fit? My data set is very large, so it would take quite some time to experiment one by one (specially whence thinking might beat brute-forcing it). Edit: seems like it's doing ANSI, but i'm not 100% on it. | TITLE:
MySQL Administrator Backups: "Compatibility Mode", What Exactly is this doing?
QUESTION:
In Mysql Administrator, when doing backups, what exactly is "Compatibility Mode"? I'm trying to bridge backups generated by webmin with the upload tool available inside mysql administrator. My data already has a couple of inconsistencies (ticks, commas, etc, I think) I just wont try to kink out (they might just reappear in the future anyways). These kinks generate errors when I try to restore out of my backups. Now, if I generate backups from webmin, and then use MySQL administrator to restore them, they fail. But if I generate the backups using MySQL Administrator AND tick "Compatibility Mode", then head over to MySQL administrator (another instance) and restore... it works! According to MySQL, "Compatibility Mode" is; Compatibility mode creates backup files that are compatible with older versions of MySQL Administrator. Webmin, on the other hand, gives me the following options for compatibility: ANSI MySQL 3.2.3 MySQL 4.0 PostgreSQL Oracle Microsoft SQL DB2 MaxDB Which would you say is a best fit? My data set is very large, so it would take quite some time to experiment one by one (specially whence thinking might beat brute-forcing it). Edit: seems like it's doing ANSI, but i'm not 100% on it.
ANSWER:
Compatibility mode - the mode that helps you create exports compabible with different versions of MYSQL or other databases. You see, some versions of MySQL had different commands that were used in various versions. So what compatibility mode allows you to do is take a database and export the SQL to be compatible with another version of MySQL. Thus, you may want to upgrade your MySQL 3 server to 4 - this compatibility mode allows for the export your database or individual tables to create a SQL file that can import into a MySQL 4 version server (should work in 5 also). I use webmin, also, and run MySQL 5. I use compatibility mode for MySQL 4.... I steer clear of any of the other ones, because I'm not running those other databases. As far as the MySQL commands that were different between MySQL 3.x and 4.x, I believe there were changes in regards to how CURRENT_TIMESTAMP is translated from MySQL 3 to 4, and also MySQL 3 doesn't support charsets, according to this forum post here: http://www.phpbuilder.com/board/showthread.php?t=10330692 | [
"mysql",
"backup"
] | 6 | 1 | 8,185 | 1 | 0 | 2008-08-12T00:21:58.790000 | 2008-08-23T00:46:30.907000 |
8,371 | 8,380 | How do you redirect HTTPS to HTTP? | How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches. I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for. On my client's desktops I have SOME shortcuts which point to http://production_server and https://production_server (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at https://mirror_server (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL). It's very easy to find Apache solutions for http->https redirection, but for the life of me I can't do the opposite. Ideas? | This has not been tested but I think this should work using mod_rewrite RewriteEngine On RewriteCond %{HTTPS} on RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} | How do you redirect HTTPS to HTTP? How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches. I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for. On my client's desktops I have SOME shortcuts which point to http://production_server and https://production_server (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at https://mirror_server (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL). It's very easy to find Apache solutions for http->https redirection, but for the life of me I can't do the opposite. Ideas? | TITLE:
How do you redirect HTTPS to HTTP?
QUESTION:
How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches. I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for. On my client's desktops I have SOME shortcuts which point to http://production_server and https://production_server (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at https://mirror_server (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL). It's very easy to find Apache solutions for http->https redirection, but for the life of me I can't do the opposite. Ideas?
ANSWER:
This has not been tested but I think this should work using mod_rewrite RewriteEngine On RewriteCond %{HTTPS} on RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} | [
"apache",
"ssl",
"redirect",
"https"
] | 189 | 143 | 495,296 | 11 | 0 | 2008-08-12T00:36:32.223000 | 2008-08-12T00:48:49.577000 |
8,398 | 8,433 | How do I debug JavaScript in Visual Studio 2005? | I just saw this mentioned in Stack Overflow question Best WYSIWYG CSS editor and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it? Is there a separate debugger for JavaScript? I know how to work the one for code-behind pages... I usually use Firebug to deal with debugging JavaScript code. I'm using Visual Studio 2005. | I prefer using Firebug for projects I can't use Visual Studio 2008 on. | How do I debug JavaScript in Visual Studio 2005? I just saw this mentioned in Stack Overflow question Best WYSIWYG CSS editor and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it? Is there a separate debugger for JavaScript? I know how to work the one for code-behind pages... I usually use Firebug to deal with debugging JavaScript code. I'm using Visual Studio 2005. | TITLE:
How do I debug JavaScript in Visual Studio 2005?
QUESTION:
I just saw this mentioned in Stack Overflow question Best WYSIWYG CSS editor and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it? Is there a separate debugger for JavaScript? I know how to work the one for code-behind pages... I usually use Firebug to deal with debugging JavaScript code. I'm using Visual Studio 2005.
ANSWER:
I prefer using Firebug for projects I can't use Visual Studio 2008 on. | [
"javascript",
"visual-studio",
"visual-studio-2005",
"debugging"
] | 17 | 8 | 10,917 | 11 | 0 | 2008-08-12T01:22:38.197000 | 2008-08-12T03:12:49.317000 |
8,422 | 402,856 | How do you handle audit logging with SSRS? | I have some reports in SQL Server Reporting Services 2005 that I need to keep audit logs for. The audit log should include who ran what report with what parameters. I can't use Windows authentication. What is the best way to log this information? | The previous comments were dead on accurate that you can mine the data from the ReportServer ExecutionLog table in SQL Server 2000/2005 or the ExecutionLogStorage table in SQL Server 2008. If you are using form-based authentication to access the reports instead of windows authentication, then you are probably passing some unique UserID, CompanyID, CustomerID, or other value as a parameter in your reports. If this is the case, then the built-in table captures the parameters already. If you aren't passing the unique user identifier as a parameter, then you will probably need to rely on logging report executions in your application itself. | How do you handle audit logging with SSRS? I have some reports in SQL Server Reporting Services 2005 that I need to keep audit logs for. The audit log should include who ran what report with what parameters. I can't use Windows authentication. What is the best way to log this information? | TITLE:
How do you handle audit logging with SSRS?
QUESTION:
I have some reports in SQL Server Reporting Services 2005 that I need to keep audit logs for. The audit log should include who ran what report with what parameters. I can't use Windows authentication. What is the best way to log this information?
ANSWER:
The previous comments were dead on accurate that you can mine the data from the ReportServer ExecutionLog table in SQL Server 2000/2005 or the ExecutionLogStorage table in SQL Server 2008. If you are using form-based authentication to access the reports instead of windows authentication, then you are probably passing some unique UserID, CompanyID, CustomerID, or other value as a parameter in your reports. If this is the case, then the built-in table captures the parameters already. If you aren't passing the unique user identifier as a parameter, then you will probably need to rely on logging report executions in your application itself. | [
"sql-server",
"sql-server-2005",
"reporting-services",
"reportingservices-2005"
] | 6 | 5 | 8,827 | 5 | 0 | 2008-08-12T02:39:06.437000 | 2008-12-31T12:10:30.493000 |
8,435 | 8,436 | How do you get the icons out of shell32.dll? | I'd like to get the Tree icon to use for a homegrown app. Does anyone know how to extract the images out as.icon files? I'd like both the 16x16 and 32x32, or I'd just do a screen capture. | In Visual Studio, choose "File Open..." then "File...". Then pick the Shell32.dll. A folder tree should be opened, and you will find the icons in the "Icon" folder. To save an Icon, you can right-click on the icon in the folder tree and choose "Export". | How do you get the icons out of shell32.dll? I'd like to get the Tree icon to use for a homegrown app. Does anyone know how to extract the images out as.icon files? I'd like both the 16x16 and 32x32, or I'd just do a screen capture. | TITLE:
How do you get the icons out of shell32.dll?
QUESTION:
I'd like to get the Tree icon to use for a homegrown app. Does anyone know how to extract the images out as.icon files? I'd like both the 16x16 and 32x32, or I'd just do a screen capture.
ANSWER:
In Visual Studio, choose "File Open..." then "File...". Then pick the Shell32.dll. A folder tree should be opened, and you will find the icons in the "Icon" folder. To save an Icon, you can right-click on the icon in the folder tree and choose "Export". | [
"windows",
"powershell",
"icons"
] | 69 | 58 | 120,479 | 13 | 0 | 2008-08-12T03:26:38.557000 | 2008-08-12T03:32:20.590000 |
8,439 | 12,283 | Conditional Visibility and Page Breaks with SQL Server 2005 Reporting Services | I know there's a bug with conditional visibility and page breaks with SQL 2005, but I wonder if anyone has come up with a work around. I have a table that has a conditional visibility expression, and I need a page break at the end of the table. If I set the PageBreakAtEnd property to true. It is ignored no matter what. Remove the visibility condition and it works. If I place the table inside a rectangle with the conditional visibility on the table, and the page break on the table. Same result. The page break property is ignored. If I set the rectangle with the PageBreakAtEnd property and the table with the visibility condition, then I still get a page break even when the table isn't shown. Any other ideas on what to try? I'm almost at the point where I need a separate report rather than conditional visibility:( Edit: @Josh: That has the same problems. If the second table has conditional visibility it doesn't work. If it doesn't have the visibility expression, then I get the page break all the time. @ Erick: I really wanted that to be the answer but unfortunately it doesn't work. When the visibility expression evaluates to hidden, there's a big gap where the rectangles would be (which I can live with), and when it evaluates to visible, the page breaks still don't work. | Place two rectangles, one inside the other. Place your table inside the inner rectangle and set it to always be visible. Set the inner rectangle's Page Break to Insert After Rectangle. Set the outer rectangle's visibility to use your conditional expression. The page break and the conditional visibility are now separated, and the inner rectangle's page break won't be processed if it is not visible, but it will if it is visible. Edit: When I tried this, it did not appear to work in the Preview tab in Visual Studio, but it did work in the Print Preview and when I exported the report to PDF. | Conditional Visibility and Page Breaks with SQL Server 2005 Reporting Services I know there's a bug with conditional visibility and page breaks with SQL 2005, but I wonder if anyone has come up with a work around. I have a table that has a conditional visibility expression, and I need a page break at the end of the table. If I set the PageBreakAtEnd property to true. It is ignored no matter what. Remove the visibility condition and it works. If I place the table inside a rectangle with the conditional visibility on the table, and the page break on the table. Same result. The page break property is ignored. If I set the rectangle with the PageBreakAtEnd property and the table with the visibility condition, then I still get a page break even when the table isn't shown. Any other ideas on what to try? I'm almost at the point where I need a separate report rather than conditional visibility:( Edit: @Josh: That has the same problems. If the second table has conditional visibility it doesn't work. If it doesn't have the visibility expression, then I get the page break all the time. @ Erick: I really wanted that to be the answer but unfortunately it doesn't work. When the visibility expression evaluates to hidden, there's a big gap where the rectangles would be (which I can live with), and when it evaluates to visible, the page breaks still don't work. | TITLE:
Conditional Visibility and Page Breaks with SQL Server 2005 Reporting Services
QUESTION:
I know there's a bug with conditional visibility and page breaks with SQL 2005, but I wonder if anyone has come up with a work around. I have a table that has a conditional visibility expression, and I need a page break at the end of the table. If I set the PageBreakAtEnd property to true. It is ignored no matter what. Remove the visibility condition and it works. If I place the table inside a rectangle with the conditional visibility on the table, and the page break on the table. Same result. The page break property is ignored. If I set the rectangle with the PageBreakAtEnd property and the table with the visibility condition, then I still get a page break even when the table isn't shown. Any other ideas on what to try? I'm almost at the point where I need a separate report rather than conditional visibility:( Edit: @Josh: That has the same problems. If the second table has conditional visibility it doesn't work. If it doesn't have the visibility expression, then I get the page break all the time. @ Erick: I really wanted that to be the answer but unfortunately it doesn't work. When the visibility expression evaluates to hidden, there's a big gap where the rectangles would be (which I can live with), and when it evaluates to visible, the page breaks still don't work.
ANSWER:
Place two rectangles, one inside the other. Place your table inside the inner rectangle and set it to always be visible. Set the inner rectangle's Page Break to Insert After Rectangle. Set the outer rectangle's visibility to use your conditional expression. The page break and the conditional visibility are now separated, and the inner rectangle's page break won't be processed if it is not visible, but it will if it is visible. Edit: When I tried this, it did not appear to work in the Preview tab in Visual Studio, but it did work in the Print Preview and when I exported the report to PDF. | [
"sql-server-2005",
"reporting-services"
] | 19 | 11 | 24,997 | 7 | 0 | 2008-08-12T03:46:11.043000 | 2008-08-15T14:22:26.470000 |
8,441 | 8,454 | Mod-Rewrite loading files behind the DocumentRoot | I'm using.htaccess and mod_rewrite to point to files that reside behind the DocumentRoot. My folder structure looks like this: home/ webroot/ other_files/ I have a.htaccess file in webroot with the following content: RewriteEngine on RewriteRule ^(.*)$ /home/other_files/$1 If I try to access http://example.com/file.html I receive the following error: The requested URL /home/other_files/file.html was not found on this server. Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction? | I believe you need to add a section with (options) to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site: Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0::1/128 You could then rewrite a URL to go to /doc/ and the server would know where to get the files from. | Mod-Rewrite loading files behind the DocumentRoot I'm using.htaccess and mod_rewrite to point to files that reside behind the DocumentRoot. My folder structure looks like this: home/ webroot/ other_files/ I have a.htaccess file in webroot with the following content: RewriteEngine on RewriteRule ^(.*)$ /home/other_files/$1 If I try to access http://example.com/file.html I receive the following error: The requested URL /home/other_files/file.html was not found on this server. Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction? | TITLE:
Mod-Rewrite loading files behind the DocumentRoot
QUESTION:
I'm using.htaccess and mod_rewrite to point to files that reside behind the DocumentRoot. My folder structure looks like this: home/ webroot/ other_files/ I have a.htaccess file in webroot with the following content: RewriteEngine on RewriteRule ^(.*)$ /home/other_files/$1 If I try to access http://example.com/file.html I receive the following error: The requested URL /home/other_files/file.html was not found on this server. Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction?
ANSWER:
I believe you need to add a section with (options) to your server configuration before apache will be able to serve anything from it. For an example, my DocumentRoot is /var/www but there is this section in the default available site: Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0::1/128 You could then rewrite a URL to go to /doc/ and the server would know where to get the files from. | [
".htaccess",
"mod-rewrite"
] | 13 | 13 | 6,589 | 3 | 0 | 2008-08-12T03:58:21.910000 | 2008-08-12T04:21:54.857000 |
8,447 | 8,480 | What does the [Flags] Enum Attribute mean in C#? | From time to time I see an enum like the following: [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 } I don't understand what exactly the [Flags] attribute does. Anyone have a good explanation or example they could post? | The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example: var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue; Note that the [Flags] attribute doesn't enable this by itself - all it does is allow a nice representation by the.ToString() method: enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }...
var str1 = (Suits.Spades | Suits.Diamonds).ToString(); // "5" var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString(); // "Spades, Diamonds" It is also important to note that [Flags] does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. Incorrect declaration: [Flags] public enum MyColors { Yellow, // 0 Green, // 1 Red, // 2 Blue // 3 } The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags. Here's an example of a correct declaration: [Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 } To retrieve the distinct values in your property, one can do this: if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // Yellow is allowed... } or prior to.NET 4: if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // Yellow is allowed... }
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green) { // Green is allowed... } Under the covers This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros: Yellow: 00000001 Green: 00000010 Red: 00000100 Blue: 00001000 Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR | operator, AllowedColors looks like this: myProperties.AllowedColors: 00001110 So when you retrieve the value you are actually performing bitwise AND & on the values: myProperties.AllowedColors: 00001110 MyColor.Green: 00000010 ----------------------- 00000010 // Hey, this is the same as MyColor.Green! The None = 0 value And regarding the use of 0 in your enumeration, quoting from MSDN: [Flags] public enum MyColors { None = 0,.... } Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. You can find more info about the flags attribute and its usage at msdn and designing flags at msdn | What does the [Flags] Enum Attribute mean in C#? From time to time I see an enum like the following: [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 } I don't understand what exactly the [Flags] attribute does. Anyone have a good explanation or example they could post? | TITLE:
What does the [Flags] Enum Attribute mean in C#?
QUESTION:
From time to time I see an enum like the following: [Flags] public enum Options { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 } I don't understand what exactly the [Flags] attribute does. Anyone have a good explanation or example they could post?
ANSWER:
The [Flags] attribute should be used whenever the enumerable represents a collection of possible values, rather than a single value. Such collections are often used with bitwise operators, for example: var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue; Note that the [Flags] attribute doesn't enable this by itself - all it does is allow a nice representation by the.ToString() method: enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 } [Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }...
var str1 = (Suits.Spades | Suits.Diamonds).ToString(); // "5" var str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString(); // "Spades, Diamonds" It is also important to note that [Flags] does not automatically make the enum values powers of two. If you omit the numeric values, the enum will not work as one might expect in bitwise operations, because by default the values start with 0 and increment. Incorrect declaration: [Flags] public enum MyColors { Yellow, // 0 Green, // 1 Red, // 2 Blue // 3 } The values, if declared this way, will be Yellow = 0, Green = 1, Red = 2, Blue = 3. This will render it useless as flags. Here's an example of a correct declaration: [Flags] public enum MyColors { Yellow = 1, Green = 2, Red = 4, Blue = 8 } To retrieve the distinct values in your property, one can do this: if (myProperties.AllowedColors.HasFlag(MyColor.Yellow)) { // Yellow is allowed... } or prior to.NET 4: if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow) { // Yellow is allowed... }
if((myProperties.AllowedColors & MyColor.Green) == MyColor.Green) { // Green is allowed... } Under the covers This works because you used powers of two in your enumeration. Under the covers, your enumeration values look like this in binary ones and zeros: Yellow: 00000001 Green: 00000010 Red: 00000100 Blue: 00001000 Similarly, after you've set your property AllowedColors to Red, Green and Blue using the binary bitwise OR | operator, AllowedColors looks like this: myProperties.AllowedColors: 00001110 So when you retrieve the value you are actually performing bitwise AND & on the values: myProperties.AllowedColors: 00001110 MyColor.Green: 00000010 ----------------------- 00000010 // Hey, this is the same as MyColor.Green! The None = 0 value And regarding the use of 0 in your enumeration, quoting from MSDN: [Flags] public enum MyColors { None = 0,.... } Use None as the name of the flag enumerated constant whose value is zero. You cannot use the None enumerated constant in a bitwise AND operation to test for a flag because the result is always zero. However, you can perform a logical, not a bitwise, comparison between the numeric value and the None enumerated constant to determine whether any bits in the numeric value are set. You can find more info about the flags attribute and its usage at msdn and designing flags at msdn | [
"c#",
"enums",
"flags"
] | 1,753 | 2,531 | 655,063 | 14 | 0 | 2008-08-12T04:09:16.083000 | 2008-08-12T05:10:46.427000 |
8,448 | 8,468 | F# curried function | Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept? | (Edit: a small Ocaml FP Koan to start things off) The Koan of Currying (A koan about food, that is not about food) A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened... until the next morning when he woke up and his stomach felt fine. My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations. We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing another function (assuming this function is being used in other instances with other variables) would be a waste. type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree let rec tree_map f tree = match tree with | N(x,left,right) -> N(f x, tree_map f left, tree_map f right) | E(x) -> E(f x)
let sample_tree = N(1,E(3),E(4) let multiply x y = x * y let sample_tree2 = tree_map (multiply 3) sample_tree but this is the same as: let sample_tree2 = tree_map (fun x -> x * 3) sample_tree So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A recurrence relation to create prime numbers. Awful lot of similarity in there: let rec f_recurrence f a seed n = match n with | a -> seed | _ -> let prev = f_recurrence f a seed (n-1) in prev + (f n prev)
let rowland = f_recurrence gcd 1 7 let cloitre = f_recurrence lcm 1 1
let rowland_prime n = (rowland (n+1)) - (rowland n) let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1 Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f_recurrence. | F# curried function Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept? | TITLE:
F# curried function
QUESTION:
Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?
ANSWER:
(Edit: a small Ocaml FP Koan to start things off) The Koan of Currying (A koan about food, that is not about food) A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened... until the next morning when he woke up and his stomach felt fine. My examples will cover using it for the reuse and encapsulation of code. This is fairly obvious once you look at these and should give you a concrete, simple example that you can think of applying in numerous situations. We want to do a map over a tree. This function could be curried and applied to each node if it needs more then one argument -- since we'd be applying the one at the node as it's final argument. It doesn't have to be curried, but writing another function (assuming this function is being used in other instances with other variables) would be a waste. type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree let rec tree_map f tree = match tree with | N(x,left,right) -> N(f x, tree_map f left, tree_map f right) | E(x) -> E(f x)
let sample_tree = N(1,E(3),E(4) let multiply x y = x * y let sample_tree2 = tree_map (multiply 3) sample_tree but this is the same as: let sample_tree2 = tree_map (fun x -> x * 3) sample_tree So this simple case isn't convincing. It really is though, and powerful once you use the language more and naturally come across these situations. The other example with some code reuse as currying. A recurrence relation to create prime numbers. Awful lot of similarity in there: let rec f_recurrence f a seed n = match n with | a -> seed | _ -> let prev = f_recurrence f a seed (n-1) in prev + (f n prev)
let rowland = f_recurrence gcd 1 7 let cloitre = f_recurrence lcm 1 1
let rowland_prime n = (rowland (n+1)) - (rowland n) let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1 Ok, now rowland and cloitre are curried functions, since they have free variables, and we can get any index of it's sequence without knowing or worrying about f_recurrence. | [
"f#",
"functional-programming",
"currying"
] | 19 | 21 | 7,102 | 6 | 0 | 2008-08-12T04:11:15.800000 | 2008-08-12T04:46:33.480000 |
8,451 | 8,486 | Secure Memory Allocator in C++ | I want to create an allocator which provides memory with the following attributes: cannot be paged to disk. is incredibly hard to access through an attached debugger The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem. Updates Josh mentions using VirtualAlloc to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the VirtualLock function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem. // template class LockedVirtualMemAllocator: public std::allocator<_Ty> { public: template LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&) { // assign from a related LockedVirtualMemAllocator (do nothing) return (*this); }
template struct rebind { typedef LockedVirtualMemAllocator other; };
pointer allocate( size_type _n ) { SIZE_T allocLen = (_n * sizeof(_Ty)); DWORD allocType = MEM_COMMIT; DWORD allocProtect = PAGE_READWRITE; LPVOID pMem =::VirtualAlloc( NULL, allocLen, allocType, allocProtect ); if ( pMem!= NULL ) {::VirtualLock( pMem, allocLen ); } return reinterpret_cast ( pMem ); } pointer allocate( size_type _n, const void* ) { return allocate( _n ); }
void deallocate(void* _pPtr, size_type _n ) { if ( _pPtr!= NULL ) { SIZE_T allocLen = (_n * sizeof(_Ty));::SecureZeroMemory( _pPtr, allocLen );::VirtualUnlock( _pPtr, allocLen );::VirtualFree( _pPtr, 0, MEM_RELEASE ); } } }; and is used //a memory safe std::string typedef std::basic_string, LockedVirtualMemAllocato > modulestring_t; Ted Percival mentions mlock, but I have no implementation of that yet. I found Practical Cryptography by Neil Furguson and Bruce Schneier quite helpful as well. | You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way. Even if you could somehow completely lock down your process and guarantee that the OS would never allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time. You cannot protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. | Secure Memory Allocator in C++ I want to create an allocator which provides memory with the following attributes: cannot be paged to disk. is incredibly hard to access through an attached debugger The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem. Updates Josh mentions using VirtualAlloc to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the VirtualLock function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem. // template class LockedVirtualMemAllocator: public std::allocator<_Ty> { public: template LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&) { // assign from a related LockedVirtualMemAllocator (do nothing) return (*this); }
template struct rebind { typedef LockedVirtualMemAllocator other; };
pointer allocate( size_type _n ) { SIZE_T allocLen = (_n * sizeof(_Ty)); DWORD allocType = MEM_COMMIT; DWORD allocProtect = PAGE_READWRITE; LPVOID pMem =::VirtualAlloc( NULL, allocLen, allocType, allocProtect ); if ( pMem!= NULL ) {::VirtualLock( pMem, allocLen ); } return reinterpret_cast ( pMem ); } pointer allocate( size_type _n, const void* ) { return allocate( _n ); }
void deallocate(void* _pPtr, size_type _n ) { if ( _pPtr!= NULL ) { SIZE_T allocLen = (_n * sizeof(_Ty));::SecureZeroMemory( _pPtr, allocLen );::VirtualUnlock( _pPtr, allocLen );::VirtualFree( _pPtr, 0, MEM_RELEASE ); } } }; and is used //a memory safe std::string typedef std::basic_string, LockedVirtualMemAllocato > modulestring_t; Ted Percival mentions mlock, but I have no implementation of that yet. I found Practical Cryptography by Neil Furguson and Bruce Schneier quite helpful as well. | TITLE:
Secure Memory Allocator in C++
QUESTION:
I want to create an allocator which provides memory with the following attributes: cannot be paged to disk. is incredibly hard to access through an attached debugger The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem. Updates Josh mentions using VirtualAlloc to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the VirtualLock function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem. // template class LockedVirtualMemAllocator: public std::allocator<_Ty> { public: template LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&) { // assign from a related LockedVirtualMemAllocator (do nothing) return (*this); }
template struct rebind { typedef LockedVirtualMemAllocator other; };
pointer allocate( size_type _n ) { SIZE_T allocLen = (_n * sizeof(_Ty)); DWORD allocType = MEM_COMMIT; DWORD allocProtect = PAGE_READWRITE; LPVOID pMem =::VirtualAlloc( NULL, allocLen, allocType, allocProtect ); if ( pMem!= NULL ) {::VirtualLock( pMem, allocLen ); } return reinterpret_cast ( pMem ); } pointer allocate( size_type _n, const void* ) { return allocate( _n ); }
void deallocate(void* _pPtr, size_type _n ) { if ( _pPtr!= NULL ) { SIZE_T allocLen = (_n * sizeof(_Ty));::SecureZeroMemory( _pPtr, allocLen );::VirtualUnlock( _pPtr, allocLen );::VirtualFree( _pPtr, 0, MEM_RELEASE ); } } }; and is used //a memory safe std::string typedef std::basic_string, LockedVirtualMemAllocato > modulestring_t; Ted Percival mentions mlock, but I have no implementation of that yet. I found Practical Cryptography by Neil Furguson and Bruce Schneier quite helpful as well.
ANSWER:
You can't really protect against memory access. You can probably prevent paging if you are running as an admin or as the system, but you cannot prevent the admin or system from reading your memory. Even if you could somehow completely block other processes from reading your memory (which you can't), another process could still actually inject a new thread into your process and read the memory that way. Even if you could somehow completely lock down your process and guarantee that the OS would never allow anyone else to access your process, you still don't have full protection. The entire OS could be running in a virtual machine, which could be paused and inspected at any time. You cannot protect memory contents from the owner of the system. Hollywood and the music industry have been aching for this for years. If it were possible, they'd already be doing it. | [
"c++",
"security",
"memory",
"ram-scraping"
] | 15 | 19 | 9,738 | 13 | 0 | 2008-08-12T04:18:09.873000 | 2008-08-12T05:17:09.473000 |
8,452 | 8,471 | Custom WPF command pattern example | I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? | Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does. You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so: public static class CommandBank { /// Command definition for Closing a window public static RoutedUICommand CloseWindow { get; private set; }
/// Static private constructor, sets up all application wide commands. static CommandBank() { CloseWindow = new RoutedUICommand(); CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt)); //... } Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above: /// Closes the window provided as a parameter public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e) { ((Window)e.Parameter).Close(); }
/// Allows a Command to execute if the CommandParameter is not a null value public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Parameter!= null; e.Handled = true; } The second method there can even be shared with other Commands without me having to repeat it all over the place. Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close. public partial class SimpleWindow: Window { private void WindowLoaded(object sender, RoutedEventArgs e) { //... this.CommandBindings.Add( new CommandBinding( CommandBank.CloseWindow, CommandBank.CloseWindowExecute, CommandBank.CanExecuteIfParameterIsNotNull));
foreach (CommandBinding binding in this.CommandBindings) { RoutedCommand command = (RoutedCommand)binding.Command; if (command.InputGestures.Count > 0) { foreach (InputGesture gesture in command.InputGestures) { var iBind = new InputBinding(command, gesture); iBind.CommandParameter = this; this.InputBindings.Add(iBind); } } }
// menuItemExit is defined in XAML menuItemExit.Command = CommandBank.CloseWindow; menuItemExit.CommandParameter = this; //... }
//.... } I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event. Let me know if you have any follow up questions.:) | Custom WPF command pattern example I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands? | TITLE:
Custom WPF command pattern example
QUESTION:
I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?
ANSWER:
Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does. You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so: public static class CommandBank { /// Command definition for Closing a window public static RoutedUICommand CloseWindow { get; private set; }
/// Static private constructor, sets up all application wide commands. static CommandBank() { CloseWindow = new RoutedUICommand(); CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt)); //... } Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above: /// Closes the window provided as a parameter public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e) { ((Window)e.Parameter).Close(); }
/// Allows a Command to execute if the CommandParameter is not a null value public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = e.Parameter!= null; e.Handled = true; } The second method there can even be shared with other Commands without me having to repeat it all over the place. Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close. public partial class SimpleWindow: Window { private void WindowLoaded(object sender, RoutedEventArgs e) { //... this.CommandBindings.Add( new CommandBinding( CommandBank.CloseWindow, CommandBank.CloseWindowExecute, CommandBank.CanExecuteIfParameterIsNotNull));
foreach (CommandBinding binding in this.CommandBindings) { RoutedCommand command = (RoutedCommand)binding.Command; if (command.InputGestures.Count > 0) { foreach (InputGesture gesture in command.InputGestures) { var iBind = new InputBinding(command, gesture); iBind.CommandParameter = this; this.InputBindings.Add(iBind); } } }
// menuItemExit is defined in XAML menuItemExit.Command = CommandBank.CloseWindow; menuItemExit.CommandParameter = this; //... }
//.... } I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event. Let me know if you have any follow up questions.:) | [
"wpf",
"design-patterns",
"command"
] | 37 | 38 | 9,471 | 4 | 0 | 2008-08-12T04:18:30.853000 | 2008-08-12T04:58:38.620000 |
8,472 | 8,637 | Practical non-image based CAPTCHA approaches? | It looks like we'll be adding CAPTCHA support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here! We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense: http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible! However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky. I have written a traditional CAPTCHA control for ASP.NET which we can re-use. However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request. I've seen things like.. ASCII text captcha: \/\/(_)\/\/ math puzzles: what is 7 minus 3 times 2? trivia questions: what tastes better, a toad or a popsicle? Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based compatible CAPTCHA if possible. Ideas? | A method that I have developed and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.: I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for: var antiSpam = function() { if (document.getElementById("antiSpam")) { a = document.getElementById("antiSpam"); if (isNaN(a.value) == true) { a.value = 0; } else { a.value = parseInt(a.value) + 1; } } setTimeout("antiSpam()", 1000); }
antiSpam(); Then when the form is submitted, If the antispam value is still "lalalala", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through. If AntiSpam = A Integer If AntiSpam >= 10 Comment = Approved Else Comment = Spam Else Comment = Spam The theory being that: A spam bot will not support JavaScript and will submit what it sees If the bot does support JavaScript it will submit the form instantly The commenter has at least read some of the page before posting The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem. Response to comments @MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call. @AviD: I'm aware that this method is prone to direct attacks as I've mentioned on my blog. However, it will defend against your average spam bot which blindly submits rubbish to any form it can find. | Practical non-image based CAPTCHA approaches? It looks like we'll be adding CAPTCHA support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here! We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense: http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible! However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky. I have written a traditional CAPTCHA control for ASP.NET which we can re-use. However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request. I've seen things like.. ASCII text captcha: \/\/(_)\/\/ math puzzles: what is 7 minus 3 times 2? trivia questions: what tastes better, a toad or a popsicle? Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based compatible CAPTCHA if possible. Ideas? | TITLE:
Practical non-image based CAPTCHA approaches?
QUESTION:
It looks like we'll be adding CAPTCHA support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here! We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense: http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs The advantage of this approach is that, for most people, the CAPTCHA won't ever be visible! However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky. I have written a traditional CAPTCHA control for ASP.NET which we can re-use. However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request. I've seen things like.. ASCII text captcha: \/\/(_)\/\/ math puzzles: what is 7 minus 3 times 2? trivia questions: what tastes better, a toad or a popsicle? Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based compatible CAPTCHA if possible. Ideas?
ANSWER:
A method that I have developed and which seems to work perfectly (although I probably don't get as much comment spam as you), is to have a hidden field and fill it with a bogus value e.g.: I then have a piece of JavaScript which updates the value every second with the number of seconds the page has been loaded for: var antiSpam = function() { if (document.getElementById("antiSpam")) { a = document.getElementById("antiSpam"); if (isNaN(a.value) == true) { a.value = 0; } else { a.value = parseInt(a.value) + 1; } } setTimeout("antiSpam()", 1000); }
antiSpam(); Then when the form is submitted, If the antispam value is still "lalalala", then I mark it as spam. If the antispam value is an integer, I check to see if it is above something like 10 (seconds). If it's below 10, I mark it as spam, if it's 10 or more, I let it through. If AntiSpam = A Integer If AntiSpam >= 10 Comment = Approved Else Comment = Spam Else Comment = Spam The theory being that: A spam bot will not support JavaScript and will submit what it sees If the bot does support JavaScript it will submit the form instantly The commenter has at least read some of the page before posting The downside to this method is that it requires JavaScript, and if you don't have JavaScript enabled, your comment will be marked as spam, however, I do review comments marked as spam, so this is not a problem. Response to comments @MrAnalogy: The server side approach sounds quite a good idea and is exactly the same as doing it in JavaScript. Good Call. @AviD: I'm aware that this method is prone to direct attacks as I've mentioned on my blog. However, it will defend against your average spam bot which blindly submits rubbish to any form it can find. | [
"security",
"language-agnostic",
"captcha"
] | 317 | 205 | 83,757 | 103 | 0 | 2008-08-12T04:59:35.017000 | 2008-08-12T09:34:30.670000 |
8,485 | 49,184 | Use the routing engine for form submissions in ASP.NET MVC Preview 4 | I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions. For example, I have a route like this: routes.MapRoute( "TestController-TestAction", "TestController.mvc/TestAction/{paramName}", new { controller = "TestController", action = "TestAction", id = "TestTopic" } ); And a form declaration that looks like this: <% using (Html.Form("TestController", "TestAction", FormMethod.Get)) { %> <% } %> which renders to: The resulting URL of a form submission is: localhost/TestController.mvc/TestAction?paramName=value Is there any way to have this form submission route to the desired URL of: localhost/TestController.mvc/TestAction/value The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript. | Solution: public ActionResult TestAction(string paramName) { if (!String.IsNullOrEmpty(Request["paramName"])) { return RedirectToAction("TestAction", new { paramName = Request["paramName"]}); } /*... */ } | Use the routing engine for form submissions in ASP.NET MVC Preview 4 I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions. For example, I have a route like this: routes.MapRoute( "TestController-TestAction", "TestController.mvc/TestAction/{paramName}", new { controller = "TestController", action = "TestAction", id = "TestTopic" } ); And a form declaration that looks like this: <% using (Html.Form("TestController", "TestAction", FormMethod.Get)) { %> <% } %> which renders to: The resulting URL of a form submission is: localhost/TestController.mvc/TestAction?paramName=value Is there any way to have this form submission route to the desired URL of: localhost/TestController.mvc/TestAction/value The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript. | TITLE:
Use the routing engine for form submissions in ASP.NET MVC Preview 4
QUESTION:
I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions. For example, I have a route like this: routes.MapRoute( "TestController-TestAction", "TestController.mvc/TestAction/{paramName}", new { controller = "TestController", action = "TestAction", id = "TestTopic" } ); And a form declaration that looks like this: <% using (Html.Form("TestController", "TestAction", FormMethod.Get)) { %> <% } %> which renders to: The resulting URL of a form submission is: localhost/TestController.mvc/TestAction?paramName=value Is there any way to have this form submission route to the desired URL of: localhost/TestController.mvc/TestAction/value The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.
ANSWER:
Solution: public ActionResult TestAction(string paramName) { if (!String.IsNullOrEmpty(Request["paramName"])) { return RedirectToAction("TestAction", new { paramName = Request["paramName"]}); } /*... */ } | [
"asp.net-mvc",
"forms",
"asp.net-mvc-routing"
] | 12 | 9 | 3,567 | 3 | 0 | 2008-08-12T05:16:01.427000 | 2008-09-08T04:58:18.700000 |
8,493 | 15,363 | What's in your .procmailrc | Are there any handy general items you put in your.procmailrc file? | Many mailers prefix a mail's subject with "Re: " when replying, if that prefix isn't already there. German Outlook instead prefixes with "AW: " (for "AntWort") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like "Re: AW: Re: AW: Re: AW: Re: AW: Lunch". So I now have::0f * ^Subject: (Antwort|AW): |sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\1Re: \7\nX-Orig-Subject: \2\7/' Which curtails these (and an "Antwort: " prefix that I've evidently also been bothered by at some point) down to a single "Re: ". | What's in your .procmailrc Are there any handy general items you put in your.procmailrc file? | TITLE:
What's in your .procmailrc
QUESTION:
Are there any handy general items you put in your.procmailrc file?
ANSWER:
Many mailers prefix a mail's subject with "Re: " when replying, if that prefix isn't already there. German Outlook instead prefixes with "AW: " (for "AntWort") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like "Re: AW: Re: AW: Re: AW: Re: AW: Lunch". So I now have::0f * ^Subject: (Antwort|AW): |sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\1Re: \7\nX-Orig-Subject: \2\7/' Which curtails these (and an "Antwort: " prefix that I've evidently also been bothered by at some point) down to a single "Re: ". | [
"email",
"unix",
"procmail"
] | 6 | 5 | 1,259 | 4 | 0 | 2008-08-12T05:24:36.307000 | 2008-08-18T23:15:11.400000 |
8,508 | 8,515 | How should I monitor potential threats to my site? | By looking at our DB's error log, we found that there was a constant stream of almost successful SQL injection attacks. Some quick coding avoided that, but how could I have setup a monitor for both the DB and Web server (including POST requests) to check for this? By this I mean if there are off the shelf tools for script-kiddies, are there off the shelf tools that will alert you to their sudden random interest in your site? | Funnily enough, Scott Hanselman had a post on UrlScan today which is one thing you could do to help monitor and minimize potential threats. It's a pretty interesting read. | How should I monitor potential threats to my site? By looking at our DB's error log, we found that there was a constant stream of almost successful SQL injection attacks. Some quick coding avoided that, but how could I have setup a monitor for both the DB and Web server (including POST requests) to check for this? By this I mean if there are off the shelf tools for script-kiddies, are there off the shelf tools that will alert you to their sudden random interest in your site? | TITLE:
How should I monitor potential threats to my site?
QUESTION:
By looking at our DB's error log, we found that there was a constant stream of almost successful SQL injection attacks. Some quick coding avoided that, but how could I have setup a monitor for both the DB and Web server (including POST requests) to check for this? By this I mean if there are off the shelf tools for script-kiddies, are there off the shelf tools that will alert you to their sudden random interest in your site?
ANSWER:
Funnily enough, Scott Hanselman had a post on UrlScan today which is one thing you could do to help monitor and minimize potential threats. It's a pretty interesting read. | [
"monitor",
"alert"
] | 6 | 5 | 624 | 5 | 0 | 2008-08-12T05:40:49.847000 | 2008-08-12T05:47:15.777000 |
8,517 | 36,791 | Lucene exact ordering | I've had this long term issue in not quite understanding how to implement a decent Lucene sort or ranking. Say I have a list of cities and their populations. If someone searches "new" or "london" I want the list of prefix matches ordered by population, and I have that working with a prefix search and an sort by field reversed, where there is a population field, IE New Mexico, New York; or London, Londonderry. However I also always want the exact matching name to be at the top. So in the case of "London" the list should show "London, London, Londonderry" where the first London is in the UK and the second London is in Connecticut, even if Londonderry has a higher population than London CT. Does anyone have a single query solution? | dlamblin,let me see if I get this correctly: You want to make a prefix-based query, and then sort the results by population, and maybe combine the sort order with preference for exact matches. I suggest you separate the search from the sort and use a CustomSorter for the sorting: Here's a blog entry describing a custom sorter. The classic Lucene book describes this well. | Lucene exact ordering I've had this long term issue in not quite understanding how to implement a decent Lucene sort or ranking. Say I have a list of cities and their populations. If someone searches "new" or "london" I want the list of prefix matches ordered by population, and I have that working with a prefix search and an sort by field reversed, where there is a population field, IE New Mexico, New York; or London, Londonderry. However I also always want the exact matching name to be at the top. So in the case of "London" the list should show "London, London, Londonderry" where the first London is in the UK and the second London is in Connecticut, even if Londonderry has a higher population than London CT. Does anyone have a single query solution? | TITLE:
Lucene exact ordering
QUESTION:
I've had this long term issue in not quite understanding how to implement a decent Lucene sort or ranking. Say I have a list of cities and their populations. If someone searches "new" or "london" I want the list of prefix matches ordered by population, and I have that working with a prefix search and an sort by field reversed, where there is a population field, IE New Mexico, New York; or London, Londonderry. However I also always want the exact matching name to be at the top. So in the case of "London" the list should show "London, London, Londonderry" where the first London is in the UK and the second London is in Connecticut, even if Londonderry has a higher population than London CT. Does anyone have a single query solution?
ANSWER:
dlamblin,let me see if I get this correctly: You want to make a prefix-based query, and then sort the results by population, and maybe combine the sort order with preference for exact matches. I suggest you separate the search from the sort and use a CustomSorter for the sorting: Here's a blog entry describing a custom sorter. The classic Lucene book describes this well. | [
"lucene"
] | 4 | 3 | 2,887 | 3 | 0 | 2008-08-12T05:51:01.947000 | 2008-08-31T11:40:56.760000 |
8,532 | 9,085 | With Lucene: Why do I get a Too Many Clauses error if I do a prefix search? | I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a Too Many Clauses error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query. Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries? | I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite() From: http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html public Query rewrite(IndexReader reader) throws IOException
Expert: called to re-write queries into primitive queries. For example, a PrefixQuery will be rewritten into a BooleanQuery that consists of TermQuerys.
Throws: IOException | With Lucene: Why do I get a Too Many Clauses error if I do a prefix search? I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a Too Many Clauses error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query. Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries? | TITLE:
With Lucene: Why do I get a Too Many Clauses error if I do a prefix search?
QUESTION:
I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a Too Many Clauses error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query. Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries?
ANSWER:
I've hit this before. It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite() From: http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html public Query rewrite(IndexReader reader) throws IOException
Expert: called to re-write queries into primitive queries. For example, a PrefixQuery will be rewritten into a BooleanQuery that consists of TermQuerys.
Throws: IOException | [
"exception",
"lucene"
] | 8 | 5 | 7,032 | 3 | 0 | 2008-08-12T06:04:48.940000 | 2008-08-12T17:58:08.627000 |
8,545 | 8,559 | Closet server versus Colo? | As a programmer I need a place to store my stuff. I've been running a server in my parents closet for a long time, but I recently came across a decent 2U server. I have no experience dealing with hosting companies, beyond the very cheap stuff, and I'm wondering what I should look for in a colo or if I should just keep my closet server. | There are three major factors here. Cost. The colo will obviously be more expensive than sticking a server in your parents' closet. Quality. The colo should be a lot more reliable than the server in your parents' closet. They aren't as likely to go down when there's a power surge. They should provide some support if things do go wrong on their end. They will also likely give you better bandwidth. Convenience. It is a lot easier to fix a broken box when you can walk over to it and plug up a monitor. Going to the colo to troubleshoot is probably not going to be convenient, if it's even possible. Transferring files from your laptop to the server in the closet is also going to be a lot faster than transferring over the Internet. On the other hand, if it's your box in the closet, you have to deal with the hardware problems, so it can balance out. Personally, I pay for a (shared) server. I find that having someone else handle the server is worth it. Uploading large files can get really frustrating, but having to maintain an extra box in the closet is too much hassle for me. You really have to decide what you value most. Is it worth the extra money to you to have a more reliable, more hands-off server? | Closet server versus Colo? As a programmer I need a place to store my stuff. I've been running a server in my parents closet for a long time, but I recently came across a decent 2U server. I have no experience dealing with hosting companies, beyond the very cheap stuff, and I'm wondering what I should look for in a colo or if I should just keep my closet server. | TITLE:
Closet server versus Colo?
QUESTION:
As a programmer I need a place to store my stuff. I've been running a server in my parents closet for a long time, but I recently came across a decent 2U server. I have no experience dealing with hosting companies, beyond the very cheap stuff, and I'm wondering what I should look for in a colo or if I should just keep my closet server.
ANSWER:
There are three major factors here. Cost. The colo will obviously be more expensive than sticking a server in your parents' closet. Quality. The colo should be a lot more reliable than the server in your parents' closet. They aren't as likely to go down when there's a power surge. They should provide some support if things do go wrong on their end. They will also likely give you better bandwidth. Convenience. It is a lot easier to fix a broken box when you can walk over to it and plug up a monitor. Going to the colo to troubleshoot is probably not going to be convenient, if it's even possible. Transferring files from your laptop to the server in the closet is also going to be a lot faster than transferring over the Internet. On the other hand, if it's your box in the closet, you have to deal with the hardware problems, so it can balance out. Personally, I pay for a (shared) server. I find that having someone else handle the server is worth it. Uploading large files can get really frustrating, but having to maintain an extra box in the closet is too much hassle for me. You really have to decide what you value most. Is it worth the extra money to you to have a more reliable, more hands-off server? | [
"hardware",
"storage"
] | 1 | 3 | 654 | 3 | 0 | 2008-08-12T06:18:08.680000 | 2008-08-12T06:48:26.340000 |
8,546 | 8,553 | Is there a "try to lock, skip if timed out" operation in C#? | I need to try to lock on an object, and if its already locked just continue (after time out, or without it). The C# lock statement is blocking. | I believe that you can use Monitor.TryEnter(). The lock statement just translates to a Monitor.Enter() call and a try catch block. | Is there a "try to lock, skip if timed out" operation in C#? I need to try to lock on an object, and if its already locked just continue (after time out, or without it). The C# lock statement is blocking. | TITLE:
Is there a "try to lock, skip if timed out" operation in C#?
QUESTION:
I need to try to lock on an object, and if its already locked just continue (after time out, or without it). The C# lock statement is blocking.
ANSWER:
I believe that you can use Monitor.TryEnter(). The lock statement just translates to a Monitor.Enter() call and a try catch block. | [
"c#",
"multithreading",
"locking"
] | 74 | 44 | 33,959 | 6 | 0 | 2008-08-12T06:19:38.550000 | 2008-08-12T06:29:24.070000 |
8,549 | 8,580 | Visual Studio refactoring: Remove method | Is there any Visual Studio Add-In that can do the remove method refactoring? Suppose you have the following method: Result DoSomething(parameters) { return ComputeResult(parameters); } Or the variant where Result is void. The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call. | If I understand the question, then Resharper calls this 'inline method' - Ctrl - R + I | Visual Studio refactoring: Remove method Is there any Visual Studio Add-In that can do the remove method refactoring? Suppose you have the following method: Result DoSomething(parameters) { return ComputeResult(parameters); } Or the variant where Result is void. The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call. | TITLE:
Visual Studio refactoring: Remove method
QUESTION:
Is there any Visual Studio Add-In that can do the remove method refactoring? Suppose you have the following method: Result DoSomething(parameters) { return ComputeResult(parameters); } Or the variant where Result is void. The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call.
ANSWER:
If I understand the question, then Resharper calls this 'inline method' - Ctrl - R + I | [
"visual-studio",
"refactoring",
"methods"
] | 7 | 6 | 7,326 | 6 | 0 | 2008-08-12T06:22:06.377000 | 2008-08-12T07:48:33.443000 |
8,569 | 13,367 | What's your "best practice" for the first Java EE Spring project? | I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices, tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... | Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on: MyProject / src / main / resources / spring / datasource.xml - My single data source bean. persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans. services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans. controllers.xml - My Spring MVC controllers. Depends on services.xml beans. views.xml - My view implementations. This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you. In my (limited) experience, I've seen this approach yeild the following benefits: Clearer architecture Clearly named context files gives those unfamiliar with your project structure a reasonable place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier. Helps domain design If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples: Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml, or put them in their own transactionPolicy.xml? Talk it over with your team. Should your transaction policy be pluggable? Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments? Integration testing You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans). Specifically, you can annotate an integration test class as such: @ContextConfiguration(locations = { "/spring/datasource.xml", "/spring/persistence.xml" }) Works well with Spring IDE's Beans Graph Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph. I've used this before to give new team members a high-level overview of our application's organization. | What's your "best practice" for the first Java EE Spring project? I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices, tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate... | TITLE:
What's your "best practice" for the first Java EE Spring project?
QUESTION:
I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off. Do you have any best practices, tipps or major DO NOTs for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...
ANSWER:
Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on: MyProject / src / main / resources / spring / datasource.xml - My single data source bean. persistence.xml - My DAOs/Repositories. Depends on datasource.xml beans. services.xml - Service layer implementations. These are usually the beans to which I apply transactionality using AOP. Depends on persistence.xml beans. controllers.xml - My Spring MVC controllers. Depends on services.xml beans. views.xml - My view implementations. This list is neither perfect nor exhaustive, but I hope it illustrates the point. Choose whatever naming strategy and granularity works best for you. In my (limited) experience, I've seen this approach yeild the following benefits: Clearer architecture Clearly named context files gives those unfamiliar with your project structure a reasonable place to start looking for bean definitions. Can make detecting circular/unwanted dependencies a little easier. Helps domain design If you want to add a bean definition, but it doesn't fit well in any of your context files, perhaps there's a new concept or concern emerging? Examples: Suppose you want to make your Service layer transactional with AOP. Do you add those bean definitions to services.xml, or put them in their own transactionPolicy.xml? Talk it over with your team. Should your transaction policy be pluggable? Add Acegi/Spring Security beans to your controllers.xml file, or create a security.xml context file? Do you have different security requirements for different deployments/environments? Integration testing You can wire up a subset of your application for integration testing (ex: given the above files, to test the database you need to create only datasource.xml and persistence.xml beans). Specifically, you can annotate an integration test class as such: @ContextConfiguration(locations = { "/spring/datasource.xml", "/spring/persistence.xml" }) Works well with Spring IDE's Beans Graph Having lots of focused and well-named context files makes it easy to create custom BeansConfigSets to visualize the layers of your app using Spring IDE's Beans Graph. I've used this before to give new team members a high-level overview of our application's organization. | [
"java",
"spring",
"jakarta-ee",
"aop"
] | 32 | 28 | 11,733 | 11 | 0 | 2008-08-12T07:36:14.107000 | 2008-08-16T21:12:19.233000 |
8,585 | 8,593 | Watch for change in ip address status | Is there a way to watch for changes in the ip-address much the same as it is possible to watch for changes to files using the FileSystemWatcher? I'm connecting to a machine via tcp/ip but it takes a while until it gives me an ip-address. I would like to dim out the connect button until I have a valid ip-address. | Check NetworkChange class. It raises an event when a network address changes. | Watch for change in ip address status Is there a way to watch for changes in the ip-address much the same as it is possible to watch for changes to files using the FileSystemWatcher? I'm connecting to a machine via tcp/ip but it takes a while until it gives me an ip-address. I would like to dim out the connect button until I have a valid ip-address. | TITLE:
Watch for change in ip address status
QUESTION:
Is there a way to watch for changes in the ip-address much the same as it is possible to watch for changes to files using the FileSystemWatcher? I'm connecting to a machine via tcp/ip but it takes a while until it gives me an ip-address. I would like to dim out the connect button until I have a valid ip-address.
ANSWER:
Check NetworkChange class. It raises an event when a network address changes. | [
".net",
"windows"
] | 5 | 6 | 585 | 1 | 0 | 2008-08-12T07:53:40.857000 | 2008-08-12T07:59:54.573000 |
8,599 | 8,655 | Best binary XML format for JavaME | Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device. And it goes without saying that it needs to be smaller than XML, and faster to parse. The data would be something akin to SVG. | You might want to take a look at wbxml (Wireless Binary XML) it is optimized for size, and often used on mobile phones, but it is not optimized for parsing speed. | Best binary XML format for JavaME Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device. And it goes without saying that it needs to be smaller than XML, and faster to parse. The data would be something akin to SVG. | TITLE:
Best binary XML format for JavaME
QUESTION:
Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device. And it goes without saying that it needs to be smaller than XML, and faster to parse. The data would be something akin to SVG.
ANSWER:
You might want to take a look at wbxml (Wireless Binary XML) it is optimized for size, and often used on mobile phones, but it is not optimized for parsing speed. | [
"java",
"xml",
"java-me",
"mobile"
] | 10 | 6 | 1,685 | 4 | 0 | 2008-08-12T08:08:11.327000 | 2008-08-12T10:42:35.917000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.