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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27,983 | 30,503 | SQL Group By with an Order By | I have a table of tags and want to get the highest count tags from the list. Sample data looks like this id (1) tag ('night') id (2) tag ('awesome') id (3) tag ('night') using SELECT COUNT(*), `Tag` from `images-tags` GROUP BY `Tag` gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so. I tried this... SELECT COUNT(id), `Tag` from `images-tags` GROUP BY `Tag` ORDER BY COUNT(id) DESC LIMIT 20 and I keep getting an "Invalid use of group function - ErrNr 1111" What am I doing wrong? I'm using MySQL 4.1.25-Debian | In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias: SELECT COUNT(id) AS theCount, `Tag` from `images-tags` GROUP BY `Tag` ORDER BY theCount DESC LIMIT 20 | SQL Group By with an Order By I have a table of tags and want to get the highest count tags from the list. Sample data looks like this id (1) tag ('night') id (2) tag ('awesome') id (3) tag ('night') using SELECT COUNT(*), `Tag` from `images-tags` GROUP BY `Tag` gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so. I tried this... SELECT COUNT(id), `Tag` from `images-tags` GROUP BY `Tag` ORDER BY COUNT(id) DESC LIMIT 20 and I keep getting an "Invalid use of group function - ErrNr 1111" What am I doing wrong? I'm using MySQL 4.1.25-Debian | TITLE:
SQL Group By with an Order By
QUESTION:
I have a table of tags and want to get the highest count tags from the list. Sample data looks like this id (1) tag ('night') id (2) tag ('awesome') id (3) tag ('night') using SELECT COUNT(*), `Tag` from `images-tags` GROUP BY `Tag` gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so. I tried this... SELECT COUNT(id), `Tag` from `images-tags` GROUP BY `Tag` ORDER BY COUNT(id) DESC LIMIT 20 and I keep getting an "Invalid use of group function - ErrNr 1111" What am I doing wrong? I'm using MySQL 4.1.25-Debian
ANSWER:
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias: SELECT COUNT(id) AS theCount, `Tag` from `images-tags` GROUP BY `Tag` ORDER BY theCount DESC LIMIT 20 | [
"mysql",
"sql",
"mysql-error-1111"
] | 164 | 243 | 713,427 | 5 | 0 | 2008-08-26T13:09:15.883000 | 2008-08-27T15:46:41.113000 |
27,998 | 28,289 | Exporting a C++ class from a DLL | Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a DLL with accessible functions I just export them using the standard __declspec(dllexport) directive. Then access them either dynamically via LoadLibrary() or at compile time with a header and lib file. How do you do this when you want to export an entire class (and all it's public methods and properties)? Is it possible to dynamically load that class at runtime and if so, how? How would you do it with a header and lib for compile time linking? | What about late-binding? As in loading it with LoadLibrary() and GetProcAddress()? I'm used being able to load the library at run time and it would be great if you could do that here. So there are two ways to load the DLL. The first is to reference one or more symbols from the DLL (your classname, for example), supply an appropriate import.LIB and let the linker figure everything out. The second is to explicitly load the DLL via LoadLibrary. Either approach works fine for C-level function exports. You can either let the linker handle it or call GetProcAddress as you noted. But when it comes to exported classes, typically only the first approach is used, i.e., implicitly link to the DLL. In this case the DLL is loaded at application start time, and the application fails to load if the DLL can't be found. If you want to link to a class defined in a DLL, and you want that DLL to be loaded dynamically, sometime after program initiation, you have two options: Create objects of the class using a special factory function, which internally will have to use (a tiny bit of) assembler to "hook up" newly created objects to their appropriate offsets. This has to be done at run-time AFTER the DLL has been loaded, obviously. A good explanation of this approach can be found here. Use a delay-load DLL. All things considered... probably better to just go with implicit linking, in which case you definitely want to use the preprocessor technique shown above. In fact, if you create a new DLL in Visual Studio and choose the "export symbols" option these macros will be created for you. Good luck... | Exporting a C++ class from a DLL Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a DLL with accessible functions I just export them using the standard __declspec(dllexport) directive. Then access them either dynamically via LoadLibrary() or at compile time with a header and lib file. How do you do this when you want to export an entire class (and all it's public methods and properties)? Is it possible to dynamically load that class at runtime and if so, how? How would you do it with a header and lib for compile time linking? | TITLE:
Exporting a C++ class from a DLL
QUESTION:
Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a DLL with accessible functions I just export them using the standard __declspec(dllexport) directive. Then access them either dynamically via LoadLibrary() or at compile time with a header and lib file. How do you do this when you want to export an entire class (and all it's public methods and properties)? Is it possible to dynamically load that class at runtime and if so, how? How would you do it with a header and lib for compile time linking?
ANSWER:
What about late-binding? As in loading it with LoadLibrary() and GetProcAddress()? I'm used being able to load the library at run time and it would be great if you could do that here. So there are two ways to load the DLL. The first is to reference one or more symbols from the DLL (your classname, for example), supply an appropriate import.LIB and let the linker figure everything out. The second is to explicitly load the DLL via LoadLibrary. Either approach works fine for C-level function exports. You can either let the linker handle it or call GetProcAddress as you noted. But when it comes to exported classes, typically only the first approach is used, i.e., implicitly link to the DLL. In this case the DLL is loaded at application start time, and the application fails to load if the DLL can't be found. If you want to link to a class defined in a DLL, and you want that DLL to be loaded dynamically, sometime after program initiation, you have two options: Create objects of the class using a special factory function, which internally will have to use (a tiny bit of) assembler to "hook up" newly created objects to their appropriate offsets. This has to be done at run-time AFTER the DLL has been loaded, obviously. A good explanation of this approach can be found here. Use a delay-load DLL. All things considered... probably better to just go with implicit linking, in which case you definitely want to use the preprocessor technique shown above. In fact, if you create a new DLL in Visual Studio and choose the "export symbols" option these macros will be created for you. Good luck... | [
"c++",
"windows",
"dll"
] | 29 | 17 | 43,818 | 6 | 0 | 2008-08-26T13:18:30.480000 | 2008-08-26T15:07:29.330000 |
28,002 | 1,255,015 | Regular cast vs. static_cast vs. dynamic_cast | I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. MyClass *m = (MyClass *)ptr; all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code? MyClass *m = (MyClass *)ptr; MyClass *m = static_cast (ptr); MyClass *m = dynamic_cast (ptr); | static_cast static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example: void func(void *data) { // Conversion from MyClass* -> void* is implicit MyClass *c = static_cast (data);... }
int main() { MyClass c; start_thread(&func, &c) // func(&c) will be called.join(); } In this example, you know that you passed a MyClass object, and thus there isn't any need for a runtime check to ensure this. dynamic_cast dynamic_cast is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case). if (JumpStm *j = dynamic_cast (&stm)) {... } else if (ExprStm *e = dynamic_cast (&stm)) {... } You can not use dynamic_cast for downcast (casting to a derived class) if the argument type is not polymorphic. For example, the following code is not valid, because Base doesn't contain any virtual function: struct Base { }; struct Derived: Base { }; int main() { Derived d; Base *b = &d dynamic_cast (b); // Invalid } An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion (assuming the base class is accessible, i.e. it's a public inheritance). Regular Cast These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe, because it does not use dynamic_cast. In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that. Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking. | Regular cast vs. static_cast vs. dynamic_cast I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. MyClass *m = (MyClass *)ptr; all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code? MyClass *m = (MyClass *)ptr; MyClass *m = static_cast (ptr); MyClass *m = dynamic_cast (ptr); | TITLE:
Regular cast vs. static_cast vs. dynamic_cast
QUESTION:
I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. MyClass *m = (MyClass *)ptr; all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code? MyClass *m = (MyClass *)ptr; MyClass *m = static_cast (ptr); MyClass *m = dynamic_cast (ptr);
ANSWER:
static_cast static_cast is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example: void func(void *data) { // Conversion from MyClass* -> void* is implicit MyClass *c = static_cast (data);... }
int main() { MyClass c; start_thread(&func, &c) // func(&c) will be called.join(); } In this example, you know that you passed a MyClass object, and thus there isn't any need for a runtime check to ensure this. dynamic_cast dynamic_cast is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast exception is thrown in that case). if (JumpStm *j = dynamic_cast (&stm)) {... } else if (ExprStm *e = dynamic_cast (&stm)) {... } You can not use dynamic_cast for downcast (casting to a derived class) if the argument type is not polymorphic. For example, the following code is not valid, because Base doesn't contain any virtual function: struct Base { }; struct Derived: Base { }; int main() { Derived d; Base *b = &d dynamic_cast (b); // Invalid } An "up-cast" (cast to the base class) is always valid with both static_cast and dynamic_cast, and also without any cast, as an "up-cast" is an implicit conversion (assuming the base class is accessible, i.e. it's a public inheritance). Regular Cast These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast. Needless to say, this is much more powerful as it combines all of const_cast, static_cast and reinterpret_cast, but it's also unsafe, because it does not use dynamic_cast. In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast sequence would give you a compile-time error for that. Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking. | [
"c++",
"pointers",
"casting"
] | 2,043 | 1,849 | 909,200 | 8 | 0 | 2008-08-26T13:20:55.357000 | 2009-08-10T13:50:45.557000 |
28,003 | 28,008 | Use table metadata for select statement in SQL Server? | I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server. I want to do something like: select [table] from [db] where table [has column 'classtypeid'] How can I do something like this? | Use the ANSI information_schema views, this will also work in MySQL select table_name from information_schema.columns where column_name = 'classtypeid' | Use table metadata for select statement in SQL Server? I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server. I want to do something like: select [table] from [db] where table [has column 'classtypeid'] How can I do something like this? | TITLE:
Use table metadata for select statement in SQL Server?
QUESTION:
I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server. I want to do something like: select [table] from [db] where table [has column 'classtypeid'] How can I do something like this?
ANSWER:
Use the ANSI information_schema views, this will also work in MySQL select table_name from information_schema.columns where column_name = 'classtypeid' | [
"sql",
"sql-server"
] | 3 | 5 | 2,952 | 2 | 0 | 2008-08-26T13:20:57.087000 | 2008-08-26T13:23:08.580000 |
28,011 | 28,148 | Ruby / Rails pre-epoch dates on windows | Working with dates in ruby and rails on windows, I'm having problems with pre-epoch dates (before 1970) throwing out of range exceptions. I tried using both Time and DateTime objects, but still have the same problems. | If you only need dates (no times), the Date class in ruby should handle dates before 1970. But it has only a resolution of days. I don't know if there are solutions, if you also need times before 1970 (source) | Ruby / Rails pre-epoch dates on windows Working with dates in ruby and rails on windows, I'm having problems with pre-epoch dates (before 1970) throwing out of range exceptions. I tried using both Time and DateTime objects, but still have the same problems. | TITLE:
Ruby / Rails pre-epoch dates on windows
QUESTION:
Working with dates in ruby and rails on windows, I'm having problems with pre-epoch dates (before 1970) throwing out of range exceptions. I tried using both Time and DateTime objects, but still have the same problems.
ANSWER:
If you only need dates (no times), the Date class in ruby should handle dates before 1970. But it has only a resolution of days. I don't know if there are solutions, if you also need times before 1970 (source) | [
"ruby-on-rails",
"ruby",
"date"
] | 2 | 1 | 717 | 3 | 0 | 2008-08-26T13:23:50.543000 | 2008-08-26T14:14:26.943000 |
28,051 | 28,055 | Best way to share ASP.NET .ascx controls across different website applications? | Suppose you have 2 different ASP.NET applications in IIS. Also, you have some ASCX controls that you want to share across these 2 applications. What's the best way to create a "user control library", so that you can use the same control implementation in the 2 applications, withuot having to duplicate code? Controls have ASCX with HTML + code behind. Composite controls will be difficult, because we work with designers who use the HTML syntax in the ASCX files to style the controls. Tundey, we use SVN here. Do you have an example on how to implement your suggestion? How can SVN share the ASP.NET controls? Thanks! | You would need to create composite controls instead of.ASCX controls if you wanted to be able to use them in separate projects. | Best way to share ASP.NET .ascx controls across different website applications? Suppose you have 2 different ASP.NET applications in IIS. Also, you have some ASCX controls that you want to share across these 2 applications. What's the best way to create a "user control library", so that you can use the same control implementation in the 2 applications, withuot having to duplicate code? Controls have ASCX with HTML + code behind. Composite controls will be difficult, because we work with designers who use the HTML syntax in the ASCX files to style the controls. Tundey, we use SVN here. Do you have an example on how to implement your suggestion? How can SVN share the ASP.NET controls? Thanks! | TITLE:
Best way to share ASP.NET .ascx controls across different website applications?
QUESTION:
Suppose you have 2 different ASP.NET applications in IIS. Also, you have some ASCX controls that you want to share across these 2 applications. What's the best way to create a "user control library", so that you can use the same control implementation in the 2 applications, withuot having to duplicate code? Controls have ASCX with HTML + code behind. Composite controls will be difficult, because we work with designers who use the HTML syntax in the ASCX files to style the controls. Tundey, we use SVN here. Do you have an example on how to implement your suggestion? How can SVN share the ASP.NET controls? Thanks!
ANSWER:
You would need to create composite controls instead of.ASCX controls if you wanted to be able to use them in separate projects. | [
"asp.net"
] | 15 | 6 | 12,493 | 10 | 0 | 2008-08-26T13:38:04.160000 | 2008-08-26T13:39:47.870000 |
28,092 | 28,252 | WPF Listbox style with a button | I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style? Here is my style (affected code only): Thanks! | Take a look at RoutedCommand s. Define your command in myclass somewhere as follows: public static readonly RoutedCommand Login = new RoutedCommand(); Now define your button with this command: You can use CommandParameter for extra information.. Now last but not least, start listening to your command: In the constructor of the class you wish to do some nice stuff, you place: CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin)); or in XAML: And you implement the delegate the CommandBinding needs: private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e) { //Your code goes here... e has your parameter! } You can start listening to this command everywhere in your visual tree! Hope this helps PS You can also define the CommandBinding with a CanExecute delegate which will even disable your command if the CanExecute says so:) PPS Here is another example: RoutedCommands in WPF | WPF Listbox style with a button I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style? Here is my style (affected code only): Thanks! | TITLE:
WPF Listbox style with a button
QUESTION:
I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems style? Here is my style (affected code only): Thanks!
ANSWER:
Take a look at RoutedCommand s. Define your command in myclass somewhere as follows: public static readonly RoutedCommand Login = new RoutedCommand(); Now define your button with this command: You can use CommandParameter for extra information.. Now last but not least, start listening to your command: In the constructor of the class you wish to do some nice stuff, you place: CommandBindings.Add(new CommandBinding(myclass.Login, ExecuteLogin)); or in XAML: And you implement the delegate the CommandBinding needs: private void ExecuteLogin(object sender, ExecutedRoutedEventArgs e) { //Your code goes here... e has your parameter! } You can start listening to this command everywhere in your visual tree! Hope this helps PS You can also define the CommandBinding with a CanExecute delegate which will even disable your command if the CanExecute says so:) PPS Here is another example: RoutedCommands in WPF | [
"c#",
"wpf"
] | 7 | 10 | 8,329 | 3 | 0 | 2008-08-26T13:54:45.167000 | 2008-08-26T14:51:05.203000 |
28,098 | 28,111 | PHP equivalent of .NET/Java's toString() | How do I convert the value of a PHP variable to string? I was looking for something better than concatenating with an empty string: $myText = $myVar. ''; Like the ToString() method in Java or.NET. | You can use the casting operators: $myText = (string)$myVar; There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls. | PHP equivalent of .NET/Java's toString() How do I convert the value of a PHP variable to string? I was looking for something better than concatenating with an empty string: $myText = $myVar. ''; Like the ToString() method in Java or.NET. | TITLE:
PHP equivalent of .NET/Java's toString()
QUESTION:
How do I convert the value of a PHP variable to string? I was looking for something better than concatenating with an empty string: $myText = $myVar. ''; Like the ToString() method in Java or.NET.
ANSWER:
You can use the casting operators: $myText = (string)$myVar; There are more details for string casting and conversion in the Strings section of the PHP manual, including special handling for booleans and nulls. | [
"php",
"string"
] | 567 | 789 | 1,517,211 | 26 | 0 | 2008-08-26T13:56:49.873000 | 2008-08-26T14:01:50.047000 |
28,110 | 28,184 | SQL Server DateTime conversion failure | I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a varchar(50) field. I need to do a simple date comparison - datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 But it fails on the convert(): Conversion failed when converting datetime from character string. Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the convert()? Here is what I have now: select count(*) from MyTable where isdate(lastUpdate) > 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 @SQLMenace I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option. @Jon Limjap I've tried adding the third argument, and it makes no difference. @SQLMenace The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces) Wouldn't the isdate() check take care of this? I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days. @SQLMenace select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 @Brian Schkerke Place the CASE and ISDATE inside the CONVERT() function. Thanks! That did it. | Place the CASE and ISDATE inside the CONVERT() function. SELECT COUNT(*) FROM MyTable WHERE DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate) WHEN 1 THEN lastUpdate ELSE '12-30-1899' END), GetDate()) < 31 Replace '12-30-1899' with the default date of your choice. | SQL Server DateTime conversion failure I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a varchar(50) field. I need to do a simple date comparison - datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 But it fails on the convert(): Conversion failed when converting datetime from character string. Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the convert()? Here is what I have now: select count(*) from MyTable where isdate(lastUpdate) > 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 @SQLMenace I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option. @Jon Limjap I've tried adding the third argument, and it makes no difference. @SQLMenace The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces) Wouldn't the isdate() check take care of this? I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days. @SQLMenace select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 @Brian Schkerke Place the CASE and ISDATE inside the CONVERT() function. Thanks! That did it. | TITLE:
SQL Server DateTime conversion failure
QUESTION:
I have a large table with 1 million+ records. Unfortunately, the person who created the table decided to put dates in a varchar(50) field. I need to do a simple date comparison - datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 But it fails on the convert(): Conversion failed when converting datetime from character string. Apparently there is something in that field it doesn't like, and since there are so many records, I can't tell just by looking at it. How can I properly sanitize the entire date field so it does not fail on the convert()? Here is what I have now: select count(*) from MyTable where isdate(lastUpdate) > 0 and datediff(dd, convert(datetime, lastUpdate, 100), getDate()) < 31 @SQLMenace I'm not concerned about performance in this case. This is going to be a one time query. Changing the table to a datetime field is not an option. @Jon Limjap I've tried adding the third argument, and it makes no difference. @SQLMenace The problem is most likely how the data is stored, there are only two safe formats; ISO YYYYMMDD; ISO 8601 yyyy-mm-dd Thh:mm:ss:mmm (no spaces) Wouldn't the isdate() check take care of this? I don't have a need for 100% accuracy. I just want to get most of the records that are from the last 30 days. @SQLMenace select isdate('20080131') -- returns 1 select isdate('01312008') -- returns 0 @Brian Schkerke Place the CASE and ISDATE inside the CONVERT() function. Thanks! That did it.
ANSWER:
Place the CASE and ISDATE inside the CONVERT() function. SELECT COUNT(*) FROM MyTable WHERE DATEDIFF(dd, CONVERT(DATETIME, CASE IsDate(lastUpdate) WHEN 1 THEN lastUpdate ELSE '12-30-1899' END), GetDate()) < 31 Replace '12-30-1899' with the default date of your choice. | [
"sql-server",
"datetime"
] | 3 | 9 | 14,003 | 10 | 0 | 2008-08-26T14:01:43.090000 | 2008-08-26T14:27:08.053000 |
28,124 | 28,130 | calculating user defined formulas (with c++) | We would like to have user defined formulas in our c++ program. e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that? | If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. Lua is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated things, use Python instead. | calculating user defined formulas (with c++) We would like to have user defined formulas in our c++ program. e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that? | TITLE:
calculating user defined formulas (with c++)
QUESTION:
We would like to have user defined formulas in our c++ program. e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formula and add the new values. Any ideas / hints how to do something like this? So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that?
ANSWER:
If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. Lua is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated things, use Python instead. | [
"c++"
] | 11 | 2 | 3,688 | 8 | 0 | 2008-08-26T14:07:18.897000 | 2008-08-26T14:10:53.130000 |
28,147 | 28,170 | Feasibility of GPU as a CPU? | What do you think the future of GPU as a CPU initiatives like CUDA are? Do you think they are going to become mainstream and be the next adopted fad in the industry? Apple is building a new framework for using the GPU to do CPU tasks and there has been alot of success in the Nvidias CUDA project in the sciences. Would you suggest that a student commit time into this field? | First of all I don't think this questions really belongs on SO. In my opinion the GPU is a very interesting alternative whenever you do vector-based float mathematics. However this translates to: It will not become mainstream. Most mainstream (Desktop) applications do very few floating-point calculations. It has already gained traction in games (physics-engines) and in scientific calculations. If you consider any of those two as "mainstream", than yes, the GPU will become mainstream. I would not consider these two as mainstream and I therefore think, the GPU will raise to be the next adopted fad in the mainstream industry. If you, as a student have any interest in heavily physics based scientific calculations, you should absolutely commit some time to it (GPUs are very interesting pieces of hardware anyway). | Feasibility of GPU as a CPU? What do you think the future of GPU as a CPU initiatives like CUDA are? Do you think they are going to become mainstream and be the next adopted fad in the industry? Apple is building a new framework for using the GPU to do CPU tasks and there has been alot of success in the Nvidias CUDA project in the sciences. Would you suggest that a student commit time into this field? | TITLE:
Feasibility of GPU as a CPU?
QUESTION:
What do you think the future of GPU as a CPU initiatives like CUDA are? Do you think they are going to become mainstream and be the next adopted fad in the industry? Apple is building a new framework for using the GPU to do CPU tasks and there has been alot of success in the Nvidias CUDA project in the sciences. Would you suggest that a student commit time into this field?
ANSWER:
First of all I don't think this questions really belongs on SO. In my opinion the GPU is a very interesting alternative whenever you do vector-based float mathematics. However this translates to: It will not become mainstream. Most mainstream (Desktop) applications do very few floating-point calculations. It has already gained traction in games (physics-engines) and in scientific calculations. If you consider any of those two as "mainstream", than yes, the GPU will become mainstream. I would not consider these two as mainstream and I therefore think, the GPU will raise to be the next adopted fad in the mainstream industry. If you, as a student have any interest in heavily physics based scientific calculations, you should absolutely commit some time to it (GPUs are very interesting pieces of hardware anyway). | [
"cuda",
"cpu",
"gpu",
"gpgpu"
] | 13 | 5 | 2,696 | 8 | 0 | 2008-08-26T14:14:10.893000 | 2008-08-26T14:22:02.963000 |
28,150 | 28,220 | Create an Attribute to Break the Build | OK, this kind of follows on from my previous question. What I would really like to do is create some sort of attribute which allows me to decorate a method that will break the build. Much like the Obsolete("reason", true) attribute, but without falsely identifying obsolete code. To clarify: I dont want it to break the build on ANY F6 (Build) press, I only want it to break the build if a method decorated with the attribute is called somewhere else in the code. Like I said, similar to obsolete, but not the same. I know I am not alone in this, since other users want to use it for other reasons. I have never created custom attributes before so it is all new to me! | If this is for XML serialization and NHibernate, where you want the parameterless constructor to be accessible (as is the case in the example you referenced), then use a private or protected parameterless constructor for serialization, or a protected constructor for NHibernate. With the protected version, you are opening yourself up to inherited classes being able to call that code. If you don't want code calling a method, don't make it accessible. EDIT: To perhaps answer the deeper question, AFAIK the compiler only knows about three attributes: Obsolete, Conditional, and AttributeUsage. To add special handling for other attributes would require modifying the compiler. | Create an Attribute to Break the Build OK, this kind of follows on from my previous question. What I would really like to do is create some sort of attribute which allows me to decorate a method that will break the build. Much like the Obsolete("reason", true) attribute, but without falsely identifying obsolete code. To clarify: I dont want it to break the build on ANY F6 (Build) press, I only want it to break the build if a method decorated with the attribute is called somewhere else in the code. Like I said, similar to obsolete, but not the same. I know I am not alone in this, since other users want to use it for other reasons. I have never created custom attributes before so it is all new to me! | TITLE:
Create an Attribute to Break the Build
QUESTION:
OK, this kind of follows on from my previous question. What I would really like to do is create some sort of attribute which allows me to decorate a method that will break the build. Much like the Obsolete("reason", true) attribute, but without falsely identifying obsolete code. To clarify: I dont want it to break the build on ANY F6 (Build) press, I only want it to break the build if a method decorated with the attribute is called somewhere else in the code. Like I said, similar to obsolete, but not the same. I know I am not alone in this, since other users want to use it for other reasons. I have never created custom attributes before so it is all new to me!
ANSWER:
If this is for XML serialization and NHibernate, where you want the parameterless constructor to be accessible (as is the case in the example you referenced), then use a private or protected parameterless constructor for serialization, or a protected constructor for NHibernate. With the protected version, you are opening yourself up to inherited classes being able to call that code. If you don't want code calling a method, don't make it accessible. EDIT: To perhaps answer the deeper question, AFAIK the compiler only knows about three attributes: Obsolete, Conditional, and AttributeUsage. To add special handling for other attributes would require modifying the compiler. | [
".net",
"attributes"
] | 9 | 4 | 3,921 | 11 | 0 | 2008-08-26T14:15:08.393000 | 2008-08-26T14:36:30.933000 |
28,160 | 28,215 | Multiple classes in a header file vs. a single header file per class | For whatever reason, our company has a coding guideline that states: Each class shall have it's own header and implementation file. So if we wrote a class called MyString we would need an associated MyStringh.h and MyString.cxx. Does anyone else do this? Has anyone seen any compiling performance repercussions as a result? Does 5000 classes in 10000 files compile just as quickly as 5000 classes in 2500 files? If not, is the difference noticeable? [We code C++ and use GCC 3.4.4 as our everyday compiler] | The term here is translation unit and you really want to (if possible) have one class per translation unit ie, one class implementation per.cpp file, with a corresponding.h file of the same name. It's usually more efficient (from a compile/link) standpoint to do things this way, especially if you're doing things like incremental link and so forth. The idea being, translation units are isolated such that, when one translation unit changes, you don't have to rebuild a lot of stuff, as you would have to if you started lumping many abstractions into a single translation unit. Also you'll find many errors/diagnostics are reported via file name ("Error in Myclass.cpp, line 22") and it helps if there's a one-to-one correspondence between files and classes. (Or I suppose you could call it a 2 to 1 correspondence). | Multiple classes in a header file vs. a single header file per class For whatever reason, our company has a coding guideline that states: Each class shall have it's own header and implementation file. So if we wrote a class called MyString we would need an associated MyStringh.h and MyString.cxx. Does anyone else do this? Has anyone seen any compiling performance repercussions as a result? Does 5000 classes in 10000 files compile just as quickly as 5000 classes in 2500 files? If not, is the difference noticeable? [We code C++ and use GCC 3.4.4 as our everyday compiler] | TITLE:
Multiple classes in a header file vs. a single header file per class
QUESTION:
For whatever reason, our company has a coding guideline that states: Each class shall have it's own header and implementation file. So if we wrote a class called MyString we would need an associated MyStringh.h and MyString.cxx. Does anyone else do this? Has anyone seen any compiling performance repercussions as a result? Does 5000 classes in 10000 files compile just as quickly as 5000 classes in 2500 files? If not, is the difference noticeable? [We code C++ and use GCC 3.4.4 as our everyday compiler]
ANSWER:
The term here is translation unit and you really want to (if possible) have one class per translation unit ie, one class implementation per.cpp file, with a corresponding.h file of the same name. It's usually more efficient (from a compile/link) standpoint to do things this way, especially if you're doing things like incremental link and so forth. The idea being, translation units are isolated such that, when one translation unit changes, you don't have to rebuild a lot of stuff, as you would have to if you started lumping many abstractions into a single translation unit. Also you'll find many errors/diagnostics are reported via file name ("Error in Myclass.cpp, line 22") and it helps if there's a one-to-one correspondence between files and classes. (Or I suppose you could call it a 2 to 1 correspondence). | [
"c++",
"performance",
"file-organization"
] | 91 | 95 | 102,242 | 13 | 0 | 2008-08-26T14:19:34.967000 | 2008-08-26T14:34:39.797000 |
28,165 | 28,247 | Does PHP have an equivalent to this type of Python string substitution? | Python has this wonderful way of handling string substitutions using dictionaries: >>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' I love this because you can specify a value once in the dictionary and then replace it all over the place in the string. I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward. Does anybody have a nice clean way to do this kind of string substitution in PHP? Edit Here's the code from the sprintf page that I liked best. $v) { $tmp[$char. $k. $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); }
echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks'));?> | function subst($str, $dict){ return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str); } You call it like so: echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks')); | Does PHP have an equivalent to this type of Python string substitution? Python has this wonderful way of handling string substitutions using dictionaries: >>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' I love this because you can specify a value once in the dictionary and then replace it all over the place in the string. I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward. Does anybody have a nice clean way to do this kind of string substitution in PHP? Edit Here's the code from the sprintf page that I liked best. $v) { $tmp[$char. $k. $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); }
echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks'));?> | TITLE:
Does PHP have an equivalent to this type of Python string substitution?
QUESTION:
Python has this wonderful way of handling string substitutions using dictionaries: >>> 'The %(site)s site %(adj)s because it %(adj)s' % {'site':'Stackoverflow', 'adj':'rocks'} 'The Stackoverflow site rocks because it rocks' I love this because you can specify a value once in the dictionary and then replace it all over the place in the string. I've tried to achieve something similar in PHP using various string replace functions but everything I've come up with feels awkward. Does anybody have a nice clean way to do this kind of string substitution in PHP? Edit Here's the code from the sprintf page that I liked best. $v) { $tmp[$char. $k. $char] = $v; } return str_replace(array_keys($tmp), array_values($tmp), $str); }
echo sprintf3( 'The %site% site %adj% because it %adj%', array('site'=>'Stackoverflow', 'adj'=>'rocks'));?>
ANSWER:
function subst($str, $dict){ return preg_replace(array_map(create_function('$a', 'return "/%\\($a\\)s/";'), array_keys($dict)), array_values($dict), $str); } You call it like so: echo subst('The %(site)s site %(adj)s because it %(adj)s', array('site'=>'Stackoverflow', 'adj'=>'rocks')); | [
"php",
"python",
"string"
] | 13 | 5 | 2,814 | 3 | 0 | 2008-08-26T14:20:48.910000 | 2008-08-26T14:49:54.707000 |
28,171 | 28,193 | Why does Visual Studio create a new .vsmdi file? | If I open a solution in Visual Studio 2008 and run a unit test then VS creates a new.vsmdi file in the Solution Items folder and gives it the next number available e.g. My Solution2.vsmdi. Any idea why VS is doing this and how I can get it to stop doing this? | It appears that the VSMDI problem is a known bug and has been around since VS2005 Team System but it has no clear fix as yet. Another reason to NOT use MS Test. An MSDN blog details how to run unit tests without VSMDI files. | Why does Visual Studio create a new .vsmdi file? If I open a solution in Visual Studio 2008 and run a unit test then VS creates a new.vsmdi file in the Solution Items folder and gives it the next number available e.g. My Solution2.vsmdi. Any idea why VS is doing this and how I can get it to stop doing this? | TITLE:
Why does Visual Studio create a new .vsmdi file?
QUESTION:
If I open a solution in Visual Studio 2008 and run a unit test then VS creates a new.vsmdi file in the Solution Items folder and gives it the next number available e.g. My Solution2.vsmdi. Any idea why VS is doing this and how I can get it to stop doing this?
ANSWER:
It appears that the VSMDI problem is a known bug and has been around since VS2005 Team System but it has no clear fix as yet. Another reason to NOT use MS Test. An MSDN blog details how to run unit tests without VSMDI files. | [
"visual-studio-2010",
"visual-studio",
"visual-studio-2008",
"mstest"
] | 63 | 30 | 32,134 | 4 | 0 | 2008-08-26T14:22:42.713000 | 2008-08-26T14:28:15.537000 |
28,196 | 30,733 | How to select posts with specific tags/categories in WordPress | This is a very specific question regarding MySQL as implemented in WordPress. I'm trying to develop a plugin that will show (select) posts that have specific ' tags ' and belong to specific ' categories ' (both multiple) I was told it's impossible because of the way categories and tags are stored: wp_posts contains a list of posts, each post have an "ID" wp_terms contains a list of terms (both categories and tags). Each term has a TERM_ID wp_term_taxonomy has a list of terms with their TERM_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag) wp_term_relationships has associations between terms and posts How can I join the tables to get all posts with tags "Nuclear" and "Deals" that also belong to the category "Category1"? | I misunderstood you. I thought you wanted Nuclear or Deals. The below should give you only Nuclear and Deals. select p.* from wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr, wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2
where p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id
and p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id
and p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id
and (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1') and (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear') and (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals') | How to select posts with specific tags/categories in WordPress This is a very specific question regarding MySQL as implemented in WordPress. I'm trying to develop a plugin that will show (select) posts that have specific ' tags ' and belong to specific ' categories ' (both multiple) I was told it's impossible because of the way categories and tags are stored: wp_posts contains a list of posts, each post have an "ID" wp_terms contains a list of terms (both categories and tags). Each term has a TERM_ID wp_term_taxonomy has a list of terms with their TERM_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag) wp_term_relationships has associations between terms and posts How can I join the tables to get all posts with tags "Nuclear" and "Deals" that also belong to the category "Category1"? | TITLE:
How to select posts with specific tags/categories in WordPress
QUESTION:
This is a very specific question regarding MySQL as implemented in WordPress. I'm trying to develop a plugin that will show (select) posts that have specific ' tags ' and belong to specific ' categories ' (both multiple) I was told it's impossible because of the way categories and tags are stored: wp_posts contains a list of posts, each post have an "ID" wp_terms contains a list of terms (both categories and tags). Each term has a TERM_ID wp_term_taxonomy has a list of terms with their TERM_IDs and has a Taxonomy definition for each one of those (either a Category or a Tag) wp_term_relationships has associations between terms and posts How can I join the tables to get all posts with tags "Nuclear" and "Deals" that also belong to the category "Category1"?
ANSWER:
I misunderstood you. I thought you wanted Nuclear or Deals. The below should give you only Nuclear and Deals. select p.* from wp_posts p, wp_terms t, wp_term_taxonomy tt, wp_term_relationship tr, wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2 wp_terms t2, wp_term_taxonomy tt2, wp_term_relationship tr2
where p.id = tr.object_id and t.term_id = tt.term_id and tr.term_taxonomy_id = tt.term_taxonomy_id
and p.id = tr2.object_id and t2.term_id = tt2.term_id and tr2.term_taxonomy_id = tt2.term_taxonomy_id
and p.id = tr3.object_id and t3.term_id = tt3.term_id and tr3.term_taxonomy_id = tt3.term_taxonomy_id
and (tt.taxonomy = 'category' and tt.term_id = t.term_id and t.name = 'Category1') and (tt2.taxonomy = 'post_tag' and tt2.term_id = t2.term_id and t2.name = 'Nuclear') and (tt3.taxonomy = 'post_tag' and tt3.term_id = t3.term_id and t3.name = 'Deals') | [
"php",
"mysql",
"sql",
"wordpress",
"plugins"
] | 10 | 5 | 7,949 | 6 | 0 | 2008-08-26T14:29:38.093000 | 2008-08-27T17:57:29.053000 |
28,197 | 106,682 | Do you follow the Personal Software Process? Does your organization/team follow the Team Software Process? | For more information - Personal Software Process on Wikipedia and Team Software Process on Wikipedia. I have two questions: What benefits have you seen from these processes? What tools and/or methods do you use to follow these processes? | I went through the training and then my company paid for me to go to Carnegie Mellon and go through the PSP instructor training course to get certified as an instructor. I think the goal was to use this as part of our company's CMM/CMMI effort. I met Watts Humphrey and found him to be a kind, gentle soul with some deeply held ideas about process. I read several of his books as well. Here's my take on it in a nutshell - it is too structured for most people to follow, assuming you follow things to the letter. The idea of estimation based on historic info is OK, particularly in the classroom setting, but in the real world where estimates are undone in a day due to the changing tide of requirements and direction, it is far less useful. I've also done Wide Band Delphi estimation and that was OK but honestly wasn't necessarily any better than the 'best guess' I'd make. My team was less than enthusiastic about PSP and that is part of the problem - developer buy-in. My company was doing it for the wrong reason - simply to say "hey, look we use PSP and have some certified instructors!". In the end, I've found using a 'agile' approach to be better. I have a backlog of work to do and can generally estimate it pretty well. I've been doing it long enough that I can make pretty good rough estimates on time and frankly don't think that the time tracking really improves things much. Perhaps in some environments it would work well, but at my place, we'll keep pumping out quality software without all the process hoops that yield questionable benefits. Just my two cents. | Do you follow the Personal Software Process? Does your organization/team follow the Team Software Process? For more information - Personal Software Process on Wikipedia and Team Software Process on Wikipedia. I have two questions: What benefits have you seen from these processes? What tools and/or methods do you use to follow these processes? | TITLE:
Do you follow the Personal Software Process? Does your organization/team follow the Team Software Process?
QUESTION:
For more information - Personal Software Process on Wikipedia and Team Software Process on Wikipedia. I have two questions: What benefits have you seen from these processes? What tools and/or methods do you use to follow these processes?
ANSWER:
I went through the training and then my company paid for me to go to Carnegie Mellon and go through the PSP instructor training course to get certified as an instructor. I think the goal was to use this as part of our company's CMM/CMMI effort. I met Watts Humphrey and found him to be a kind, gentle soul with some deeply held ideas about process. I read several of his books as well. Here's my take on it in a nutshell - it is too structured for most people to follow, assuming you follow things to the letter. The idea of estimation based on historic info is OK, particularly in the classroom setting, but in the real world where estimates are undone in a day due to the changing tide of requirements and direction, it is far less useful. I've also done Wide Band Delphi estimation and that was OK but honestly wasn't necessarily any better than the 'best guess' I'd make. My team was less than enthusiastic about PSP and that is part of the problem - developer buy-in. My company was doing it for the wrong reason - simply to say "hey, look we use PSP and have some certified instructors!". In the end, I've found using a 'agile' approach to be better. I have a backlog of work to do and can generally estimate it pretty well. I've been doing it long enough that I can make pretty good rough estimates on time and frankly don't think that the time tracking really improves things much. Perhaps in some environments it would work well, but at my place, we'll keep pumping out quality software without all the process hoops that yield questionable benefits. Just my two cents. | [
"process",
"personal-software-process"
] | 15 | 14 | 4,322 | 10 | 0 | 2008-08-26T14:29:56.143000 | 2008-09-20T01:15:38.300000 |
28,202 | 28,448 | Best Apache Ant Template | Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly. Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one? Thank you. | An alternative to making a template is to evolve one by gradually generalising your current project's Ant script so that there are fewer changes to make the next time you copy it for use on a new project. There are several things you can do. Use ${ant.project.name} in file names, so you only have to mention your application name in the project element. For example, if you generate myapp.jar:...... Structure your source directory structure so that you can package your build by copying whole directories, rather than naming individual files. For example, if you are copying JAR files to a web application archive, do something like: Use properties files for machine-specific and project-specific build file properties.... Note that Ant properties cannot be changed once set, so you override a value by defining a new value before the default value. | Best Apache Ant Template Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly. Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one? Thank you. | TITLE:
Best Apache Ant Template
QUESTION:
Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly. Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one? Thank you.
ANSWER:
An alternative to making a template is to evolve one by gradually generalising your current project's Ant script so that there are fewer changes to make the next time you copy it for use on a new project. There are several things you can do. Use ${ant.project.name} in file names, so you only have to mention your application name in the project element. For example, if you generate myapp.jar:...... Structure your source directory structure so that you can package your build by copying whole directories, rather than naming individual files. For example, if you are copying JAR files to a web application archive, do something like: Use properties files for machine-specific and project-specific build file properties.... Note that Ant properties cannot be changed once set, so you override a value by defining a new value before the default value. | [
"java",
"ant"
] | 7 | 9 | 7,078 | 7 | 0 | 2008-08-26T14:31:28.777000 | 2008-08-26T15:48:52.647000 |
28,212 | 28,244 | How can I convert types in C++? | I'm using two different libraries in my project, and both of them supply a basic rectangle struct. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't. library a: typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; library b: class Rect { int x; int y; int width; int height; /*... */ }; Now, I can't make a converter class, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types. I can't make an operator that takes the struct from a and supplies an object of the class from b: foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function So, is there a sensible way around this? edit: I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, reinterpret_cast has the same problem..) edit2: Actually, none of the suggestions really answer my actual question, Konrad Rudolph seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by CodingTheWheel. | If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way. | How can I convert types in C++? I'm using two different libraries in my project, and both of them supply a basic rectangle struct. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't. library a: typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; library b: class Rect { int x; int y; int width; int height; /*... */ }; Now, I can't make a converter class, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types. I can't make an operator that takes the struct from a and supplies an object of the class from b: foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function So, is there a sensible way around this? edit: I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, reinterpret_cast has the same problem..) edit2: Actually, none of the suggestions really answer my actual question, Konrad Rudolph seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by CodingTheWheel. | TITLE:
How can I convert types in C++?
QUESTION:
I'm using two different libraries in my project, and both of them supply a basic rectangle struct. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of these, I could create conversions, from the outside, I can't. library a: typedef struct rectangle { sint16 x; sint16 y; uint16 w; uint16 h; } rectangle; library b: class Rect { int x; int y; int width; int height; /*... */ }; Now, I can't make a converter class, because C++ will only look for a conversion in one step. This is probably a good thing, because there would be a lot of possibilities involving creating new objects of all kinds of types. I can't make an operator that takes the struct from a and supplies an object of the class from b: foo.cpp:123 error: ‘operator b::Rect(const rectangle&)’ must be a nonstatic member function So, is there a sensible way around this? edit: I should perhaps also point out that I'd really like some solution that makes working with the result seamless, since I don't expect to be that coder. (Though I agree, old-school, explicit, conversion would have been a good choice. The other branch, reinterpret_cast has the same problem..) edit2: Actually, none of the suggestions really answer my actual question, Konrad Rudolph seems to be correct. C++ actually can't do this. Sucks, but true. (If it makes any difference, I'm going to try subclassing as suggested by CodingTheWheel.
ANSWER:
If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way. | [
"c++",
"oop",
"types"
] | 0 | 2 | 1,342 | 7 | 0 | 2008-08-26T14:33:17.663000 | 2008-08-26T14:48:00.420000 |
28,219 | 28,225 | In ASP.NET, what are the different ways to inline code in the .aspx? | Can I get a 'when to use' for these and others? <% %> <%# EVAL() %> Thanks | Check out the Web Forms Syntax Reference on MSDN. For basics, <% %> is used for pure code blocks. I generally only use this for if statements is used to add text into your markup; that is, it equates to <%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario. One thing that this means is that you can use these expressions to set values of runat="server" controls, which you can't do with the <%= %> syntax. Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate. The others mentioned in the linked article are less common, though certainly have their uses, too. | In ASP.NET, what are the different ways to inline code in the .aspx? Can I get a 'when to use' for these and others? <% %> <%# EVAL() %> Thanks | TITLE:
In ASP.NET, what are the different ways to inline code in the .aspx?
QUESTION:
Can I get a 'when to use' for these and others? <% %> <%# EVAL() %> Thanks
ANSWER:
Check out the Web Forms Syntax Reference on MSDN. For basics, <% %> is used for pure code blocks. I generally only use this for if statements is used to add text into your markup; that is, it equates to <%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario. One thing that this means is that you can use these expressions to set values of runat="server" controls, which you can't do with the <%= %> syntax. Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate. The others mentioned in the linked article are less common, though certainly have their uses, too. | [
".net",
"asp.net",
"syntax"
] | 4 | 15 | 1,093 | 4 | 0 | 2008-08-26T14:35:45.753000 | 2008-08-26T14:38:11.363000 |
28,224 | 113,250 | Bash reg-exp substitution | Is there a way to run a regexp-string replace on the current line in the bash? I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line. My current approach is to finish the line, press Ctrl + A (to get to the start of the line), insert a # (to comment out the line), press enter and then use the ^oldword^newword syntax ( ^oldword^newword executes the previous command after substituting oldword by newword). But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time). Probably there is some emacs-like key-command for this, that I don't know about. Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again). | Unfortunately, no, there's not really a better way. If you're just tired of making the keystrokes, you can use macros to trim them down. Add the following to your ~/.inputrc: "\C-x6": "\C-a#\C-m^" "\C-x7": "\C-m\C-P\C-a\C-d\C-m" Now, in a new bash instance (or after reloading.inputrc in your current shell by pressing C-x C-r ), you can do the following: Type a bogus command (e.g., ls abcxyz ). Press Ctrl-x, then 6. The macro inserts a # at the beginning of the line, executes the commented line, and types your first ^. Type your correction (e.g., xyz^def ). Press Ctrl-x, then 7. The macro completes your substitution, then goes up to the previous (commented) line, removes the comment character, and executes it again. It's not exactly elegant, but I think it's the best you're going to get with readline. | Bash reg-exp substitution Is there a way to run a regexp-string replace on the current line in the bash? I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line. My current approach is to finish the line, press Ctrl + A (to get to the start of the line), insert a # (to comment out the line), press enter and then use the ^oldword^newword syntax ( ^oldword^newword executes the previous command after substituting oldword by newword). But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time). Probably there is some emacs-like key-command for this, that I don't know about. Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again). | TITLE:
Bash reg-exp substitution
QUESTION:
Is there a way to run a regexp-string replace on the current line in the bash? I find myself rather often in the situation, where I have typed a long commandline and then realize, that I would like to change a word somewhere in the line. My current approach is to finish the line, press Ctrl + A (to get to the start of the line), insert a # (to comment out the line), press enter and then use the ^oldword^newword syntax ( ^oldword^newword executes the previous command after substituting oldword by newword). But there has to be a better (faster) way to achieve this. (The mouse is not possible, since I am in an ssh-sessions most of the time). Probably there is some emacs-like key-command for this, that I don't know about. Edit: I have tried using vi-mode. Something strange happened. Although I am a loving vim-user, I had serious trouble using my beloved bash. All those finger-movements, that have been burned into my subconscious suddenly stopped working. I quickly returned to emacs-mode and considered, giving emacs a try as my favorite editor (although I guess, the same thing might happen again).
ANSWER:
Unfortunately, no, there's not really a better way. If you're just tired of making the keystrokes, you can use macros to trim them down. Add the following to your ~/.inputrc: "\C-x6": "\C-a#\C-m^" "\C-x7": "\C-m\C-P\C-a\C-d\C-m" Now, in a new bash instance (or after reloading.inputrc in your current shell by pressing C-x C-r ), you can do the following: Type a bogus command (e.g., ls abcxyz ). Press Ctrl-x, then 6. The macro inserts a # at the beginning of the line, executes the commented line, and types your first ^. Type your correction (e.g., xyz^def ). Press Ctrl-x, then 7. The macro completes your substitution, then goes up to the previous (commented) line, removes the comment character, and executes it again. It's not exactly elegant, but I think it's the best you're going to get with readline. | [
"regex",
"bash"
] | 4 | 1 | 2,051 | 3 | 0 | 2008-08-26T14:37:31.773000 | 2008-09-22T05:02:38.877000 |
28,235 | 28,472 | Should I be doing JSPX instead of JSP? | Using JDeveloper, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing JSPX instead of JSP, but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route? | The main difference is that a JSPX file (officially called a 'JSP document') may be easier to work with because the requirement for well-formed XML may allow your editor to identify more typos and syntax errors as you type. However, there are also disadvantages. For example, well-formed XML must escape things like less-than signs, so your file could end up with content like: | Should I be doing JSPX instead of JSP? Using JDeveloper, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing JSPX instead of JSP, but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route? | TITLE:
Should I be doing JSPX instead of JSP?
QUESTION:
Using JDeveloper, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing JSPX instead of JSP, but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route?
ANSWER:
The main difference is that a JSPX file (officially called a 'JSP document') may be easier to work with because the requirement for well-formed XML may allow your editor to identify more typos and syntax errors as you type. However, there are also disadvantages. For example, well-formed XML must escape things like less-than signs, so your file could end up with content like: | [
"jsp",
"jspx"
] | 52 | 55 | 65,953 | 8 | 0 | 2008-08-26T14:41:55.757000 | 2008-08-26T15:59:40.030000 |
28,241 | 28,255 | Java Singleton vs static - is there a real performance benefit? | I am merging a CVS branch and one of the larger changes is the replacement wherever it occurs of a Singleton pattern with abstract classes that have a static initialisation block and all static methods. Is this something that's worth keeping since it will require merging a lot of conflicts, what sort of situation would I be looking at for this refactoring to be worthwhile? We are running this app under Weblogic 8.1 (so JDK 1.4.2) sorry Thomas, let me clarify.. the HEAD version has the traditional singleton pattern (private constructor, getInstance() etc) the branch version has no constructor, is a 'public abstract class' and modified all the methods on the object to be 'static'. The code that used to exist in the private constructor is moved into a static block. Then all usages of the class are changed which causes multiple conflicts in the merge. There are a few cases where this change was made. | From a strict runtime performance point of view, the difference is really negligible. The main difference between the two lies down in the fact that the "static" lifecycle is linked to the classloader, whereas for the singleton it's a regular instance lifecycle. Usually it's better to stay away from the ClassLoader business, you avoid some tricky problems, especially when you try to reload the web application. | Java Singleton vs static - is there a real performance benefit? I am merging a CVS branch and one of the larger changes is the replacement wherever it occurs of a Singleton pattern with abstract classes that have a static initialisation block and all static methods. Is this something that's worth keeping since it will require merging a lot of conflicts, what sort of situation would I be looking at for this refactoring to be worthwhile? We are running this app under Weblogic 8.1 (so JDK 1.4.2) sorry Thomas, let me clarify.. the HEAD version has the traditional singleton pattern (private constructor, getInstance() etc) the branch version has no constructor, is a 'public abstract class' and modified all the methods on the object to be 'static'. The code that used to exist in the private constructor is moved into a static block. Then all usages of the class are changed which causes multiple conflicts in the merge. There are a few cases where this change was made. | TITLE:
Java Singleton vs static - is there a real performance benefit?
QUESTION:
I am merging a CVS branch and one of the larger changes is the replacement wherever it occurs of a Singleton pattern with abstract classes that have a static initialisation block and all static methods. Is this something that's worth keeping since it will require merging a lot of conflicts, what sort of situation would I be looking at for this refactoring to be worthwhile? We are running this app under Weblogic 8.1 (so JDK 1.4.2) sorry Thomas, let me clarify.. the HEAD version has the traditional singleton pattern (private constructor, getInstance() etc) the branch version has no constructor, is a 'public abstract class' and modified all the methods on the object to be 'static'. The code that used to exist in the private constructor is moved into a static block. Then all usages of the class are changed which causes multiple conflicts in the merge. There are a few cases where this change was made.
ANSWER:
From a strict runtime performance point of view, the difference is really negligible. The main difference between the two lies down in the fact that the "static" lifecycle is linked to the classloader, whereas for the singleton it's a regular instance lifecycle. Usually it's better to stay away from the ClassLoader business, you avoid some tricky problems, especially when you try to reload the web application. | [
"java",
"design-patterns",
"singleton"
] | 15 | 16 | 26,824 | 7 | 0 | 2008-08-26T14:45:48.617000 | 2008-08-26T14:52:01.783000 |
28,243 | 109,708 | cannot install ruby gems - zlib error | I'm trying to install some Ruby Gems so I can use Ruby to notify me when I get twitter messages. However, after doing a gem update --system, I now get a zlib error every time I try and do a gem install of anything. below is the console output I get when trying to install ruby gems. (along with the output from gem environment ). C:\data\ruby>gem install twitter ERROR: While executing gem... (Zlib::BufError) buffer error
C:\data\ruby>gem update --system Updating RubyGems ERROR: While executing gem... (Zlib::BufError) buffer error
C:\data\ruby>gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.2.0 - RUBY VERSION: 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] - INSTALLATION DIRECTORY: c:/ruby/lib/ruby/gems/1.8 - RUBY EXECUTABLE: c:/ruby/bin/ruby.exe - EXECUTABLE DIRECTORY: c:/ruby/bin - RUBYGEMS PLATFORMS: - ruby - x86-mswin32-60 - GEM PATHS: - c:/ruby/lib/ruby/gems/1.8 - GEM CONFIGURATION: -:update_sources => true -:verbose => true -:benchmark => false -:backtrace => false -:bulk_threshold => 1000 - REMOTE SOURCES: - http://gems.rubyforge.org/ | I just started getting this tonight as well. Googling turned up a bunch of suggestions that didn't deliver results gem update --system and some paste in code from jamis that is supposed to replace a function in package.rb but the original it is supposed to replace is nowhere to be found. Reinstalling rubygems didn't help. I'm reinstalling ruby right now.........and it is fixed. Pain though. | cannot install ruby gems - zlib error I'm trying to install some Ruby Gems so I can use Ruby to notify me when I get twitter messages. However, after doing a gem update --system, I now get a zlib error every time I try and do a gem install of anything. below is the console output I get when trying to install ruby gems. (along with the output from gem environment ). C:\data\ruby>gem install twitter ERROR: While executing gem... (Zlib::BufError) buffer error
C:\data\ruby>gem update --system Updating RubyGems ERROR: While executing gem... (Zlib::BufError) buffer error
C:\data\ruby>gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.2.0 - RUBY VERSION: 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] - INSTALLATION DIRECTORY: c:/ruby/lib/ruby/gems/1.8 - RUBY EXECUTABLE: c:/ruby/bin/ruby.exe - EXECUTABLE DIRECTORY: c:/ruby/bin - RUBYGEMS PLATFORMS: - ruby - x86-mswin32-60 - GEM PATHS: - c:/ruby/lib/ruby/gems/1.8 - GEM CONFIGURATION: -:update_sources => true -:verbose => true -:benchmark => false -:backtrace => false -:bulk_threshold => 1000 - REMOTE SOURCES: - http://gems.rubyforge.org/ | TITLE:
cannot install ruby gems - zlib error
QUESTION:
I'm trying to install some Ruby Gems so I can use Ruby to notify me when I get twitter messages. However, after doing a gem update --system, I now get a zlib error every time I try and do a gem install of anything. below is the console output I get when trying to install ruby gems. (along with the output from gem environment ). C:\data\ruby>gem install twitter ERROR: While executing gem... (Zlib::BufError) buffer error
C:\data\ruby>gem update --system Updating RubyGems ERROR: While executing gem... (Zlib::BufError) buffer error
C:\data\ruby>gem environment RubyGems Environment: - RUBYGEMS VERSION: 1.2.0 - RUBY VERSION: 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32] - INSTALLATION DIRECTORY: c:/ruby/lib/ruby/gems/1.8 - RUBY EXECUTABLE: c:/ruby/bin/ruby.exe - EXECUTABLE DIRECTORY: c:/ruby/bin - RUBYGEMS PLATFORMS: - ruby - x86-mswin32-60 - GEM PATHS: - c:/ruby/lib/ruby/gems/1.8 - GEM CONFIGURATION: -:update_sources => true -:verbose => true -:benchmark => false -:backtrace => false -:bulk_threshold => 1000 - REMOTE SOURCES: - http://gems.rubyforge.org/
ANSWER:
I just started getting this tonight as well. Googling turned up a bunch of suggestions that didn't deliver results gem update --system and some paste in code from jamis that is supposed to replace a function in package.rb but the original it is supposed to replace is nowhere to be found. Reinstalling rubygems didn't help. I'm reinstalling ruby right now.........and it is fixed. Pain though. | [
"ruby",
"rubygems"
] | 9 | 3 | 30,010 | 9 | 0 | 2008-08-26T14:47:52.357000 | 2008-09-20T23:03:25.863000 |
28,256 | 29,124 | Equation (expression) parser with precedence? | I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis. Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis. So right now "1+11*5" returns 60, not 56 as one might expect. While this is suitable for the current project, I want to have a general purpose routine I can use for later projects. Edited for clarity: What is a good algorithm for parsing equations with precedence? I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code. Grammar: I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as "2+3 * (42/13)". Language: I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise. Code Example I posted the test code for the simple expression parser I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose the macro hack because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser. Related question Smart design of a math parser? | The hard way You want a recursive descent parser. To get precedence you need to think recursively, for example, using your sample string, 1+11*5 to do this manually, you would have to read the 1, then see the plus and start a whole new recursive parse "session" starting with 11... and make sure to parse the 11 * 5 into its own factor, yielding a parse tree with 1 + (11 * 5). This all feels so painful even to attempt to explain, especially with the added powerlessness of C. See, after parsing the 11, if the * was actually a + instead, you would have to abandon the attempt at making a term and instead parse the 11 itself as a factor. My head is already exploding. It's possible with the recursive decent strategy, but there is a better way... The easy (right) way If you use a GPL tool like Bison, you probably don't need to worry about licensing issues since the C code generated by bison is not covered by the GPL (IANAL but I'm pretty sure GPL tools don't force the GPL on generated code/binaries; for example Apple compiles code like say, Aperture with GCC and they sell it without having to GPL said code). Download Bison (or something equivalent, ANTLR, etc.). There is usually some sample code that you can just run bison on and get your desired C code that demonstrates this four function calculator: http://www.gnu.org/software/bison/manual/html_node/Infix-Calc.html Look at the generated code, and see that this is not as easy as it sounds. Also, the advantages of using a tool like Bison are 1) you learn something (especially if you read the Dragon book and learn about grammars), 2) you avoid NIH trying to reinvent the wheel. With a real parser-generator tool, you actually have a hope at scaling up later, showing other people you know that parsers are the domain of parsing tools. Update: People here have offered much sound advice. My only warning against skipping the parsing tools or just using the Shunting Yard algorithm or a hand rolled recursive decent parser is that little toy languages 1 may someday turn into big actual languages with functions (sin, cos, log) and variables, conditions and for loops. Flex/Bison may very well be overkill for a small, simple interpreter, but a one off parser+evaluator may cause trouble down the line when changes need to be made or features need to be added. Your situation will vary and you will need to use your judgement; just don't punish other people for your sins [2] and build a less than adequate tool. My favorite tool for parsing The best tool in the world for the job is the Parsec library (for recursive decent parsers) which comes with the programming language Haskell. It looks a lot like BNF, or like some specialized tool or domain specific language for parsing (sample code [3]), but it is in fact just a regular library in Haskell, meaning that it compiles in the same build step as the rest of your Haskell code, and you can write arbitrary Haskell code and call that within your parser, and you can mix and match other libraries all in the same code. (Embedding a parsing language like this in a language other than Haskell results in loads of syntactic cruft, by the way. I did this in C# and it works quite well but it is not so pretty and succinct.) Notes: 1 Richard Stallman says, in Why you should not use Tcl The principal lesson of Emacs is that a language for extensions should not be a mere "extension language". It should be a real programming language, designed for writing and maintaining substantial programs. Because people will want to do that! [2] Yes, I am forever scarred from using that "language". Also note that when I submitted this entry, the preview was correct, but SO's less than adequate parser ate my close anchor tag on the first paragraph, proving that parsers are not something to be trifled with because if you use regexes and one off hacks you will probably get something subtle and small wrong. [3] Snippet of a Haskell parser using Parsec: a four function calculator extended with exponents, parentheses, whitespace for multiplication, and constants (like pi and e). aexpr = expr `chainl1` toOp expr = optChainl1 term addop (toScalar 0) term = factor `chainl1` mulop factor = sexpr `chainr1` powop sexpr = parens aexpr <|> scalar <|> ident
powop = sym "^" >>= return. (B Pow) <|> sym "^-" >>= return. (\x y -> B Pow x (B Sub (toScalar 0) y))
toOp = sym "->" >>= return. (B To)
mulop = sym "*" >>= return. (B Mul) <|> sym "/" >>= return. (B Div) <|> sym "%" >>= return. (B Mod) <|> return. (B Mul)
addop = sym "+" >>= return. (B Add) <|> sym "-" >>= return. (B Sub)
scalar = number >>= return. toScalar
ident = literal >>= return. Lit
parens p = do lparen result <- p rparen return result | Equation (expression) parser with precedence? I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis. Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis. So right now "1+11*5" returns 60, not 56 as one might expect. While this is suitable for the current project, I want to have a general purpose routine I can use for later projects. Edited for clarity: What is a good algorithm for parsing equations with precedence? I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code. Grammar: I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as "2+3 * (42/13)". Language: I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise. Code Example I posted the test code for the simple expression parser I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose the macro hack because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser. Related question Smart design of a math parser? | TITLE:
Equation (expression) parser with precedence?
QUESTION:
I've developed an equation parser using a simple stack algorithm that will handle binary (+, -, |, &, *, /, etc) operators, unary (!) operators, and parenthesis. Using this method, however, leaves me with everything having the same precedence - it's evaluated left to right regardless of operator, although precedence can be enforced using parenthesis. So right now "1+11*5" returns 60, not 56 as one might expect. While this is suitable for the current project, I want to have a general purpose routine I can use for later projects. Edited for clarity: What is a good algorithm for parsing equations with precedence? I'm interested in something simple to implement and understand that I can code myself to avoid licensing issues with available code. Grammar: I don't understand the grammar question - I've written this by hand. It's simple enough that I don't see the need for YACC or Bison. I merely need to calculate strings with equations such as "2+3 * (42/13)". Language: I'm doing this in C, but I'm interested in an algorithm, not a language specific solution. C is low level enough that it'll be easy to convert to another language should the need arise. Code Example I posted the test code for the simple expression parser I was talking about above. The project requirements altered and so I never needed to optimize the code for performance or space as it wasn't incorporated into the project. It's in the original verbose form, and should be readily understandable. If I do anything further with it in terms of operator precedence, I'll probably choose the macro hack because it matches the rest of the program in simplicity. If I ever use this in a real project, though, I'll be going for a more compact/speedy parser. Related question Smart design of a math parser?
ANSWER:
The hard way You want a recursive descent parser. To get precedence you need to think recursively, for example, using your sample string, 1+11*5 to do this manually, you would have to read the 1, then see the plus and start a whole new recursive parse "session" starting with 11... and make sure to parse the 11 * 5 into its own factor, yielding a parse tree with 1 + (11 * 5). This all feels so painful even to attempt to explain, especially with the added powerlessness of C. See, after parsing the 11, if the * was actually a + instead, you would have to abandon the attempt at making a term and instead parse the 11 itself as a factor. My head is already exploding. It's possible with the recursive decent strategy, but there is a better way... The easy (right) way If you use a GPL tool like Bison, you probably don't need to worry about licensing issues since the C code generated by bison is not covered by the GPL (IANAL but I'm pretty sure GPL tools don't force the GPL on generated code/binaries; for example Apple compiles code like say, Aperture with GCC and they sell it without having to GPL said code). Download Bison (or something equivalent, ANTLR, etc.). There is usually some sample code that you can just run bison on and get your desired C code that demonstrates this four function calculator: http://www.gnu.org/software/bison/manual/html_node/Infix-Calc.html Look at the generated code, and see that this is not as easy as it sounds. Also, the advantages of using a tool like Bison are 1) you learn something (especially if you read the Dragon book and learn about grammars), 2) you avoid NIH trying to reinvent the wheel. With a real parser-generator tool, you actually have a hope at scaling up later, showing other people you know that parsers are the domain of parsing tools. Update: People here have offered much sound advice. My only warning against skipping the parsing tools or just using the Shunting Yard algorithm or a hand rolled recursive decent parser is that little toy languages 1 may someday turn into big actual languages with functions (sin, cos, log) and variables, conditions and for loops. Flex/Bison may very well be overkill for a small, simple interpreter, but a one off parser+evaluator may cause trouble down the line when changes need to be made or features need to be added. Your situation will vary and you will need to use your judgement; just don't punish other people for your sins [2] and build a less than adequate tool. My favorite tool for parsing The best tool in the world for the job is the Parsec library (for recursive decent parsers) which comes with the programming language Haskell. It looks a lot like BNF, or like some specialized tool or domain specific language for parsing (sample code [3]), but it is in fact just a regular library in Haskell, meaning that it compiles in the same build step as the rest of your Haskell code, and you can write arbitrary Haskell code and call that within your parser, and you can mix and match other libraries all in the same code. (Embedding a parsing language like this in a language other than Haskell results in loads of syntactic cruft, by the way. I did this in C# and it works quite well but it is not so pretty and succinct.) Notes: 1 Richard Stallman says, in Why you should not use Tcl The principal lesson of Emacs is that a language for extensions should not be a mere "extension language". It should be a real programming language, designed for writing and maintaining substantial programs. Because people will want to do that! [2] Yes, I am forever scarred from using that "language". Also note that when I submitted this entry, the preview was correct, but SO's less than adequate parser ate my close anchor tag on the first paragraph, proving that parsers are not something to be trifled with because if you use regexes and one off hacks you will probably get something subtle and small wrong. [3] Snippet of a Haskell parser using Parsec: a four function calculator extended with exponents, parentheses, whitespace for multiplication, and constants (like pi and e). aexpr = expr `chainl1` toOp expr = optChainl1 term addop (toScalar 0) term = factor `chainl1` mulop factor = sexpr `chainr1` powop sexpr = parens aexpr <|> scalar <|> ident
powop = sym "^" >>= return. (B Pow) <|> sym "^-" >>= return. (\x y -> B Pow x (B Sub (toScalar 0) y))
toOp = sym "->" >>= return. (B To)
mulop = sym "*" >>= return. (B Mul) <|> sym "/" >>= return. (B Div) <|> sym "%" >>= return. (B Mod) <|> return. (B Mul)
addop = sym "+" >>= return. (B Add) <|> sym "-" >>= return. (B Sub)
scalar = number >>= return. toScalar
ident = literal >>= return. Lit
parens p = do lparen result <- p rparen return result | [
"algorithm",
"parsing",
"equation"
] | 122 | 71 | 102,013 | 16 | 0 | 2008-08-26T14:52:05.060000 | 2008-08-26T22:39:39.693000 |
28,268 | 28,277 | Any pitfalls developing C#/.NET code in a VM running on a Mac? | I am considering buying an Apple MacBook Pro. Are there any pitfalls developing C#/.NET code in a virtual machine running on a Mac? Also, is it better to run Vista or XP Pro for this purpose? | I can't tell you any specific experiences since I don't have a Mac, but I did want to point out that there was an awesome episode of the DeepFriedBytes podcast that discussed this very topic. It made me want to give it a try. They discuss the pros and cons of going this route - well worth the listen IMO if this is something you're considering: Episode 5: Developing.NET Software on a Mac | Any pitfalls developing C#/.NET code in a VM running on a Mac? I am considering buying an Apple MacBook Pro. Are there any pitfalls developing C#/.NET code in a virtual machine running on a Mac? Also, is it better to run Vista or XP Pro for this purpose? | TITLE:
Any pitfalls developing C#/.NET code in a VM running on a Mac?
QUESTION:
I am considering buying an Apple MacBook Pro. Are there any pitfalls developing C#/.NET code in a virtual machine running on a Mac? Also, is it better to run Vista or XP Pro for this purpose?
ANSWER:
I can't tell you any specific experiences since I don't have a Mac, but I did want to point out that there was an awesome episode of the DeepFriedBytes podcast that discussed this very topic. It made me want to give it a try. They discuss the pros and cons of going this route - well worth the listen IMO if this is something you're considering: Episode 5: Developing.NET Software on a Mac | [
".net",
"macos",
"vmware"
] | 5 | 13 | 2,215 | 16 | 0 | 2008-08-26T14:57:47.090000 | 2008-08-26T15:00:54.947000 |
28,280 | 29,660 | Can I maintain state between calls to a SQL Server UDF? | I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. I'd like to add a scalar function to my script that gets the next available ID (i.e. last used ID + 1) but I'm not sure this is possible because there doesn't seem to be a way to use a global or static variable from within a UDF, I can't use a temp table, and I can't update a permanent table from within a function. Currently my script looks like this: declare @v_baseID int exec dbo.getNextID @v_baseID out --sproc to get the next available id --Lots of these - where n is a hardcoded value insert into tableOfStuff (someStuff, uniqueID) values ('stuff', @v_baseID + n ) exec dbo.UpdateNextID @v_baseID + lastUsedn --sproc to update the last used id But I would like it to look like this: --Lots of these insert into tableOfStuff (someStuff, uniqueID) values ('stuff', getNextID() ) Hardcoding the offset is a pain in the arse, and is error prone. Packaging it up into a simple scalar function is very appealing, but I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. We're using SQL Server 2005 at the moment. edits for clarification: Two users hitting it won't happen. This is an upgrade script that will be run only once, and never concurrently. The actual sproc isn't prefixed with sp_, fixed the example code. In normal usage, we do use an id table and a sproc to get IDs as needed, I was just looking for a cleaner way to do it in this script, which essentially just dumps a bunch of data into the db. | I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. You aren't missing anything; SQL Server does not support global variables, and it doesn't support data modification within UDFs. And even if you wanted to do something as kludgy as using CONTEXT_INFO (see http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx ), you can't set that from within a UDF anyway. Is there a way you can get around the "hardcoding" of the offset by making that a variable and looping over the iteration of it, doing the inserts within that loop? | Can I maintain state between calls to a SQL Server UDF? I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. I'd like to add a scalar function to my script that gets the next available ID (i.e. last used ID + 1) but I'm not sure this is possible because there doesn't seem to be a way to use a global or static variable from within a UDF, I can't use a temp table, and I can't update a permanent table from within a function. Currently my script looks like this: declare @v_baseID int exec dbo.getNextID @v_baseID out --sproc to get the next available id --Lots of these - where n is a hardcoded value insert into tableOfStuff (someStuff, uniqueID) values ('stuff', @v_baseID + n ) exec dbo.UpdateNextID @v_baseID + lastUsedn --sproc to update the last used id But I would like it to look like this: --Lots of these insert into tableOfStuff (someStuff, uniqueID) values ('stuff', getNextID() ) Hardcoding the offset is a pain in the arse, and is error prone. Packaging it up into a simple scalar function is very appealing, but I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. We're using SQL Server 2005 at the moment. edits for clarification: Two users hitting it won't happen. This is an upgrade script that will be run only once, and never concurrently. The actual sproc isn't prefixed with sp_, fixed the example code. In normal usage, we do use an id table and a sproc to get IDs as needed, I was just looking for a cleaner way to do it in this script, which essentially just dumps a bunch of data into the db. | TITLE:
Can I maintain state between calls to a SQL Server UDF?
QUESTION:
I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. I'd like to add a scalar function to my script that gets the next available ID (i.e. last used ID + 1) but I'm not sure this is possible because there doesn't seem to be a way to use a global or static variable from within a UDF, I can't use a temp table, and I can't update a permanent table from within a function. Currently my script looks like this: declare @v_baseID int exec dbo.getNextID @v_baseID out --sproc to get the next available id --Lots of these - where n is a hardcoded value insert into tableOfStuff (someStuff, uniqueID) values ('stuff', @v_baseID + n ) exec dbo.UpdateNextID @v_baseID + lastUsedn --sproc to update the last used id But I would like it to look like this: --Lots of these insert into tableOfStuff (someStuff, uniqueID) values ('stuff', getNextID() ) Hardcoding the offset is a pain in the arse, and is error prone. Packaging it up into a simple scalar function is very appealing, but I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. We're using SQL Server 2005 at the moment. edits for clarification: Two users hitting it won't happen. This is an upgrade script that will be run only once, and never concurrently. The actual sproc isn't prefixed with sp_, fixed the example code. In normal usage, we do use an id table and a sproc to get IDs as needed, I was just looking for a cleaner way to do it in this script, which essentially just dumps a bunch of data into the db.
ANSWER:
I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. You aren't missing anything; SQL Server does not support global variables, and it doesn't support data modification within UDFs. And even if you wanted to do something as kludgy as using CONTEXT_INFO (see http://weblogs.sqlteam.com/mladenp/archive/2007/04/23/60185.aspx ), you can't set that from within a UDF anyway. Is there a way you can get around the "hardcoding" of the offset by making that a variable and looping over the iteration of it, doing the inserts within that loop? | [
"sql",
"sql-server",
"sql-server-2005"
] | 1 | 2 | 452 | 3 | 0 | 2008-08-26T15:01:50.620000 | 2008-08-27T07:14:44.853000 |
28,293 | 28,562 | Generating an object model in Ruby from an XML DTD | I have an XML document with a DTD, and would love to be able to access the XML model, something like this: title = Thing.Items[0].Title Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML? Thanks! | You can use the ruby version of xml-simple. You shouldn't need to install the gem as I believe it's already installed with rails. http://xml-simple.rubyforge.org/ | Generating an object model in Ruby from an XML DTD I have an XML document with a DTD, and would love to be able to access the XML model, something like this: title = Thing.Items[0].Title Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML? Thanks! | TITLE:
Generating an object model in Ruby from an XML DTD
QUESTION:
I have an XML document with a DTD, and would love to be able to access the XML model, something like this: title = Thing.Items[0].Title Is there a way, in Ruby, to generate this kind of object model based on a DTD? Or am I stuck using REXML? Thanks!
ANSWER:
You can use the ruby version of xml-simple. You shouldn't need to install the gem as I believe it's already installed with rails. http://xml-simple.rubyforge.org/ | [
"xml",
"ruby",
"dtd"
] | 0 | 0 | 1,464 | 3 | 0 | 2008-08-26T15:08:39.420000 | 2008-08-26T16:42:06.027000 |
28,301 | 28,494 | Impose a total ordering on all instances of *any* class in Java | I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. class TotalOrder implements Comparator {
public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0;
int h1 = System.identityHashCode(o1); int h2 = System.identityHashCode(o2);
if (h1!= h2) { return h1 < h2? -1: 1; }
// equals returned false but identity hash code was same, assume o1 == o2 return 0; }
boolean equal(Object o1, Object o2) { return o1 == null? o2 == null: o1.equals(o2); } } Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable? | Hey, look at what I found! http://gafter.blogspot.com/2007/03/compact-object-comparator.html Oh yes, I forgot about the IdentityHashMap (Java 6 and above only). Just have to pay attention at releasing your comparator. | Impose a total ordering on all instances of *any* class in Java I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. class TotalOrder implements Comparator {
public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0;
int h1 = System.identityHashCode(o1); int h2 = System.identityHashCode(o2);
if (h1!= h2) { return h1 < h2? -1: 1; }
// equals returned false but identity hash code was same, assume o1 == o2 return 0; }
boolean equal(Object o1, Object o2) { return o1 == null? o2 == null: o1.equals(o2); } } Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable? | TITLE:
Impose a total ordering on all instances of *any* class in Java
QUESTION:
I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. class TotalOrder implements Comparator {
public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0;
int h1 = System.identityHashCode(o1); int h2 = System.identityHashCode(o2);
if (h1!= h2) { return h1 < h2? -1: 1; }
// equals returned false but identity hash code was same, assume o1 == o2 return 0; }
boolean equal(Object o1, Object o2) { return o1 == null? o2 == null: o1.equals(o2); } } Will the code above impose a total ordering on all instances of any class, even if that class does not implement Comparable?
ANSWER:
Hey, look at what I found! http://gafter.blogspot.com/2007/03/compact-object-comparator.html Oh yes, I forgot about the IdentityHashMap (Java 6 and above only). Just have to pay attention at releasing your comparator. | [
"java",
"algorithm"
] | 3 | 2 | 948 | 7 | 0 | 2008-08-26T15:11:27.383000 | 2008-08-26T16:08:54.250000 |
28,302 | 29,860 | Free Network Monitor | I am having trouble integrating two products, one of which is mine and they appear not to be talking. So I want to make sure they are communicating correctly. I had a look around for network monitor and found TCP Spy. This works but only shows 1 side of the conversation at a time (it has to run locally) I would ideally like to see both sides at the same time - but you can't run two copies of TCP Spy. I've hit Sourceforge, but nothing seems to jump out - I'm a Windows developer, I don't have perl installed. I've found a couple of others which are cripple-ware and totally useless, so I was wondering what do the SO guys use for watching the TCP conversation? BTW - the 'not-written-here' product is not a browser. | I tried Wireshark and Microsoft Network Monitor, but neither detected my (and the program I am trying to communicate with) transfer. If I had a day to sit and configure it I probably could get it working but I just wanted the bytes sent and, more specifically, bytes received. In the end I found HHD Software's Accurate Network Monitor software which did what I wanted it to, even if it was slight clunky. | Free Network Monitor I am having trouble integrating two products, one of which is mine and they appear not to be talking. So I want to make sure they are communicating correctly. I had a look around for network monitor and found TCP Spy. This works but only shows 1 side of the conversation at a time (it has to run locally) I would ideally like to see both sides at the same time - but you can't run two copies of TCP Spy. I've hit Sourceforge, but nothing seems to jump out - I'm a Windows developer, I don't have perl installed. I've found a couple of others which are cripple-ware and totally useless, so I was wondering what do the SO guys use for watching the TCP conversation? BTW - the 'not-written-here' product is not a browser. | TITLE:
Free Network Monitor
QUESTION:
I am having trouble integrating two products, one of which is mine and they appear not to be talking. So I want to make sure they are communicating correctly. I had a look around for network monitor and found TCP Spy. This works but only shows 1 side of the conversation at a time (it has to run locally) I would ideally like to see both sides at the same time - but you can't run two copies of TCP Spy. I've hit Sourceforge, but nothing seems to jump out - I'm a Windows developer, I don't have perl installed. I've found a couple of others which are cripple-ware and totally useless, so I was wondering what do the SO guys use for watching the TCP conversation? BTW - the 'not-written-here' product is not a browser.
ANSWER:
I tried Wireshark and Microsoft Network Monitor, but neither detected my (and the program I am trying to communicate with) transfer. If I had a day to sit and configure it I probably could get it working but I just wanted the bytes sent and, more specifically, bytes received. In the end I found HHD Software's Accurate Network Monitor software which did what I wanted it to, even if it was slight clunky. | [
"windows",
"sockets",
"network-monitoring"
] | 9 | 0 | 1,706 | 10 | 0 | 2008-08-26T15:12:18.833000 | 2008-08-27T10:28:24.797000 |
28,303 | 28,328 | Web 2.0 Color Combinations | What are the most user-friendly color combinations for Web 2.0 websites, such as background, button colors, etc.? | ColorSchemer will suggest good schemes for you. If you want to try something out on your own, try Color Combinations. | Web 2.0 Color Combinations What are the most user-friendly color combinations for Web 2.0 websites, such as background, button colors, etc.? | TITLE:
Web 2.0 Color Combinations
QUESTION:
What are the most user-friendly color combinations for Web 2.0 websites, such as background, button colors, etc.?
ANSWER:
ColorSchemer will suggest good schemes for you. If you want to try something out on your own, try Color Combinations. | [
"colors",
"color-scheme"
] | 15 | 11 | 16,392 | 10 | 0 | 2008-08-26T15:13:03.043000 | 2008-08-26T15:16:53.067000 |
28,353 | 37,116 | How can I get notification when a mirrored SQL Server database has failed over | We have a couple of mirrored SQL Server databases. My first problem - the key problem - is to get a notification when the db fails over. I don't need to know because, erm, its mirrored and so it (almost) all carries on working automagically but it would useful to be advised and I'm currently getting failovers when I don't think I should be so it want to know when they occur (without too much digging) to see if I can determine why. I have services running that I could fairly easily use to monitor this - so the alternative question would be "How do I programmatically determine which is the principal and which is the mirror" - preferably in a more intelligent fashion than just attempting to connect each in turn (which would mostly work but...). Thanks, Murph Addendum: One of the answers queries why I don't need to know when it fails over - the answer is that we're developing using ADO.NET and that has automatic failover support, all you have to do is add Failover Partner=MIRRORSERVER (where MIRRORSERVER is the name of your mirror server instance) to your connection string and your code will fail over transparently - you may get some errors depending on what connections are active but in our case very few. | Right, The two answers and a little thought got me to something approaching an answer. First a little more clarification: The app is written in C# (2.0+) and uses ADO.NET to talk to SQL Server 2005. The mirror setup is two W2k3 servers hosting the Principal and the Mirror plus a third server hosting an express instance as a monitor. The nice thing about this is a failover is all but transparent to the app using the database, it will throw an error for some connections but fundamentally everything will carry on nicely. Yes we're getting the odd false positive but the whole point is to have the system carry on working with the least amount of fuss and mirror does deliver this very nicely. Further, the issue is not with serious server failure - that's usually a bit more obvious but with a failover for other reasons (c.f. the false positives above) as we do have a couple of things that can't, for various reasons, fail over and in any case so we can see if we can identify the circumstance where we get false positives. So, given the above, simply checking the status of the boxes is not quite enough and chasing through the event log is probably overly complex - the answer is, as it turns out, fairly simple: sp_helpserver The first column returned by sp_helpserver is the server name. If you run the request at regular intervals saving the previous server name and doing a comparison each time you'll be able to identify when a change has taken place and then take the appropriate action. The following is a console app that demonstrates the principal - although it needs some work (e.g. the connection ought to be non-pooled and new each time) but its enough for now (so I'd then accept this as "the" answer"). Parameters are Principal, Mirror, Database using System; using System.Data.SqlClient;
namespace FailoverMonitorConcept { class Program { static void Main(string[] args) { string server = args[0]; string failover = args[1]; string database = args[2];
string connStr = string.Format("Integrated Security=SSPI;Persist Security Info=True;Data Source={0};Failover Partner={1};Packet Size=4096;Initial Catalog={2}", server, failover, database); string sql = "EXEC sp_helpserver";
SqlConnection dc = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand(sql, dc); Console.WriteLine("Connection string: " + connStr); Console.WriteLine("Press any key to test, press q to quit");
string priorServerName = ""; char key = ' ';
while(key.ToString().ToLower()!= "q") { dc.Open(); try { string serverName = cmd.ExecuteScalar() as string; Console.WriteLine(DateTime.Now.ToLongTimeString() + " - Server name: " + serverName); if (priorServerName == "") { priorServerName = serverName; } else if (priorServerName!= serverName) { Console.WriteLine("***** SERVER CHANGED *****"); Console.WriteLine("New server: " + serverName); priorServerName = serverName; } } catch (System.Data.SqlClient.SqlException ex) { Console.WriteLine("Error: " + ex.ToString()); } finally { dc.Close(); } key = Console.ReadKey(true).KeyChar;
}
Console.WriteLine("Finis!");
} } } I wouldn't have arrived here without a) asking the question and then b) getting the responses which made me actually think Murph | How can I get notification when a mirrored SQL Server database has failed over We have a couple of mirrored SQL Server databases. My first problem - the key problem - is to get a notification when the db fails over. I don't need to know because, erm, its mirrored and so it (almost) all carries on working automagically but it would useful to be advised and I'm currently getting failovers when I don't think I should be so it want to know when they occur (without too much digging) to see if I can determine why. I have services running that I could fairly easily use to monitor this - so the alternative question would be "How do I programmatically determine which is the principal and which is the mirror" - preferably in a more intelligent fashion than just attempting to connect each in turn (which would mostly work but...). Thanks, Murph Addendum: One of the answers queries why I don't need to know when it fails over - the answer is that we're developing using ADO.NET and that has automatic failover support, all you have to do is add Failover Partner=MIRRORSERVER (where MIRRORSERVER is the name of your mirror server instance) to your connection string and your code will fail over transparently - you may get some errors depending on what connections are active but in our case very few. | TITLE:
How can I get notification when a mirrored SQL Server database has failed over
QUESTION:
We have a couple of mirrored SQL Server databases. My first problem - the key problem - is to get a notification when the db fails over. I don't need to know because, erm, its mirrored and so it (almost) all carries on working automagically but it would useful to be advised and I'm currently getting failovers when I don't think I should be so it want to know when they occur (without too much digging) to see if I can determine why. I have services running that I could fairly easily use to monitor this - so the alternative question would be "How do I programmatically determine which is the principal and which is the mirror" - preferably in a more intelligent fashion than just attempting to connect each in turn (which would mostly work but...). Thanks, Murph Addendum: One of the answers queries why I don't need to know when it fails over - the answer is that we're developing using ADO.NET and that has automatic failover support, all you have to do is add Failover Partner=MIRRORSERVER (where MIRRORSERVER is the name of your mirror server instance) to your connection string and your code will fail over transparently - you may get some errors depending on what connections are active but in our case very few.
ANSWER:
Right, The two answers and a little thought got me to something approaching an answer. First a little more clarification: The app is written in C# (2.0+) and uses ADO.NET to talk to SQL Server 2005. The mirror setup is two W2k3 servers hosting the Principal and the Mirror plus a third server hosting an express instance as a monitor. The nice thing about this is a failover is all but transparent to the app using the database, it will throw an error for some connections but fundamentally everything will carry on nicely. Yes we're getting the odd false positive but the whole point is to have the system carry on working with the least amount of fuss and mirror does deliver this very nicely. Further, the issue is not with serious server failure - that's usually a bit more obvious but with a failover for other reasons (c.f. the false positives above) as we do have a couple of things that can't, for various reasons, fail over and in any case so we can see if we can identify the circumstance where we get false positives. So, given the above, simply checking the status of the boxes is not quite enough and chasing through the event log is probably overly complex - the answer is, as it turns out, fairly simple: sp_helpserver The first column returned by sp_helpserver is the server name. If you run the request at regular intervals saving the previous server name and doing a comparison each time you'll be able to identify when a change has taken place and then take the appropriate action. The following is a console app that demonstrates the principal - although it needs some work (e.g. the connection ought to be non-pooled and new each time) but its enough for now (so I'd then accept this as "the" answer"). Parameters are Principal, Mirror, Database using System; using System.Data.SqlClient;
namespace FailoverMonitorConcept { class Program { static void Main(string[] args) { string server = args[0]; string failover = args[1]; string database = args[2];
string connStr = string.Format("Integrated Security=SSPI;Persist Security Info=True;Data Source={0};Failover Partner={1};Packet Size=4096;Initial Catalog={2}", server, failover, database); string sql = "EXEC sp_helpserver";
SqlConnection dc = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand(sql, dc); Console.WriteLine("Connection string: " + connStr); Console.WriteLine("Press any key to test, press q to quit");
string priorServerName = ""; char key = ' ';
while(key.ToString().ToLower()!= "q") { dc.Open(); try { string serverName = cmd.ExecuteScalar() as string; Console.WriteLine(DateTime.Now.ToLongTimeString() + " - Server name: " + serverName); if (priorServerName == "") { priorServerName = serverName; } else if (priorServerName!= serverName) { Console.WriteLine("***** SERVER CHANGED *****"); Console.WriteLine("New server: " + serverName); priorServerName = serverName; } } catch (System.Data.SqlClient.SqlException ex) { Console.WriteLine("Error: " + ex.ToString()); } finally { dc.Close(); } key = Console.ReadKey(true).KeyChar;
}
Console.WriteLine("Finis!");
} } } I wouldn't have arrived here without a) asking the question and then b) getting the responses which made me actually think Murph | [
"sql-server"
] | 2 | 2 | 5,048 | 3 | 0 | 2008-08-26T15:22:38.373000 | 2008-08-31T21:18:40.210000 |
28,363 | 101,026 | Database compare tools | My company has a number of relatively small Access databases (2-5MB) that control our user assisted design tools. Naturally these databases evolve over time as data bugs are found and fixed and as the schema changes to support new features in the tools. Can anyone recommend a database diff tool to compare both the data and schema from one version of the database to the next? Any suggestions will be appreciated: free, open source, or commercial. | I use Red Gate Sql Compare for comparing schemas. It also has an interesting feature that allows you to save a snapshot of the schema which you can then use in later diffs. for example compare the schema of today with the schema of a month ago. | Database compare tools My company has a number of relatively small Access databases (2-5MB) that control our user assisted design tools. Naturally these databases evolve over time as data bugs are found and fixed and as the schema changes to support new features in the tools. Can anyone recommend a database diff tool to compare both the data and schema from one version of the database to the next? Any suggestions will be appreciated: free, open source, or commercial. | TITLE:
Database compare tools
QUESTION:
My company has a number of relatively small Access databases (2-5MB) that control our user assisted design tools. Naturally these databases evolve over time as data bugs are found and fixed and as the schema changes to support new features in the tools. Can anyone recommend a database diff tool to compare both the data and schema from one version of the database to the next? Any suggestions will be appreciated: free, open source, or commercial.
ANSWER:
I use Red Gate Sql Compare for comparing schemas. It also has an interesting feature that allows you to save a snapshot of the schema which you can then use in later diffs. for example compare the schema of today with the schema of a month ago. | [
"database",
"diff"
] | 3 | 5 | 3,579 | 7 | 0 | 2008-08-26T15:25:16.713000 | 2008-09-19T10:43:47.077000 |
28,369 | 32,028 | Is "safe_eval" really safe? | I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy). The functionality to do this (the rexec module ) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is this Python Cookbok recipe, "safe_eval". Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives? EDIT: I just discovered RestrictedPython, which is part of Zope. Any opinions on this are welcome. | Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files: >>> names['f'] = open('foo', 'w+') >>> safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names) >>> names['baz'] Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random. On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast: >>> import compiler >>> ast = compiler.parse("print 'Hello world!'") That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities. | Is "safe_eval" really safe? I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy). The functionality to do this (the rexec module ) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is this Python Cookbok recipe, "safe_eval". Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives? EDIT: I just discovered RestrictedPython, which is part of Zope. Any opinions on this are welcome. | TITLE:
Is "safe_eval" really safe?
QUESTION:
I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy). The functionality to do this (the rexec module ) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is this Python Cookbok recipe, "safe_eval". Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives? EDIT: I just discovered RestrictedPython, which is part of Zope. Any opinions on this are welcome.
ANSWER:
Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files: >>> names['f'] = open('foo', 'w+') >>> safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names) >>> names['baz'] Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random. On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast: >>> import compiler >>> ast = compiler.parse("print 'Hello world!'") That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities. | [
"python",
"security"
] | 5 | 3 | 4,543 | 6 | 0 | 2008-08-26T15:27:03.587000 | 2008-08-28T11:35:19.353000 |
28,377 | 28,452 | Performance difference between IIf() and If | In Visual Basic, is there a performance difference when using the IIf function instead of the If statement? | VB has the following If statement which the question refers to, I think: ' Usage 1 Dim result = If(a > 5, "World", "Hello") ' Usage 2 Dim foo = If(result, "Alternative") The first is basically C#'s ternary conditional operator and the second is its coalesce operator (return result unless it’s Nothing, in which case return "Alternative" ). If has thus replaced IIf and the latter is obsolete. Like in C#, VB's conditional If operator short-circuits, so you can now safely write the following, which is not possible using the IIf function: Dim len = If(text Is Nothing, 0, text.Length) | Performance difference between IIf() and If In Visual Basic, is there a performance difference when using the IIf function instead of the If statement? | TITLE:
Performance difference between IIf() and If
QUESTION:
In Visual Basic, is there a performance difference when using the IIf function instead of the If statement?
ANSWER:
VB has the following If statement which the question refers to, I think: ' Usage 1 Dim result = If(a > 5, "World", "Hello") ' Usage 2 Dim foo = If(result, "Alternative") The first is basically C#'s ternary conditional operator and the second is its coalesce operator (return result unless it’s Nothing, in which case return "Alternative" ). If has thus replaced IIf and the latter is obsolete. Like in C#, VB's conditional If operator short-circuits, so you can now safely write the following, which is not possible using the IIf function: Dim len = If(text Is Nothing, 0, text.Length) | [
"vb.net",
"if-statement",
"iif-function"
] | 102 | 144 | 66,662 | 9 | 0 | 2008-08-26T15:29:45.907000 | 2008-08-26T15:51:53.013000 |
28,380 | 3,869,611 | Proxy which requires authentication with Android Emulator | Has anybody managed to get the Android Emulator working behind a proxy that requires authentication? I've tried setting the -http-proxy argument to http://DOMAIN/USERNAME:PASSWORD@IP:PORT but am having no success. I've tried following the docs to no avail. I've also tried the -verbose-proxy setting but this no longer seems to exist. Any pointers? | I Managed to do it in the Adndroid 2.2 Emulator. Go to "Settings" -> "Wireless & Networks" -> "Mobile Networks" -> "Access Point Names" -> "Telkila" Over there set the proxy host name in the property "Proxy" and the Proxy port in the property "Port" | Proxy which requires authentication with Android Emulator Has anybody managed to get the Android Emulator working behind a proxy that requires authentication? I've tried setting the -http-proxy argument to http://DOMAIN/USERNAME:PASSWORD@IP:PORT but am having no success. I've tried following the docs to no avail. I've also tried the -verbose-proxy setting but this no longer seems to exist. Any pointers? | TITLE:
Proxy which requires authentication with Android Emulator
QUESTION:
Has anybody managed to get the Android Emulator working behind a proxy that requires authentication? I've tried setting the -http-proxy argument to http://DOMAIN/USERNAME:PASSWORD@IP:PORT but am having no success. I've tried following the docs to no avail. I've also tried the -verbose-proxy setting but this no longer seems to exist. Any pointers?
ANSWER:
I Managed to do it in the Adndroid 2.2 Emulator. Go to "Settings" -> "Wireless & Networks" -> "Mobile Networks" -> "Access Point Names" -> "Telkila" Over there set the proxy host name in the property "Proxy" and the Proxy port in the property "Port" | [
"android",
"authentication",
"proxy",
"android-emulator"
] | 56 | 46 | 77,058 | 16 | 0 | 2008-08-26T15:30:38.367000 | 2010-10-06T05:06:17.610000 |
28,387 | 28,444 | SQL Server 2k5 memory consumption? | I have a development vm which is running sql server as well as some other apps for my stack, and I found that the other apps are performing awfully. After doing some digging, SQL Server was hogging the memory. After a quick web search I discovered that by default, it will consume as much memory as it can in order to cache data and give it back to the system as other apps request it, but this process often doesn't happen fast enough, apparently my situation is a common problem. There however is a way to limit the memory SQL Server is allowed to have. My question is, how should I set this limit. Obviously I'm going to need to do some guess and check, but is there an absolute minimum threshhold? Any recommendations are appreciated. Edit: I'll note that out developer machines have 2 gigs of memory so I'd like to be able to run the vm on 768 mb or less if possible. This vm will be only used for local dev and testing, so the load will be very minimal. After code has been tested locally it goes to another environment where the SQL server box is dedicated. What I'm really looking for here is recommendations on minimums | Since this is a development environment, I agree with Greg, just use trial and error. It's not that crucial to get it perfectly right. But if you do a lot of work in the VM, why not give it at least half of the 2GB? | SQL Server 2k5 memory consumption? I have a development vm which is running sql server as well as some other apps for my stack, and I found that the other apps are performing awfully. After doing some digging, SQL Server was hogging the memory. After a quick web search I discovered that by default, it will consume as much memory as it can in order to cache data and give it back to the system as other apps request it, but this process often doesn't happen fast enough, apparently my situation is a common problem. There however is a way to limit the memory SQL Server is allowed to have. My question is, how should I set this limit. Obviously I'm going to need to do some guess and check, but is there an absolute minimum threshhold? Any recommendations are appreciated. Edit: I'll note that out developer machines have 2 gigs of memory so I'd like to be able to run the vm on 768 mb or less if possible. This vm will be only used for local dev and testing, so the load will be very minimal. After code has been tested locally it goes to another environment where the SQL server box is dedicated. What I'm really looking for here is recommendations on minimums | TITLE:
SQL Server 2k5 memory consumption?
QUESTION:
I have a development vm which is running sql server as well as some other apps for my stack, and I found that the other apps are performing awfully. After doing some digging, SQL Server was hogging the memory. After a quick web search I discovered that by default, it will consume as much memory as it can in order to cache data and give it back to the system as other apps request it, but this process often doesn't happen fast enough, apparently my situation is a common problem. There however is a way to limit the memory SQL Server is allowed to have. My question is, how should I set this limit. Obviously I'm going to need to do some guess and check, but is there an absolute minimum threshhold? Any recommendations are appreciated. Edit: I'll note that out developer machines have 2 gigs of memory so I'd like to be able to run the vm on 768 mb or less if possible. This vm will be only used for local dev and testing, so the load will be very minimal. After code has been tested locally it goes to another environment where the SQL server box is dedicated. What I'm really looking for here is recommendations on minimums
ANSWER:
Since this is a development environment, I agree with Greg, just use trial and error. It's not that crucial to get it perfectly right. But if you do a lot of work in the VM, why not give it at least half of the 2GB? | [
"sql-server",
"performance"
] | 3 | 1 | 703 | 4 | 0 | 2008-08-26T15:33:05.647000 | 2008-08-26T15:47:39.763000 |
28,395 | 28,411 | Passing $_POST values with cURL | How do you pass $_POST values to a page using cURL? | Should work fine. $data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an @ (for fields) $data['file'] = '@/home/user/world.jpg';
$handle = curl_init($url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); curl_exec($handle); curl_close($handle) We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST s. It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded. $data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server. $data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); $data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data. $data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data)); I hope this will help others save their time. See: curl_init curl_setopt | Passing $_POST values with cURL How do you pass $_POST values to a page using cURL? | TITLE:
Passing $_POST values with cURL
QUESTION:
How do you pass $_POST values to a page using cURL?
ANSWER:
Should work fine. $data = array('name' => 'Ross', 'php_master' => true);
// You can POST a file by prefixing with an @ (for fields) $data['file'] = '@/home/user/world.jpg';
$handle = curl_init($url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); curl_exec($handle); curl_close($handle) We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST s. It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded. $data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server. $data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); $data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data. $data = array('name' => 'Ross', 'php_master' => true); curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data)); I hope this will help others save their time. See: curl_init curl_setopt | [
"php",
"post",
"curl"
] | 99 | 173 | 196,703 | 6 | 0 | 2008-08-26T15:35:07.857000 | 2008-08-26T15:38:34.557000 |
28,428 | 28,454 | How do I get the path where the user installed my Java application? | I want to bring up a file dialog in Java that defaults to the application installation directory. What's the best way to get that information programmatically? | System.getProperty("user.dir") gets the directory the Java VM was started from. | How do I get the path where the user installed my Java application? I want to bring up a file dialog in Java that defaults to the application installation directory. What's the best way to get that information programmatically? | TITLE:
How do I get the path where the user installed my Java application?
QUESTION:
I want to bring up a file dialog in Java that defaults to the application installation directory. What's the best way to get that information programmatically?
ANSWER:
System.getProperty("user.dir") gets the directory the Java VM was started from. | [
"java",
"environment-variables"
] | 4 | 8 | 4,581 | 2 | 0 | 2008-08-26T15:43:09.743000 | 2008-08-26T15:52:17.927000 |
28,433 | 28,442 | Comparing two XML Schemas | Are there any tools to effectively compare two XML schema's? I have seen some generic XML diff tools, but I was wondering if there is anything that knows more about schemas. | I would look into DeltaXML. It seems to have the features you're looking for. They even have a guide on how to compare schemas. | Comparing two XML Schemas Are there any tools to effectively compare two XML schema's? I have seen some generic XML diff tools, but I was wondering if there is anything that knows more about schemas. | TITLE:
Comparing two XML Schemas
QUESTION:
Are there any tools to effectively compare two XML schema's? I have seen some generic XML diff tools, but I was wondering if there is anything that knows more about schemas.
ANSWER:
I would look into DeltaXML. It seems to have the features you're looking for. They even have a guide on how to compare schemas. | [
"xml",
"comparison",
"xsd"
] | 8 | 6 | 7,612 | 1 | 0 | 2008-08-26T15:43:54.843000 | 2008-08-26T15:46:00.110000 |
28,464 | 28,479 | When do you use dependency injection? | I've been using StructureMap recently and have enjoyed the experience thoroughly. However, I can see how one can easily get carried away with interfacing everything out and end up with classes that take in a boatload of interfaces into their constructors. Even though that really isn't a huge problem when you're using a dependency injection framework, it still feels that there are certain properties that really don't need to be interfaced out just for the sake of interfacing them. Where do you draw the line on what to interface out vs just adding a property to the class? | Think about your design. DI allows you to change how your code functions via configuration changes. It also allows you to break dependencies between classes so that you can isolate and test objects easier. You have to determine where this makes sense and where it doesn't. There's no pat answer. A good rule of thumb is that if its too hard to test, you've got some issues with single responsibility and static dependencies. Isolate code that performs a single function into a class and break that static dependency by extracting an interface and using a DI framework to inject the correct instance at runtime. By doing this, you make it trivial to test the two parts separately. | When do you use dependency injection? I've been using StructureMap recently and have enjoyed the experience thoroughly. However, I can see how one can easily get carried away with interfacing everything out and end up with classes that take in a boatload of interfaces into their constructors. Even though that really isn't a huge problem when you're using a dependency injection framework, it still feels that there are certain properties that really don't need to be interfaced out just for the sake of interfacing them. Where do you draw the line on what to interface out vs just adding a property to the class? | TITLE:
When do you use dependency injection?
QUESTION:
I've been using StructureMap recently and have enjoyed the experience thoroughly. However, I can see how one can easily get carried away with interfacing everything out and end up with classes that take in a boatload of interfaces into their constructors. Even though that really isn't a huge problem when you're using a dependency injection framework, it still feels that there are certain properties that really don't need to be interfaced out just for the sake of interfacing them. Where do you draw the line on what to interface out vs just adding a property to the class?
ANSWER:
Think about your design. DI allows you to change how your code functions via configuration changes. It also allows you to break dependencies between classes so that you can isolate and test objects easier. You have to determine where this makes sense and where it doesn't. There's no pat answer. A good rule of thumb is that if its too hard to test, you've got some issues with single responsibility and static dependencies. Isolate code that performs a single function into a class and break that static dependency by extracting an interface and using a DI framework to inject the correct instance at runtime. By doing this, you make it trivial to test the two parts separately. | [
"dependency-injection"
] | 16 | 9 | 1,579 | 9 | 0 | 2008-08-26T15:55:44.237000 | 2008-08-26T16:03:59.240000 |
28,478 | 28,498 | If, IIf() and If() | I recently asked a question about IIf vs. If and found out that there is another function in VB called If which basically does the same thing as IIf but is a short-circuit. Does this If function perform better than the IIf function? Does the If statement trump the If and IIf functions? | Damn, I really thought you were talking about the operator all along.;-) Anyway … Does this If function perform better than the IIf function? Definitely. Remember, it's built into the language. Only one of the two conditional arguments has to be evaluated, potentially saving a costly operation. Does the If statement trump the If and IIf functions? I think you can't compare the two because they do different things. If your code semantically performs an assignment you should emphasize this, instead of the decision-making. Use the If operator here instead of the statement. This is especially true if you can use it in the initialization of a variable because otherwise the variable will be default initialized, resulting in slower code: Dim result = If(a > 0, Math.Sqrt(a), -1.0)
' versus
Dim result As Double ' Redundant default initialization! If a > 0 Then result = Math.Sqrt(a) Else result = -1 End If | If, IIf() and If() I recently asked a question about IIf vs. If and found out that there is another function in VB called If which basically does the same thing as IIf but is a short-circuit. Does this If function perform better than the IIf function? Does the If statement trump the If and IIf functions? | TITLE:
If, IIf() and If()
QUESTION:
I recently asked a question about IIf vs. If and found out that there is another function in VB called If which basically does the same thing as IIf but is a short-circuit. Does this If function perform better than the IIf function? Does the If statement trump the If and IIf functions?
ANSWER:
Damn, I really thought you were talking about the operator all along.;-) Anyway … Does this If function perform better than the IIf function? Definitely. Remember, it's built into the language. Only one of the two conditional arguments has to be evaluated, potentially saving a costly operation. Does the If statement trump the If and IIf functions? I think you can't compare the two because they do different things. If your code semantically performs an assignment you should emphasize this, instead of the decision-making. Use the If operator here instead of the statement. This is especially true if you can use it in the initialization of a variable because otherwise the variable will be default initialized, resulting in slower code: Dim result = If(a > 0, Math.Sqrt(a), -1.0)
' versus
Dim result As Double ' Redundant default initialization! If a > 0 Then result = Math.Sqrt(a) Else result = -1 End If | [
".net",
"vb.net",
"if-statement",
"iif-function"
] | 11 | 15 | 4,786 | 2 | 0 | 2008-08-26T16:03:37.260000 | 2008-08-26T16:10:32.827000 |
28,481 | 28,490 | What is the purpose of the designer files in Visual Studio 2008 Web application projects? | There is a conversion process that is needed when migrating Visual Studio 2005 web site to Visual Studio 2008 web application projects. It looks like VS2008 is creating a.designer. file for every aspx when you right click on a file or the project itself in Solution Explorer and select 'Convert to Web Application.' What is the purpose of these designer files? And these won't exist on a release build of the web application, they are just intermediate files used during development, hopefully? | They hold all the form designer stuff that used to go in the #Region " Web Form Designer Generated Code " section of the code. instead of putting it in the.aspx.vb file where people might edit it (mistakenly or not), it's been moved to a separate file, so that you don't have ever look at it. | What is the purpose of the designer files in Visual Studio 2008 Web application projects? There is a conversion process that is needed when migrating Visual Studio 2005 web site to Visual Studio 2008 web application projects. It looks like VS2008 is creating a.designer. file for every aspx when you right click on a file or the project itself in Solution Explorer and select 'Convert to Web Application.' What is the purpose of these designer files? And these won't exist on a release build of the web application, they are just intermediate files used during development, hopefully? | TITLE:
What is the purpose of the designer files in Visual Studio 2008 Web application projects?
QUESTION:
There is a conversion process that is needed when migrating Visual Studio 2005 web site to Visual Studio 2008 web application projects. It looks like VS2008 is creating a.designer. file for every aspx when you right click on a file or the project itself in Solution Explorer and select 'Convert to Web Application.' What is the purpose of these designer files? And these won't exist on a release build of the web application, they are just intermediate files used during development, hopefully?
ANSWER:
They hold all the form designer stuff that used to go in the #Region " Web Form Designer Generated Code " section of the code. instead of putting it in the.aspx.vb file where people might edit it (mistakenly or not), it's been moved to a separate file, so that you don't have ever look at it. | [
"visual-studio-2008",
"web-applications"
] | 2 | 5 | 1,128 | 2 | 0 | 2008-08-26T16:04:53.450000 | 2008-08-26T16:07:34.613000 |
28,529 | 28,537 | How would you handle errors when using jQuery.ajax()? | When using jQuery 's ajax method to submit form data, what is the best way to handle errors? This is an example of what a call might look like: $.ajax({ url: "userCreation.ashx", data: { u:userName, p:password, e:email }, type: "POST", beforeSend: function(){disableSubmitButton();}, complete: function(){enableSubmitButton();}, error: function(xhr, statusText, errorThrown){ // Work out what the error was and display the appropriate message }, success: function(data){ displayUserCreatedMessage(); refreshUserList(); } }); The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens. My problem seems to be that by throwing an exception the ashx causes the statusText and errorThrown to be undefined. I can get to the XMLHttpRequest.responseText which contains the HTML that makes up the standard.net error page. I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages. Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take? How do you handle these situations? | Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take? How do you handle these situations? Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially). However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code. | How would you handle errors when using jQuery.ajax()? When using jQuery 's ajax method to submit form data, what is the best way to handle errors? This is an example of what a call might look like: $.ajax({ url: "userCreation.ashx", data: { u:userName, p:password, e:email }, type: "POST", beforeSend: function(){disableSubmitButton();}, complete: function(){enableSubmitButton();}, error: function(xhr, statusText, errorThrown){ // Work out what the error was and display the appropriate message }, success: function(data){ displayUserCreatedMessage(); refreshUserList(); } }); The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens. My problem seems to be that by throwing an exception the ashx causes the statusText and errorThrown to be undefined. I can get to the XMLHttpRequest.responseText which contains the HTML that makes up the standard.net error page. I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages. Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take? How do you handle these situations? | TITLE:
How would you handle errors when using jQuery.ajax()?
QUESTION:
When using jQuery 's ajax method to submit form data, what is the best way to handle errors? This is an example of what a call might look like: $.ajax({ url: "userCreation.ashx", data: { u:userName, p:password, e:email }, type: "POST", beforeSend: function(){disableSubmitButton();}, complete: function(){enableSubmitButton();}, error: function(xhr, statusText, errorThrown){ // Work out what the error was and display the appropriate message }, success: function(data){ displayUserCreatedMessage(); refreshUserList(); } }); The request might fail for a number of reasons, such as duplicate user name, duplicate email address etc, and the ashx is written to throw an exception when this happens. My problem seems to be that by throwing an exception the ashx causes the statusText and errorThrown to be undefined. I can get to the XMLHttpRequest.responseText which contains the HTML that makes up the standard.net error page. I am finding the page title in the responseText and using the title to work out which error was thrown. Although I have a suspicion that this will fall apart when I enable custom error handling pages. Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take? How do you handle these situations?
ANSWER:
Should I be throwing the errors in the ashx, or should I be returning a status code as part of the data returned by the call to userCreation.ashx, then using this to decide what action to take? How do you handle these situations? Personally, if possible, I would prefer to handle this on the server side and work up a message to the user there. This works very well in a scenario where you only want to display a message to the user telling them what happened (validation message, essentially). However, if you want to perform an action based on what happened on the server, you may want to use a status code and write some javascript to perform various actions based on that status code. | [
"asp.net",
"jquery",
"ajax"
] | 33 | 16 | 6,710 | 3 | 0 | 2008-08-26T16:26:45.347000 | 2008-08-26T16:29:46.977000 |
28,530 | 38,903 | Corporate-Friendly Open Source Licenses | What open source licenses are more corporate-friendly, i.e., they can be used in commercial products without the need to open source the commercial product? | I recommend the Apache License (specifically, version 2). It is not a “copy left” license and it addresses several matters that are important to established companies and their lawyers. “Copy left” is the philosophy of the free software foundation requiring anything incorporating the licensed opens source code to also be licensed as open source. That philosophy is regarded as poison by established companies that want to keep their products proprietary. Aside from not having “copy left” provisions, the Apache license specifically addresses the grant of rights from project contributors and it expressly addresses the fact that modern companies are typically made up for more than one legal entity (for example, a parent company and its subsidiaries). Most open source licenses don’t address these points. Whatever license you choose, if you want your code to be “corporate friendly,” in the sense that you want it to be incorporated into commercial, non-open source products, it is essential that you avoid GPL and other “copy left” type licenses. While it would be best to consult with your own lawyer before investing time or money in a project for which this is an important factor, a quick shorthand for licenses that are and are not “copy left” can be found on the Free Software Foundation’s website. They identify which licenses they don’t find meet their standards as “copy left.” The ones FSF rejects are most likely the ones that will be corporate friendly in this sense. (Although the question didn’t ask this, it is worth mentioning that, with very few exceptions, even GPL and other “copy left” type licenses are perfectly corporate friendly if they are only used internally by the commercial entities and not incorporated into their products.) | Corporate-Friendly Open Source Licenses What open source licenses are more corporate-friendly, i.e., they can be used in commercial products without the need to open source the commercial product? | TITLE:
Corporate-Friendly Open Source Licenses
QUESTION:
What open source licenses are more corporate-friendly, i.e., they can be used in commercial products without the need to open source the commercial product?
ANSWER:
I recommend the Apache License (specifically, version 2). It is not a “copy left” license and it addresses several matters that are important to established companies and their lawyers. “Copy left” is the philosophy of the free software foundation requiring anything incorporating the licensed opens source code to also be licensed as open source. That philosophy is regarded as poison by established companies that want to keep their products proprietary. Aside from not having “copy left” provisions, the Apache license specifically addresses the grant of rights from project contributors and it expressly addresses the fact that modern companies are typically made up for more than one legal entity (for example, a parent company and its subsidiaries). Most open source licenses don’t address these points. Whatever license you choose, if you want your code to be “corporate friendly,” in the sense that you want it to be incorporated into commercial, non-open source products, it is essential that you avoid GPL and other “copy left” type licenses. While it would be best to consult with your own lawyer before investing time or money in a project for which this is an important factor, a quick shorthand for licenses that are and are not “copy left” can be found on the Free Software Foundation’s website. They identify which licenses they don’t find meet their standards as “copy left.” The ones FSF rejects are most likely the ones that will be corporate friendly in this sense. (Although the question didn’t ask this, it is worth mentioning that, with very few exceptions, even GPL and other “copy left” type licenses are perfectly corporate friendly if they are only used internally by the commercial entities and not incorporated into their products.) | [
"open-source"
] | 36 | 30 | 11,677 | 10 | 0 | 2008-08-26T16:26:51.417000 | 2008-09-02T05:45:35.067000 |
28,538 | 28,594 | Java import/export dependencies | I'm trying to find a way to list the (static) dependency requirements of a jar file, in terms of which symbols are required at run time. I can see that the methods exported by classes can be listed using "javap", but there doesn't seem to be an opposite facility to list the 'imports'. Is it possible to do this? This would be similar to the dumpbin utility in Windows development which can be used to list the exports and imports of a DLL. EDIT: Thanks for the responses; I checked out all of the suggestions; accepted DependencyFinder as it most closely meets what I was looking for. | You could use the Outbound dependencies feature of DependencyFinder. You can do that entirely in the GUI, or in command line exporting XML. | Java import/export dependencies I'm trying to find a way to list the (static) dependency requirements of a jar file, in terms of which symbols are required at run time. I can see that the methods exported by classes can be listed using "javap", but there doesn't seem to be an opposite facility to list the 'imports'. Is it possible to do this? This would be similar to the dumpbin utility in Windows development which can be used to list the exports and imports of a DLL. EDIT: Thanks for the responses; I checked out all of the suggestions; accepted DependencyFinder as it most closely meets what I was looking for. | TITLE:
Java import/export dependencies
QUESTION:
I'm trying to find a way to list the (static) dependency requirements of a jar file, in terms of which symbols are required at run time. I can see that the methods exported by classes can be listed using "javap", but there doesn't seem to be an opposite facility to list the 'imports'. Is it possible to do this? This would be similar to the dumpbin utility in Windows development which can be used to list the exports and imports of a DLL. EDIT: Thanks for the responses; I checked out all of the suggestions; accepted DependencyFinder as it most closely meets what I was looking for.
ANSWER:
You could use the Outbound dependencies feature of DependencyFinder. You can do that entirely in the GUI, or in command line exporting XML. | [
"java",
"import",
"export"
] | 6 | 3 | 4,871 | 4 | 0 | 2008-08-26T16:30:07.960000 | 2008-08-26T16:54:45.170000 |
28,559 | 28,714 | Most Pythonic way equivalent for: while ((x = next()) != END) | What's the best Python idiom for this C construct? while ((x = next())!= END) {.... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END):.... | Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I cannot say: while x=next(): // do something here! Since that's not possible, there are a number of "idiomatically correct" ways of doing this: while 1: x = next() if x!= END: // Blah else: break Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling: class Pita( object ): __slots__ = ('pocket',) marker = object() def __init__(self, v=marker): if v is not self.marker: self.pocket = v def __call__(self, v=marker): if v is not self.marker: self.pocket = v return self.pocket Now you can do: p = Pita() while p( next() )!= END: // do stuff with p.pocket! Thanks for this question; learning about the __call__ idiom was really cool!:) EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found here | Most Pythonic way equivalent for: while ((x = next()) != END) What's the best Python idiom for this C construct? while ((x = next())!= END) {.... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END):.... | TITLE:
Most Pythonic way equivalent for: while ((x = next()) != END)
QUESTION:
What's the best Python idiom for this C construct? while ((x = next())!= END) {.... } I don't have the ability to recode next(). update: and the answer from seems to be: for x in iter(next, END):....
ANSWER:
Short answer: there's no way to do inline variable assignment in a while loop in Python. Meaning that I cannot say: while x=next(): // do something here! Since that's not possible, there are a number of "idiomatically correct" ways of doing this: while 1: x = next() if x!= END: // Blah else: break Obviously, this is kind of ugly. You can also use one of the "iterator" approaches listed above, but, again, that may not be ideal. Finally, you can use the "pita pocket" approach that I actually just found while googling: class Pita( object ): __slots__ = ('pocket',) marker = object() def __init__(self, v=marker): if v is not self.marker: self.pocket = v def __call__(self, v=marker): if v is not self.marker: self.pocket = v return self.pocket Now you can do: p = Pita() while p( next() )!= END: // do stuff with p.pocket! Thanks for this question; learning about the __call__ idiom was really cool!:) EDIT: I'd like to give credit where credit is due. The 'pita pocket' idiom was found here | [
"c",
"python"
] | 12 | 4 | 945 | 7 | 0 | 2008-08-26T16:37:52.263000 | 2008-08-26T17:50:30.357000 |
28,560 | 28,790 | Is it possible to use nHibernate with Paradox database? | Is it possible to configure nHibernate to connect to Paradox database ( *.db files)? | Yes, sort of. There is no support included in the trunk, you need to write your own dialect. Or you can port the Paradox dialect created for Hibernate. | Is it possible to use nHibernate with Paradox database? Is it possible to configure nHibernate to connect to Paradox database ( *.db files)? | TITLE:
Is it possible to use nHibernate with Paradox database?
QUESTION:
Is it possible to configure nHibernate to connect to Paradox database ( *.db files)?
ANSWER:
Yes, sort of. There is no support included in the trunk, you need to write your own dialect. Or you can port the Paradox dialect created for Hibernate. | [
"database",
"nhibernate",
"paradox"
] | 2 | 1 | 425 | 1 | 0 | 2008-08-26T16:38:05.570000 | 2008-08-26T18:24:39.947000 |
28,577 | 28,871 | Globalization architecture | I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc. I need any product to be localized to x number of languages. What I've done so far, is to make any column that should be localized and nvarchar(MAX) and then i store an XML string like this: Super fast laptop Super hurtig bærbar And when I load it from the database, into my business logic objects, I parse the XML string to a Dictionary where the key is the culture/language code. So when I want to display the name of a product, I do this: lblName.Text = product.Name["en-us"]; Does anyone have a better solution? | You should store the current language somewhere (in a singleton, for instance) and in the product.Name property use the language setting to get the correct string. This way you only have to write the language specific code once for each field rather than thinking about languages everywhere the field is used. For example, assuming your singleton is defined in the Localizer class that stores an enum corresponding to the current language: public class Product { private idType id; public string Name { get { return Localizer.Instance.GetLocalString(id, "Name"); } } } Where GetLocalString looks something like: public string GetLocalString(idType objectId, string fieldName) { switch (_currentLanguage) { case Language.English: // db access code to retrieve your string, may need to include the table // the object is in (e.g. "Products" "Orders" etc.) db.GetValue(objectId, fieldName, "en-us"); break; } } | Globalization architecture I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc. I need any product to be localized to x number of languages. What I've done so far, is to make any column that should be localized and nvarchar(MAX) and then i store an XML string like this: Super fast laptop Super hurtig bærbar And when I load it from the database, into my business logic objects, I parse the XML string to a Dictionary where the key is the culture/language code. So when I want to display the name of a product, I do this: lblName.Text = product.Name["en-us"]; Does anyone have a better solution? | TITLE:
Globalization architecture
QUESTION:
I need to store products for an e-commerce solution in a database. Each product should have descriptive information, such as name, description etc. I need any product to be localized to x number of languages. What I've done so far, is to make any column that should be localized and nvarchar(MAX) and then i store an XML string like this: Super fast laptop Super hurtig bærbar And when I load it from the database, into my business logic objects, I parse the XML string to a Dictionary where the key is the culture/language code. So when I want to display the name of a product, I do this: lblName.Text = product.Name["en-us"]; Does anyone have a better solution?
ANSWER:
You should store the current language somewhere (in a singleton, for instance) and in the product.Name property use the language setting to get the correct string. This way you only have to write the language specific code once for each field rather than thinking about languages everywhere the field is used. For example, assuming your singleton is defined in the Localizer class that stores an enum corresponding to the current language: public class Product { private idType id; public string Name { get { return Localizer.Instance.GetLocalString(id, "Name"); } } } Where GetLocalString looks something like: public string GetLocalString(idType objectId, string fieldName) { switch (_currentLanguage) { case Language.English: // db access code to retrieve your string, may need to include the table // the object is in (e.g. "Products" "Orders" etc.) db.GetValue(objectId, fieldName, "en-us"); break; } } | [
"c#",
"architecture",
"localization",
"globalization"
] | 4 | 2 | 674 | 4 | 0 | 2008-08-26T16:48:46.963000 | 2008-08-26T19:08:53.837000 |
28,578 | 28,583 | How can I merge my files when the folder structure has changed using Borland StarTeam? | I'm in the process of refactoring some code which includes moving folders around, and I would like to regularly merge to keep things current. What is the best way to merge after I've moved folders around in my working copy? | You can move the files around in StarTeam also. Then merge after that. Whatever you do, make sure you don't delete the files and re-add in StarTeam. You'll lose the file history if you do that. | How can I merge my files when the folder structure has changed using Borland StarTeam? I'm in the process of refactoring some code which includes moving folders around, and I would like to regularly merge to keep things current. What is the best way to merge after I've moved folders around in my working copy? | TITLE:
How can I merge my files when the folder structure has changed using Borland StarTeam?
QUESTION:
I'm in the process of refactoring some code which includes moving folders around, and I would like to regularly merge to keep things current. What is the best way to merge after I've moved folders around in my working copy?
ANSWER:
You can move the files around in StarTeam also. Then merge after that. Whatever you do, make sure you don't delete the files and re-add in StarTeam. You'll lose the file history if you do that. | [
"version-control",
"refactoring",
"merge",
"starteam"
] | 2 | 3 | 917 | 5 | 0 | 2008-08-26T16:48:51.113000 | 2008-08-26T16:51:30.157000 |
28,588 | 28,604 | How do you set up an OpenID provider (server) in Ubuntu? | I want to log onto Stack Overflow using OpenID, but I thought I'd set up my own OpenID provider, just because it's harder:) How do you do this in Ubuntu? Edit: Replacing 'server' with the correct term OpenID provider (Identity provider would also be correct according to wikipedia ). | I personnally used phpMyID just for StackOverflow. It's a simple two-files PHP script to put somewhere on a subdomain. Of course, it's not as easy as installing a.deb, but since OpenID relies completely on HTTP, I'm not sure it's advisable to install a self-contained server... | How do you set up an OpenID provider (server) in Ubuntu? I want to log onto Stack Overflow using OpenID, but I thought I'd set up my own OpenID provider, just because it's harder:) How do you do this in Ubuntu? Edit: Replacing 'server' with the correct term OpenID provider (Identity provider would also be correct according to wikipedia ). | TITLE:
How do you set up an OpenID provider (server) in Ubuntu?
QUESTION:
I want to log onto Stack Overflow using OpenID, but I thought I'd set up my own OpenID provider, just because it's harder:) How do you do this in Ubuntu? Edit: Replacing 'server' with the correct term OpenID provider (Identity provider would also be correct according to wikipedia ).
ANSWER:
I personnally used phpMyID just for StackOverflow. It's a simple two-files PHP script to put somewhere on a subdomain. Of course, it's not as easy as installing a.deb, but since OpenID relies completely on HTTP, I'm not sure it's advisable to install a self-contained server... | [
"linux",
"ubuntu",
"openid"
] | 15 | 5 | 12,841 | 6 | 0 | 2008-08-26T16:53:12.740000 | 2008-08-26T16:58:58.233000 |
28,590 | 28,614 | Why is it bad practice to make multiple database connections in one request? | A discussion about Singletons in PHP has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient? How about some answers (with evidence, folks) from some people in the know? | Database connections are a limited resource. Some DBs have a very low connection limit, and wasting connections is a major problem. By consuming many connections, you may be blocking others for using the database. Additionally, throwing a ton of extra connections at the DB doesn't help anything unless there are resources on the DB server sitting idle. If you've got 8 cores and only one is being used to satisfy a query, then sure, making another connection might help. More likely, though, you are already using all the available cores. You're also likely hitting the same harddrive for every DB request, and adding additional lock contention. If your DB has anything resembling high utilization, adding extra connections won't help. That'd be like spawning extra threads in an application with the blind hope that the extra concurrency will make processing faster. It might in some certain circumstances, but in other cases it'll just slow you down as you thrash the hard drive, waste time task-switching, and introduce synchronization overhead. | Why is it bad practice to make multiple database connections in one request? A discussion about Singletons in PHP has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient? How about some answers (with evidence, folks) from some people in the know? | TITLE:
Why is it bad practice to make multiple database connections in one request?
QUESTION:
A discussion about Singletons in PHP has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient? How about some answers (with evidence, folks) from some people in the know?
ANSWER:
Database connections are a limited resource. Some DBs have a very low connection limit, and wasting connections is a major problem. By consuming many connections, you may be blocking others for using the database. Additionally, throwing a ton of extra connections at the DB doesn't help anything unless there are resources on the DB server sitting idle. If you've got 8 cores and only one is being used to satisfy a query, then sure, making another connection might help. More likely, though, you are already using all the available cores. You're also likely hitting the same harddrive for every DB request, and adding additional lock contention. If your DB has anything resembling high utilization, adding extra connections won't help. That'd be like spawning extra threads in an application with the blind hope that the extra concurrency will make processing faster. It might in some certain circumstances, but in other cases it'll just slow you down as you thrash the hard drive, waste time task-switching, and introduce synchronization overhead. | [
"database",
"resources",
"database-connection"
] | 5 | 10 | 13,253 | 5 | 0 | 2008-08-26T16:53:53.567000 | 2008-08-26T17:03:06.273000 |
28,599 | 28,717 | How do I support SSL Client Certificate authentication? | I want to do what myopenid does -- once you've logged, you can click a button that generates you an SSL certificate; the browser then downloads this certificate and stores it. When you later go back to yourid.myopenid.com, your browser can use its stored certificate for authentication so you don't ever need a password. So my questions is what is required to get this working? How do I generate certificates? How do I validate them once they're presented back to me? My stack is Rails on Apache using Passenger, but I'm not too particular. | These are usually referred to as client side certificates. I've not actually used it but a modified version of restful-authentication can be found here here that looks like what your after. I found this via Dr. Nic's post | How do I support SSL Client Certificate authentication? I want to do what myopenid does -- once you've logged, you can click a button that generates you an SSL certificate; the browser then downloads this certificate and stores it. When you later go back to yourid.myopenid.com, your browser can use its stored certificate for authentication so you don't ever need a password. So my questions is what is required to get this working? How do I generate certificates? How do I validate them once they're presented back to me? My stack is Rails on Apache using Passenger, but I'm not too particular. | TITLE:
How do I support SSL Client Certificate authentication?
QUESTION:
I want to do what myopenid does -- once you've logged, you can click a button that generates you an SSL certificate; the browser then downloads this certificate and stores it. When you later go back to yourid.myopenid.com, your browser can use its stored certificate for authentication so you don't ever need a password. So my questions is what is required to get this working? How do I generate certificates? How do I validate them once they're presented back to me? My stack is Rails on Apache using Passenger, but I'm not too particular.
ANSWER:
These are usually referred to as client side certificates. I've not actually used it but a modified version of restful-authentication can be found here here that looks like what your after. I found this via Dr. Nic's post | [
"ruby-on-rails",
"apache",
"ssl"
] | 12 | 8 | 14,950 | 5 | 0 | 2008-08-26T16:57:52.293000 | 2008-08-26T17:51:06.487000 |
28,605 | 28,618 | C on Visual Studio | I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either: learn the ins and out of C in Visual Studio recommend a better C IDE + compiler Edit: See also: https://stackoverflow.com/questions/951516/a-good-c-ide | Answering the purely subject question "recommend me a better C IDE and compiler" I find Ming32w and Code::blocks (now with combined installer) very useful on windows but YMMV as you are obviously used to the MS IDE and are just struggling with C. May I suggest you concentrate on console applications to get a feel for the language first before you attempt to tie it together with a windows UI which in my experience is the hardest bit of windows development. | C on Visual Studio I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either: learn the ins and out of C in Visual Studio recommend a better C IDE + compiler Edit: See also: https://stackoverflow.com/questions/951516/a-good-c-ide | TITLE:
C on Visual Studio
QUESTION:
I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either: learn the ins and out of C in Visual Studio recommend a better C IDE + compiler Edit: See also: https://stackoverflow.com/questions/951516/a-good-c-ide
ANSWER:
Answering the purely subject question "recommend me a better C IDE and compiler" I find Ming32w and Code::blocks (now with combined installer) very useful on windows but YMMV as you are obviously used to the MS IDE and are just struggling with C. May I suggest you concentrate on console applications to get a feel for the language first before you attempt to tie it together with a windows UI which in my experience is the hardest bit of windows development. | [
"c++",
"c",
"ide",
"compiler-construction"
] | 23 | 11 | 61,960 | 15 | 0 | 2008-08-26T16:59:00.107000 | 2008-08-26T17:03:41.390000 |
28,637 | 28,648 | Is DateTime.Now the best way to measure a function's performance? | I need to find a bottleneck and need to accurately as possible measure time. Is the following code snippet the best way to measure the performance? DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime); | No, it's not. Use the Stopwatch (in System.Diagnostics ) Stopwatch sw = Stopwatch.StartNew(); PerformWork(); sw.Stop();
Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds); Stopwatch automatically checks for the existence of high-precision timers. It is worth mentioning that DateTime.Now often is quite a bit slower than DateTime.UtcNow due to the work that has to be done with timezones, DST and such. DateTime.UtcNow typically has a resolution of 15 ms. See John Chapman's blog post about DateTime.Now precision for a great summary. Interesting trivia: The stopwatch falls back on DateTime.UtcNow if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field Stopwatch.IsHighResolution. | Is DateTime.Now the best way to measure a function's performance? I need to find a bottleneck and need to accurately as possible measure time. Is the following code snippet the best way to measure the performance? DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime); | TITLE:
Is DateTime.Now the best way to measure a function's performance?
QUESTION:
I need to find a bottleneck and need to accurately as possible measure time. Is the following code snippet the best way to measure the performance? DateTime startTime = DateTime.Now;
// Some execution process
DateTime endTime = DateTime.Now; TimeSpan totalTimeTaken = endTime.Subtract(startTime);
ANSWER:
No, it's not. Use the Stopwatch (in System.Diagnostics ) Stopwatch sw = Stopwatch.StartNew(); PerformWork(); sw.Stop();
Console.WriteLine("Time taken: {0}ms", sw.Elapsed.TotalMilliseconds); Stopwatch automatically checks for the existence of high-precision timers. It is worth mentioning that DateTime.Now often is quite a bit slower than DateTime.UtcNow due to the work that has to be done with timezones, DST and such. DateTime.UtcNow typically has a resolution of 15 ms. See John Chapman's blog post about DateTime.Now precision for a great summary. Interesting trivia: The stopwatch falls back on DateTime.UtcNow if your hardware doesn't support a high frequency counter. You can check to see if Stopwatch uses hardware to achieve high precision by looking at the static field Stopwatch.IsHighResolution. | [
"c#",
".net",
"performance",
"datetime",
"timer"
] | 494 | 674 | 76,037 | 16 | 0 | 2008-08-26T17:09:45.417000 | 2008-08-26T17:13:32.240000 |
28,642 | 28,715 | Finding controls that use a certain interface in ASP.NET | Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from System.Web.UI.WebControls.Button, and then implements an interface that I have set up. So think... public class Button: System.Web.UI.WebControls.Button, IMyButtonInterface {... } In the codebehind of a page, I'd like to find all instances of this button from the ASPX. Because I don't really know what the type is going to be, just the interface it implements, that's all I have to go on when looping through the control tree. Thing is, I've never had to determine if an object uses an interface versus just testing its type. How can I loop through the control tree and yank anything that implements IMyButtonInterface in a clean way (Linq would be fine)? Again, know it's something obvious, but just now started using interfaces heavily and I can't seem to focus my Google results enough to figure it out:) Edit: GetType() returns the actual class, but doesn't return the interface, so I can't test on that (e.g., it'd return " MyNamespace.Button " instead of " IMyButtonInterface "). In trying to use " as " or " is " in a recursive function, the type parameter doesn't even get recognized within the function! It's rather bizarre. So if(ctrl.GetType() == typeToFind) //ok
if(ctrl is typeToFind) //typeToFind isn't recognized! eh? Definitely scratching my head over this one. | Longhorn213 almost has the right answer, but as as Sean Chambers and bdukes say, you should use ctrl is IInterfaceToFind instead of ctrl.GetType() == aTypeVariable The reason why is that if you use.GetType() you will get the true type of an object, not necessarily what it can also be cast to in its inheritance/Interface implementation chain. Also,.GetType() will never return an abstract type/interface since you can't new up an abstract type or interface. GetType() returns concrete types only. The reason this doesn't work if(ctrl is typeToFind) Is because the type of the variable typeToFind is actually System.RuntimeType, not the type you've set its value to. Example, if you set a string's value to " foo ", its type is still string not " foo ". I hope that makes sense. It's very easy to get confused when working with types. I'm chronically confused when working with them. The most import thing to note about longhorn213's answer is that you have to use recursion or you may miss some of the controls on the page. Although we have a working solution here, I too would love to see if there is a more succinct way to do this with LINQ. | Finding controls that use a certain interface in ASP.NET Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from System.Web.UI.WebControls.Button, and then implements an interface that I have set up. So think... public class Button: System.Web.UI.WebControls.Button, IMyButtonInterface {... } In the codebehind of a page, I'd like to find all instances of this button from the ASPX. Because I don't really know what the type is going to be, just the interface it implements, that's all I have to go on when looping through the control tree. Thing is, I've never had to determine if an object uses an interface versus just testing its type. How can I loop through the control tree and yank anything that implements IMyButtonInterface in a clean way (Linq would be fine)? Again, know it's something obvious, but just now started using interfaces heavily and I can't seem to focus my Google results enough to figure it out:) Edit: GetType() returns the actual class, but doesn't return the interface, so I can't test on that (e.g., it'd return " MyNamespace.Button " instead of " IMyButtonInterface "). In trying to use " as " or " is " in a recursive function, the type parameter doesn't even get recognized within the function! It's rather bizarre. So if(ctrl.GetType() == typeToFind) //ok
if(ctrl is typeToFind) //typeToFind isn't recognized! eh? Definitely scratching my head over this one. | TITLE:
Finding controls that use a certain interface in ASP.NET
QUESTION:
Having a heckuva time with this one, though I feel I'm missing something obvious. I have a control that inherits from System.Web.UI.WebControls.Button, and then implements an interface that I have set up. So think... public class Button: System.Web.UI.WebControls.Button, IMyButtonInterface {... } In the codebehind of a page, I'd like to find all instances of this button from the ASPX. Because I don't really know what the type is going to be, just the interface it implements, that's all I have to go on when looping through the control tree. Thing is, I've never had to determine if an object uses an interface versus just testing its type. How can I loop through the control tree and yank anything that implements IMyButtonInterface in a clean way (Linq would be fine)? Again, know it's something obvious, but just now started using interfaces heavily and I can't seem to focus my Google results enough to figure it out:) Edit: GetType() returns the actual class, but doesn't return the interface, so I can't test on that (e.g., it'd return " MyNamespace.Button " instead of " IMyButtonInterface "). In trying to use " as " or " is " in a recursive function, the type parameter doesn't even get recognized within the function! It's rather bizarre. So if(ctrl.GetType() == typeToFind) //ok
if(ctrl is typeToFind) //typeToFind isn't recognized! eh? Definitely scratching my head over this one.
ANSWER:
Longhorn213 almost has the right answer, but as as Sean Chambers and bdukes say, you should use ctrl is IInterfaceToFind instead of ctrl.GetType() == aTypeVariable The reason why is that if you use.GetType() you will get the true type of an object, not necessarily what it can also be cast to in its inheritance/Interface implementation chain. Also,.GetType() will never return an abstract type/interface since you can't new up an abstract type or interface. GetType() returns concrete types only. The reason this doesn't work if(ctrl is typeToFind) Is because the type of the variable typeToFind is actually System.RuntimeType, not the type you've set its value to. Example, if you set a string's value to " foo ", its type is still string not " foo ". I hope that makes sense. It's very easy to get confused when working with types. I'm chronically confused when working with them. The most import thing to note about longhorn213's answer is that you have to use recursion or you may miss some of the controls on the page. Although we have a working solution here, I too would love to see if there is a more succinct way to do this with LINQ. | [
"c#",
"asp.net"
] | 7 | 7 | 2,545 | 7 | 0 | 2008-08-26T17:11:41.603000 | 2008-08-26T17:50:51.637000 |
28,654 | 28,667 | Debugging Web Service with SOAP Packet | I have a web service that I created in C# and a test harness that was provided by my client. Unfortunately my web service doesn't seem to be parsing the objects created by the test harness. I believe the problem lies with serializing the soap packet. Using TCPTrace I was able to get the soap packet passed to the web service but only on a remote machine so I can't debug it there. Is there a way of calling my local webservice with the soap packet generated rather than my current test harness where I manually create objects and call the web service through a web reference? [edit] The machine that I got the soap packet was on a vm so I can't link it to my machine. I suppose I'm looking for a tool that I can paste the soap packet into and it will in turn call my web service | A somewhat manual process would be to use the Poster add-in for Firefox. There is also a java utility called SoapUI that has some discovery based automated templates that you can then modify and run against your service. | Debugging Web Service with SOAP Packet I have a web service that I created in C# and a test harness that was provided by my client. Unfortunately my web service doesn't seem to be parsing the objects created by the test harness. I believe the problem lies with serializing the soap packet. Using TCPTrace I was able to get the soap packet passed to the web service but only on a remote machine so I can't debug it there. Is there a way of calling my local webservice with the soap packet generated rather than my current test harness where I manually create objects and call the web service through a web reference? [edit] The machine that I got the soap packet was on a vm so I can't link it to my machine. I suppose I'm looking for a tool that I can paste the soap packet into and it will in turn call my web service | TITLE:
Debugging Web Service with SOAP Packet
QUESTION:
I have a web service that I created in C# and a test harness that was provided by my client. Unfortunately my web service doesn't seem to be parsing the objects created by the test harness. I believe the problem lies with serializing the soap packet. Using TCPTrace I was able to get the soap packet passed to the web service but only on a remote machine so I can't debug it there. Is there a way of calling my local webservice with the soap packet generated rather than my current test harness where I manually create objects and call the web service through a web reference? [edit] The machine that I got the soap packet was on a vm so I can't link it to my machine. I suppose I'm looking for a tool that I can paste the soap packet into and it will in turn call my web service
ANSWER:
A somewhat manual process would be to use the Poster add-in for Firefox. There is also a java utility called SoapUI that has some discovery based automated templates that you can then modify and run against your service. | [
"c#",
"web-services",
"soap",
"tcptrace-pocketsoap"
] | 2 | 2 | 2,203 | 4 | 0 | 2008-08-26T17:14:55.467000 | 2008-08-26T17:19:44.830000 |
28,664 | 28,687 | What is the best/a very good meta-data reader library? | Right now, I'm particularly interested in reading the data from MP3 files (ID3 tags?), but the more it can do (eg EXIF from images?) the better without compromising the ID3 tag reading abilities. I'm interested in making a script that goes through my media (right now, my music files) and makes sure the file name and directory path correspond to the file's metadata and then create a log of mismatched files so I can check to see which is accurate and make the proper changes. I'm thinking Ruby or Python (see a related question specifically for Python ) would be best for this, but I'm open to using any language really (and would actually probably prefer an application language like C, C++, Java, C# in case this project goes off). | There is a great post on using PowerShell and TagLibSharp on Joel "Jaykul" Bennet's site. You could use TagLibSharp to read the metatdata with any.NET based language, but PowerShell is quite appropriate for what you are trying to do. | What is the best/a very good meta-data reader library? Right now, I'm particularly interested in reading the data from MP3 files (ID3 tags?), but the more it can do (eg EXIF from images?) the better without compromising the ID3 tag reading abilities. I'm interested in making a script that goes through my media (right now, my music files) and makes sure the file name and directory path correspond to the file's metadata and then create a log of mismatched files so I can check to see which is accurate and make the proper changes. I'm thinking Ruby or Python (see a related question specifically for Python ) would be best for this, but I'm open to using any language really (and would actually probably prefer an application language like C, C++, Java, C# in case this project goes off). | TITLE:
What is the best/a very good meta-data reader library?
QUESTION:
Right now, I'm particularly interested in reading the data from MP3 files (ID3 tags?), but the more it can do (eg EXIF from images?) the better without compromising the ID3 tag reading abilities. I'm interested in making a script that goes through my media (right now, my music files) and makes sure the file name and directory path correspond to the file's metadata and then create a log of mismatched files so I can check to see which is accurate and make the proper changes. I'm thinking Ruby or Python (see a related question specifically for Python ) would be best for this, but I'm open to using any language really (and would actually probably prefer an application language like C, C++, Java, C# in case this project goes off).
ANSWER:
There is a great post on using PowerShell and TagLibSharp on Joel "Jaykul" Bennet's site. You could use TagLibSharp to read the metatdata with any.NET based language, but PowerShell is quite appropriate for what you are trying to do. | [
"metadata"
] | 5 | 1 | 1,421 | 5 | 0 | 2008-08-26T17:18:21.433000 | 2008-08-26T17:35:11.440000 |
28,668 | 28,692 | Best way to extract data from a FileMaker Pro database in a script? | My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine. I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful. It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand. Note: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages. Conclusion: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections). | It has been a really long time since I did anything with FileMaker Pro, but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however, I don't know how, or if, that translates to the linux/perl/python world though). This article shows how to share/expose your FileMaker data via ODBC & JDBC: Sharing FileMaker Pro data via ODBC or JDBC From there, if you're able to create an ODBC/JDBC connection you could query out data as needed. | Best way to extract data from a FileMaker Pro database in a script? My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine. I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful. It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand. Note: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages. Conclusion: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections). | TITLE:
Best way to extract data from a FileMaker Pro database in a script?
QUESTION:
My job would be easier, or at least less tedious if I could come up with an automated way (preferably in a Python script) to extract useful information from a FileMaker Pro database. I am working on Linux machine and the FileMaker database is on the same LAN running on an OS X machine. I can log into the webby interface from my machine. I'm quite handy with SQL, and if somebody could point me to some FileMaker plug-in that could give me SQL access to the data within FileMaker, I would be pleased as punch. Everything I've found only goes the other way: Having FileMaker get data from SQL sources. Not useful. It's not my first choice, but I'd use Perl instead of Python if there was a Perl-y solution at hand. Note: XML/XSLT services (as suggested by some folks) are only available on FM Server, not FM Pro. Otherwise, that would probably be the best solution. ODBC is turning out to be extremely difficult to even get working. There is absolutely zero feedback from FM when you set it up so you have to dig through /var/log/system.log and parse obscure error messages. Conclusion: I got it working by running a python script locally on the machine that queries the FM database through the ODBC connections. The script is actually a TCPServer that accepts socket connections from other systems on the LAN, runs the queries, and returns the data through the socket connection. I had to do this to bypass the fact that FM Pro only accepts ODBC connections locally (FM server is required for external connections).
ANSWER:
It has been a really long time since I did anything with FileMaker Pro, but I know that it does have capabilities for an ODBC (and JDBC) connection to be made to it (however, I don't know how, or if, that translates to the linux/perl/python world though). This article shows how to share/expose your FileMaker data via ODBC & JDBC: Sharing FileMaker Pro data via ODBC or JDBC From there, if you're able to create an ODBC/JDBC connection you could query out data as needed. | [
"python",
"linux",
"perl",
"scripting",
"filemaker"
] | 10 | 6 | 11,109 | 3 | 0 | 2008-08-26T17:20:47.557000 | 2008-08-26T17:36:19.533000 |
28,675 | 28,684 | How to avoid OutOfMemoryError when using Bytebuffers and NIO? | I'm using ByteBuffers and FileChannels to write binary data to a file. When doing that for big files or successively for multiple files, I get an OutOfMemoryError exception. I've read elsewhere that using Bytebuffers with NIO is broken and should be avoided. Does any of you already faced this kind of problem and found a solution to efficiently save large amounts of binary data in a file in java? Is the jvm option -XX:MaxDirectMemorySize the way to go? | I would say don't create a huge ByteBuffer that contains ALL of the data at once. Create a much smaller ByteBuffer, fill it with data, then write this data to the FileChannel. Then reset the ByteBuffer and continue until all the data is written. | How to avoid OutOfMemoryError when using Bytebuffers and NIO? I'm using ByteBuffers and FileChannels to write binary data to a file. When doing that for big files or successively for multiple files, I get an OutOfMemoryError exception. I've read elsewhere that using Bytebuffers with NIO is broken and should be avoided. Does any of you already faced this kind of problem and found a solution to efficiently save large amounts of binary data in a file in java? Is the jvm option -XX:MaxDirectMemorySize the way to go? | TITLE:
How to avoid OutOfMemoryError when using Bytebuffers and NIO?
QUESTION:
I'm using ByteBuffers and FileChannels to write binary data to a file. When doing that for big files or successively for multiple files, I get an OutOfMemoryError exception. I've read elsewhere that using Bytebuffers with NIO is broken and should be avoided. Does any of you already faced this kind of problem and found a solution to efficiently save large amounts of binary data in a file in java? Is the jvm option -XX:MaxDirectMemorySize the way to go?
ANSWER:
I would say don't create a huge ByteBuffer that contains ALL of the data at once. Create a much smaller ByteBuffer, fill it with data, then write this data to the FileChannel. Then reset the ByteBuffer and continue until all the data is written. | [
"java",
"nio",
"bytebuffer",
"filechannel"
] | 3 | 7 | 9,284 | 6 | 0 | 2008-08-26T17:23:01.267000 | 2008-08-26T17:26:45.953000 |
28,709 | 549,032 | Eclipse 3.2.2 content assist not finding classes in the project | In Eclipse 3.2.2 on Linux content assist is not finding classes within the same project. Upgrading above 3.2 is not an option as SWT is not available above 3.2 for Solaris. I have seen suggestions to clean the workspace, reopen the workspace, run eclipse with the -clean command, none of which has worked. | Thanks for your last comment it worked partially. If there is any kind of errors, the content assist wont work. Once fixed, it partially works. I say partially because, there appear to be a bug, when I do Perl EPIC inheritance ex: package FG::CatalogueFichier; use FG::Catalogue; our @ISA = qw(FG::Catalogue); use strict;, the inheritted subroutines are not displayed in the content assist. | Eclipse 3.2.2 content assist not finding classes in the project In Eclipse 3.2.2 on Linux content assist is not finding classes within the same project. Upgrading above 3.2 is not an option as SWT is not available above 3.2 for Solaris. I have seen suggestions to clean the workspace, reopen the workspace, run eclipse with the -clean command, none of which has worked. | TITLE:
Eclipse 3.2.2 content assist not finding classes in the project
QUESTION:
In Eclipse 3.2.2 on Linux content assist is not finding classes within the same project. Upgrading above 3.2 is not an option as SWT is not available above 3.2 for Solaris. I have seen suggestions to clean the workspace, reopen the workspace, run eclipse with the -clean command, none of which has worked.
ANSWER:
Thanks for your last comment it worked partially. If there is any kind of errors, the content assist wont work. Once fixed, it partially works. I say partially because, there appear to be a bug, when I do Perl EPIC inheritance ex: package FG::CatalogueFichier; use FG::Catalogue; our @ISA = qw(FG::Catalogue); use strict;, the inheritted subroutines are not displayed in the content assist. | [
"linux",
"eclipse",
"eclipse-3.2"
] | 1 | 1 | 2,797 | 4 | 0 | 2008-08-26T17:48:04.560000 | 2009-02-14T12:20:23.330000 |
28,716 | 28,735 | Which PHP opcode cacher should I use to improve performance? | I'm trying to improve performance under high load and would like to implement opcode caching. Which of the following should I use? APC - Installation Guide eAccelerator - Installation Guide XCache - Installation Guide I'm also open to any other alternatives that have slipped under my radar. Currently running on a stock Debian Etch with Apache 2 and PHP 5.2 [Update 1] HowtoForge installation links added [Update 2] Based on the answers and feedback given, I have tested all 3 implementations using the following Apache JMeter test plan on my application: Login Access Home Page With 50 concurrent connections, the results are as follows: No Opcode Caching APC eAccelerator XCache Performance Graph (smaller is better) From the above results, eAccelerator has a slight edge in performance compared to APC and XCache. However, what matters most from the above data is that any sort of opcode caching gives a tremendous boost in performance. I have decided to use APC due to the following 2 reasons: Package is available in official Debian repository More functional control panel To summarize my experience: Ease of Installation: APC > eAccelerator > XCache Performance: eAccelerator > APC, XCache Control Panel: APC > XCache > eAccelerator | I think the answer might depend on the type of web applications you are running. I had to make this decision myself two years ago and couldn't decide between Zend Optimizer and eAccelerator. In order to make my decision, I used ab (apache bench) to test the server, and tested the three combinations (zend, eaccelerator, both running) and proved that eAccelerator on its own gave the greatest performance. If you have the luxury of time, I would recommend doing similar tests yourself, and making the decision based on your results. | Which PHP opcode cacher should I use to improve performance? I'm trying to improve performance under high load and would like to implement opcode caching. Which of the following should I use? APC - Installation Guide eAccelerator - Installation Guide XCache - Installation Guide I'm also open to any other alternatives that have slipped under my radar. Currently running on a stock Debian Etch with Apache 2 and PHP 5.2 [Update 1] HowtoForge installation links added [Update 2] Based on the answers and feedback given, I have tested all 3 implementations using the following Apache JMeter test plan on my application: Login Access Home Page With 50 concurrent connections, the results are as follows: No Opcode Caching APC eAccelerator XCache Performance Graph (smaller is better) From the above results, eAccelerator has a slight edge in performance compared to APC and XCache. However, what matters most from the above data is that any sort of opcode caching gives a tremendous boost in performance. I have decided to use APC due to the following 2 reasons: Package is available in official Debian repository More functional control panel To summarize my experience: Ease of Installation: APC > eAccelerator > XCache Performance: eAccelerator > APC, XCache Control Panel: APC > XCache > eAccelerator | TITLE:
Which PHP opcode cacher should I use to improve performance?
QUESTION:
I'm trying to improve performance under high load and would like to implement opcode caching. Which of the following should I use? APC - Installation Guide eAccelerator - Installation Guide XCache - Installation Guide I'm also open to any other alternatives that have slipped under my radar. Currently running on a stock Debian Etch with Apache 2 and PHP 5.2 [Update 1] HowtoForge installation links added [Update 2] Based on the answers and feedback given, I have tested all 3 implementations using the following Apache JMeter test plan on my application: Login Access Home Page With 50 concurrent connections, the results are as follows: No Opcode Caching APC eAccelerator XCache Performance Graph (smaller is better) From the above results, eAccelerator has a slight edge in performance compared to APC and XCache. However, what matters most from the above data is that any sort of opcode caching gives a tremendous boost in performance. I have decided to use APC due to the following 2 reasons: Package is available in official Debian repository More functional control panel To summarize my experience: Ease of Installation: APC > eAccelerator > XCache Performance: eAccelerator > APC, XCache Control Panel: APC > XCache > eAccelerator
ANSWER:
I think the answer might depend on the type of web applications you are running. I had to make this decision myself two years ago and couldn't decide between Zend Optimizer and eAccelerator. In order to make my decision, I used ab (apache bench) to test the server, and tested the three combinations (zend, eaccelerator, both running) and proved that eAccelerator on its own gave the greatest performance. If you have the luxury of time, I would recommend doing similar tests yourself, and making the decision based on your results. | [
"php",
"performance",
"caching"
] | 59 | 18 | 10,942 | 7 | 0 | 2008-08-26T17:50:53.303000 | 2008-08-26T17:58:05.783000 |
28,723 | 35,299 | Best way to unit test ASP.NET MVC action methods that use BindingHelperExtensions.UpdateFrom? | In handling a form post I have something like public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form);
this.orderService.Save(order);
return this.RedirectToAction("Details", new { id = order.ID }); } I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing. I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new. I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like [SomeFilter] public Insert(Contact contact) | I'm now using ModelBinder so that my action method can look (basically) like: public ActionResult Insert(Contact contact) {
if (this.ViewData.ModelState.IsValid) { this.contactService.SaveContact(contact);
return this.RedirectToAction("Details", new { id = contact.ID }); } else { return this.RedirectToAction("Create"); } } | Best way to unit test ASP.NET MVC action methods that use BindingHelperExtensions.UpdateFrom? In handling a form post I have something like public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form);
this.orderService.Save(order);
return this.RedirectToAction("Details", new { id = order.ID }); } I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing. I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new. I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like [SomeFilter] public Insert(Contact contact) | TITLE:
Best way to unit test ASP.NET MVC action methods that use BindingHelperExtensions.UpdateFrom?
QUESTION:
In handling a form post I have something like public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form);
this.orderService.Save(order);
return this.RedirectToAction("Details", new { id = order.ID }); } I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing. I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new. I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like [SomeFilter] public Insert(Contact contact)
ANSWER:
I'm now using ModelBinder so that my action method can look (basically) like: public ActionResult Insert(Contact contact) {
if (this.ViewData.ModelState.IsValid) { this.contactService.SaveContact(contact);
return this.RedirectToAction("Details", new { id = contact.ID }); } else { return this.RedirectToAction("Create"); } } | [
"asp.net-mvc",
"unit-testing"
] | 1 | 1 | 762 | 3 | 0 | 2008-08-26T17:53:56.887000 | 2008-08-29T21:09:42.947000 |
28,739 | 28,828 | Get `df` to show updated information on FreeBSD | I recently ran out of disk space on a drive on a FreeBSD server. I truncated the file that was causing problems but I'm not seeing the change reflected when running df. When I run du -d0 on the partition it shows the correct value. Is there any way to force this information to be updated? What is causing the output here to be different? | This probably centres on how you truncated the file. du and df report different things as this post on unix.com explains. Just because space is not used does not necessarily mean that it's free... | Get `df` to show updated information on FreeBSD I recently ran out of disk space on a drive on a FreeBSD server. I truncated the file that was causing problems but I'm not seeing the change reflected when running df. When I run du -d0 on the partition it shows the correct value. Is there any way to force this information to be updated? What is causing the output here to be different? | TITLE:
Get `df` to show updated information on FreeBSD
QUESTION:
I recently ran out of disk space on a drive on a FreeBSD server. I truncated the file that was causing problems but I'm not seeing the change reflected when running df. When I run du -d0 on the partition it shows the correct value. Is there any way to force this information to be updated? What is causing the output here to be different?
ANSWER:
This probably centres on how you truncated the file. du and df report different things as this post on unix.com explains. Just because space is not used does not necessarily mean that it's free... | [
"filesystems",
"system-administration",
"freebsd"
] | 0 | 2 | 8,537 | 3 | 0 | 2008-08-26T18:00:52.423000 | 2008-08-26T18:50:47.233000 |
28,756 | 28,763 | The best way to get a count of IEnumerable<T> | Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection? Possible with LINQ or Lambda? | You will have to enumerate to get a count. Other constructs like the List keep a running count. | The best way to get a count of IEnumerable<T> Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection? Possible with LINQ or Lambda? | TITLE:
The best way to get a count of IEnumerable<T>
QUESTION:
Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection? Possible with LINQ or Lambda?
ANSWER:
You will have to enumerate to get a count. Other constructs like the List keep a running count. | [
"c#",
"linq"
] | 35 | 16 | 60,614 | 11 | 0 | 2008-08-26T18:09:30.903000 | 2008-08-26T18:12:23.893000 |
28,757 | 28,821 | Any good Subversion virtual appliance recommendations? | I'm looking for a quick-and-dirty solution to this, I have to set up a Subversion server really quickly, like by the end of the day tomorrow. My initial thought was to just download a virtual appliance that we could load onto our host machine. The problem I am having however is that all the appliances I have found so far are stuck in svn version 1.4 or lower. Does anybody know of an appliance that has svn 1.5 running? I don't need any of the other bits like issue tracking, WebSVN or any of that stuff. Thanks, Wally EDIT: To answer some of the questions, I would prefer for the host OS to be some flavour of Linux so that I can avoid having to purchase an additional Windows license. | I would simply go with installing SVN, and using the SVN Daemon, and completely ignoring Apache. There should be no appliance needed. Very simple to install, very easy to configure. Just take a vanilla windows/linux box and install the subversion server. It'll probably take all of 1/2 and hour to set up. | Any good Subversion virtual appliance recommendations? I'm looking for a quick-and-dirty solution to this, I have to set up a Subversion server really quickly, like by the end of the day tomorrow. My initial thought was to just download a virtual appliance that we could load onto our host machine. The problem I am having however is that all the appliances I have found so far are stuck in svn version 1.4 or lower. Does anybody know of an appliance that has svn 1.5 running? I don't need any of the other bits like issue tracking, WebSVN or any of that stuff. Thanks, Wally EDIT: To answer some of the questions, I would prefer for the host OS to be some flavour of Linux so that I can avoid having to purchase an additional Windows license. | TITLE:
Any good Subversion virtual appliance recommendations?
QUESTION:
I'm looking for a quick-and-dirty solution to this, I have to set up a Subversion server really quickly, like by the end of the day tomorrow. My initial thought was to just download a virtual appliance that we could load onto our host machine. The problem I am having however is that all the appliances I have found so far are stuck in svn version 1.4 or lower. Does anybody know of an appliance that has svn 1.5 running? I don't need any of the other bits like issue tracking, WebSVN or any of that stuff. Thanks, Wally EDIT: To answer some of the questions, I would prefer for the host OS to be some flavour of Linux so that I can avoid having to purchase an additional Windows license.
ANSWER:
I would simply go with installing SVN, and using the SVN Daemon, and completely ignoring Apache. There should be no appliance needed. Very simple to install, very easy to configure. Just take a vanilla windows/linux box and install the subversion server. It'll probably take all of 1/2 and hour to set up. | [
"svn",
"version-control"
] | 7 | 5 | 6,083 | 11 | 0 | 2008-08-26T18:09:36.693000 | 2008-08-26T18:42:57.283000 |
28,765 | 28,822 | Using Visual Studio 2008 Web Deployment projects - getting an error finding aspnet_merge.exe | I recently upgraded a VS2005 web deployment project to VS2008 - and now I get the following error when building: The specified task executable location "bin\aspnet_merge.exe" is invalid. Here is the source of the error (from the web deployment targets file): What is the solution to this problem? Note - I also created a web deployment project from scratch in VS2008 and got the same error. | Apparently aspnet_merge.exe (and all the other SDK tools) are NOT packaged in Visual Studio 2008. Visual Studio 2005 packaged these tools as part of its installation. The place to get this is an installation of the Windows 2008 SDK ( latest download ). Windows 7/Windows 2008 R2 SDK: here The solution is to install the Windows SDK and make sure you set FrameworkSDKDir as an environment variable before starting the IDE. Batch command to set this variable: SET FrameworkSDKDir="C:\Program Files\Microsoft SDKs\Windows\v6.1" NOTE: You will need to modify to point to where you installed the SDK if not in the default location. Now VS2008 will know where to find aspnet_merge.exe. | Using Visual Studio 2008 Web Deployment projects - getting an error finding aspnet_merge.exe I recently upgraded a VS2005 web deployment project to VS2008 - and now I get the following error when building: The specified task executable location "bin\aspnet_merge.exe" is invalid. Here is the source of the error (from the web deployment targets file): What is the solution to this problem? Note - I also created a web deployment project from scratch in VS2008 and got the same error. | TITLE:
Using Visual Studio 2008 Web Deployment projects - getting an error finding aspnet_merge.exe
QUESTION:
I recently upgraded a VS2005 web deployment project to VS2008 - and now I get the following error when building: The specified task executable location "bin\aspnet_merge.exe" is invalid. Here is the source of the error (from the web deployment targets file): What is the solution to this problem? Note - I also created a web deployment project from scratch in VS2008 and got the same error.
ANSWER:
Apparently aspnet_merge.exe (and all the other SDK tools) are NOT packaged in Visual Studio 2008. Visual Studio 2005 packaged these tools as part of its installation. The place to get this is an installation of the Windows 2008 SDK ( latest download ). Windows 7/Windows 2008 R2 SDK: here The solution is to install the Windows SDK and make sure you set FrameworkSDKDir as an environment variable before starting the IDE. Batch command to set this variable: SET FrameworkSDKDir="C:\Program Files\Microsoft SDKs\Windows\v6.1" NOTE: You will need to modify to point to where you installed the SDK if not in the default location. Now VS2008 will know where to find aspnet_merge.exe. | [
"asp.net",
"visual-studio-2008"
] | 4 | 8 | 4,799 | 2 | 0 | 2008-08-26T18:13:13.687000 | 2008-08-26T18:43:11.183000 |
28,768 | 28,868 | Simple Object to Database Product | I've been taking a look at some different products for.NET which propose to speed up development time by providing a way for business objects to map seamlessly to an automatically generated database. I've never had a problem writing a data access layer, but I'm wondering if this type of product will really save the time it claims. I also worry that I will be giving up too much control over the database and make it harder to track down any data level problems. Do these type of products make it better or worse in the already tough case that the database and business object structure must change? For example: Object Relation Mapping from Dev Express In essence, is it worth it? Will I save "THAT" much time, effort, and future bugs? | I have used SubSonic and EntitySpaces. Once you get the hang of them, I beleive they can save you time, but as complexity of your app and volume of data grow, you may outgrow these tools. You start to lose time trying to figure out if something like a performance issue is related to the ORM or to your code. So, to answer your question, I think it depends. I tend to agree with Eric on this, high volume enterprise apps are not a good place for general purpose ORMs, but in standard fare smaller CRUD type apps, you might see some saved time. | Simple Object to Database Product I've been taking a look at some different products for.NET which propose to speed up development time by providing a way for business objects to map seamlessly to an automatically generated database. I've never had a problem writing a data access layer, but I'm wondering if this type of product will really save the time it claims. I also worry that I will be giving up too much control over the database and make it harder to track down any data level problems. Do these type of products make it better or worse in the already tough case that the database and business object structure must change? For example: Object Relation Mapping from Dev Express In essence, is it worth it? Will I save "THAT" much time, effort, and future bugs? | TITLE:
Simple Object to Database Product
QUESTION:
I've been taking a look at some different products for.NET which propose to speed up development time by providing a way for business objects to map seamlessly to an automatically generated database. I've never had a problem writing a data access layer, but I'm wondering if this type of product will really save the time it claims. I also worry that I will be giving up too much control over the database and make it harder to track down any data level problems. Do these type of products make it better or worse in the already tough case that the database and business object structure must change? For example: Object Relation Mapping from Dev Express In essence, is it worth it? Will I save "THAT" much time, effort, and future bugs?
ANSWER:
I have used SubSonic and EntitySpaces. Once you get the hang of them, I beleive they can save you time, but as complexity of your app and volume of data grow, you may outgrow these tools. You start to lose time trying to figure out if something like a performance issue is related to the ORM or to your code. So, to answer your question, I think it depends. I tend to agree with Eric on this, high volume enterprise apps are not a good place for general purpose ORMs, but in standard fare smaller CRUD type apps, you might see some saved time. | [
"c#",
".net",
"database",
"orm"
] | 0 | 3 | 524 | 5 | 0 | 2008-08-26T18:14:42.733000 | 2008-08-26T19:05:45.590000 |
28,793 | 677,830 | vim commands in Eclipse | I have been doing some java development lately and have started using Eclipse. For the most part, I think it is great, but being a C/C++ guy used to doing all of his editing in vim, I find myself needlessly hitting the Esc key over and over. It would be really nice if I got all the nice features of Eclipse, but still could do basic editing the same way I can in vim. Anyone know of any Eclipse pluggins that would help with this? | Vrapper: an Eclipse plugin which acts as a wrapper for Eclipse text editors to provide a Vim-like input scheme for moving around and editing text. Unlike other plugins which embed Vim in Eclipse, Vrapper imitates the behaviour of Vim while still using whatever editor you have opened in the workbench. The goal is to have the comfort and ease which comes with the different modes, complex commands and count/operator/motion combinations which are the key features behind editing with Vim, while preserving the powerful features of the different Eclipse text editors, like code generation and refactoring... | vim commands in Eclipse I have been doing some java development lately and have started using Eclipse. For the most part, I think it is great, but being a C/C++ guy used to doing all of his editing in vim, I find myself needlessly hitting the Esc key over and over. It would be really nice if I got all the nice features of Eclipse, but still could do basic editing the same way I can in vim. Anyone know of any Eclipse pluggins that would help with this? | TITLE:
vim commands in Eclipse
QUESTION:
I have been doing some java development lately and have started using Eclipse. For the most part, I think it is great, but being a C/C++ guy used to doing all of his editing in vim, I find myself needlessly hitting the Esc key over and over. It would be really nice if I got all the nice features of Eclipse, but still could do basic editing the same way I can in vim. Anyone know of any Eclipse pluggins that would help with this?
ANSWER:
Vrapper: an Eclipse plugin which acts as a wrapper for Eclipse text editors to provide a Vim-like input scheme for moving around and editing text. Unlike other plugins which embed Vim in Eclipse, Vrapper imitates the behaviour of Vim while still using whatever editor you have opened in the workbench. The goal is to have the comfort and ease which comes with the different modes, complex commands and count/operator/motion combinations which are the key features behind editing with Vim, while preserving the powerful features of the different Eclipse text editors, like code generation and refactoring... | [
"eclipse",
"vim"
] | 58 | 69 | 21,217 | 3 | 0 | 2008-08-26T18:26:07.400000 | 2009-03-24T15:09:39.273000 |
28,796 | 29,770 | What refactoring tools do you use for Python? | I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly. Does anyone have experience with Python refactoring tools? Bonus points if they can fix class names in the XML documents too. | In the meantime, I've tried it two tools that have some sort of integration with vim. The first is Rope, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn. The second is Bicycle Repair Man which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago. Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them. | What refactoring tools do you use for Python? I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly. Does anyone have experience with Python refactoring tools? Bonus points if they can fix class names in the XML documents too. | TITLE:
What refactoring tools do you use for Python?
QUESTION:
I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly. Does anyone have experience with Python refactoring tools? Bonus points if they can fix class names in the XML documents too.
ANSWER:
In the meantime, I've tried it two tools that have some sort of integration with vim. The first is Rope, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It is a bit text-driven, but that's alright for me, just takes longer to learn. The second is Bicycle Repair Man which I guess wins points on name. Also plugs into vim and emacs. Haven't played much with it yet, but I remember trying it a long time ago. Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them. | [
"python",
"refactoring"
] | 75 | 59 | 43,121 | 7 | 0 | 2008-08-26T18:26:51.517000 | 2008-08-27T09:15:42.863000 |
28,808 | 157,505 | PAD (Portable Application Description) files for shareware / freeware | I've been told that I should include PAD files with the freeware applications I distribute so hosting sites can list the information correctly and check for updates, etc. Can you give me some info on using PAD files? Here are general questions which come to mind: Is it worth the effort? Do you use PADGen or an online tool like www.padbuilder.com? Do you digitally sign yours? | I do use padgen, it does not take too long to make a pad file, but what takes time is submitting it... just copy+paste stuff from your marketing material into it. keep storing all your pad files on your webserver and new version updates are listed in 1000+ small shareware/software sites automatically. however, download amounts from these sites are usually < 1000/mo. not signed mine. | PAD (Portable Application Description) files for shareware / freeware I've been told that I should include PAD files with the freeware applications I distribute so hosting sites can list the information correctly and check for updates, etc. Can you give me some info on using PAD files? Here are general questions which come to mind: Is it worth the effort? Do you use PADGen or an online tool like www.padbuilder.com? Do you digitally sign yours? | TITLE:
PAD (Portable Application Description) files for shareware / freeware
QUESTION:
I've been told that I should include PAD files with the freeware applications I distribute so hosting sites can list the information correctly and check for updates, etc. Can you give me some info on using PAD files? Here are general questions which come to mind: Is it worth the effort? Do you use PADGen or an online tool like www.padbuilder.com? Do you digitally sign yours?
ANSWER:
I do use padgen, it does not take too long to make a pad file, but what takes time is submitting it... just copy+paste stuff from your marketing material into it. keep storing all your pad files on your webserver and new version updates are listed in 1000+ small shareware/software sites automatically. however, download amounts from these sites are usually < 1000/mo. not signed mine. | [
"open-source",
"software-distribution"
] | 2 | 1 | 679 | 1 | 0 | 2008-08-26T18:32:35.217000 | 2008-10-01T13:11:03.033000 |
28,817 | 34,953 | How to find out which CVS tags cover which files and paths? | There is a legacy CVS repository, which contains a large number of directories, sub-directories, and paths. There is also a large number of branches and tags that do not necessarilly cover all paths & files - usually a subset. How can I find out, which branch / tag covers, which files and paths? CVS log already provides the list of tags per file. The task requires me to transpose this into files per tag. I could not find such functionality in current WinCVS (CVSNT) implementation. Given ample empty cycles I can write a Perl script that would do that, the algorithm is not complex, but it needs to be done. I would imagine there are some people who needed such information and solved this problem. Thus, I think should be a readily available (open source / free) tool for this. | To determine what tags apply to a particular file use: cvs log This will output all the versions of the file and what tags have been applied to the version. To determine what files are included in a single tag, the only thing I can think of is to check out using the tag and see what files come back. The command for that is any of: cvs update -r cvs co -r cvs export -r | How to find out which CVS tags cover which files and paths? There is a legacy CVS repository, which contains a large number of directories, sub-directories, and paths. There is also a large number of branches and tags that do not necessarilly cover all paths & files - usually a subset. How can I find out, which branch / tag covers, which files and paths? CVS log already provides the list of tags per file. The task requires me to transpose this into files per tag. I could not find such functionality in current WinCVS (CVSNT) implementation. Given ample empty cycles I can write a Perl script that would do that, the algorithm is not complex, but it needs to be done. I would imagine there are some people who needed such information and solved this problem. Thus, I think should be a readily available (open source / free) tool for this. | TITLE:
How to find out which CVS tags cover which files and paths?
QUESTION:
There is a legacy CVS repository, which contains a large number of directories, sub-directories, and paths. There is also a large number of branches and tags that do not necessarilly cover all paths & files - usually a subset. How can I find out, which branch / tag covers, which files and paths? CVS log already provides the list of tags per file. The task requires me to transpose this into files per tag. I could not find such functionality in current WinCVS (CVSNT) implementation. Given ample empty cycles I can write a Perl script that would do that, the algorithm is not complex, but it needs to be done. I would imagine there are some people who needed such information and solved this problem. Thus, I think should be a readily available (open source / free) tool for this.
ANSWER:
To determine what tags apply to a particular file use: cvs log This will output all the versions of the file and what tags have been applied to the version. To determine what files are included in a single tag, the only thing I can think of is to check out using the tag and see what files come back. The command for that is any of: cvs update -r cvs co -r cvs export -r | [
"cvs"
] | 8 | 7 | 28,192 | 6 | 0 | 2008-08-26T18:40:27.133000 | 2008-08-29T18:27:33.553000 |
28,820 | 33,251 | Windows Mobile - What scripting platforms are available? | We have a number of users with Windows Mobile 6 and need to apply minor changes. eg. update a registry setting. One option is push and execute an executable file using our device management software. I'd like this to be a little more friendly for the admins who are familiar with scripting in VBScript/JScript etc. What are the options for scripting on Windows Mobile devices? | Once option that the devs over at xda-developers seem to enjoy is Mortscript I have never bothered to use it, but I have used many cab installers that distribute mortscript so that they can do various tasks | Windows Mobile - What scripting platforms are available? We have a number of users with Windows Mobile 6 and need to apply minor changes. eg. update a registry setting. One option is push and execute an executable file using our device management software. I'd like this to be a little more friendly for the admins who are familiar with scripting in VBScript/JScript etc. What are the options for scripting on Windows Mobile devices? | TITLE:
Windows Mobile - What scripting platforms are available?
QUESTION:
We have a number of users with Windows Mobile 6 and need to apply minor changes. eg. update a registry setting. One option is push and execute an executable file using our device management software. I'd like this to be a little more friendly for the admins who are familiar with scripting in VBScript/JScript etc. What are the options for scripting on Windows Mobile devices?
ANSWER:
Once option that the devs over at xda-developers seem to enjoy is Mortscript I have never bothered to use it, but I have used many cab installers that distribute mortscript so that they can do various tasks | [
"windows-mobile",
"scripting",
"system-administration",
"administration"
] | 6 | 2 | 7,440 | 5 | 0 | 2008-08-26T18:42:14.257000 | 2008-08-28T19:58:21 |
28,823 | 29,500 | XML => HTML with Hpricot and Rails | I have never worked with web services and rails, and obviously this is something I need to learn. I have chosen to use hpricot because it looks great. Anyway, _why's been nice enough to provide the following example on the hpricot website: #!ruby require 'hpricot' require 'open-uri' # load the RedHanded home page doc = Hpricot(open("http://redhanded.hobix.com/index.html")) # change the CSS class on links (doc/"span.entryPermalink").set("class", "newLinks") # remove the sidebar (doc/"#sidebar").remove # print the altered HTML puts doc Which looks simple, elegant, and easy peasey. Works great in Ruby, but my question is: How do I break this up in rails? I experimented with adding this all to a single controller, but couldn't think of the best way to call it in a view. So if you were parsing an XML file from a web API and printing it in nice clean HTML with Hpricot, how would you break up the activity over the models, views, and controllers, and what would you put where? | Model, model, model, model, model. Skinny controllers, simple views. The RedHandedHomePage model does the parsing on initialization, then call 'def render' in the controller, set output to an instance variable, and print that in a view. | XML => HTML with Hpricot and Rails I have never worked with web services and rails, and obviously this is something I need to learn. I have chosen to use hpricot because it looks great. Anyway, _why's been nice enough to provide the following example on the hpricot website: #!ruby require 'hpricot' require 'open-uri' # load the RedHanded home page doc = Hpricot(open("http://redhanded.hobix.com/index.html")) # change the CSS class on links (doc/"span.entryPermalink").set("class", "newLinks") # remove the sidebar (doc/"#sidebar").remove # print the altered HTML puts doc Which looks simple, elegant, and easy peasey. Works great in Ruby, but my question is: How do I break this up in rails? I experimented with adding this all to a single controller, but couldn't think of the best way to call it in a view. So if you were parsing an XML file from a web API and printing it in nice clean HTML with Hpricot, how would you break up the activity over the models, views, and controllers, and what would you put where? | TITLE:
XML => HTML with Hpricot and Rails
QUESTION:
I have never worked with web services and rails, and obviously this is something I need to learn. I have chosen to use hpricot because it looks great. Anyway, _why's been nice enough to provide the following example on the hpricot website: #!ruby require 'hpricot' require 'open-uri' # load the RedHanded home page doc = Hpricot(open("http://redhanded.hobix.com/index.html")) # change the CSS class on links (doc/"span.entryPermalink").set("class", "newLinks") # remove the sidebar (doc/"#sidebar").remove # print the altered HTML puts doc Which looks simple, elegant, and easy peasey. Works great in Ruby, but my question is: How do I break this up in rails? I experimented with adding this all to a single controller, but couldn't think of the best way to call it in a view. So if you were parsing an XML file from a web API and printing it in nice clean HTML with Hpricot, how would you break up the activity over the models, views, and controllers, and what would you put where?
ANSWER:
Model, model, model, model, model. Skinny controllers, simple views. The RedHandedHomePage model does the parsing on initialization, then call 'def render' in the controller, set output to an instance variable, and print that in a view. | [
"ruby-on-rails",
"xml",
"ruby",
"hpricot",
"open-uri"
] | 1 | 2 | 1,979 | 2 | 0 | 2008-08-26T18:44:40.540000 | 2008-08-27T04:12:04.077000 |
28,826 | 28,844 | What exactly is Microsoft Expression Studio and how does it integrate with Visual Studio? | My university is part of MSDNAA, so I downloaded it a while back, but I just got around to installing it. I guess part of it replaces FrontPage for web editing, and there appears to be a video editor and a vector graphics editor, but I don't think I've even scratched the surface of what it is and what it can do. Could someone enlighten me, especially since I haven't found an "Expression Studio for Dummies" type website. | Expression Studio is basically a design studio. It consists of a bunch of design software that Microsoft has bought for the most part. The audience is designers, not developers. The gist of the software is that Expression Blend enables designers and programmers to work seamlessly together in letting the designer create the graphical user interface. In a normal workflow, the designer would deliver a mockup which the developer would have to implement. Using Expression Blend in combination with WPF, this is no longer necessary. The graphical UI made by the designer is functional. All the developer has to do is write the code for the function behind the design. This in itself is great because developers invariably fail to implement the design as thought out by the designer. Technical limitations, lack of communication … whatever the reason. UIs never look like them mockup done up front. Expression Design is basically a vector drawing program that can be used to design smaller components that are then used within Expression Blend as parts of the UI. For example, graphical buttons could be designed that way. It can also be used as a vanilla drawing program. I did the graphics in my thesis using Expression Design. | What exactly is Microsoft Expression Studio and how does it integrate with Visual Studio? My university is part of MSDNAA, so I downloaded it a while back, but I just got around to installing it. I guess part of it replaces FrontPage for web editing, and there appears to be a video editor and a vector graphics editor, but I don't think I've even scratched the surface of what it is and what it can do. Could someone enlighten me, especially since I haven't found an "Expression Studio for Dummies" type website. | TITLE:
What exactly is Microsoft Expression Studio and how does it integrate with Visual Studio?
QUESTION:
My university is part of MSDNAA, so I downloaded it a while back, but I just got around to installing it. I guess part of it replaces FrontPage for web editing, and there appears to be a video editor and a vector graphics editor, but I don't think I've even scratched the surface of what it is and what it can do. Could someone enlighten me, especially since I haven't found an "Expression Studio for Dummies" type website.
ANSWER:
Expression Studio is basically a design studio. It consists of a bunch of design software that Microsoft has bought for the most part. The audience is designers, not developers. The gist of the software is that Expression Blend enables designers and programmers to work seamlessly together in letting the designer create the graphical user interface. In a normal workflow, the designer would deliver a mockup which the developer would have to implement. Using Expression Blend in combination with WPF, this is no longer necessary. The graphical UI made by the designer is functional. All the developer has to do is write the code for the function behind the design. This in itself is great because developers invariably fail to implement the design as thought out by the designer. Technical limitations, lack of communication … whatever the reason. UIs never look like them mockup done up front. Expression Design is basically a vector drawing program that can be used to design smaller components that are then used within Expression Blend as parts of the UI. For example, graphical buttons could be designed that way. It can also be used as a vanilla drawing program. I did the graphics in my thesis using Expression Design. | [
"visual-studio",
"integration",
"expression-studio"
] | 11 | 18 | 12,065 | 7 | 0 | 2008-08-26T18:49:25.630000 | 2008-08-26T18:54:56.520000 |
28,832 | 28,906 | Java and manually executing finalize | If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object? This would be an approximate example: MyObject m = new MyObject();
m.finalize();
m = null;
System.gc() Would the explicit call to finalize() make the JVM 's garbage collector not to run the finalize() method on object m? | According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it: private static class Blah { public void finalize() { System.out.println("finalizing!"); } }
private static void f() throws Throwable { Blah blah = new Blah(); blah.finalize(); }
public static void main(String[] args) throws Throwable { System.out.println("start"); f(); System.gc(); System.out.println("done"); } The output is: start finalizing! finalizing! done Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually. | Java and manually executing finalize If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object? This would be an approximate example: MyObject m = new MyObject();
m.finalize();
m = null;
System.gc() Would the explicit call to finalize() make the JVM 's garbage collector not to run the finalize() method on object m? | TITLE:
Java and manually executing finalize
QUESTION:
If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object? This would be an approximate example: MyObject m = new MyObject();
m.finalize();
m = null;
System.gc() Would the explicit call to finalize() make the JVM 's garbage collector not to run the finalize() method on object m?
ANSWER:
According to this simple test program, the JVM will still make its call to finalize() even if you explicitly called it: private static class Blah { public void finalize() { System.out.println("finalizing!"); } }
private static void f() throws Throwable { Blah blah = new Blah(); blah.finalize(); }
public static void main(String[] args) throws Throwable { System.out.println("start"); f(); System.gc(); System.out.println("done"); } The output is: start finalizing! finalizing! done Every resource out there says to never call finalize() explicitly, and pretty much never even implement the method because there are no guarantees as to if and when it will be called. You're better off just closing all of your resources manually. | [
"java",
"garbage-collection",
"finalize"
] | 18 | 30 | 20,587 | 3 | 0 | 2008-08-26T18:51:41.520000 | 2008-08-26T19:23:06.483000 |
28,839 | 28,873 | What causes Visual Studio to fail to load an assembly incorrectly? | I had been happily coding along on a decent sized solution (just over 13k LOC, 5 projects) which utilizes Linq to Sql for it's data access. All of sudden I performed a normal build and I received a sweet, sweet ambiguous message: Error 1 Build failed due to validation errors in C:\xxx\xxx.dbml. Open the file and resolve the issues in the Error List, then try rebuilding the project. C:\xxx\xxx.dbml I had not touched my data access layer for weeks and no adjustments had been made to the DBML file. I tried plenty of foolhardy tricks like re-creating the layout file, making copies and re-adding the existing files back to the project after restarting Visual Studio (in case of some file-level corruption); all to no avail. I forgot to wear my Visual Studio Skills +5 talismans, so I began searching around and the only answer that I found which made sense was to reset my packages because Visual Studio was not loading an assembly correctly. After running " devenv.exe /resetskippkgs " I was, in fact, able to add the dbml file back to the DAL project and rebuild the solution. I’m glad it’s fixed, but I would rather also gain a deeper understand from this experience. Does anyone know how or why this happens in Visual Studio 2008? New Edit: 10/30/2008 THIS WAS NOT SOMETHING THAT JUST HAPPENED TO ME. Rich Strahl recently wrote on his "web log" about the same experience. He links to another blog with the same issue and used the same action. I have encountered this issue a few times since this original post as well, making me think that this is not some random issue. If anyone finds the definitive answer please post. | TBH, I have had a couple of instances like this where files "seemed to go crazy".. However, upon investigation it has appeared that the files have changed in some way, shape or form.. (e.g. sometimes changes can be made to the file by inadvertantly changing a property somewhere that seems unrelated). I think there are too many possible issues that could really cause this, and based on the fact that the problem has been resovled, it seems like an answer will not be found.. | What causes Visual Studio to fail to load an assembly incorrectly? I had been happily coding along on a decent sized solution (just over 13k LOC, 5 projects) which utilizes Linq to Sql for it's data access. All of sudden I performed a normal build and I received a sweet, sweet ambiguous message: Error 1 Build failed due to validation errors in C:\xxx\xxx.dbml. Open the file and resolve the issues in the Error List, then try rebuilding the project. C:\xxx\xxx.dbml I had not touched my data access layer for weeks and no adjustments had been made to the DBML file. I tried plenty of foolhardy tricks like re-creating the layout file, making copies and re-adding the existing files back to the project after restarting Visual Studio (in case of some file-level corruption); all to no avail. I forgot to wear my Visual Studio Skills +5 talismans, so I began searching around and the only answer that I found which made sense was to reset my packages because Visual Studio was not loading an assembly correctly. After running " devenv.exe /resetskippkgs " I was, in fact, able to add the dbml file back to the DAL project and rebuild the solution. I’m glad it’s fixed, but I would rather also gain a deeper understand from this experience. Does anyone know how or why this happens in Visual Studio 2008? New Edit: 10/30/2008 THIS WAS NOT SOMETHING THAT JUST HAPPENED TO ME. Rich Strahl recently wrote on his "web log" about the same experience. He links to another blog with the same issue and used the same action. I have encountered this issue a few times since this original post as well, making me think that this is not some random issue. If anyone finds the definitive answer please post. | TITLE:
What causes Visual Studio to fail to load an assembly incorrectly?
QUESTION:
I had been happily coding along on a decent sized solution (just over 13k LOC, 5 projects) which utilizes Linq to Sql for it's data access. All of sudden I performed a normal build and I received a sweet, sweet ambiguous message: Error 1 Build failed due to validation errors in C:\xxx\xxx.dbml. Open the file and resolve the issues in the Error List, then try rebuilding the project. C:\xxx\xxx.dbml I had not touched my data access layer for weeks and no adjustments had been made to the DBML file. I tried plenty of foolhardy tricks like re-creating the layout file, making copies and re-adding the existing files back to the project after restarting Visual Studio (in case of some file-level corruption); all to no avail. I forgot to wear my Visual Studio Skills +5 talismans, so I began searching around and the only answer that I found which made sense was to reset my packages because Visual Studio was not loading an assembly correctly. After running " devenv.exe /resetskippkgs " I was, in fact, able to add the dbml file back to the DAL project and rebuild the solution. I’m glad it’s fixed, but I would rather also gain a deeper understand from this experience. Does anyone know how or why this happens in Visual Studio 2008? New Edit: 10/30/2008 THIS WAS NOT SOMETHING THAT JUST HAPPENED TO ME. Rich Strahl recently wrote on his "web log" about the same experience. He links to another blog with the same issue and used the same action. I have encountered this issue a few times since this original post as well, making me think that this is not some random issue. If anyone finds the definitive answer please post.
ANSWER:
TBH, I have had a couple of instances like this where files "seemed to go crazy".. However, upon investigation it has appeared that the files have changed in some way, shape or form.. (e.g. sometimes changes can be made to the file by inadvertantly changing a property somewhere that seems unrelated). I think there are too many possible issues that could really cause this, and based on the fact that the problem has been resovled, it seems like an answer will not be found.. | [
"visual-studio",
"visual-studio-2008",
"linq-to-sql"
] | 4 | 1 | 2,612 | 4 | 0 | 2008-08-26T18:53:57.117000 | 2008-08-26T19:11:59.350000 |
28,843 | 33,738 | Can SlickEdit automatically update its tag files? | I prefer SlickEdit for my IDE but the only way I can get it to update the tag files to incorporate code changes is to recreate the project and/or run start a re-tag manually. Is there a way to setup Slick Edit so that it automatically incorporates changes in the code base that happen after project creation. This problem is especially noticeable when working on large shared code bases where I must check out files that have been modified by other users. | Okay, I asked a question on the SlickEdit forums. http://community.slickedit.com/index.php?topic=3854.0 EDIT: Winnar! Options->Editing->Background Tagging of Other Files | Can SlickEdit automatically update its tag files? I prefer SlickEdit for my IDE but the only way I can get it to update the tag files to incorporate code changes is to recreate the project and/or run start a re-tag manually. Is there a way to setup Slick Edit so that it automatically incorporates changes in the code base that happen after project creation. This problem is especially noticeable when working on large shared code bases where I must check out files that have been modified by other users. | TITLE:
Can SlickEdit automatically update its tag files?
QUESTION:
I prefer SlickEdit for my IDE but the only way I can get it to update the tag files to incorporate code changes is to recreate the project and/or run start a re-tag manually. Is there a way to setup Slick Edit so that it automatically incorporates changes in the code base that happen after project creation. This problem is especially noticeable when working on large shared code bases where I must check out files that have been modified by other users.
ANSWER:
Okay, I asked a question on the SlickEdit forums. http://community.slickedit.com/index.php?topic=3854.0 EDIT: Winnar! Options->Editing->Background Tagging of Other Files | [
"ide",
"slickedit"
] | 6 | 6 | 2,619 | 1 | 0 | 2008-08-26T18:54:48.860000 | 2008-08-29T01:08:16.107000 |
28,881 | 28,903 | Why doesn't **sort** sort the same on every machine? | Using the same sort command with the same input produces different results on different machines. How do I fix that? | The man-page on OS X says: ******* WARNING ******* The locale specified by the environment affects sort order. Set LC_ALL=C to get the traditional sort order that uses native byte values. which might explain things. If some of your systems have no locale support, they would default to that locale (C), so you wouldn't have to set it on those. If you have some that supports locales and want the same behavior, set LC_ALL=C on those systems. That would be the way to have as many systems as I know do it the same way. If you don't have any locale-less systems, just making sure they share locale would probably be enough. For more canonical information, see The Single UNIX ® Specification, Version 2 description of locale, environment variables, setlocale() and the description of the sort(1) utility. | Why doesn't **sort** sort the same on every machine? Using the same sort command with the same input produces different results on different machines. How do I fix that? | TITLE:
Why doesn't **sort** sort the same on every machine?
QUESTION:
Using the same sort command with the same input produces different results on different machines. How do I fix that?
ANSWER:
The man-page on OS X says: ******* WARNING ******* The locale specified by the environment affects sort order. Set LC_ALL=C to get the traditional sort order that uses native byte values. which might explain things. If some of your systems have no locale support, they would default to that locale (C), so you wouldn't have to set it on those. If you have some that supports locales and want the same behavior, set LC_ALL=C on those systems. That would be the way to have as many systems as I know do it the same way. If you don't have any locale-less systems, just making sure they share locale would probably be enough. For more canonical information, see The Single UNIX ® Specification, Version 2 description of locale, environment variables, setlocale() and the description of the sort(1) utility. | [
"bash",
"unix",
"sorting",
"ksh"
] | 17 | 25 | 8,172 | 4 | 0 | 2008-08-26T19:15:47.267000 | 2008-08-26T19:21:56.177000 |
28,894 | 28,947 | .NET Compiler -- DEBUG vs. RELEASE | For years I have been using the DEBUG compiler constant in VB.NET to write messages to the console. I've also been using System.Diagnostics.Debug.Write in similar fashion. It was always my understanding that when RELEASE was used as the build option, that all of these statements were left out by the compiler, freeing your production code of the overhead of debug statements. Recently when working with Silverlight 2 Beta 2, I noticed that Visual Studio actually attached to a RELEASE build that I was running off of a public website and displayed DEBUG statements which I assumed weren't even compiled! Now, my first inclination is to assume that that there is something wrong with my environment, but I also want to ask anyone with deep knowledge on System.Diagnostics.Debug and the DEBUG build option in general what I may be misunderstanding here. | The preferred method is to actually use the conditional attribute to wrap your debug calls, not use the compiler directives. #ifs can get tricky and can lead to weird build problems. An example of using a conditional attribute is as follows (in C#, but works in VB.NET too): [ Conditional("Debug") ] private void WriteDebug(string debugString) { // do stuff } When you compile without the DEBUG flag set, any call to WriteDebug will be removed as was assumed was happening with Debug.Write(). | .NET Compiler -- DEBUG vs. RELEASE For years I have been using the DEBUG compiler constant in VB.NET to write messages to the console. I've also been using System.Diagnostics.Debug.Write in similar fashion. It was always my understanding that when RELEASE was used as the build option, that all of these statements were left out by the compiler, freeing your production code of the overhead of debug statements. Recently when working with Silverlight 2 Beta 2, I noticed that Visual Studio actually attached to a RELEASE build that I was running off of a public website and displayed DEBUG statements which I assumed weren't even compiled! Now, my first inclination is to assume that that there is something wrong with my environment, but I also want to ask anyone with deep knowledge on System.Diagnostics.Debug and the DEBUG build option in general what I may be misunderstanding here. | TITLE:
.NET Compiler -- DEBUG vs. RELEASE
QUESTION:
For years I have been using the DEBUG compiler constant in VB.NET to write messages to the console. I've also been using System.Diagnostics.Debug.Write in similar fashion. It was always my understanding that when RELEASE was used as the build option, that all of these statements were left out by the compiler, freeing your production code of the overhead of debug statements. Recently when working with Silverlight 2 Beta 2, I noticed that Visual Studio actually attached to a RELEASE build that I was running off of a public website and displayed DEBUG statements which I assumed weren't even compiled! Now, my first inclination is to assume that that there is something wrong with my environment, but I also want to ask anyone with deep knowledge on System.Diagnostics.Debug and the DEBUG build option in general what I may be misunderstanding here.
ANSWER:
The preferred method is to actually use the conditional attribute to wrap your debug calls, not use the compiler directives. #ifs can get tricky and can lead to weird build problems. An example of using a conditional attribute is as follows (in C#, but works in VB.NET too): [ Conditional("Debug") ] private void WriteDebug(string debugString) { // do stuff } When you compile without the DEBUG flag set, any call to WriteDebug will be removed as was assumed was happening with Debug.Write(). | [
".net",
"compiler-construction",
"debugging"
] | 19 | 22 | 11,941 | 7 | 0 | 2008-08-26T19:20:09.470000 | 2008-08-26T19:45:54.900000 |
28,896 | 28,917 | Datatypes for physics | I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other) What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#? Also, what's the smallest ammount of time I can get between t and t+1? One tick? EDIT: Clarifying: What is the smallest unit of time in C#? [TimeSpan].Tick? | In.Net a decimal will be the most precise datatype that you could use for position. I would just write a class for the position: public class Position { decimal x; decimal y; decimal z; } As for time, your processor can't give you anything smaller than one tick. Sounds like an fun project! Good luck! | Datatypes for physics I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other) What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#? Also, what's the smallest ammount of time I can get between t and t+1? One tick? EDIT: Clarifying: What is the smallest unit of time in C#? [TimeSpan].Tick? | TITLE:
Datatypes for physics
QUESTION:
I'm currently designing a program that will involve some physics (nothing too fancy, a few balls crashing to each other) What's the most exact datatype I can use to represent position (without a feeling of discrete jumps) in c#? Also, what's the smallest ammount of time I can get between t and t+1? One tick? EDIT: Clarifying: What is the smallest unit of time in C#? [TimeSpan].Tick?
ANSWER:
In.Net a decimal will be the most precise datatype that you could use for position. I would just write a class for the position: public class Position { decimal x; decimal y; decimal z; } As for time, your processor can't give you anything smaller than one tick. Sounds like an fun project! Good luck! | [
"c#",
"types",
"physics"
] | 10 | 9 | 843 | 8 | 0 | 2008-08-26T19:20:35.493000 | 2008-08-26T19:27:49.203000 |
28,922 | 28,924 | SQLServer Get Results Where Value Is Null | I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as: WHERE database.foobar = NULL and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query. Can anyone help me out? | Correct syntax is WHERE database.foobar IS NULL. See http://msdn.microsoft.com/en-us/library/ms188795.aspx for more info | SQLServer Get Results Where Value Is Null I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as: WHERE database.foobar = NULL and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query. Can anyone help me out? | TITLE:
SQLServer Get Results Where Value Is Null
QUESTION:
I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as: WHERE database.foobar = NULL and it does not return anything. However, I know that there is at least one result because I created an instance in the database where 'foobar' is equal to null. If I take out the where statement it shows data so I know it is not the rest of the query. Can anyone help me out?
ANSWER:
Correct syntax is WHERE database.foobar IS NULL. See http://msdn.microsoft.com/en-us/library/ms188795.aspx for more info | [
"sql",
"sql-server",
"oracle"
] | 3 | 6 | 226 | 4 | 0 | 2008-08-26T19:32:20.783000 | 2008-08-26T19:33:04.277000 |
28,932 | 3,541,878 | Best JavaScript compressor | What is the the best JavaScript compressor available? I'm looking for a tool that: is easy to use has a high compression rate Produce reliable end results (doesn't mess up the code) | I recently released UglifyJS, a JavaScript compressor which is written in JavaScript (runs on the NodeJS Node.js platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any Node.js internals). It's a lot faster than both YUI Compressor and Google Closure, it compresses better than YUI on all scripts I tested it on, and it's safer than Closure (knows to deal with "eval" or "with"). Other than whitespace removal, UglifyJS also does the following: changes local variable names (usually to single characters) joins consecutive var declarations avoids inserting any unneeded brackets, parens and semicolons optimizes IFs (removes "else" when it detects that it's not needed, transforms IFs into the &&, || or?/: operators when possible, etc.). transforms foo["bar"] into foo.bar where possible removes quotes from keys in object literals, where possible resolves simple expressions when this leads to smaller code (1+3*4 ==> 13) PS: Oh, it can "beautify" as well.;-) | Best JavaScript compressor What is the the best JavaScript compressor available? I'm looking for a tool that: is easy to use has a high compression rate Produce reliable end results (doesn't mess up the code) | TITLE:
Best JavaScript compressor
QUESTION:
What is the the best JavaScript compressor available? I'm looking for a tool that: is easy to use has a high compression rate Produce reliable end results (doesn't mess up the code)
ANSWER:
I recently released UglifyJS, a JavaScript compressor which is written in JavaScript (runs on the NodeJS Node.js platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any Node.js internals). It's a lot faster than both YUI Compressor and Google Closure, it compresses better than YUI on all scripts I tested it on, and it's safer than Closure (knows to deal with "eval" or "with"). Other than whitespace removal, UglifyJS also does the following: changes local variable names (usually to single characters) joins consecutive var declarations avoids inserting any unneeded brackets, parens and semicolons optimizes IFs (removes "else" when it detects that it's not needed, transforms IFs into the &&, || or?/: operators when possible, etc.). transforms foo["bar"] into foo.bar where possible removes quotes from keys in object literals, where possible resolves simple expressions when this leads to smaller code (1+3*4 ==> 13) PS: Oh, it can "beautify" as well.;-) | [
"javascript",
"compression"
] | 174 | 150 | 116,108 | 13 | 0 | 2008-08-26T19:36:20.273000 | 2010-08-22T14:50:31.130000 |
28,941 | 28,955 | Best architecture for handling file system changes? | Here is the scenario: I'm writing an app that will watch for any changes in a specific directory. This directory will be flooded with thousands of files a minute each with an "almost" unique GUID. The file format is this: GUID.dat where GUID == xxxxxxxxxxxxxxxxxxxxxxxxxxxxx (the internal contents aren't relevant, but it's just text data) My app will be a form that has one single text box that shows all the files that are being added and deleted in real time. Every time a new file comes in I have to update the textbox with this file, BUT I must first make sure that this semi-unique GUID is really unique, if it is, update the textbox with this new file. When a file is removed from that directory, make sure it exists, then delete it, update textbox accordingly. The problem is that I've been using the.NET filewatcher and it seems that there is an internal buffer that gets blown up every time the (buffersize + 1)-th file comes in. I also tried to keep an internal List in my app, and just add every single file that comes in, but do the unique-GUID check later, but no dice. | A couple of things that I have in my head: If the guid is not unique, would it not overwrite the file with the same name, or is the check based on a lookup which does some external action (e.g. check the archive)? (i.e. is this a YAGNI moment?) I've used FileSystemWatcher before with pretty good success, can you give us some ideas as to how your actually doing things? When you say "no dice" when working with your custom list, what was the problem? And how were you checking for file system changes without FileSystemWatcher?! Sorry no answer as yet, just would like to know more about the problem:) | Best architecture for handling file system changes? Here is the scenario: I'm writing an app that will watch for any changes in a specific directory. This directory will be flooded with thousands of files a minute each with an "almost" unique GUID. The file format is this: GUID.dat where GUID == xxxxxxxxxxxxxxxxxxxxxxxxxxxxx (the internal contents aren't relevant, but it's just text data) My app will be a form that has one single text box that shows all the files that are being added and deleted in real time. Every time a new file comes in I have to update the textbox with this file, BUT I must first make sure that this semi-unique GUID is really unique, if it is, update the textbox with this new file. When a file is removed from that directory, make sure it exists, then delete it, update textbox accordingly. The problem is that I've been using the.NET filewatcher and it seems that there is an internal buffer that gets blown up every time the (buffersize + 1)-th file comes in. I also tried to keep an internal List in my app, and just add every single file that comes in, but do the unique-GUID check later, but no dice. | TITLE:
Best architecture for handling file system changes?
QUESTION:
Here is the scenario: I'm writing an app that will watch for any changes in a specific directory. This directory will be flooded with thousands of files a minute each with an "almost" unique GUID. The file format is this: GUID.dat where GUID == xxxxxxxxxxxxxxxxxxxxxxxxxxxxx (the internal contents aren't relevant, but it's just text data) My app will be a form that has one single text box that shows all the files that are being added and deleted in real time. Every time a new file comes in I have to update the textbox with this file, BUT I must first make sure that this semi-unique GUID is really unique, if it is, update the textbox with this new file. When a file is removed from that directory, make sure it exists, then delete it, update textbox accordingly. The problem is that I've been using the.NET filewatcher and it seems that there is an internal buffer that gets blown up every time the (buffersize + 1)-th file comes in. I also tried to keep an internal List in my app, and just add every single file that comes in, but do the unique-GUID check later, but no dice.
ANSWER:
A couple of things that I have in my head: If the guid is not unique, would it not overwrite the file with the same name, or is the check based on a lookup which does some external action (e.g. check the archive)? (i.e. is this a YAGNI moment?) I've used FileSystemWatcher before with pretty good success, can you give us some ideas as to how your actually doing things? When you say "no dice" when working with your custom list, what was the problem? And how were you checking for file system changes without FileSystemWatcher?! Sorry no answer as yet, just would like to know more about the problem:) | [
".net",
"architecture",
"concurrency",
"filesystemwatcher"
] | 2 | 3 | 554 | 2 | 0 | 2008-08-26T19:42:47.483000 | 2008-08-26T19:48:48.107000 |
28,949 | 29,038 | Why do you not explicitly call finalize() or start the garbage collector? | After reading this question, I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for this down to a few sentences? I'm sure I could read a technical report from Sun on this matter, but I think a nice, short, simple answer would satisfy my curiosity. | The short answer: Java garbage collection is a very finely tuned tool. System.gc() is a sledge-hammer. Java's heap is divided into different generations, each of which is collected using a different strategy. If you attach a profiler to a healthy app, you'll see that it very rarely has to run the most expensive kinds of collections because most objects are caught by the faster copying collector in the young generation. Calling System.gc() directly, while technically not guaranteed to do anything, in practice will trigger an expensive, stop-the-world full heap collection. This is almost always the wrong thing to do. You think you're saving resources, but you're actually wasting them for no good reason, forcing Java to recheck all your live objects “just in case”. If you are having problems with GC pauses during critical moments, you're better off configuring the JVM to use the concurrent mark/sweep collector, which was designed specifically to minimise time spent paused, than trying to take a sledgehammer to the problem and just breaking it further. The Sun document you were thinking of is here: Java SE 6 HotSpot™ Virtual Machine Garbage Collection Tuning (Another thing you might not know: implementing a finalize() method on your object makes garbage collection slower. Firstly, it will take two GC runs to collect the object: one to run finalize() and the next to ensure that the object wasn't resurrected during finalization. Secondly, objects with finalize() methods have to be treated as special cases by the GC because they have to be collected individually, they can't just be thrown away in bulk.) | Why do you not explicitly call finalize() or start the garbage collector? After reading this question, I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for this down to a few sentences? I'm sure I could read a technical report from Sun on this matter, but I think a nice, short, simple answer would satisfy my curiosity. | TITLE:
Why do you not explicitly call finalize() or start the garbage collector?
QUESTION:
After reading this question, I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for this down to a few sentences? I'm sure I could read a technical report from Sun on this matter, but I think a nice, short, simple answer would satisfy my curiosity.
ANSWER:
The short answer: Java garbage collection is a very finely tuned tool. System.gc() is a sledge-hammer. Java's heap is divided into different generations, each of which is collected using a different strategy. If you attach a profiler to a healthy app, you'll see that it very rarely has to run the most expensive kinds of collections because most objects are caught by the faster copying collector in the young generation. Calling System.gc() directly, while technically not guaranteed to do anything, in practice will trigger an expensive, stop-the-world full heap collection. This is almost always the wrong thing to do. You think you're saving resources, but you're actually wasting them for no good reason, forcing Java to recheck all your live objects “just in case”. If you are having problems with GC pauses during critical moments, you're better off configuring the JVM to use the concurrent mark/sweep collector, which was designed specifically to minimise time spent paused, than trying to take a sledgehammer to the problem and just breaking it further. The Sun document you were thinking of is here: Java SE 6 HotSpot™ Virtual Machine Garbage Collection Tuning (Another thing you might not know: implementing a finalize() method on your object makes garbage collection slower. Firstly, it will take two GC runs to collect the object: one to run finalize() and the next to ensure that the object wasn't resurrected during finalization. Secondly, objects with finalize() methods have to be treated as special cases by the GC because they have to be collected individually, they can't just be thrown away in bulk.) | [
"java",
"garbage-collection"
] | 28 | 44 | 15,452 | 7 | 0 | 2008-08-26T19:46:46.367000 | 2008-08-26T21:54:39.990000 |
28,950 | 28,970 | Guide to choosing between REST vs SOAP services? | Does anyone have links to documentation or guides on making the decision between REST vs. SOAP? I understand both of these but am looking for some references on the key decision points, eg, security, which may make you lean towards one or the other. | Google first hit seems pretty comprehensive. I think the problem here is there are too many advocates of one or the other, may be better of googling and getting more of a handle of the pro's/con's yourself and making your own decision. I know that sounds kinda lame, but ultimately these sort of design decisions fall down to the developer/architect working on it, and 99% of the time, the problem domain will be the deciding factor (or at least it should be), not a guide on the net. | Guide to choosing between REST vs SOAP services? Does anyone have links to documentation or guides on making the decision between REST vs. SOAP? I understand both of these but am looking for some references on the key decision points, eg, security, which may make you lean towards one or the other. | TITLE:
Guide to choosing between REST vs SOAP services?
QUESTION:
Does anyone have links to documentation or guides on making the decision between REST vs. SOAP? I understand both of these but am looking for some references on the key decision points, eg, security, which may make you lean towards one or the other.
ANSWER:
Google first hit seems pretty comprehensive. I think the problem here is there are too many advocates of one or the other, may be better of googling and getting more of a handle of the pro's/con's yourself and making your own decision. I know that sounds kinda lame, but ultimately these sort of design decisions fall down to the developer/architect working on it, and 99% of the time, the problem domain will be the deciding factor (or at least it should be), not a guide on the net. | [
"architecture",
"rest",
"soap"
] | 10 | 6 | 9,771 | 4 | 0 | 2008-08-26T19:46:56.553000 | 2008-08-26T19:53:04.103000 |
28,952 | 488,509 | CPU utilization by database? | Is it possible to get a breakdown of CPU utilization by database? I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like taskmgr ) or each SPID (like spwho2k5 ), I want to view the total CPU utilization of each database. Assume a single SQL instance. I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the sqlservr.exe CPU load. | Sort of. Check this query out: SELECT total_worker_time/execution_count AS AvgCPU, total_worker_time AS TotalCPU, total_elapsed_time/execution_count AS AvgDuration, total_elapsed_time AS TotalDuration, (total_logical_reads+total_physical_reads)/execution_count AS AvgReads, (total_logical_reads+total_physical_reads) AS TotalReads, execution_count, SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1, ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS txt, query_plan FROM sys.dm_exec_query_stats AS qs cross apply sys.dm_exec_sql_text(qs.sql_handle) AS st cross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp ORDER BY 1 DESC This will get you the queries in the plan cache in order of how much CPU they've used up. You can run this periodically, like in a SQL Agent job, and insert the results into a table to make sure the data persists beyond reboots. When you read the results, you'll probably realize why we can't correlate that data directly back to an individual database. First, a single query can also hide its true database parent by doing tricks like this: USE msdb DECLARE @StringToExecute VARCHAR(1000) SET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog' EXEC @StringToExecute The query would be executed in MSDB, but it would poll results from AdventureWorks. Where should we assign the CPU consumption? It gets worse when you: Join between multiple databases Run a transaction in multiple databases, and the locking effort spans multiple databases Run SQL Agent jobs in MSDB that "work" in MSDB, but back up individual databases It goes on and on. That's why it makes sense to performance tune at the query level instead of the database level. In SQL Server 2008R2, Microsoft introduced performance management and app management features that will let us package a single database in a distributable and deployable DAC pack, and they're promising features to make it easier to manage performance of individual databases and their applications. It still doesn't do what you're looking for, though. For more of those, check out the T-SQL repository at Toad World's SQL Server wiki (formerly at SQLServerPedia). Updated on 1/29 to include total numbers instead of just averages. | CPU utilization by database? Is it possible to get a breakdown of CPU utilization by database? I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like taskmgr ) or each SPID (like spwho2k5 ), I want to view the total CPU utilization of each database. Assume a single SQL instance. I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the sqlservr.exe CPU load. | TITLE:
CPU utilization by database?
QUESTION:
Is it possible to get a breakdown of CPU utilization by database? I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like taskmgr ) or each SPID (like spwho2k5 ), I want to view the total CPU utilization of each database. Assume a single SQL instance. I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the sqlservr.exe CPU load.
ANSWER:
Sort of. Check this query out: SELECT total_worker_time/execution_count AS AvgCPU, total_worker_time AS TotalCPU, total_elapsed_time/execution_count AS AvgDuration, total_elapsed_time AS TotalDuration, (total_logical_reads+total_physical_reads)/execution_count AS AvgReads, (total_logical_reads+total_physical_reads) AS TotalReads, execution_count, SUBSTRING(st.TEXT, (qs.statement_start_offset/2)+1, ((CASE qs.statement_end_offset WHEN -1 THEN datalength(st.TEXT) ELSE qs.statement_end_offset END - qs.statement_start_offset)/2) + 1) AS txt, query_plan FROM sys.dm_exec_query_stats AS qs cross apply sys.dm_exec_sql_text(qs.sql_handle) AS st cross apply sys.dm_exec_query_plan (qs.plan_handle) AS qp ORDER BY 1 DESC This will get you the queries in the plan cache in order of how much CPU they've used up. You can run this periodically, like in a SQL Agent job, and insert the results into a table to make sure the data persists beyond reboots. When you read the results, you'll probably realize why we can't correlate that data directly back to an individual database. First, a single query can also hide its true database parent by doing tricks like this: USE msdb DECLARE @StringToExecute VARCHAR(1000) SET @StringToExecute = 'SELECT * FROM AdventureWorks.dbo.ErrorLog' EXEC @StringToExecute The query would be executed in MSDB, but it would poll results from AdventureWorks. Where should we assign the CPU consumption? It gets worse when you: Join between multiple databases Run a transaction in multiple databases, and the locking effort spans multiple databases Run SQL Agent jobs in MSDB that "work" in MSDB, but back up individual databases It goes on and on. That's why it makes sense to performance tune at the query level instead of the database level. In SQL Server 2008R2, Microsoft introduced performance management and app management features that will let us package a single database in a distributable and deployable DAC pack, and they're promising features to make it easier to manage performance of individual databases and their applications. It still doesn't do what you're looking for, though. For more of those, check out the T-SQL repository at Toad World's SQL Server wiki (formerly at SQLServerPedia). Updated on 1/29 to include total numbers instead of just averages. | [
"sql-server",
"monitoring"
] | 31 | 91 | 76,839 | 8 | 0 | 2008-08-26T19:48:09.437000 | 2009-01-28T17:20:34.043000 |
28,961 | 322,393 | What's the best way to use web services in python? | I have a medium sized application that runs as a.net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting. I wanted to know what is the best/most practical solution for using web-services in python. Edit: I need to consume a complex soap WS and I have no control over it. | Jython and IronPython give access to great Java &.NET SOAP libraries. If you need CPython, ZSI has been flaky for me, but it could be possible to use a tool like Robin to wrap a good C++ SOAP library such as gSOAP or Apache Axis C++ | What's the best way to use web services in python? I have a medium sized application that runs as a.net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting. I wanted to know what is the best/most practical solution for using web-services in python. Edit: I need to consume a complex soap WS and I have no control over it. | TITLE:
What's the best way to use web services in python?
QUESTION:
I have a medium sized application that runs as a.net web-service which I do not control, and I want to create a loose pythonic API above it to enable easy scripting. I wanted to know what is the best/most practical solution for using web-services in python. Edit: I need to consume a complex soap WS and I have no control over it.
ANSWER:
Jython and IronPython give access to great Java &.NET SOAP libraries. If you need CPython, ZSI has been flaky for me, but it could be possible to use a tool like Robin to wrap a good C++ SOAP library such as gSOAP or Apache Axis C++ | [
"python",
"web-services",
"soap"
] | 8 | 1 | 1,137 | 3 | 0 | 2008-08-26T19:49:54.517000 | 2008-11-26T22:34:53.517000 |
28,965 | 29,084 | Checklist for Web Site Programming Vulnerabilities | Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to defend against them. What categories of vunerabilities? crashing site breaking into server breaking into other people's logins spam sockpuppeting, meatpuppeting etc... What kind of defensive programming techniques? etc... | From the Open Web Application Security Project: The OWASP Top Ten vulnerabilities (pdf) For a more painfully exhaustive list: Category:Vulnerability The top ten are: Cross-site scripting (XSS) Injection flaws (SQL injection, script injection) Malicious file execution Insecure direct object reference Cross-site request forgery (XSRF) Information leakage and improper error handling Broken authentication and session management Insecure cryptographic storage Insecure communications Failure to restrict URL access | Checklist for Web Site Programming Vulnerabilities Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to defend against them. What categories of vunerabilities? crashing site breaking into server breaking into other people's logins spam sockpuppeting, meatpuppeting etc... What kind of defensive programming techniques? etc... | TITLE:
Checklist for Web Site Programming Vulnerabilities
QUESTION:
Watching SO come online has been quite an education for me. I'd like to make a checklist of various vunerabilities and exploits used against web sites, and what programming techniques can be used to defend against them. What categories of vunerabilities? crashing site breaking into server breaking into other people's logins spam sockpuppeting, meatpuppeting etc... What kind of defensive programming techniques? etc...
ANSWER:
From the Open Web Application Security Project: The OWASP Top Ten vulnerabilities (pdf) For a more painfully exhaustive list: Category:Vulnerability The top ten are: Cross-site scripting (XSS) Injection flaws (SQL injection, script injection) Malicious file execution Insecure direct object reference Cross-site request forgery (XSRF) Information leakage and improper error handling Broken authentication and session management Insecure cryptographic storage Insecure communications Failure to restrict URL access | [
"security",
"defensive-programming"
] | 17 | 12 | 1,960 | 9 | 0 | 2008-08-26T19:51:32.187000 | 2008-08-26T22:20:09.163000 |
29,004 | 29,032 | Parsing XML using unix terminal | Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved? Example XML input: My desired CSV output: Foo, Bar, | If you just want the name attributes of any element, here is a quick but incomplete solution. (Your example text is in the file example ) grep "name" example | cut -d"\"" -f2,2 | xargs -I{} echo "{}," | Parsing XML using unix terminal Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved? Example XML input: My desired CSV output: Foo, Bar, | TITLE:
Parsing XML using unix terminal
QUESTION:
Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved? Example XML input: My desired CSV output: Foo, Bar,
ANSWER:
If you just want the name attributes of any element, here is a quick but incomplete solution. (Your example text is in the file example ) grep "name" example | cut -d"\"" -f2,2 | xargs -I{} echo "{}," | [
"xml",
"unix",
"parsing",
"shell",
"csv"
] | 15 | 7 | 50,656 | 9 | 0 | 2008-08-26T20:09:40.303000 | 2008-08-26T21:47:42.753000 |
29,011 | 30,719 | Is there a way to combine named scopes into a new named scope? | I have class Foo < ActiveRecord::Base named_scope:a, lambda { |a|:conditions => {:a => a } } named_scope:b, lambda { |b|:conditions => {:b => b } } end I'd like class Foo < ActiveRecord::Base named_scope:ab, lambda { |a,b|:conditions => {:a => a,:b => b } } end but I'd prefer to do it in a DRY fashion. I can get the same effect by using Foo.a(something).b(something_else) but it's not particularly lovely. | Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method? def self.ab(a, b) a(a).b(b) end You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional. If you're stuck on named_scope, can't you extend it to do much the same thing? Let me know if I'm totally off base with what you're wanting to do. | Is there a way to combine named scopes into a new named scope? I have class Foo < ActiveRecord::Base named_scope:a, lambda { |a|:conditions => {:a => a } } named_scope:b, lambda { |b|:conditions => {:b => b } } end I'd like class Foo < ActiveRecord::Base named_scope:ab, lambda { |a,b|:conditions => {:a => a,:b => b } } end but I'd prefer to do it in a DRY fashion. I can get the same effect by using Foo.a(something).b(something_else) but it's not particularly lovely. | TITLE:
Is there a way to combine named scopes into a new named scope?
QUESTION:
I have class Foo < ActiveRecord::Base named_scope:a, lambda { |a|:conditions => {:a => a } } named_scope:b, lambda { |b|:conditions => {:b => b } } end I'd like class Foo < ActiveRecord::Base named_scope:ab, lambda { |a,b|:conditions => {:a => a,:b => b } } end but I'd prefer to do it in a DRY fashion. I can get the same effect by using Foo.a(something).b(something_else) but it's not particularly lovely.
ANSWER:
Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method? def self.ab(a, b) a(a).b(b) end You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional. If you're stuck on named_scope, can't you extend it to do much the same thing? Let me know if I'm totally off base with what you're wanting to do. | [
"ruby-on-rails",
"rails-activerecord",
"named-scope"
] | 10 | 2 | 14,209 | 6 | 0 | 2008-08-26T20:13:46.020000 | 2008-08-27T17:50:49.600000 |
29,030 | 30,691 | SharePoint SPContext.List in a custom application page | I have a custom SharePoint application page deployed to the _layouts folder. It's a custom "new form" for a custom content type. During my interactions with this page, I will need to add an item to my list. When the page first loads, I can use SPContext.Current.List to see the current list I'm working with. But after I fill in my form and the form posts back onto itself and IsPostBack is true, then SPContext.Current.List is null so I can't find the list that I need to add my stuff into. Is this expected? How should I retain some info about my context list across the postback? Should I just populate some asp:hidden control with my list's guid and then just pull it back from that on the postback? That seems safe, I guess. FWIW, this is the MOSS 2007 Standard version. | Generally speaking I try and copy whatever approach the product group has taken when looking to add functionality of my own. In this case they add their own edit/view/add pages via the list definition itself. I built a solution that also needed its own custom "New" form, not open source unfortunately, though if you are interested you can download it, its called "Tagged Links" (Social Bookmarking for SharePoint) and you can find some links on my blog. To give you a few hints and tips, the following should set you off in the right direction: Created a new list definition. Created a new Content Type In the content type you can define your own "FormTemplates" that references a Rendering Template which determine what gets displayed in the "Middle" bit of those forms. Copied the standard Rendering Template, but then made the changes to it that I needed. Wrapped it all up in a solution, and deployed. My Rendering Template actually included an overridden "Save" Button where I did a lot of the extra work I needed to do during the save. Anyway, it is a little too much work in my opinion but, I think, it most closely matches the standard approach taken by the product developers. Let me know if you need more detail and I will see if I can put together a step-by-step blog post, but hopefully this gets you off on the right direction. | SharePoint SPContext.List in a custom application page I have a custom SharePoint application page deployed to the _layouts folder. It's a custom "new form" for a custom content type. During my interactions with this page, I will need to add an item to my list. When the page first loads, I can use SPContext.Current.List to see the current list I'm working with. But after I fill in my form and the form posts back onto itself and IsPostBack is true, then SPContext.Current.List is null so I can't find the list that I need to add my stuff into. Is this expected? How should I retain some info about my context list across the postback? Should I just populate some asp:hidden control with my list's guid and then just pull it back from that on the postback? That seems safe, I guess. FWIW, this is the MOSS 2007 Standard version. | TITLE:
SharePoint SPContext.List in a custom application page
QUESTION:
I have a custom SharePoint application page deployed to the _layouts folder. It's a custom "new form" for a custom content type. During my interactions with this page, I will need to add an item to my list. When the page first loads, I can use SPContext.Current.List to see the current list I'm working with. But after I fill in my form and the form posts back onto itself and IsPostBack is true, then SPContext.Current.List is null so I can't find the list that I need to add my stuff into. Is this expected? How should I retain some info about my context list across the postback? Should I just populate some asp:hidden control with my list's guid and then just pull it back from that on the postback? That seems safe, I guess. FWIW, this is the MOSS 2007 Standard version.
ANSWER:
Generally speaking I try and copy whatever approach the product group has taken when looking to add functionality of my own. In this case they add their own edit/view/add pages via the list definition itself. I built a solution that also needed its own custom "New" form, not open source unfortunately, though if you are interested you can download it, its called "Tagged Links" (Social Bookmarking for SharePoint) and you can find some links on my blog. To give you a few hints and tips, the following should set you off in the right direction: Created a new list definition. Created a new Content Type In the content type you can define your own "FormTemplates" that references a Rendering Template which determine what gets displayed in the "Middle" bit of those forms. Copied the standard Rendering Template, but then made the changes to it that I needed. Wrapped it all up in a solution, and deployed. My Rendering Template actually included an overridden "Save" Button where I did a lot of the extra work I needed to do during the save. Anyway, it is a little too much work in my opinion but, I think, it most closely matches the standard approach taken by the product developers. Let me know if you need more detail and I will see if I can put together a step-by-step blog post, but hopefully this gets you off on the right direction. | [
"sharepoint",
"spcontext",
"applicationpage"
] | 1 | 2 | 3,779 | 4 | 0 | 2008-08-26T21:47:22.817000 | 2008-08-27T17:30:42.720000 |
29,040 | 425,518 | Linq To SQL: Can I eager load only one field in a joined table? | I have one table "orders" with a foreing key "ProductID". I want to show the orders in a grid with the product name, without LazyLoad for better performance, but I if use DataLoadOptions it retrieves all Product fields, which seams like a overkill. Is there a way to retrieve only the Product name in the first query? Can I set some attribute in the DBML? In this table says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means. Edit: Changed the title, because I'm not really sure the there is no solution. Can't believe no one has the same problem, it is a very common scenario. | I get the solution in this other question Which.net ORM can deal with this scenario, that is related to the liammclennan answer but more clear (maybe the question was more clear too) | Linq To SQL: Can I eager load only one field in a joined table? I have one table "orders" with a foreing key "ProductID". I want to show the orders in a grid with the product name, without LazyLoad for better performance, but I if use DataLoadOptions it retrieves all Product fields, which seams like a overkill. Is there a way to retrieve only the Product name in the first query? Can I set some attribute in the DBML? In this table says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means. Edit: Changed the title, because I'm not really sure the there is no solution. Can't believe no one has the same problem, it is a very common scenario. | TITLE:
Linq To SQL: Can I eager load only one field in a joined table?
QUESTION:
I have one table "orders" with a foreing key "ProductID". I want to show the orders in a grid with the product name, without LazyLoad for better performance, but I if use DataLoadOptions it retrieves all Product fields, which seams like a overkill. Is there a way to retrieve only the Product name in the first query? Can I set some attribute in the DBML? In this table says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means. Edit: Changed the title, because I'm not really sure the there is no solution. Can't believe no one has the same problem, it is a very common scenario.
ANSWER:
I get the solution in this other question Which.net ORM can deal with this scenario, that is related to the liammclennan answer but more clear (maybe the question was more clear too) | [
".net",
"sql",
"performance",
"linq-to-sql"
] | 1 | 0 | 1,182 | 3 | 0 | 2008-08-26T21:55:09.333000 | 2009-01-08T19:21:07.053000 |
29,044 | 29,046 | Good Free Alternative To MS Access | Consider the need to develop a lightweight desktop DB application on the Microsoft platforms. It could be done fairly easily with MS Access but I'd like to be able to distribute it to others and I don't want to pay for a runtime license. Requirements: easy distribution to others no runtime licensing issues Considerations and Candidates: Base from the OpenOffice suite. My concerns were around its stability. MySQL + writing custom DB code in C++ or Python or whatever seems like a rather heavy-handed solution. Question: What are the low cost or free database alternatives to MS Access? See Also: Open Source Reporting Engines @Schnapple Bruceatk kind of hit on what I'm thinking of; it's not so much the DB engine as I want the other niceties that Access brings to the party. The nice form designer, the nice reporting engine etc. But you do raise a very good point about the installation footprint. I had considered that but I've not made any firm decisions about which way I'm going with this yet anyway. It'll probably be something fairly lightweight anyway and a small installation footprint would definitely be a plus. @Remou, No I was unaware that the MS Access 2007 runtime is free; thanks for pointing that out. The last time I'd bothered to investigate it (I don't remember when it was) I think it was a fairly expensive license for the runtime because I think they were trying to sell it to Corporate IT departments. And thanks to everyone else who responded as well; I was completely unaware of those other options you all pointed out. | One thing to keep in mind here is the MS Access product is much more than just the raw database engine. It provides a full application development platform, including form and menu designer, client application language and environment (VBA), and report designer. When you take all those things together, MS Access really has no peer. But for the scope of this question, we're concerned with the raw database engine. With that in mind: SQLlite, Firebird, VistaDB (not free), SQL Server Compact Edition (not Express) and now SQL Server LocalDB all come to mind. Another thought: while the original question does ask about desktop databases, its likely some people will land here looking for a database to use with a web site. It's important to remember that these are all in-process databases, and as such are rarely if ever appropriate for use on the web. If you want to build a web site, where it's common to need to support significant concurrent access, you generally want a database server engine, like MS SQL, Postgresql, MySQL, Oracle, or their brethren. At the same time, those server engines are rarely if ever appropriate for a single-user desktop application. | Good Free Alternative To MS Access Consider the need to develop a lightweight desktop DB application on the Microsoft platforms. It could be done fairly easily with MS Access but I'd like to be able to distribute it to others and I don't want to pay for a runtime license. Requirements: easy distribution to others no runtime licensing issues Considerations and Candidates: Base from the OpenOffice suite. My concerns were around its stability. MySQL + writing custom DB code in C++ or Python or whatever seems like a rather heavy-handed solution. Question: What are the low cost or free database alternatives to MS Access? See Also: Open Source Reporting Engines @Schnapple Bruceatk kind of hit on what I'm thinking of; it's not so much the DB engine as I want the other niceties that Access brings to the party. The nice form designer, the nice reporting engine etc. But you do raise a very good point about the installation footprint. I had considered that but I've not made any firm decisions about which way I'm going with this yet anyway. It'll probably be something fairly lightweight anyway and a small installation footprint would definitely be a plus. @Remou, No I was unaware that the MS Access 2007 runtime is free; thanks for pointing that out. The last time I'd bothered to investigate it (I don't remember when it was) I think it was a fairly expensive license for the runtime because I think they were trying to sell it to Corporate IT departments. And thanks to everyone else who responded as well; I was completely unaware of those other options you all pointed out. | TITLE:
Good Free Alternative To MS Access
QUESTION:
Consider the need to develop a lightweight desktop DB application on the Microsoft platforms. It could be done fairly easily with MS Access but I'd like to be able to distribute it to others and I don't want to pay for a runtime license. Requirements: easy distribution to others no runtime licensing issues Considerations and Candidates: Base from the OpenOffice suite. My concerns were around its stability. MySQL + writing custom DB code in C++ or Python or whatever seems like a rather heavy-handed solution. Question: What are the low cost or free database alternatives to MS Access? See Also: Open Source Reporting Engines @Schnapple Bruceatk kind of hit on what I'm thinking of; it's not so much the DB engine as I want the other niceties that Access brings to the party. The nice form designer, the nice reporting engine etc. But you do raise a very good point about the installation footprint. I had considered that but I've not made any firm decisions about which way I'm going with this yet anyway. It'll probably be something fairly lightweight anyway and a small installation footprint would definitely be a plus. @Remou, No I was unaware that the MS Access 2007 runtime is free; thanks for pointing that out. The last time I'd bothered to investigate it (I don't remember when it was) I think it was a fairly expensive license for the runtime because I think they were trying to sell it to Corporate IT departments. And thanks to everyone else who responded as well; I was completely unaware of those other options you all pointed out.
ANSWER:
One thing to keep in mind here is the MS Access product is much more than just the raw database engine. It provides a full application development platform, including form and menu designer, client application language and environment (VBA), and report designer. When you take all those things together, MS Access really has no peer. But for the scope of this question, we're concerned with the raw database engine. With that in mind: SQLlite, Firebird, VistaDB (not free), SQL Server Compact Edition (not Express) and now SQL Server LocalDB all come to mind. Another thought: while the original question does ask about desktop databases, its likely some people will land here looking for a database to use with a web site. It's important to remember that these are all in-process databases, and as such are rarely if ever appropriate for use on the web. If you want to build a web site, where it's common to need to support significant concurrent access, you generally want a database server engine, like MS SQL, Postgresql, MySQL, Oracle, or their brethren. At the same time, those server engines are rarely if ever appropriate for a single-user desktop application. | [
"database",
"ms-access",
"desktop"
] | 105 | 65 | 153,452 | 28 | 0 | 2008-08-26T21:57:21.340000 | 2008-08-26T21:59:10.120000 |
29,053 | 29,073 | Javascript Browser Quirks - array.Length | Code: Unusual Array Lengths! Notice the extra comma in the array declaration. The code above gives different outputs for various browsers: Safari: 5 Firefox: 5 IE: 6 The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array. On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies. My questions: i. Which one of these is correct? Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault. ii. Are there any other such Javascript browser quirks that I should be wary of? Edit: Yes, there are loads of Javascript quirks. www.quirksmode.org is a good resource for the same. iii. How do I avoid errors such as these? Edit: Use JSLint to validate your javascript. Or, use some external libraries. Or, sanitize your code. Thanks to DamienB, JasonBunting, John and Konrad Rudolph for their inputs. | It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don't have it handy to test). Since there is no actual value provided, I imagine it's filling it with something like 'null' which certainly doesn't seem to be what you intended to have happen when you created the array. At the end of the day though, it doesn't really matter which is "correct" since the reality is that either you are targeting only one browser, in which case you can ignore what the others do, or you are targeting multiple browsers in which case your code needs to work on all of them. In this case the obvious solution is to never include the dangling comma in an array initializer. If you have problems avoiding it (e.g. for some reason you have developed a (bad, imho) habit of including it) and other problems like this, then something like JSLint might help. | Javascript Browser Quirks - array.Length Code: Unusual Array Lengths! Notice the extra comma in the array declaration. The code above gives different outputs for various browsers: Safari: 5 Firefox: 5 IE: 6 The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array. On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies. My questions: i. Which one of these is correct? Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault. ii. Are there any other such Javascript browser quirks that I should be wary of? Edit: Yes, there are loads of Javascript quirks. www.quirksmode.org is a good resource for the same. iii. How do I avoid errors such as these? Edit: Use JSLint to validate your javascript. Or, use some external libraries. Or, sanitize your code. Thanks to DamienB, JasonBunting, John and Konrad Rudolph for their inputs. | TITLE:
Javascript Browser Quirks - array.Length
QUESTION:
Code: Unusual Array Lengths! Notice the extra comma in the array declaration. The code above gives different outputs for various browsers: Safari: 5 Firefox: 5 IE: 6 The extra comma in the array is being ignored by Safari and FF while IE treats it as another object in the array. On some search, I have found mixed opinions about which answer is correct. Most people say that IE is correct but then Safari is also doing the same thing as Firefox. I haven't tested this on other browsers like Opera but I assume that there are discrepancies. My questions: i. Which one of these is correct? Edit: By general consensus (and ECMAScript guidelines) we assume that IE is again at fault. ii. Are there any other such Javascript browser quirks that I should be wary of? Edit: Yes, there are loads of Javascript quirks. www.quirksmode.org is a good resource for the same. iii. How do I avoid errors such as these? Edit: Use JSLint to validate your javascript. Or, use some external libraries. Or, sanitize your code. Thanks to DamienB, JasonBunting, John and Konrad Rudolph for their inputs.
ANSWER:
It seems to me that the Firefox behavior is correct. What is the value of the 6th value in IE (sorry I don't have it handy to test). Since there is no actual value provided, I imagine it's filling it with something like 'null' which certainly doesn't seem to be what you intended to have happen when you created the array. At the end of the day though, it doesn't really matter which is "correct" since the reality is that either you are targeting only one browser, in which case you can ignore what the others do, or you are targeting multiple browsers in which case your code needs to work on all of them. In this case the obvious solution is to never include the dangling comma in an array initializer. If you have problems avoiding it (e.g. for some reason you have developed a (bad, imho) habit of including it) and other problems like this, then something like JSLint might help. | [
"javascript"
] | 27 | 9 | 7,757 | 7 | 0 | 2008-08-26T22:00:38.773000 | 2008-08-26T22:13:41.083000 |
29,061 | 29,083 | How do you use ssh in a shell script? | When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script? | Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use ssh user@host command for example ssh user@host ls In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host. | How do you use ssh in a shell script? When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script? | TITLE:
How do you use ssh in a shell script?
QUESTION:
When I try to use an ssh command in a shell script, the command just sits there. Do you have an example of how to use ssh in a shell script?
ANSWER:
Depends on what you want to do, and how you use it. If you just want to execute a command remotely and safely on another machine, just use ssh user@host command for example ssh user@host ls In order to do this safely you need to either ask the user for the password during runtime, or set up keys on the remote host. | [
"bash",
"shell",
"ssh",
"ksh",
"rsh"
] | 19 | 39 | 40,543 | 5 | 0 | 2008-08-26T22:05:37.310000 | 2008-08-26T22:19:48.573000 |
29,088 | 29,108 | What is the difference between a group and match in .NET's RegEx? | What is the difference between a Group and a Match in.NET's RegEx? | A Match is an object that indicates a particular regular expression matched (a portion of) the target text. A Group indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code: string text = "One car red car blue car"; string pat = @"(\w+)\s+(car)"; Match m = r.Match(text); m would be match object that contains two groups - group 1, from (\w+), and that captured "One", and group 2 (from (car) ) that matched, well, "car". | What is the difference between a group and match in .NET's RegEx? What is the difference between a Group and a Match in.NET's RegEx? | TITLE:
What is the difference between a group and match in .NET's RegEx?
QUESTION:
What is the difference between a Group and a Match in.NET's RegEx?
ANSWER:
A Match is an object that indicates a particular regular expression matched (a portion of) the target text. A Group indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code: string text = "One car red car blue car"; string pat = @"(\w+)\s+(car)"; Match m = r.Match(text); m would be match object that contains two groups - group 1, from (\w+), and that captured "One", and group 2 (from (car) ) that matched, well, "car". | [
".net",
"regex"
] | 6 | 8 | 3,125 | 2 | 0 | 2008-08-26T22:23:25.757000 | 2008-08-26T22:33:04 |
29,099 | 29,274 | What makes a language Object-Oriented? | Since debate without meaningful terms is meaningless, I figured I would point at the elephant in the room and ask: What exactly makes a language "object-oriented"? I'm not looking for a textbook answer here, but one based on your experiences with OO languages that work well in your domain, whatever it may be. A related question that might help to answer first is: What is the archetype of object-oriented languages and why? | Definitions for Object-Orientation are of course a huge can of worms, but here are my 2 cents: To me, Object-Orientation is all about objects that collaborate by sending messages. That is, to me, the single most important trait of an object-oriented language. If I had to put up an ordered list of all the features that an object-oriented language must have, it would look like this: Objects sending messages to other objects Everything is an Object Late Binding Subtype Polymorphism Inheritance or something similarly expressive, like Delegation Encapsulation Information Hiding Abstraction Obviously, this list is very controversial, since it excludes a great variety of languages that are widely regarded as object-oriented, such as Java, C# and C++, all of which violate points 1, 2 and 3. However, there is no doubt that those languages allow for object-oriented programming (but so does C ) and even facilitate it (which C doesn't). So, I have come to call languages that satisfy those requirements "purely object-oriented". As archetypical object-oriented languages I would name Self and Newspeak. Both satisfy the above-mentioned requirements. Both are inspired by and successors to Smalltalk, and both actually manage to be "more OO" in some sense. The things that I like about Self and Newspeak are that both take the message sending paradigm to the extreme (Newspeak even more so than Self). In Newspeak, everything is a message send. There are no instance variables, no fields, no attributes, no constants, no class names. They are all emulated by using getters and setters. In Self, there are no classes, only objects. This emphasizes, what OO is really about: objects, not classes. | What makes a language Object-Oriented? Since debate without meaningful terms is meaningless, I figured I would point at the elephant in the room and ask: What exactly makes a language "object-oriented"? I'm not looking for a textbook answer here, but one based on your experiences with OO languages that work well in your domain, whatever it may be. A related question that might help to answer first is: What is the archetype of object-oriented languages and why? | TITLE:
What makes a language Object-Oriented?
QUESTION:
Since debate without meaningful terms is meaningless, I figured I would point at the elephant in the room and ask: What exactly makes a language "object-oriented"? I'm not looking for a textbook answer here, but one based on your experiences with OO languages that work well in your domain, whatever it may be. A related question that might help to answer first is: What is the archetype of object-oriented languages and why?
ANSWER:
Definitions for Object-Orientation are of course a huge can of worms, but here are my 2 cents: To me, Object-Orientation is all about objects that collaborate by sending messages. That is, to me, the single most important trait of an object-oriented language. If I had to put up an ordered list of all the features that an object-oriented language must have, it would look like this: Objects sending messages to other objects Everything is an Object Late Binding Subtype Polymorphism Inheritance or something similarly expressive, like Delegation Encapsulation Information Hiding Abstraction Obviously, this list is very controversial, since it excludes a great variety of languages that are widely regarded as object-oriented, such as Java, C# and C++, all of which violate points 1, 2 and 3. However, there is no doubt that those languages allow for object-oriented programming (but so does C ) and even facilitate it (which C doesn't). So, I have come to call languages that satisfy those requirements "purely object-oriented". As archetypical object-oriented languages I would name Self and Newspeak. Both satisfy the above-mentioned requirements. Both are inspired by and successors to Smalltalk, and both actually manage to be "more OO" in some sense. The things that I like about Self and Newspeak are that both take the message sending paradigm to the extreme (Newspeak even more so than Self). In Newspeak, everything is a message send. There are no instance variables, no fields, no attributes, no constants, no class names. They are all emulated by using getters and setters. In Self, there are no classes, only objects. This emphasizes, what OO is really about: objects, not classes. | [
"language-agnostic",
"oop",
"programming-languages",
"glossary"
] | 37 | 32 | 26,250 | 16 | 0 | 2008-08-26T22:28:19.237000 | 2008-08-27T00:51:49.703000 |
29,100 | 109,932 | How are you generating tests from specifications? | I came across a printed article by Bertrand Meyer where he states that tests can be generated from specifications. My development team does nothing like this, but it sounds like a good technique to consider. How are you generating tests from specifications? How would you describe the success your having in discovering program faults via this method? | There are all sorts of ways to do it, ranging from what I'd consider an 'art form' (and not necessarily good art) all the way to mathematically derived tests from formal specifications. At the end of the day, your development team needs to decided on what they can do based on the schedule they are working with. That being said, being able to test software against specs is a Good Thing. Only your team can gauge the 'depth' of your tests, and that will probably be a function of how good your specs are. If they say something like, 'the login UI needs to provide a cancel button and a login button, and they need to work', your tests are going to be pretty general. But keep in mind - even very general tests are a Good Thing. Testing is a Good Thing. Too many developers have a bad attitude when it comes to testing, but at the end of the day, you're shipping software which should work, and to me, that means a lot. The effectiveness your tests will having in finding program faults will depend on the detail you put into them. What is especially nice about having test procedures written to specs is that you can test each build to the same level of detail as the previous build (typically referred to as a regression test). | How are you generating tests from specifications? I came across a printed article by Bertrand Meyer where he states that tests can be generated from specifications. My development team does nothing like this, but it sounds like a good technique to consider. How are you generating tests from specifications? How would you describe the success your having in discovering program faults via this method? | TITLE:
How are you generating tests from specifications?
QUESTION:
I came across a printed article by Bertrand Meyer where he states that tests can be generated from specifications. My development team does nothing like this, but it sounds like a good technique to consider. How are you generating tests from specifications? How would you describe the success your having in discovering program faults via this method?
ANSWER:
There are all sorts of ways to do it, ranging from what I'd consider an 'art form' (and not necessarily good art) all the way to mathematically derived tests from formal specifications. At the end of the day, your development team needs to decided on what they can do based on the schedule they are working with. That being said, being able to test software against specs is a Good Thing. Only your team can gauge the 'depth' of your tests, and that will probably be a function of how good your specs are. If they say something like, 'the login UI needs to provide a cancel button and a login button, and they need to work', your tests are going to be pretty general. But keep in mind - even very general tests are a Good Thing. Testing is a Good Thing. Too many developers have a bad attitude when it comes to testing, but at the end of the day, you're shipping software which should work, and to me, that means a lot. The effectiveness your tests will having in finding program faults will depend on the detail you put into them. What is especially nice about having test procedures written to specs is that you can test each build to the same level of detail as the previous build (typically referred to as a regression test). | [
"testing",
"automated-tests",
"specifications",
"faults"
] | 5 | 0 | 298 | 4 | 0 | 2008-08-26T22:28:22.530000 | 2008-09-21T01:24:22.607000 |
29,104 | 29,118 | Requirements Gathering | How do you go about the requirements gathering phase? Does anyone have a good set of guidelines or tips to follow? What are some good questions to ask the stakeholders? I am currently working on a new project and there are a lot of unknowns. I am in the process of coming up with a list of questions to ask the stakeholders. However I cant help but to feel that I am missing something or forgetting to ask a critical question. | You're almost certainly missing something. A lot of things, probably. Don't worry, it's ok. Even if you remembered everything and covered all the bases stakeholders aren't going to be able to give you very good, clear requirements without any point of reference. The best way to do this sort of thing is to get what you can from them now, then take that and give them something to react to. It can be a paper prototype, a mockup, version 0.1 of the software, whatever. Then they can start telling you what they really want. | Requirements Gathering How do you go about the requirements gathering phase? Does anyone have a good set of guidelines or tips to follow? What are some good questions to ask the stakeholders? I am currently working on a new project and there are a lot of unknowns. I am in the process of coming up with a list of questions to ask the stakeholders. However I cant help but to feel that I am missing something or forgetting to ask a critical question. | TITLE:
Requirements Gathering
QUESTION:
How do you go about the requirements gathering phase? Does anyone have a good set of guidelines or tips to follow? What are some good questions to ask the stakeholders? I am currently working on a new project and there are a lot of unknowns. I am in the process of coming up with a list of questions to ask the stakeholders. However I cant help but to feel that I am missing something or forgetting to ask a critical question.
ANSWER:
You're almost certainly missing something. A lot of things, probably. Don't worry, it's ok. Even if you remembered everything and covered all the bases stakeholders aren't going to be able to give you very good, clear requirements without any point of reference. The best way to do this sort of thing is to get what you can from them now, then take that and give them something to react to. It can be a paper prototype, a mockup, version 0.1 of the software, whatever. Then they can start telling you what they really want. | [
"requirements-management"
] | 29 | 20 | 23,156 | 20 | 0 | 2008-08-26T22:31:13.007000 | 2008-08-26T22:36:16.053000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.