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
37,374
37,587
How do you implement caching in Linq to SQL?
We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results? We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable. EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.
A quick answer: Use the Repository pattern (see Domain Driven Design by Evans) to fetch your entities. Each repository will cache the things it will hold, ideally by letting each instance of the repository access a singleton cache (each thread/request will instantiate a new repository but there can be only one cache). The above answer works on one machine only. To be able to use this on many machines, use memcached as your caching solution. Good luck!
How do you implement caching in Linq to SQL? We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results? We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable. EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.
TITLE: How do you implement caching in Linq to SQL? QUESTION: We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results? We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable. EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture. ANSWER: A quick answer: Use the Repository pattern (see Domain Driven Design by Evans) to fetch your entities. Each repository will cache the things it will hold, ideally by letting each instance of the repository access a singleton cache (each thread/request will instantiate a new repository but there can be only one cache). The above answer works on one machine only. To be able to use this on many machines, use memcached as your caching solution. Good luck!
[ ".net", "sql", "linq-to-sql", "iis", "caching" ]
33
10
18,524
6
0
2008-09-01T02:13:07.163000
2008-09-01T07:55:00.320000
37,375
37,387
How do I unit test a WCF service?
We have a whole bunch of DLLs that give us access to our database and other applications and services. We've wrapped these DLLs with a thin WCF service layer which our clients then consume. I'm a little unsure on how to write unit tests that only test the WCF service layer. Should I just write unit tests for the DLLs, and integration tests for the WCF services? I'd appreciate any wisdom... I know that if my unit tests actually go to the database they won't actually be true unit tests. I also understand that I don't really need to test the WCF service host in a unit test. So, I'm confused about exactly what to test and how.
The consumer of your service doesn't care what's underneath your service. To really test your service layer, I think your layer needs to go down to DLLs and the database and write at least CRUD test.
How do I unit test a WCF service? We have a whole bunch of DLLs that give us access to our database and other applications and services. We've wrapped these DLLs with a thin WCF service layer which our clients then consume. I'm a little unsure on how to write unit tests that only test the WCF service layer. Should I just write unit tests for the DLLs, and integration tests for the WCF services? I'd appreciate any wisdom... I know that if my unit tests actually go to the database they won't actually be true unit tests. I also understand that I don't really need to test the WCF service host in a unit test. So, I'm confused about exactly what to test and how.
TITLE: How do I unit test a WCF service? QUESTION: We have a whole bunch of DLLs that give us access to our database and other applications and services. We've wrapped these DLLs with a thin WCF service layer which our clients then consume. I'm a little unsure on how to write unit tests that only test the WCF service layer. Should I just write unit tests for the DLLs, and integration tests for the WCF services? I'd appreciate any wisdom... I know that if my unit tests actually go to the database they won't actually be true unit tests. I also understand that I don't really need to test the WCF service host in a unit test. So, I'm confused about exactly what to test and how. ANSWER: The consumer of your service doesn't care what's underneath your service. To really test your service layer, I think your layer needs to go down to DLLs and the database and write at least CRUD test.
[ "wcf", "unit-testing" ]
18
4
15,050
3
0
2008-09-01T02:13:52.090000
2008-09-01T02:27:57.143000
37,378
37,406
How to convince my co-workers not to use datasets for enterprise development (.NET 2.0+)
Everyone I work with is obsessed with the data-centric approach to enterprise development and hates the idea of using custom collections/objects. What is the best way to convince them otherwise?
If you are working on legacy code (e.g., apps ported from.NET 1.x to 2.0 or 3.5) then it would be a bad idea to depart from datasets. Why change something that already works? If you are, however, creating a new apps, there a few things that you can cite: Appeal to experiencing pain in maintaining apps that stick with DataSets Cite performance benefits for your new approach Bait them with a good middle-ground. Move to.NET 3.5, and promote LINQ to SQL, for instance: while still sticking to data-driven architecture, is a huge, huge departure to string-indexed data sets, and enforces... voila! Custom collections -- in a manner that is hidden from them. What is important is that whatever approach you use you remain consistent, and you are completely honest with the pros and cons of your approaches. If all else fails (e.g., you have a development team that utterly refuses to budge from old practices and is skeptical of learning new things), this is a very, very clear sign that you've outgrown your team it's time to leave your company!
How to convince my co-workers not to use datasets for enterprise development (.NET 2.0+) Everyone I work with is obsessed with the data-centric approach to enterprise development and hates the idea of using custom collections/objects. What is the best way to convince them otherwise?
TITLE: How to convince my co-workers not to use datasets for enterprise development (.NET 2.0+) QUESTION: Everyone I work with is obsessed with the data-centric approach to enterprise development and hates the idea of using custom collections/objects. What is the best way to convince them otherwise? ANSWER: If you are working on legacy code (e.g., apps ported from.NET 1.x to 2.0 or 3.5) then it would be a bad idea to depart from datasets. Why change something that already works? If you are, however, creating a new apps, there a few things that you can cite: Appeal to experiencing pain in maintaining apps that stick with DataSets Cite performance benefits for your new approach Bait them with a good middle-ground. Move to.NET 3.5, and promote LINQ to SQL, for instance: while still sticking to data-driven architecture, is a huge, huge departure to string-indexed data sets, and enforces... voila! Custom collections -- in a manner that is hidden from them. What is important is that whatever approach you use you remain consistent, and you are completely honest with the pros and cons of your approaches. If all else fails (e.g., you have a development team that utterly refuses to budge from old practices and is skeptical of learning new things), this is a very, very clear sign that you've outgrown your team it's time to leave your company!
[ "oop" ]
13
10
1,847
16
0
2008-09-01T02:16:17.623000
2008-09-01T03:09:06.450000
37,381
37,408
What's a good way to write a Cocoa front-end to an Erlang application?
I'm exploring the possibility of writing an application in Erlang, but it would need to have a portion written in Cocoa (presumably Objective-C). I'd like the front-end and back-end to be able to communicate easily. How can this best be done? I can think of using C ports and connected processes, but I think I'd like a reverse situation (the front-end starting and connecting to the back-end). There are named pipes (FIFOs), or I could use network communications over a TCP port or a named BSD socket. Does anyone have experience in this area?
One way would be to have the Erlang core of the application be a daemon that the Cocoa front-end communicates with over a Unix-domain socket using some simple protocol you devise. The use of a Unix-domain socket means that the Erlang daemon could be launched on-demand by launchd and the Cocoa front-end could find the path to the socket to use via an environment variable. That makes the rendezvous between the app and the daemon trivial, and it also makes it straightforward to develop multiple front-ends (or possibly a framework that wraps communication with the daemon). The Mac OS X launchd system is really cool this way. If you specify that a job should be launched on-demand via a secure Unix-domain socket, launchd will actually create the socket itself with appropriate permissions, and advertise its location via the environment variable named in the job's property list. The job, when started, will actually be passed a file descriptor to the socket by launchd when it does a simple check-in. Ultimately this means that the entire process of the front-end opening the socket to communicate with the daemon, launchd launching the daemon, and the daemon responding to the communication can be secure, even if the front-end and the daemon run at different privilege levels.
What's a good way to write a Cocoa front-end to an Erlang application? I'm exploring the possibility of writing an application in Erlang, but it would need to have a portion written in Cocoa (presumably Objective-C). I'd like the front-end and back-end to be able to communicate easily. How can this best be done? I can think of using C ports and connected processes, but I think I'd like a reverse situation (the front-end starting and connecting to the back-end). There are named pipes (FIFOs), or I could use network communications over a TCP port or a named BSD socket. Does anyone have experience in this area?
TITLE: What's a good way to write a Cocoa front-end to an Erlang application? QUESTION: I'm exploring the possibility of writing an application in Erlang, but it would need to have a portion written in Cocoa (presumably Objective-C). I'd like the front-end and back-end to be able to communicate easily. How can this best be done? I can think of using C ports and connected processes, but I think I'd like a reverse situation (the front-end starting and connecting to the back-end). There are named pipes (FIFOs), or I could use network communications over a TCP port or a named BSD socket. Does anyone have experience in this area? ANSWER: One way would be to have the Erlang core of the application be a daemon that the Cocoa front-end communicates with over a Unix-domain socket using some simple protocol you devise. The use of a Unix-domain socket means that the Erlang daemon could be launched on-demand by launchd and the Cocoa front-end could find the path to the socket to use via an environment variable. That makes the rendezvous between the app and the daemon trivial, and it also makes it straightforward to develop multiple front-ends (or possibly a framework that wraps communication with the daemon). The Mac OS X launchd system is really cool this way. If you specify that a job should be launched on-demand via a secure Unix-domain socket, launchd will actually create the socket itself with appropriate permissions, and advertise its location via the environment variable named in the job's property list. The job, when started, will actually be passed a file descriptor to the socket by launchd when it does a simple check-in. Ultimately this means that the entire process of the front-end opening the socket to communicate with the daemon, launchd launching the daemon, and the daemon responding to the communication can be secure, even if the front-end and the daemon run at different privilege levels.
[ "objective-c", "cocoa", "macos", "erlang" ]
13
10
2,007
6
0
2008-09-01T02:22:26.423000
2008-09-01T03:11:18.473000
37,391
1,381,855
Arithmetic with Arbitrarily Large Integers in PHP
Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide). My target is dealing with 128-bit integers. There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated. Approach #1: Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands. Approach #2: Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions). Approach #3: Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.
The PHP GMP extension will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so: gmp_strval(gmp_init($n, 10), 2);
Arithmetic with Arbitrarily Large Integers in PHP Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide). My target is dealing with 128-bit integers. There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated. Approach #1: Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands. Approach #2: Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions). Approach #3: Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.
TITLE: Arithmetic with Arbitrarily Large Integers in PHP QUESTION: Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide). My target is dealing with 128-bit integers. There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated. Approach #1: Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands. Approach #2: Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions). Approach #3: Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply. ANSWER: The PHP GMP extension will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so: gmp_strval(gmp_init($n, 10), 2);
[ "php", "integer" ]
8
4
4,916
4
0
2008-09-01T02:37:53.483000
2009-09-04T22:46:54.650000
37,396
37,415
Linux Lightweight Distro and X Windows for Development
I want to build a lightweight linux configuration to use for development. The first idea is to use it inside a Virtual Machine under Windows, or old Laptops with 1Gb RAM top. Maybe even a distributable environment for developers. So the whole idea is to use a LAMP server, Java Application Server (Tomcat or Jetty) and X Windows (any Window manager, from FVWM to Enlightment), Eclipse, maybe jEdit and of course Firefox. Edit: I am changing this post to compile a possible list of distros and window managers that can be used to configure a real lightweight development environment. I am using as base personal experiences on this matter. Info about the distros can be easily found in their sites. So please, focus on personal use of those systems Distros Ubuntu / Xubuntu Pros: Personal Experience in old systems or low RAM environment - @ Schroeder, @ SCdF Several sugestions based on personal knowledge - @ Kyle, @ Peter Hoffmann Gentoo Pros: Not targeted to Desktop Users - @ paan Don't come with a huge ammount of applications - @ paan Slackware Pros: Suggested as best performance in a wise install/configuration - @ Ryan Damn Small Linux Pros: Main focus is the lightweight factor - 50MB LiveCD - @ Ryan Debian Pros: Very versatile, can be configured for both heavy and lightweight computers - @ Ryan APT as package manager - @ Kyle Based on compatibility and usability - @ Kyle -- Fell Free to add Prós and Cons on this, so we can compile a good Reference. -- X Windows suggestion keep coming about XFCE. If others are to add here, open a session for it Like the distro one:)
I would recommend Xubuntu. It's based on Ubuntu/Debian and optimized for small footprint with the Xfce desktop environment.
Linux Lightweight Distro and X Windows for Development I want to build a lightweight linux configuration to use for development. The first idea is to use it inside a Virtual Machine under Windows, or old Laptops with 1Gb RAM top. Maybe even a distributable environment for developers. So the whole idea is to use a LAMP server, Java Application Server (Tomcat or Jetty) and X Windows (any Window manager, from FVWM to Enlightment), Eclipse, maybe jEdit and of course Firefox. Edit: I am changing this post to compile a possible list of distros and window managers that can be used to configure a real lightweight development environment. I am using as base personal experiences on this matter. Info about the distros can be easily found in their sites. So please, focus on personal use of those systems Distros Ubuntu / Xubuntu Pros: Personal Experience in old systems or low RAM environment - @ Schroeder, @ SCdF Several sugestions based on personal knowledge - @ Kyle, @ Peter Hoffmann Gentoo Pros: Not targeted to Desktop Users - @ paan Don't come with a huge ammount of applications - @ paan Slackware Pros: Suggested as best performance in a wise install/configuration - @ Ryan Damn Small Linux Pros: Main focus is the lightweight factor - 50MB LiveCD - @ Ryan Debian Pros: Very versatile, can be configured for both heavy and lightweight computers - @ Ryan APT as package manager - @ Kyle Based on compatibility and usability - @ Kyle -- Fell Free to add Prós and Cons on this, so we can compile a good Reference. -- X Windows suggestion keep coming about XFCE. If others are to add here, open a session for it Like the distro one:)
TITLE: Linux Lightweight Distro and X Windows for Development QUESTION: I want to build a lightweight linux configuration to use for development. The first idea is to use it inside a Virtual Machine under Windows, or old Laptops with 1Gb RAM top. Maybe even a distributable environment for developers. So the whole idea is to use a LAMP server, Java Application Server (Tomcat or Jetty) and X Windows (any Window manager, from FVWM to Enlightment), Eclipse, maybe jEdit and of course Firefox. Edit: I am changing this post to compile a possible list of distros and window managers that can be used to configure a real lightweight development environment. I am using as base personal experiences on this matter. Info about the distros can be easily found in their sites. So please, focus on personal use of those systems Distros Ubuntu / Xubuntu Pros: Personal Experience in old systems or low RAM environment - @ Schroeder, @ SCdF Several sugestions based on personal knowledge - @ Kyle, @ Peter Hoffmann Gentoo Pros: Not targeted to Desktop Users - @ paan Don't come with a huge ammount of applications - @ paan Slackware Pros: Suggested as best performance in a wise install/configuration - @ Ryan Damn Small Linux Pros: Main focus is the lightweight factor - 50MB LiveCD - @ Ryan Debian Pros: Very versatile, can be configured for both heavy and lightweight computers - @ Ryan APT as package manager - @ Kyle Based on compatibility and usability - @ Kyle -- Fell Free to add Prós and Cons on this, so we can compile a good Reference. -- X Windows suggestion keep coming about XFCE. If others are to add here, open a session for it Like the distro one:) ANSWER: I would recommend Xubuntu. It's based on Ubuntu/Debian and optimized for small footprint with the Xfce desktop environment.
[ "linux", "desktop" ]
4
1
5,768
12
0
2008-09-01T02:44:04.170000
2008-09-01T03:23:54.200000
37,398
37,402
How do I make a fully statically linked .exe with Visual Studio Express 2005?
My current preferred C++ environment is the free and largely excellent Microsoft Visual Studio 2005 Express edition. From time to time I have sent release.exe files to other people with pleasing results. However recently I made the disturbing discovery that the pleasing results were based on more luck that I would like. Attempting to run one of these programs on an old (2001 vintage, not scrupulously updated) XP box gave me nothing but a nasty "System cannot run x.exe" (or similar) message. Some googling revealed that with this toolset, even specifying static linking results in a simple hello-world.exe actually relying on extra.dll files (msvcm80.dll etc.). An incredibly elaborate version scheming system (manifest files anyone?) then will not let the.exe run without exactly the right.dll versions. I don't want or need this stuff, I just want an old fashioned self contained.exe that does nothing but lowest common denominator Win32 operations and runs on any old win32 OS. Does anyone know if its possible to do what I want to do with my existing toolset? Thank you.
For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'. If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.
How do I make a fully statically linked .exe with Visual Studio Express 2005? My current preferred C++ environment is the free and largely excellent Microsoft Visual Studio 2005 Express edition. From time to time I have sent release.exe files to other people with pleasing results. However recently I made the disturbing discovery that the pleasing results were based on more luck that I would like. Attempting to run one of these programs on an old (2001 vintage, not scrupulously updated) XP box gave me nothing but a nasty "System cannot run x.exe" (or similar) message. Some googling revealed that with this toolset, even specifying static linking results in a simple hello-world.exe actually relying on extra.dll files (msvcm80.dll etc.). An incredibly elaborate version scheming system (manifest files anyone?) then will not let the.exe run without exactly the right.dll versions. I don't want or need this stuff, I just want an old fashioned self contained.exe that does nothing but lowest common denominator Win32 operations and runs on any old win32 OS. Does anyone know if its possible to do what I want to do with my existing toolset? Thank you.
TITLE: How do I make a fully statically linked .exe with Visual Studio Express 2005? QUESTION: My current preferred C++ environment is the free and largely excellent Microsoft Visual Studio 2005 Express edition. From time to time I have sent release.exe files to other people with pleasing results. However recently I made the disturbing discovery that the pleasing results were based on more luck that I would like. Attempting to run one of these programs on an old (2001 vintage, not scrupulously updated) XP box gave me nothing but a nasty "System cannot run x.exe" (or similar) message. Some googling revealed that with this toolset, even specifying static linking results in a simple hello-world.exe actually relying on extra.dll files (msvcm80.dll etc.). An incredibly elaborate version scheming system (manifest files anyone?) then will not let the.exe run without exactly the right.dll versions. I don't want or need this stuff, I just want an old fashioned self contained.exe that does nothing but lowest common denominator Win32 operations and runs on any old win32 OS. Does anyone know if its possible to do what I want to do with my existing toolset? Thank you. ANSWER: For the C-runtime go to the project settings, choose C/C++ then 'Code Generation'. Change the 'runtime library' setting to 'multithreaded' instead of 'multithreaded dll'. If you are using any other libraries you may need to tell the linker to ignore the dynamically linked CRT explicitly.
[ "c++", "visual-studio", "linker" ]
136
153
169,708
4
0
2008-09-01T02:49:02.053000
2008-09-01T02:55:07.780000
37,425
158,314
What is the best way to interpret Perfmon analysis into application specific observations/data?
Many of us have used Perfmon tool to do performance analysis. Especially with.Net counters, but there are so many variables going on in Perfmon, that it always becomes hard to interpret Perfmon results in to valuable feedback about my application. I want to use perfmon, (not a tool like Ants Profiler etc) but how do I accurately interpret the observations? Any inputs are welcome.
I use the Performance Analysis of Logs (PAL) tool: http://pal.codeplex.com/ It's not an "official" Microsoft tool, but I believe the author works for Microsoft. The project seems to be fairly active. In addition to the canned threshold files provided (which are pretty good), you can write your own thresholds to analyze what your app needs. The generation of the HTML report with charts is also very nice. UPDATE: PAL 2.3.2 no longer depends on the MS LogParser or MS Office Web Components; it uses PowerShell v2.0 or greater, MS.NET Framework 3.5 SP1, and the MS Chart Controls for.NET 3.5.
What is the best way to interpret Perfmon analysis into application specific observations/data? Many of us have used Perfmon tool to do performance analysis. Especially with.Net counters, but there are so many variables going on in Perfmon, that it always becomes hard to interpret Perfmon results in to valuable feedback about my application. I want to use perfmon, (not a tool like Ants Profiler etc) but how do I accurately interpret the observations? Any inputs are welcome.
TITLE: What is the best way to interpret Perfmon analysis into application specific observations/data? QUESTION: Many of us have used Perfmon tool to do performance analysis. Especially with.Net counters, but there are so many variables going on in Perfmon, that it always becomes hard to interpret Perfmon results in to valuable feedback about my application. I want to use perfmon, (not a tool like Ants Profiler etc) but how do I accurately interpret the observations? Any inputs are welcome. ANSWER: I use the Performance Analysis of Logs (PAL) tool: http://pal.codeplex.com/ It's not an "official" Microsoft tool, but I believe the author works for Microsoft. The project seems to be fairly active. In addition to the canned threshold files provided (which are pretty good), you can write your own thresholds to analyze what your app needs. The generation of the HTML report with charts is also very nice. UPDATE: PAL 2.3.2 no longer depends on the MS LogParser or MS Office Web Components; it uses PowerShell v2.0 or greater, MS.NET Framework 3.5 SP1, and the MS Chart Controls for.NET 3.5.
[ ".net", "performance", "perfmon" ]
3
4
4,912
1
0
2008-09-01T03:39:42.773000
2008-10-01T15:48:44.463000
37,428
37,461
Get back to basics. How do I get back into C++?
I haven't used C++ since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for Launchy. Is there a good book to read to get back into it? My experience since college is mainly C# and recently ruby. I bought some book for C# developers and it ended up being on how to write C++ with CLI. While a good book it wasn't quite what I was looking for.
The best way to get back into C++ is to jump in. You can't learn a real language without spending any serious time in a country where they speak it. I wouldn't try to learn a programming language without spending time coding in it either. I wouldn't recommend learning C first though. That's a good way to pick up some bad habits in C++.
Get back to basics. How do I get back into C++? I haven't used C++ since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for Launchy. Is there a good book to read to get back into it? My experience since college is mainly C# and recently ruby. I bought some book for C# developers and it ended up being on how to write C++ with CLI. While a good book it wasn't quite what I was looking for.
TITLE: Get back to basics. How do I get back into C++? QUESTION: I haven't used C++ since college. Even though I've wanted to I haven't needed to do any until I started wanting to write plugins for Launchy. Is there a good book to read to get back into it? My experience since college is mainly C# and recently ruby. I bought some book for C# developers and it ended up being on how to write C++ with CLI. While a good book it wasn't quite what I was looking for. ANSWER: The best way to get back into C++ is to jump in. You can't learn a real language without spending any serious time in a country where they speak it. I wouldn't try to learn a programming language without spending time coding in it either. I wouldn't recommend learning C first though. That's a good way to pick up some bad habits in C++.
[ "c++" ]
9
7
1,397
7
0
2008-09-01T03:47:54.657000
2008-09-01T04:43:12.683000
37,441
37,446
Reasons for SQL differences
Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise?
It's a form of "Stealth lock-in". Joel goes into great detail here: http://www.joelonsoftware.com/articles/fog0000000056.html http://www.joelonsoftware.com/articles/fog0000000052.html Companies end up tying their business functionality to non-standard or weird unsupported functionality in their implementation, this restricts their ability to move away from their vendor to a competitor. On the other hand, it's pretty short-sighted because anyone with half a brain will tend to abstract away the proprietary pieces, or avoid the lock-in altogether, if it gets too egregious.
Reasons for SQL differences Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise?
TITLE: Reasons for SQL differences QUESTION: Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise? ANSWER: It's a form of "Stealth lock-in". Joel goes into great detail here: http://www.joelonsoftware.com/articles/fog0000000056.html http://www.joelonsoftware.com/articles/fog0000000052.html Companies end up tying their business functionality to non-standard or weird unsupported functionality in their implementation, this restricts their ability to move away from their vendor to a competitor. On the other hand, it's pretty short-sighted because anyone with half a brain will tend to abstract away the proprietary pieces, or avoid the lock-in altogether, if it gets too egregious.
[ "sql", "sql-server", "postgresql" ]
5
5
613
5
0
2008-09-01T04:11:42.790000
2008-09-01T04:17:30.653000
37,449
37,452
Equivalent to StAX for C
I've used the StAX API in Java quite a bit, and find it quite a clean way of dealing with XML files. Is there any equivalent library I could use for performing similar processing in C?
libxml is a heavily used and documented XML library for C, which provides a SAX API. Expat is another, but in my experience is not as well documented.
Equivalent to StAX for C I've used the StAX API in Java quite a bit, and find it quite a clean way of dealing with XML files. Is there any equivalent library I could use for performing similar processing in C?
TITLE: Equivalent to StAX for C QUESTION: I've used the StAX API in Java quite a bit, and find it quite a clean way of dealing with XML files. Is there any equivalent library I could use for performing similar processing in C? ANSWER: libxml is a heavily used and documented XML library for C, which provides a SAX API. Expat is another, but in my experience is not as well documented.
[ "java", "c", "xml" ]
4
0
510
4
0
2008-09-01T04:18:59.153000
2008-09-01T04:22:00.707000
37,464
37,522
iPhone App Minus App Store?
If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store? It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.
Official Developer Program For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using Ad Hoc Helper available from the App Store. For further details on this method, see Craig Hockenberry's Beta testing on iPhone 2.0 article Jailbroken iPhone For jailbroken iPhones, you can use the following method which I have personally tested using the AccelerometerGraph sample app on iPhone OS 3.0. Create Self-Signed Certificate First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate: Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate. Name: iPhone Developer Certificate Type: Code Signing Let me override defaults: Yes Click Continue Validity: 3650 days Click Continue Blank out the Email address field. Click Continue until complete. You should see "This root certificate is not trusted". This is expected. Set the iPhone SDK to allow the self-signed certificate to be used: sudo /usr/bin/sed -i.bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist If you have Xcode open, restart it for this change to take effect. Manual Deployment over WiFi The following steps require openssh, and uikittools to be installed first. Replace jasoniphone.local with the hostname of the target device. Be sure to set your own password on both the mobile and root users after installing SSH. To manually compile and install your application on the phone as a system app (bypassing Apple's installation system): Project, Set Active SDK, Device and Set Active Build Configuration, Release. Compile your project normally (using Build, not Build & Go). In the build/Release-iphoneos directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device. scp -r AccelerometerGraph.app root@jasoniphone:/Applications/ Let SpringBoard know the new application has been installed: ssh mobile@jasoniphone.local uicache This only has to be done when you add or remove applications. Updated applications just need to be relaunched. To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project. Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard: ssh root@jasoniphone.local rm -r /Applications/AccelerometerGraph.app && ssh mobile@jasoniphone.local uicache
iPhone App Minus App Store? If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store? It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.
TITLE: iPhone App Minus App Store? QUESTION: If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store? It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store. ANSWER: Official Developer Program For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using Ad Hoc Helper available from the App Store. For further details on this method, see Craig Hockenberry's Beta testing on iPhone 2.0 article Jailbroken iPhone For jailbroken iPhones, you can use the following method which I have personally tested using the AccelerometerGraph sample app on iPhone OS 3.0. Create Self-Signed Certificate First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate: Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate. Name: iPhone Developer Certificate Type: Code Signing Let me override defaults: Yes Click Continue Validity: 3650 days Click Continue Blank out the Email address field. Click Continue until complete. You should see "This root certificate is not trusted". This is expected. Set the iPhone SDK to allow the self-signed certificate to be used: sudo /usr/bin/sed -i.bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist If you have Xcode open, restart it for this change to take effect. Manual Deployment over WiFi The following steps require openssh, and uikittools to be installed first. Replace jasoniphone.local with the hostname of the target device. Be sure to set your own password on both the mobile and root users after installing SSH. To manually compile and install your application on the phone as a system app (bypassing Apple's installation system): Project, Set Active SDK, Device and Set Active Build Configuration, Release. Compile your project normally (using Build, not Build & Go). In the build/Release-iphoneos directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device. scp -r AccelerometerGraph.app root@jasoniphone:/Applications/ Let SpringBoard know the new application has been installed: ssh mobile@jasoniphone.local uicache This only has to be done when you add or remove applications. Updated applications just need to be relaunched. To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project. Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard: ssh root@jasoniphone.local rm -r /Applications/AccelerometerGraph.app && ssh mobile@jasoniphone.local uicache
[ "ios", "iphone" ]
201
187
110,759
9
0
2008-09-01T04:55:58.813000
2008-09-01T06:21:23.133000
37,468
37,498
How to Determine the Installed ASP.NET Version of Host from a Web Page
I have a site running in a Windows shared hosting environment. In their control panel for the shared hosting account I have it set to use ASP.NET version 3.0 but it doesn't say 3.5 SP1 specifically. How can I view the installed version running on the server where my website is hosted in an asp.net page?
Thanks! I just dropped <%=Environment.Version%> on a page and got 2.0.50727.3053
How to Determine the Installed ASP.NET Version of Host from a Web Page I have a site running in a Windows shared hosting environment. In their control panel for the shared hosting account I have it set to use ASP.NET version 3.0 but it doesn't say 3.5 SP1 specifically. How can I view the installed version running on the server where my website is hosted in an asp.net page?
TITLE: How to Determine the Installed ASP.NET Version of Host from a Web Page QUESTION: I have a site running in a Windows shared hosting environment. In their control panel for the shared hosting account I have it set to use ASP.NET version 3.0 but it doesn't say 3.5 SP1 specifically. How can I view the installed version running on the server where my website is hosted in an asp.net page? ANSWER: Thanks! I just dropped <%=Environment.Version%> on a page and got 2.0.50727.3053
[ ".net", "asp.net" ]
5
5
13,048
4
0
2008-09-01T05:05:54.440000
2008-09-01T05:41:46.990000
37,473
37,474
How can I assert() without using abort()?
If I use assert() and the assertion fails then assert() will call abort(), ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?
Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s assert() is exactly C's assert(), with the abort() "feature" bundled in. Fortunately, this is surprisingly straightforward. Assert.hh template inline void Assert(A assertion) { if(!assertion ) throw X(); } The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, terminate() will be called, which will end the program similarly to abort(). You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you Assert(). debug.hh #ifdef NDEBUG const bool CHECK_WRONG = false; #else const bool CHECK_WRONG = true; #endif main.cc #include struct Wrong { }; int main() { try { Assert (!CHECK_WRONG || 2 + 2 == 5); std::cout << "I can go to sleep now.\n"; } catch( Wrong e ) { std::cerr << "Someone is wrong on the internet!\n"; } return 0; } If CHECK_WRONG is a constant then the call to Assert() will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to CHECK_WRONG we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds. The Assert() function is equivalent to typing if(!assertion ) throw X(); but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain assert() s. For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2.
How can I assert() without using abort()? If I use assert() and the assertion fails then assert() will call abort(), ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?
TITLE: How can I assert() without using abort()? QUESTION: If I use assert() and the assertion fails then assert() will call abort(), ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully? ANSWER: Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s assert() is exactly C's assert(), with the abort() "feature" bundled in. Fortunately, this is surprisingly straightforward. Assert.hh template inline void Assert(A assertion) { if(!assertion ) throw X(); } The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, terminate() will be called, which will end the program similarly to abort(). You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you Assert(). debug.hh #ifdef NDEBUG const bool CHECK_WRONG = false; #else const bool CHECK_WRONG = true; #endif main.cc #include struct Wrong { }; int main() { try { Assert (!CHECK_WRONG || 2 + 2 == 5); std::cout << "I can go to sleep now.\n"; } catch( Wrong e ) { std::cerr << "Someone is wrong on the internet!\n"; } return 0; } If CHECK_WRONG is a constant then the call to Assert() will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to CHECK_WRONG we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds. The Assert() function is equivalent to typing if(!assertion ) throw X(); but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain assert() s. For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2.
[ "c++", "exception", "assert" ]
27
29
26,159
6
0
2008-09-01T05:15:05.790000
2008-09-01T05:15:18.800000
37,479
37,571
How can I simply inherit methods from an existing instance?
Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name. import cgi class ClassX(object): pass #... with own __repr__ class ClassY(object): pass #... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join((" "," ")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() Output: Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters Is what I'm trying to do possible? If so, what am I doing wrong?
Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way. Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like bool, but it will for your user-defined classes: def HTMLDecorator (obj): def html (): sep = cgi.escape (repr (obj)) return sep.join ((" ", " ")) obj.html = html return obj And here is the proxy version: class HTMLDecorator(object): def __init__ (self, wrapped): self.__wrapped = wrapped def html (self): sep = cgi.escape (repr (self.__wrapped)) return sep.join ((" ", " ")) def __getattr__ (self, name): return getattr (self.__wrapped, name) def __setattr__ (self, name, value): if not name.startswith ('_HTMLDecorator__'): setattr (self.__wrapped, name, value) return super (HTMLDecorator, self).__setattr__ (name, value) def __delattr__ (self, name): delattr (self.__wraped, name)
How can I simply inherit methods from an existing instance? Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name. import cgi class ClassX(object): pass #... with own __repr__ class ClassY(object): pass #... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join((" "," ")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() Output: Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters Is what I'm trying to do possible? If so, what am I doing wrong?
TITLE: How can I simply inherit methods from an existing instance? QUESTION: Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name. import cgi class ClassX(object): pass #... with own __repr__ class ClassY(object): pass #... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join((" "," ")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() Output: Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters Is what I'm trying to do possible? If so, what am I doing wrong? ANSWER: Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way. Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like bool, but it will for your user-defined classes: def HTMLDecorator (obj): def html (): sep = cgi.escape (repr (obj)) return sep.join ((" ", " ")) obj.html = html return obj And here is the proxy version: class HTMLDecorator(object): def __init__ (self, wrapped): self.__wrapped = wrapped def html (self): sep = cgi.escape (repr (self.__wrapped)) return sep.join ((" ", " ")) def __getattr__ (self, name): return getattr (self.__wrapped, name) def __setattr__ (self, name, value): if not name.startswith ('_HTMLDecorator__'): setattr (self.__wrapped, name, value) return super (HTMLDecorator, self).__setattr__ (name, value) def __delattr__ (self, name): delattr (self.__wraped, name)
[ "python", "oop", "inheritance", "object" ]
1
2
538
6
0
2008-09-01T05:17:35.190000
2008-09-01T07:33:45.487000
37,483
37,485
Calculate Video Duration
I suck at math. I need to figure out how to calculate a video duration with only a few examples of values. For example, a value of 70966 is displayed as 1:10 minutes. A value of 30533 displays as 30 seconds. A value of 7007 displays as 7 seconds.
Looks like the numbers are in milliseconds. So to convert to seconds, divide by 1000, then divide by 60 to find minutes etc.
Calculate Video Duration I suck at math. I need to figure out how to calculate a video duration with only a few examples of values. For example, a value of 70966 is displayed as 1:10 minutes. A value of 30533 displays as 30 seconds. A value of 7007 displays as 7 seconds.
TITLE: Calculate Video Duration QUESTION: I suck at math. I need to figure out how to calculate a video duration with only a few examples of values. For example, a value of 70966 is displayed as 1:10 minutes. A value of 30533 displays as 30 seconds. A value of 7007 displays as 7 seconds. ANSWER: Looks like the numbers are in milliseconds. So to convert to seconds, divide by 1000, then divide by 60 to find minutes etc.
[ "math", "video", "duration" ]
0
2
5,099
4
0
2008-09-01T05:20:41.330000
2008-09-01T05:23:53.490000
37,486
37,512
Filter out HTML tags and resolve entities in python
Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.
Use lxml which is the best xml/html library for python. import lxml.html t = lxml.html.fromstring("...") t.text_content() And if you just want to sanitize the html look at the lxml.html.clean module
Filter out HTML tags and resolve entities in python Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.
TITLE: Filter out HTML tags and resolve entities in python QUESTION: Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python. ANSWER: Use lxml which is the best xml/html library for python. import lxml.html t = lxml.html.fromstring("...") t.text_content() And if you just want to sanitize the html look at the lxml.html.clean module
[ "python", "html" ]
18
39
27,265
8
0
2008-09-01T05:25:01.990000
2008-09-01T06:07:01.467000
37,516
37,548
Recursion in production-quality VC++ Code
When writing production-quality VC++ code, is the use of recursion acceptable? Why or why not?
Is there a way to determine at what point I would encounter a stack overflow? Not really. A stack overflow happens when you exhaust the stack space - however... The initial stack size can be changed programatically and may default to different amounts depending on your OS/compiler/etc How much of it is already used up depends on what your app (and the libraries your app uses) has previously done - this is often impossible to predict How much of the stack each call requires depends on what you do in your function. If you only allocate say 1 integer on the stack, you may be able to recurse an enourmous amount of times, but if you are allocating a 200k buffer on the stack, not so much. The only times I've ever hit one is in an infinite loop, or using the aforementioned 200k buffer. I find it far more prefereable for my app to just crash, than for it to loop forever using 100% CPU and have to be forcefully killed (this is a right PITA on a remote server over a bad connection as windows lacks SSH) A rough guideline: Do you think your recursive function is likely to call itself more than say 10,000 times consecutively? Or are you doing something dumb like allocating 200k buffers on the stack? If yes, worry about it. If no, carry on with more important things.
Recursion in production-quality VC++ Code When writing production-quality VC++ code, is the use of recursion acceptable? Why or why not?
TITLE: Recursion in production-quality VC++ Code QUESTION: When writing production-quality VC++ code, is the use of recursion acceptable? Why or why not? ANSWER: Is there a way to determine at what point I would encounter a stack overflow? Not really. A stack overflow happens when you exhaust the stack space - however... The initial stack size can be changed programatically and may default to different amounts depending on your OS/compiler/etc How much of it is already used up depends on what your app (and the libraries your app uses) has previously done - this is often impossible to predict How much of the stack each call requires depends on what you do in your function. If you only allocate say 1 integer on the stack, you may be able to recurse an enourmous amount of times, but if you are allocating a 200k buffer on the stack, not so much. The only times I've ever hit one is in an infinite loop, or using the aforementioned 200k buffer. I find it far more prefereable for my app to just crash, than for it to loop forever using 100% CPU and have to be forcefully killed (this is a right PITA on a remote server over a bad connection as windows lacks SSH) A rough guideline: Do you think your recursive function is likely to call itself more than say 10,000 times consecutively? Or are you doing something dumb like allocating 200k buffers on the stack? If yes, worry about it. If no, carry on with more important things.
[ "visual-c++", "recursion" ]
1
6
346
5
0
2008-09-01T06:13:41.857000
2008-09-01T06:58:57.333000
37,519
37,578
Add XML Comments to class properties generated by the LINQ to SQL designer
I used the LINQ to SQL designer in Visual Studio to create an object model of a database. Now, I want to add XML comments to each generated property but I can't figure out how to do it without erasing the properties the next time the dbml file is refreshed. How can this be done?
I believe it's not possible to keep xml comments in sync with autogenerated code automatically. However, xml comments can leave in separate file (just set "XML documentation file" option on "Project properties"->"Build" tab). You can create initial version of XML documentation file and update in manually if necessary
Add XML Comments to class properties generated by the LINQ to SQL designer I used the LINQ to SQL designer in Visual Studio to create an object model of a database. Now, I want to add XML comments to each generated property but I can't figure out how to do it without erasing the properties the next time the dbml file is refreshed. How can this be done?
TITLE: Add XML Comments to class properties generated by the LINQ to SQL designer QUESTION: I used the LINQ to SQL designer in Visual Studio to create an object model of a database. Now, I want to add XML comments to each generated property but I can't figure out how to do it without erasing the properties the next time the dbml file is refreshed. How can this be done? ANSWER: I believe it's not possible to keep xml comments in sync with autogenerated code automatically. However, xml comments can leave in separate file (just set "XML documentation file" option on "Project properties"->"Build" tab). You can create initial version of XML documentation file and update in manually if necessary
[ "xml", "linq", "xml-comments" ]
9
1
1,254
2
0
2008-09-01T06:15:44.880000
2008-09-01T07:46:12.180000
37,525
37,527
What steps can I give a windows user to make a given file writeable
Imagine we have a program trying to write to a particular file, but failing. On the Windows platform, what are the possible things which might be causing the file to be un-writable, and what steps could be suggested to an end user/administrator to fix it. Please include steps which might require administrator permissions (obviously users may not be administrators, but for this question, let's assume they are (or can become) administrators. Also, I'm not really familiar with how permissions are calculated in windows. - Does the user need write access to each directory up the tree, or anything similar to that?
Some suggestions: No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator) File is locked (close any program that may have the file open, then reboot if that doesn't help) File has the read-only DOS attribute set (unset it from file Properties window, or with attrib -r; you must be the file owner or an Administrator) Edit 1: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!). Edit 2: Technically, the user does need write and execute (chdir) permissions on all directories up to the root. Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this because admins can force on these so-called "traverse checks" for certain users. Edit 3: @RobM: Yes, you should check that there is no obvious reason that the user should not have the permissions she needs but does not have. I alluded to this in a less direct way in my first edit. However, in some cases users should have write permission to a file but do not because of filesystem corruption, a misbehaving program, or a mistake on their own part.
What steps can I give a windows user to make a given file writeable Imagine we have a program trying to write to a particular file, but failing. On the Windows platform, what are the possible things which might be causing the file to be un-writable, and what steps could be suggested to an end user/administrator to fix it. Please include steps which might require administrator permissions (obviously users may not be administrators, but for this question, let's assume they are (or can become) administrators. Also, I'm not really familiar with how permissions are calculated in windows. - Does the user need write access to each directory up the tree, or anything similar to that?
TITLE: What steps can I give a windows user to make a given file writeable QUESTION: Imagine we have a program trying to write to a particular file, but failing. On the Windows platform, what are the possible things which might be causing the file to be un-writable, and what steps could be suggested to an end user/administrator to fix it. Please include steps which might require administrator permissions (obviously users may not be administrators, but for this question, let's assume they are (or can become) administrators. Also, I'm not really familiar with how permissions are calculated in windows. - Does the user need write access to each directory up the tree, or anything similar to that? ANSWER: Some suggestions: No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator) File is locked (close any program that may have the file open, then reboot if that doesn't help) File has the read-only DOS attribute set (unset it from file Properties window, or with attrib -r; you must be the file owner or an Administrator) Edit 1: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help. For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!). Edit 2: Technically, the user does need write and execute (chdir) permissions on all directories up to the root. Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this because admins can force on these so-called "traverse checks" for certain users. Edit 3: @RobM: Yes, you should check that there is no obvious reason that the user should not have the permissions she needs but does not have. I alluded to this in a less direct way in my first edit. However, in some cases users should have write permission to a file but do not because of filesystem corruption, a misbehaving program, or a mistake on their own part.
[ "windows", "filesystems" ]
2
3
228
4
0
2008-09-01T06:25:36.790000
2008-09-01T06:28:56.453000
37,529
37,784
Simple audio input API on a Mac?
I'd like to pull a stream of PCM samples from a Mac's line-in or built-in mic and do a little live analysis (the exact nature doesn't pertain to this question, but it could be an FFT every so often, or some basic statistics on the sample levels, or what have you). What's a good fit for this? Writing an AudioUnit that just passes the sound through and incidentally hands it off somewhere for analysis? Writing a JACK-aware app and figuring out how to get it to play with the JACK server? Ecasound? This is a cheesy proof-of-concept hobby project, so simplicity of API is the driving factor (followed by reasonable choice of programming language).
I think portaudio is what you need. Reading from the mike from a console app is a 10 line C file (see patests in the portaudio distrib).
Simple audio input API on a Mac? I'd like to pull a stream of PCM samples from a Mac's line-in or built-in mic and do a little live analysis (the exact nature doesn't pertain to this question, but it could be an FFT every so often, or some basic statistics on the sample levels, or what have you). What's a good fit for this? Writing an AudioUnit that just passes the sound through and incidentally hands it off somewhere for analysis? Writing a JACK-aware app and figuring out how to get it to play with the JACK server? Ecasound? This is a cheesy proof-of-concept hobby project, so simplicity of API is the driving factor (followed by reasonable choice of programming language).
TITLE: Simple audio input API on a Mac? QUESTION: I'd like to pull a stream of PCM samples from a Mac's line-in or built-in mic and do a little live analysis (the exact nature doesn't pertain to this question, but it could be an FFT every so often, or some basic statistics on the sample levels, or what have you). What's a good fit for this? Writing an AudioUnit that just passes the sound through and incidentally hands it off somewhere for analysis? Writing a JACK-aware app and figuring out how to get it to play with the JACK server? Ecasound? This is a cheesy proof-of-concept hobby project, so simplicity of API is the driving factor (followed by reasonable choice of programming language). ANSWER: I think portaudio is what you need. Reading from the mike from a console app is a 10 line C file (see patests in the portaudio distrib).
[ "macos", "audio" ]
11
5
10,653
3
0
2008-09-01T06:31:32.953000
2008-09-01T11:33:42.400000
37,535
37,553
What's the easiest way to read a FoxPro DBF file from Python?
I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too. Update: Thanks @cnu, I used Yusdi Santoso's dbf.py and it works nicely. One gotcha: The memo file name extension must be lower case, i.e..fpt, not.FPT which was how the filename came over from Windows.
You can try this recipe on Active State. There is also a DBFReader module which you can try. For support for memo fields.
What's the easiest way to read a FoxPro DBF file from Python? I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too. Update: Thanks @cnu, I used Yusdi Santoso's dbf.py and it works nicely. One gotcha: The memo file name extension must be lower case, i.e..fpt, not.FPT which was how the filename came over from Windows.
TITLE: What's the easiest way to read a FoxPro DBF file from Python? QUESTION: I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too. Update: Thanks @cnu, I used Yusdi Santoso's dbf.py and it works nicely. One gotcha: The memo file name extension must be lower case, i.e..fpt, not.FPT which was how the filename came over from Windows. ANSWER: You can try this recipe on Active State. There is also a DBFReader module which you can try. For support for memo fields.
[ "python", "foxpro", "dbf", "visual-foxpro" ]
25
8
30,334
6
0
2008-09-01T06:45:40.063000
2008-09-01T07:02:10.853000
37,538
37,539
How do I determine the size of my array in C?
How do I determine the size of my array in C? That is, the number of elements the array can hold?
Executive summary: int a[17]; size_t n = sizeof(a)/sizeof(a[0]); Full answer: To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this: int a[17]; size_t n = sizeof(a) / sizeof(int); and get the proper answer (68 / 4 = 17), but if the type of a changed you would have a nasty bug if you forgot to change the sizeof(int) as well. So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array. int a[17]; size_t n = sizeof(a) / sizeof(a[0]); Another advantage is that you can now easily parameterize the array name in a macro and get: #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) int a[17]; size_t n = NELEMS(a);
How do I determine the size of my array in C? How do I determine the size of my array in C? That is, the number of elements the array can hold?
TITLE: How do I determine the size of my array in C? QUESTION: How do I determine the size of my array in C? That is, the number of elements the array can hold? ANSWER: Executive summary: int a[17]; size_t n = sizeof(a)/sizeof(a[0]); Full answer: To determine the size of your array in bytes, you can use the sizeof operator: int a[17]; size_t n = sizeof(a); On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this: int a[17]; size_t n = sizeof(a) / sizeof(int); and get the proper answer (68 / 4 = 17), but if the type of a changed you would have a nasty bug if you forgot to change the sizeof(int) as well. So the preferred divisor is sizeof(a[0]) or the equivalent sizeof(*a), the size of the first element of the array. int a[17]; size_t n = sizeof(a) / sizeof(a[0]); Another advantage is that you can now easily parameterize the array name in a macro and get: #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) int a[17]; size_t n = NELEMS(a);
[ "arrays", "c" ]
1,401
1,703
3,256,399
25
0
2008-09-01T06:49:22.723000
2008-09-01T06:49:44.203000
37,555
37,916
Adding server-side event to extender control
I have an extender control that raises a textbox's OnTextChanged event 500ms after the user has finished typing. The problem with this is that OnTextChanged gets raised when the textbox loses focus, which causes problems (because of the postback). What I'd like to do is give the extender control its own server-side event (say, OnDelayedSubmit ) so I can handle it separately. The event will originate in the extender control's behavior script (after the 500ms delay), so putting a __doPostBack in onchanged is not an option. Can anyone shed light on how to go about this?
After plenty of reading up on extender controls and JavaScript, I've cobbled together a solution that seems to be working so far. The main trick was getting the necessary postback code from server-side to the client-side behavior script. I did this by using an ExtenderControlProperty (which is set in the control's OnPreRender function), and then eval'd in the behavior script. The rest was basic event-handling stuff. So now my extender control's.cs file looks something like this: public class DelayedSubmitExtender: ExtenderControlBase, IPostBackEventHandler { // This is where we'll give the behavior script the necessary code for the // postback event protected override void OnPreRender(EventArgs e) { string postback = Page.ClientScript.GetPostBackEventReference(this, "DelayedSubmit") + ";"; PostBackEvent = postback; } // This property matches up with a pair of get & set functions in the behavior script [ExtenderControlProperty] public string PostBackEvent { get { return GetPropertyValue ("PostBackEvent", ""); } set { SetPropertyValue ("PostBackEvent", value); } } // The event handling stuff public event EventHandler Submit; // Our event protected void OnSubmit(EventArgs e) // Called to raise the event { if (Submit!= null) { Submit(this, e); } } public void RaisePostBackEvent(string eventArgument) // From IPostBackEventHandler { if (eventArgument == "DelayedSubmit") { OnSubmit(new EventArgs()); } } } And my behavior script looks something like this: DelayedSubmitBehavior = function(element) { DelayedSubmitBehavior.initializeBase(this, [element]); this._postBackEvent = null; // Stores the script required for the postback } DelayedSubmitBehavior.prototype = { // Delayed submit code removed for brevity, but normally this would be where // initialize, dispose, and client-side event handlers would go // This is the client-side part of the PostBackEvent property get_PostBackEvent: function() { return this._postBackEvent; }, set_PostBackEvent: function(value) { this._postBackEvent = value; } // This is the client-side event handler where the postback is initiated from _onTimerTick: function(sender, eventArgs) { // The following line evaluates the string var as javascript, // which will cause the desired postback eval(this._postBackEvent); } } Now the server-side event can be handled the same way you'd handle an event on any other control.
Adding server-side event to extender control I have an extender control that raises a textbox's OnTextChanged event 500ms after the user has finished typing. The problem with this is that OnTextChanged gets raised when the textbox loses focus, which causes problems (because of the postback). What I'd like to do is give the extender control its own server-side event (say, OnDelayedSubmit ) so I can handle it separately. The event will originate in the extender control's behavior script (after the 500ms delay), so putting a __doPostBack in onchanged is not an option. Can anyone shed light on how to go about this?
TITLE: Adding server-side event to extender control QUESTION: I have an extender control that raises a textbox's OnTextChanged event 500ms after the user has finished typing. The problem with this is that OnTextChanged gets raised when the textbox loses focus, which causes problems (because of the postback). What I'd like to do is give the extender control its own server-side event (say, OnDelayedSubmit ) so I can handle it separately. The event will originate in the extender control's behavior script (after the 500ms delay), so putting a __doPostBack in onchanged is not an option. Can anyone shed light on how to go about this? ANSWER: After plenty of reading up on extender controls and JavaScript, I've cobbled together a solution that seems to be working so far. The main trick was getting the necessary postback code from server-side to the client-side behavior script. I did this by using an ExtenderControlProperty (which is set in the control's OnPreRender function), and then eval'd in the behavior script. The rest was basic event-handling stuff. So now my extender control's.cs file looks something like this: public class DelayedSubmitExtender: ExtenderControlBase, IPostBackEventHandler { // This is where we'll give the behavior script the necessary code for the // postback event protected override void OnPreRender(EventArgs e) { string postback = Page.ClientScript.GetPostBackEventReference(this, "DelayedSubmit") + ";"; PostBackEvent = postback; } // This property matches up with a pair of get & set functions in the behavior script [ExtenderControlProperty] public string PostBackEvent { get { return GetPropertyValue ("PostBackEvent", ""); } set { SetPropertyValue ("PostBackEvent", value); } } // The event handling stuff public event EventHandler Submit; // Our event protected void OnSubmit(EventArgs e) // Called to raise the event { if (Submit!= null) { Submit(this, e); } } public void RaisePostBackEvent(string eventArgument) // From IPostBackEventHandler { if (eventArgument == "DelayedSubmit") { OnSubmit(new EventArgs()); } } } And my behavior script looks something like this: DelayedSubmitBehavior = function(element) { DelayedSubmitBehavior.initializeBase(this, [element]); this._postBackEvent = null; // Stores the script required for the postback } DelayedSubmitBehavior.prototype = { // Delayed submit code removed for brevity, but normally this would be where // initialize, dispose, and client-side event handlers would go // This is the client-side part of the PostBackEvent property get_PostBackEvent: function() { return this._postBackEvent; }, set_PostBackEvent: function(value) { this._postBackEvent = value; } // This is the client-side event handler where the postback is initiated from _onTimerTick: function(sender, eventArgs) { // The following line evaluates the string var as javascript, // which will cause the desired postback eval(this._postBackEvent); } } Now the server-side event can be handled the same way you'd handle an event on any other control.
[ "asp.net", ".net-3.5" ]
5
5
1,000
1
0
2008-09-01T07:04:07.760000
2008-09-01T13:12:19.590000
37,564
5,651,141
What exactly is Appdomain recycling
I am trying to figure out what exactly is Appdomain recycling? When a aspx page is requested for the first time from a DotNet application, i understand that an appdomain for that app is created, and required assemblies are loaded into that appdomain, and the request will be served. Now, if the web.config file or the contents of the bin folder, etc are modified, the appdomain will be "recycled". My question is, at the end of the recycling process, will the appdomain be loaded with assemblies and ready to serve the next request? or a page has to be requested to trigger the assemblies to load?.
Well, I think the thread was getting smoothly to a final conclusion, but in the end, it was otherwise. I'll try to answer the question based on my understanding and leveraging what i've just read about in other web sites. First of all, I myself try to avoid the term recycle other than for Application Pools since this may render someone confused. Now, getting to process, pools and AppDomain, I see the picture as follows: An Application Pool is, in short, a region of memory that is maintained up and running by a process called W3WP.exe, aka Worker Process. Recycling an Application Pool means bringing that process down, eliminating it from memory and then originating a brand new Worker Process, with a newly assigned process ID. Regarding Application Domains, I see it as subsets of memory regions, within the aforementioned region that plays the role of a container. In other words, the process in memory, W3WP.exe in this case, is a macro memory region for applications that stores subset regions, called Application Domains. Having said that, one process in memory may store different Application Domains, one for each application that is assigned to run within a given Application Pool. When it comes to recycling, as I initially told, it's something that I myself reserve only for Application Pools. For AppDomains, I prefer using the term 'restart', in order to avoid misconception. Based on this, restarting a AppDomain means starting over a given application with the newly added settings, such as refreshing the existing configuration. That happens within the boundaries of that sub-region of memory, called AppDomain, that ultimately lies within the process associated with a respective Application Pool. Those new settings may come from files such as web.config, machine.config, global.asax, Bin directory, App_Code, and there may be others. AppDomain are isolated from each other, that makes total sense. If not so, if changes to a web.config, let's say, of application 1, requited recycle of the pool, all other applications assigned to that pool would get restarted, what was definitely not desired by Microsoft and by anyone else. Summarizing my point, Process (W3WP.exe) AppDomain 1 AppDomain 2 AppDomain 3 AppDomain n n = the number of assigned applications to the Application Pool managed by the given W3WP.exe Processes are memory regions isolated from one another AppDomains are sub-memory regions isolated from one another, within the same process Global IIS settings changes may require Application Pool recycle (killing and starting a new Worker Process, W3WP.exe) Application-wide settings changes AppDomains concerns, and they may get restarted after changes in some specific files such as the ones outline above For further information, I recommend: http://blogs.msdn.com/b/david.wang/archive/2006/03/12/thoughts-on-iis-configuration-changes-and-when-it-takes-effect.aspx What causes an application pool in IIS to recycle? http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx Regards from Brazil!
What exactly is Appdomain recycling I am trying to figure out what exactly is Appdomain recycling? When a aspx page is requested for the first time from a DotNet application, i understand that an appdomain for that app is created, and required assemblies are loaded into that appdomain, and the request will be served. Now, if the web.config file or the contents of the bin folder, etc are modified, the appdomain will be "recycled". My question is, at the end of the recycling process, will the appdomain be loaded with assemblies and ready to serve the next request? or a page has to be requested to trigger the assemblies to load?.
TITLE: What exactly is Appdomain recycling QUESTION: I am trying to figure out what exactly is Appdomain recycling? When a aspx page is requested for the first time from a DotNet application, i understand that an appdomain for that app is created, and required assemblies are loaded into that appdomain, and the request will be served. Now, if the web.config file or the contents of the bin folder, etc are modified, the appdomain will be "recycled". My question is, at the end of the recycling process, will the appdomain be loaded with assemblies and ready to serve the next request? or a page has to be requested to trigger the assemblies to load?. ANSWER: Well, I think the thread was getting smoothly to a final conclusion, but in the end, it was otherwise. I'll try to answer the question based on my understanding and leveraging what i've just read about in other web sites. First of all, I myself try to avoid the term recycle other than for Application Pools since this may render someone confused. Now, getting to process, pools and AppDomain, I see the picture as follows: An Application Pool is, in short, a region of memory that is maintained up and running by a process called W3WP.exe, aka Worker Process. Recycling an Application Pool means bringing that process down, eliminating it from memory and then originating a brand new Worker Process, with a newly assigned process ID. Regarding Application Domains, I see it as subsets of memory regions, within the aforementioned region that plays the role of a container. In other words, the process in memory, W3WP.exe in this case, is a macro memory region for applications that stores subset regions, called Application Domains. Having said that, one process in memory may store different Application Domains, one for each application that is assigned to run within a given Application Pool. When it comes to recycling, as I initially told, it's something that I myself reserve only for Application Pools. For AppDomains, I prefer using the term 'restart', in order to avoid misconception. Based on this, restarting a AppDomain means starting over a given application with the newly added settings, such as refreshing the existing configuration. That happens within the boundaries of that sub-region of memory, called AppDomain, that ultimately lies within the process associated with a respective Application Pool. Those new settings may come from files such as web.config, machine.config, global.asax, Bin directory, App_Code, and there may be others. AppDomain are isolated from each other, that makes total sense. If not so, if changes to a web.config, let's say, of application 1, requited recycle of the pool, all other applications assigned to that pool would get restarted, what was definitely not desired by Microsoft and by anyone else. Summarizing my point, Process (W3WP.exe) AppDomain 1 AppDomain 2 AppDomain 3 AppDomain n n = the number of assigned applications to the Application Pool managed by the given W3WP.exe Processes are memory regions isolated from one another AppDomains are sub-memory regions isolated from one another, within the same process Global IIS settings changes may require Application Pool recycle (killing and starting a new Worker Process, W3WP.exe) Application-wide settings changes AppDomains concerns, and they may get restarted after changes in some specific files such as the ones outline above For further information, I recommend: http://blogs.msdn.com/b/david.wang/archive/2006/03/12/thoughts-on-iis-configuration-changes-and-when-it-takes-effect.aspx What causes an application pool in IIS to recycle? http://blogs.msdn.com/b/tess/archive/2006/08/02/asp-net-case-study-lost-session-variables-and-appdomain-recycles.aspx Regards from Brazil!
[ "asp.net" ]
46
69
33,363
4
0
2008-09-01T07:24:22.857000
2011-04-13T14:46:51.173000
37,568
37,641
find duplicate addresses in database, stop users entering them early?
How do I find duplicate addresses in a database, or better stop people already when filling in the form? I guess the earlier the better? Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: Quellenstrasse 66/11 Quellenstr. 66a-11 I'm talking German addresses... Thanks!
Johannes: @PConroy: This was my initial thougt also. the interesting part on this is to find good transformation rules for the different parts of the address! Any good suggestions? When we were working on this type of project before, our approach was to take our existing corpus of addresses (150k or so), then apply the most common transformations for our domain (Ireland, so "Dr"->"Drive", "Rd"->"Road", etc). I'm afraid there was no comprehensive online resource for such things at the time, so we ended up basically coming up with a list ourselves, checking things like the phone book (pressed for space there, addresses are abbreviated in all manner of ways!). As I mentioned earlier, you'd be amazed how many "duplicates" you'll detect with the addition of only a few common rules! I've recently stumbled across a page with a fairly comprehensive list of address abbreviations, although it's american english, so I'm not sure how useful it'd be in Germany! A quick google turned up a couple of sites, but they seemed like spammy newsletter sign-up traps. Although that was me googling in english, so you may have more look with "german address abbreviations" in german:)
find duplicate addresses in database, stop users entering them early? How do I find duplicate addresses in a database, or better stop people already when filling in the form? I guess the earlier the better? Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: Quellenstrasse 66/11 Quellenstr. 66a-11 I'm talking German addresses... Thanks!
TITLE: find duplicate addresses in database, stop users entering them early? QUESTION: How do I find duplicate addresses in a database, or better stop people already when filling in the form? I guess the earlier the better? Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: Quellenstrasse 66/11 Quellenstr. 66a-11 I'm talking German addresses... Thanks! ANSWER: Johannes: @PConroy: This was my initial thougt also. the interesting part on this is to find good transformation rules for the different parts of the address! Any good suggestions? When we were working on this type of project before, our approach was to take our existing corpus of addresses (150k or so), then apply the most common transformations for our domain (Ireland, so "Dr"->"Drive", "Rd"->"Road", etc). I'm afraid there was no comprehensive online resource for such things at the time, so we ended up basically coming up with a list ourselves, checking things like the phone book (pressed for space there, addresses are abbreviated in all manner of ways!). As I mentioned earlier, you'd be amazed how many "duplicates" you'll detect with the addition of only a few common rules! I've recently stumbled across a page with a fairly comprehensive list of address abbreviations, although it's american english, so I'm not sure how useful it'd be in Germany! A quick google turned up a couple of sites, but they seemed like spammy newsletter sign-up traps. Although that was me googling in english, so you may have more look with "german address abbreviations" in german:)
[ "database", "sanitization", "street-address" ]
17
4
6,719
15
0
2008-09-01T07:30:48.367000
2008-09-01T09:05:24.770000
37,573
38,104
Integrating InstantRails with Aptana or any other IDE
So I've been using InstantRails to check out Ruby on rails. I've been using Notepad++ for the editing. Now I don't want to install Ruby or Rails on my machine. Is there any walk through/tutorial on how to integrate Radrails or Netbeans with InstantRails?
Here's a tutorial: http://ruby.meetup.com/73/boards/view/viewthread?thread=2203432 (I don't know if it's any good.) And here's one with InstantRails+Netbeans: https://web.archive.org/web/20100505044104/http://weblogs.java.net/blog/bleonard/archive/2007/03/instant_rails_w.html
Integrating InstantRails with Aptana or any other IDE So I've been using InstantRails to check out Ruby on rails. I've been using Notepad++ for the editing. Now I don't want to install Ruby or Rails on my machine. Is there any walk through/tutorial on how to integrate Radrails or Netbeans with InstantRails?
TITLE: Integrating InstantRails with Aptana or any other IDE QUESTION: So I've been using InstantRails to check out Ruby on rails. I've been using Notepad++ for the editing. Now I don't want to install Ruby or Rails on my machine. Is there any walk through/tutorial on how to integrate Radrails or Netbeans with InstantRails? ANSWER: Here's a tutorial: http://ruby.meetup.com/73/boards/view/viewthread?thread=2203432 (I don't know if it's any good.) And here's one with InstantRails+Netbeans: https://web.archive.org/web/20100505044104/http://weblogs.java.net/blog/bleonard/archive/2007/03/instant_rails_w.html
[ "ruby-on-rails", "ruby", "ide", "aptana", "radrails" ]
1
1
738
2
0
2008-09-01T07:41:10.603000
2008-09-01T16:18:02.123000
37,579
390,982
Queue alternatives to MSMQ on Windows?
If you want to use a queuing product for durable messaging under Windows, running.NET 2.0 and above, which alternatives to MSMQ exist today? I know of ActiveMQ ( http://activemq.apache.org/ ), and I've seen references to WSMQ (pointing to http://wsmq.net ), but the site seems to be down. Are there any other alternatives?
I can't begin to say enough good things about Tibco EMS - an implementation of the Java JMS messaging spec. Tibco EMS has superb support for.NET clients - including Compact Framework.NET on WinCE. (They also have C client libraries too.) So if you're building a heterogeneous distributed application involving messaging code running on Windows, Unix (AIX/Solaris), Linux, or Mac OS X, then Tibco EMS is the ticket. Check out my article here: Using JMS For Distributed Software Development I used to work at Microsoft and did some implementation with MSMQ while there. But you know, Microsoft just concerns itself with Windows. They depended on 3rd parties to provide MSMQ clients to other platforms. My encounter with Tibco EMS was a much better experience. It was very evident that Tibco understood messaging much more so than Microsoft. And Tibco put the effort into supporting diverse client bindings themselves. That is why they eventually changed the product name from Tibco JMS to Tibco EMS (Enterprise Messaging Service). And I did build heterogeneous software systems around Tibco EMS. Rolled C#.NET Winform clients interacting with Java/JBoss middle-tier via Tibco EMS messaging. (And also have WinCE industrial embedded computers that use the Compact Framework.NET Tibco client.) Links To My JMS Writings
Queue alternatives to MSMQ on Windows? If you want to use a queuing product for durable messaging under Windows, running.NET 2.0 and above, which alternatives to MSMQ exist today? I know of ActiveMQ ( http://activemq.apache.org/ ), and I've seen references to WSMQ (pointing to http://wsmq.net ), but the site seems to be down. Are there any other alternatives?
TITLE: Queue alternatives to MSMQ on Windows? QUESTION: If you want to use a queuing product for durable messaging under Windows, running.NET 2.0 and above, which alternatives to MSMQ exist today? I know of ActiveMQ ( http://activemq.apache.org/ ), and I've seen references to WSMQ (pointing to http://wsmq.net ), but the site seems to be down. Are there any other alternatives? ANSWER: I can't begin to say enough good things about Tibco EMS - an implementation of the Java JMS messaging spec. Tibco EMS has superb support for.NET clients - including Compact Framework.NET on WinCE. (They also have C client libraries too.) So if you're building a heterogeneous distributed application involving messaging code running on Windows, Unix (AIX/Solaris), Linux, or Mac OS X, then Tibco EMS is the ticket. Check out my article here: Using JMS For Distributed Software Development I used to work at Microsoft and did some implementation with MSMQ while there. But you know, Microsoft just concerns itself with Windows. They depended on 3rd parties to provide MSMQ clients to other platforms. My encounter with Tibco EMS was a much better experience. It was very evident that Tibco understood messaging much more so than Microsoft. And Tibco put the effort into supporting diverse client bindings themselves. That is why they eventually changed the product name from Tibco JMS to Tibco EMS (Enterprise Messaging Service). And I did build heterogeneous software systems around Tibco EMS. Rolled C#.NET Winform clients interacting with Java/JBoss middle-tier via Tibco EMS messaging. (And also have WinCE industrial embedded computers that use the Compact Framework.NET Tibco client.) Links To My JMS Writings
[ ".net", "msmq", "soa", "messaging" ]
33
11
25,463
8
0
2008-09-01T07:46:43.867000
2008-12-24T07:44:53.203000
37,584
46,000
InfoPath 2003 and the xs:any type
I am implementing exception handling for our BizTalk services, and have run into a fairly major stumbling block. In order to make the exception processing as generic as possible, and therefore to allow us to use it for any BizTalk application, our XML error schema includes an xs:any node, into which we can place a variety of data, depending on the actual exception. The generated XML should then be presented to a user through an InfoPath 2003 form for manual intervention before being represented back to BizTalk. The problem is that InfoPath 2003 doesn't like schemas with an xs:any node. What we'd really like to do is the show the content of the exception report in a form with all relevant parameters mapped, and the entire content of the xs:any node in a text box, since users who are able to see these messages will be conversant with XML. Unfortunately, I am unable to make InfoPath even load the schema at design time. Does anyone have any recommendation for how to achieve what we need, please?
Unfortunately, things have moved on, and we have (almost) made the decision not to use InfoPath for this requirement. It's only partially to do with the xs:any issue, but more to do with (external) audit trails, calls to custom code and web services, and a couple of other factors.
InfoPath 2003 and the xs:any type I am implementing exception handling for our BizTalk services, and have run into a fairly major stumbling block. In order to make the exception processing as generic as possible, and therefore to allow us to use it for any BizTalk application, our XML error schema includes an xs:any node, into which we can place a variety of data, depending on the actual exception. The generated XML should then be presented to a user through an InfoPath 2003 form for manual intervention before being represented back to BizTalk. The problem is that InfoPath 2003 doesn't like schemas with an xs:any node. What we'd really like to do is the show the content of the exception report in a form with all relevant parameters mapped, and the entire content of the xs:any node in a text box, since users who are able to see these messages will be conversant with XML. Unfortunately, I am unable to make InfoPath even load the schema at design time. Does anyone have any recommendation for how to achieve what we need, please?
TITLE: InfoPath 2003 and the xs:any type QUESTION: I am implementing exception handling for our BizTalk services, and have run into a fairly major stumbling block. In order to make the exception processing as generic as possible, and therefore to allow us to use it for any BizTalk application, our XML error schema includes an xs:any node, into which we can place a variety of data, depending on the actual exception. The generated XML should then be presented to a user through an InfoPath 2003 form for manual intervention before being represented back to BizTalk. The problem is that InfoPath 2003 doesn't like schemas with an xs:any node. What we'd really like to do is the show the content of the exception report in a form with all relevant parameters mapped, and the entire content of the xs:any node in a text box, since users who are able to see these messages will be conversant with XML. Unfortunately, I am unable to make InfoPath even load the schema at design time. Does anyone have any recommendation for how to achieve what we need, please? ANSWER: Unfortunately, things have moved on, and we have (almost) made the decision not to use InfoPath for this requirement. It's only partially to do with the xs:any issue, but more to do with (external) audit trails, calls to custom code and web services, and a couple of other factors.
[ "xml", "forms", "infopath" ]
4
1
292
2
0
2008-09-01T07:52:00.450000
2008-09-05T15:10:43.917000
37,586
67,977
Consuming web services from Oracle PL/SQL
Our application is interfacing with a lot of web services these days. We have our own package that someone wrote a few years back using UTL_HTTP and it generally works, but needs some hard-coding of the SOAP envelope to work with certain systems. I would like to make it more generic, but lack experience to know how many scenarios I would have to deal with. The variations are in what namespaces need to be declared and the format of the elements. We have to handle both simple calls with a few parameters and those that pass a large amount of data in an encoded string. I know that 10g has UTL_DBWS, but there are not a huge number of use-cases on-line. Is it stable and flexible enough for general use? Documentation
I have used UTL_HTTP which is simple and works. If you face a challenge with your own package, you can probably find a solution in one of the many wrapper packages around UTL_HTTP on the net (Google "consuming web services from pl/sql", leading you to e.g. http://www.oracle-base.com/articles/9i/ConsumingWebServices9i.php ) The reason nobody is using UTL_DBWS is that it is not functional in a default installed database. You need to load a ton of Java classes into the database, but the standard instructions seem to be defective - the process spews Java errors right and left and ultimately fails. It seems very few people have been willing to take the time to track down the package dependencies in order to make this approach work.
Consuming web services from Oracle PL/SQL Our application is interfacing with a lot of web services these days. We have our own package that someone wrote a few years back using UTL_HTTP and it generally works, but needs some hard-coding of the SOAP envelope to work with certain systems. I would like to make it more generic, but lack experience to know how many scenarios I would have to deal with. The variations are in what namespaces need to be declared and the format of the elements. We have to handle both simple calls with a few parameters and those that pass a large amount of data in an encoded string. I know that 10g has UTL_DBWS, but there are not a huge number of use-cases on-line. Is it stable and flexible enough for general use? Documentation
TITLE: Consuming web services from Oracle PL/SQL QUESTION: Our application is interfacing with a lot of web services these days. We have our own package that someone wrote a few years back using UTL_HTTP and it generally works, but needs some hard-coding of the SOAP envelope to work with certain systems. I would like to make it more generic, but lack experience to know how many scenarios I would have to deal with. The variations are in what namespaces need to be declared and the format of the elements. We have to handle both simple calls with a few parameters and those that pass a large amount of data in an encoded string. I know that 10g has UTL_DBWS, but there are not a huge number of use-cases on-line. Is it stable and flexible enough for general use? Documentation ANSWER: I have used UTL_HTTP which is simple and works. If you face a challenge with your own package, you can probably find a solution in one of the many wrapper packages around UTL_HTTP on the net (Google "consuming web services from pl/sql", leading you to e.g. http://www.oracle-base.com/articles/9i/ConsumingWebServices9i.php ) The reason nobody is using UTL_DBWS is that it is not functional in a default installed database. You need to load a ton of Java classes into the database, but the standard instructions seem to be defective - the process spews Java errors right and left and ultimately fails. It seems very few people have been willing to take the time to track down the package dependencies in order to make this approach work.
[ "sql", "oracle", "web-services", "plsql" ]
10
6
15,893
4
0
2008-09-01T07:54:44.610000
2008-09-15T23:38:17.513000
37,591
37,631
Displaying XML data in a Winforms control
I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job. The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of: I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a Name: string format. Any suggestions or am I looking and a custom implementation? [EDIT] A section of the data that needs to be displayed:
You can transform your XML data using XSLT Another option is to use XLinq. If you want concrete code example provide us with sample data EDIT: here is a sample XSLT transform for your XML file: Server variables:: Query string items:: You can apply this transform using XslCompiledTransform class. It should give output like this: Server variables: ALL_HTTP:HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible MSIE 6.0; Windows NT 5.1; SV1) AUTH_TYPE: HTTPS:off HTTPS_KEYSIZE: HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;S ) Query string items: tid:196
Displaying XML data in a Winforms control I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job. The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of: I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a Name: string format. Any suggestions or am I looking and a custom implementation? [EDIT] A section of the data that needs to be displayed:
TITLE: Displaying XML data in a Winforms control QUESTION: I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job. The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of: I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a Name: string format. Any suggestions or am I looking and a custom implementation? [EDIT] A section of the data that needs to be displayed: ANSWER: You can transform your XML data using XSLT Another option is to use XLinq. If you want concrete code example provide us with sample data EDIT: here is a sample XSLT transform for your XML file: Server variables:: Query string items:: You can apply this transform using XslCompiledTransform class. It should give output like this: Server variables: ALL_HTTP:HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible MSIE 6.0; Windows NT 5.1; SV1) AUTH_TYPE: HTTPS:off HTTPS_KEYSIZE: HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;S ) Query string items: tid:196
[ "c#", "xml", "winforms", "formatting" ]
3
1
3,947
4
0
2008-09-01T08:03:52.047000
2008-09-01T08:42:23.827000
37,593
37,596
Where can I get free Vista style developer graphics?
What is the best source of free Vista style graphics for application development? I want 32x32 and 16x16 that I can use in a Winforms application.
If you're using Visual Studio Professional or above, you've got a zip file of icons in your VS path under Common7\VS2008ImageLibrary. Some of the images use the Vista style.
Where can I get free Vista style developer graphics? What is the best source of free Vista style graphics for application development? I want 32x32 and 16x16 that I can use in a Winforms application.
TITLE: Where can I get free Vista style developer graphics? QUESTION: What is the best source of free Vista style graphics for application development? I want 32x32 and 16x16 that I can use in a Winforms application. ANSWER: If you're using Visual Studio Professional or above, you've got a zip file of icons in your VS path under Common7\VS2008ImageLibrary. Some of the images use the Vista style.
[ "winforms", "graphics" ]
1
3
297
3
0
2008-09-01T08:04:39.937000
2008-09-01T08:07:11.477000
37,597
37,609
Why does TreeNodeCollection not implenent IEnumerable<TreeNode>?
TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics?
Yes, there are many.NET Framework collection, that does not implement generic IEnumerable. I think that's because after 2.0 there was no (at least not so match) development of the core part of FW. Meanwhile I suggest you to make use of following workaround: using System.Linq;... var nodes = GetTreeNodeCollection().OfType ();
Why does TreeNodeCollection not implenent IEnumerable<TreeNode>? TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics?
TITLE: Why does TreeNodeCollection not implenent IEnumerable<TreeNode>? QUESTION: TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics? ANSWER: Yes, there are many.NET Framework collection, that does not implement generic IEnumerable. I think that's because after 2.0 there was no (at least not so match) development of the core part of FW. Meanwhile I suggest you to make use of following workaround: using System.Linq;... var nodes = GetTreeNodeCollection().OfType ();
[ ".net", "winforms" ]
5
7
995
2
0
2008-09-01T08:08:16.527000
2008-09-01T08:17:21.467000
37,614
37,626
Connecting Team Explorer to Codeplex anonymously
I was using Codeplex and tried connecting to their source control using Team Explorer, with no joy. I also tried connecting with HTTPS or HTTP, using the server name and the project name. As I do not have a user account on Codeplex I could not login. I am just trying to check out some code without changing it. My question is: How can I connect Team Explorer to a Codeplex server anonymously?
I think you have to use the CodePlex Source Control Client. In includes cpc.exe which supports the anonymous access features of CodePlex TFS servers for non-coordinator/developer access. But according to the site: The CodePlex Client is not currently being maintained. The focus of the CodePlex team now is on the SvnBridge. I'm using TortoiseSVN with SvnBridge with no problems.
Connecting Team Explorer to Codeplex anonymously I was using Codeplex and tried connecting to their source control using Team Explorer, with no joy. I also tried connecting with HTTPS or HTTP, using the server name and the project name. As I do not have a user account on Codeplex I could not login. I am just trying to check out some code without changing it. My question is: How can I connect Team Explorer to a Codeplex server anonymously?
TITLE: Connecting Team Explorer to Codeplex anonymously QUESTION: I was using Codeplex and tried connecting to their source control using Team Explorer, with no joy. I also tried connecting with HTTPS or HTTP, using the server name and the project name. As I do not have a user account on Codeplex I could not login. I am just trying to check out some code without changing it. My question is: How can I connect Team Explorer to a Codeplex server anonymously? ANSWER: I think you have to use the CodePlex Source Control Client. In includes cpc.exe which supports the anonymous access features of CodePlex TFS servers for non-coordinator/developer access. But according to the site: The CodePlex Client is not currently being maintained. The focus of the CodePlex team now is on the SvnBridge. I'm using TortoiseSVN with SvnBridge with no problems.
[ "version-control", "tfs", "codeplex" ]
1
2
539
4
0
2008-09-01T08:23:52.013000
2008-09-01T08:36:47.800000
37,628
37,632
What is reflection and why is it useful?
What is reflection, and why is it useful? I'm particularly interested in Java, but I assume the principles are the same in any language.
The name reflection is used to describe code which is able to inspect other code in the same system (or itself). For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to. So, to give you a code example of this in Java (imagine the object in question is foo): Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test. There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common. Update from a comment: The ability to inspect the code in the system and see object types is not reflection, but rather Type Introspection. Reflection is then the ability to make modifications at runtime by making use of introspection. The distinction is necessary here as some languages support introspection, but do not support reflection. One such example is C++
What is reflection and why is it useful? What is reflection, and why is it useful? I'm particularly interested in Java, but I assume the principles are the same in any language.
TITLE: What is reflection and why is it useful? QUESTION: What is reflection, and why is it useful? I'm particularly interested in Java, but I assume the principles are the same in any language. ANSWER: The name reflection is used to describe code which is able to inspect other code in the same system (or itself). For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to. So, to give you a code example of this in Java (imagine the object in question is foo): Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test. There are some good reflection examples to get you started at http://docs.oracle.com/javase/tutorial/reflect/index.html And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common. Update from a comment: The ability to inspect the code in the system and see object types is not reflection, but rather Type Introspection. Reflection is then the ability to make modifications at runtime by making use of introspection. The distinction is necessary here as some languages support introspection, but do not support reflection. One such example is C++
[ "java", "reflection", "terminology" ]
2,546
2,016
1,037,611
25
0
2008-09-01T08:39:21.633000
2008-09-01T08:44:58.657000
37,644
37,655
Examining Berkeley DB files from the CLI
I have a set of Berkeley DB files on my Linux file system that I'd like to examine. What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts.
Check out the db-utils package. If you use apt, you can install it with the following: apt-get install db-util (or apt-get install db4.8-util or whatever version you have or prefer.) Additional links: http://rpmfind.net/linux/rpm2html/search.php?query=db-utils https://packages.ubuntu.com/search?suite=default&section=all&arch=any&keywords=db-util&searchon=names Man page of db4.4_dump
Examining Berkeley DB files from the CLI I have a set of Berkeley DB files on my Linux file system that I'd like to examine. What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts.
TITLE: Examining Berkeley DB files from the CLI QUESTION: I have a set of Berkeley DB files on my Linux file system that I'd like to examine. What useful tools exist for getting a quick overview of the contents? I can write Perl scripts that use BDB modules for examining them, but I'm looking for some CLI utility to be able to take a look inside without having to start writing scripts. ANSWER: Check out the db-utils package. If you use apt, you can install it with the following: apt-get install db-util (or apt-get install db4.8-util or whatever version you have or prefer.) Additional links: http://rpmfind.net/linux/rpm2html/search.php?query=db-utils https://packages.ubuntu.com/search?suite=default&section=all&arch=any&keywords=db-util&searchon=names Man page of db4.4_dump
[ "linux", "command-line-interface", "berkeley-db" ]
63
28
75,749
9
0
2008-09-01T09:10:27.487000
2008-09-01T09:24:51.850000
37,649
559,291
Swapping column values in MySQL
I have a MySQL table with coordinates; the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that. Is this possible to do with UPDATE in some way? UPDATE table SET X=Y, Y=X obviously won't do what I want. Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.
I just had to deal with the same and I'll summarize my findings. The UPDATE table SET X=Y, Y=X approach obviously doesn't work, as it'll just set both values to Y. Here's a method that uses a temporary variable. Thanks to Antony from the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/ for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation. UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL; This method was offered by Dipin in, yet again, the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values. UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp; Another approach I came up with that seems to work: UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id; Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from. Note that this approach requires a primary key to be present. This is my test schema: CREATE TABLE `swap_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `x` varchar(255) DEFAULT NULL, `y` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; INSERT INTO `swap_test` VALUES ('1', 'a', '10'); INSERT INTO `swap_test` VALUES ('2', NULL, '20'); INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
Swapping column values in MySQL I have a MySQL table with coordinates; the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that. Is this possible to do with UPDATE in some way? UPDATE table SET X=Y, Y=X obviously won't do what I want. Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.
TITLE: Swapping column values in MySQL QUESTION: I have a MySQL table with coordinates; the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that. Is this possible to do with UPDATE in some way? UPDATE table SET X=Y, Y=X obviously won't do what I want. Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options. ANSWER: I just had to deal with the same and I'll summarize my findings. The UPDATE table SET X=Y, Y=X approach obviously doesn't work, as it'll just set both values to Y. Here's a method that uses a temporary variable. Thanks to Antony from the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/ for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation. UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL; This method was offered by Dipin in, yet again, the comments of http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values. UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp; Another approach I came up with that seems to work: UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id; Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from. Note that this approach requires a primary key to be present. This is my test schema: CREATE TABLE `swap_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `x` varchar(255) DEFAULT NULL, `y` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; INSERT INTO `swap_test` VALUES ('1', 'a', '10'); INSERT INTO `swap_test` VALUES ('2', NULL, '20'); INSERT INTO `swap_test` VALUES ('3', 'c', NULL);
[ "mysql", "database" ]
160
252
123,832
23
0
2008-09-01T09:19:56.560000
2009-02-18T00:01:51.797000
37,650
37,656
How to implement a file download in asp.net
What is the best way to implement, from a web page a download action using asp.net 2.0? Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.
Does this help: http://www.west-wind.com/weblog/posts/76293.aspx Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt"); Response.TransmitFile( Server.MapPath("~/logfile.txt") ); Response.End(); Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.
How to implement a file download in asp.net What is the best way to implement, from a web page a download action using asp.net 2.0? Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.
TITLE: How to implement a file download in asp.net QUESTION: What is the best way to implement, from a web page a download action using asp.net 2.0? Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc. ANSWER: Does this help: http://www.west-wind.com/weblog/posts/76293.aspx Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt"); Response.TransmitFile( Server.MapPath("~/logfile.txt") ); Response.End(); Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.
[ "asp.net", "file", "download" ]
25
38
74,492
2
0
2008-09-01T09:21:14.637000
2008-09-01T09:25:28.073000
37,662
38,278
Is there an n-ary tree implementation in Perl?
I'm writing a Perl script and would like to use a n-ary tree data structure. Is there a good implementation that is available as source code (rather than part of a Perl library)?
Adding to what Matthew already said, it looks like the following modules would be suitable: Tree::Nary Tree::Simple Tree
Is there an n-ary tree implementation in Perl? I'm writing a Perl script and would like to use a n-ary tree data structure. Is there a good implementation that is available as source code (rather than part of a Perl library)?
TITLE: Is there an n-ary tree implementation in Perl? QUESTION: I'm writing a Perl script and would like to use a n-ary tree data structure. Is there a good implementation that is available as source code (rather than part of a Perl library)? ANSWER: Adding to what Matthew already said, it looks like the following modules would be suitable: Tree::Nary Tree::Simple Tree
[ "perl", "algorithm", "tree" ]
1
6
6,594
3
0
2008-09-01T09:34:37.880000
2008-09-01T18:47:02.310000
37,666
37,675
What tool to use for automatic nightly builds?
I have a few Visual Studio Solutions/Projects that are being worked on in my company, which now require a scheme for automatic nightly builds. Such a scheme needs to be able to check the latest versions from SVN, build the solutions, create the appropriate downloadable files (including installers, documentation, etc.), send e-mails to the developers upon errors and all sorts of other nifty things. What tool, or tool-set, should I use for this? I used to use FinalBuilder a few years ago and I liked that a lot but I'm not sure if they support such features as nightly-builds and email messages.
At my work we use CCNET, but with builds on check-in more than nightly - although it's easily configured for either or both. You can very easily set up unit testing to run on every checkin as well, FXCop testing, and a slew of other products. I would also advise checking out Team City as an option, because it has a free version, and the reporting and setup is reportedly much simpler (it does look nice to me). It does have a limit of somewhere around 20 team members/projects, before it hits a pay-for window. That said, we started with CCNET, and have grown several products too large to look at Team City on the free version and are very happy with what we have. Features that help with CCNET include: XML based configuration - you can usually copy and paste most of what you need. More or less you'll be able to plug your treesurgeon script in as your build script, and point CCNET at that as an executable task to run the compilation. Lots of documentation and very easy to set up nunit, ncover, fxcop, etc. Taskbar app that will let you know the status of your projects at any time, and it can also fire off an email or keep an RSS feed with the same information. But I'd definitely go with running a CI build on every check-in - for the most part will run the unit tests before checking in, but let the CCNET server handle run any applications/assemblies that would have dependencies on the assembly we're checking in, and they get re-built, and re-tested on every checkin. Given that CCNET is free free and takes very little time to set up - I'd highly recommend just going for it and seeing if it suits you, then expanding from there. (There's another thread here where I posted pretty much the same/with a few alterations - but some of the other comments may help too! Automated Builds ) Edit to add: You can easily set up your own deployment scheme for CCNET, and there are a tonne of blog posts out there to assist, and email notifications can really be set up fairly granularly, either on all successes, all failures, when it changes from success to fail, etc. There's also built in RSS, and you could even set up your own notifiers for other systems.
What tool to use for automatic nightly builds? I have a few Visual Studio Solutions/Projects that are being worked on in my company, which now require a scheme for automatic nightly builds. Such a scheme needs to be able to check the latest versions from SVN, build the solutions, create the appropriate downloadable files (including installers, documentation, etc.), send e-mails to the developers upon errors and all sorts of other nifty things. What tool, or tool-set, should I use for this? I used to use FinalBuilder a few years ago and I liked that a lot but I'm not sure if they support such features as nightly-builds and email messages.
TITLE: What tool to use for automatic nightly builds? QUESTION: I have a few Visual Studio Solutions/Projects that are being worked on in my company, which now require a scheme for automatic nightly builds. Such a scheme needs to be able to check the latest versions from SVN, build the solutions, create the appropriate downloadable files (including installers, documentation, etc.), send e-mails to the developers upon errors and all sorts of other nifty things. What tool, or tool-set, should I use for this? I used to use FinalBuilder a few years ago and I liked that a lot but I'm not sure if they support such features as nightly-builds and email messages. ANSWER: At my work we use CCNET, but with builds on check-in more than nightly - although it's easily configured for either or both. You can very easily set up unit testing to run on every checkin as well, FXCop testing, and a slew of other products. I would also advise checking out Team City as an option, because it has a free version, and the reporting and setup is reportedly much simpler (it does look nice to me). It does have a limit of somewhere around 20 team members/projects, before it hits a pay-for window. That said, we started with CCNET, and have grown several products too large to look at Team City on the free version and are very happy with what we have. Features that help with CCNET include: XML based configuration - you can usually copy and paste most of what you need. More or less you'll be able to plug your treesurgeon script in as your build script, and point CCNET at that as an executable task to run the compilation. Lots of documentation and very easy to set up nunit, ncover, fxcop, etc. Taskbar app that will let you know the status of your projects at any time, and it can also fire off an email or keep an RSS feed with the same information. But I'd definitely go with running a CI build on every check-in - for the most part will run the unit tests before checking in, but let the CCNET server handle run any applications/assemblies that would have dependencies on the assembly we're checking in, and they get re-built, and re-tested on every checkin. Given that CCNET is free free and takes very little time to set up - I'd highly recommend just going for it and seeing if it suits you, then expanding from there. (There's another thread here where I posted pretty much the same/with a few alterations - but some of the other comments may help too! Automated Builds ) Edit to add: You can easily set up your own deployment scheme for CCNET, and there are a tonne of blog posts out there to assist, and email notifications can really be set up fairly granularly, either on all successes, all failures, when it changes from success to fail, etc. There's also built in RSS, and you could even set up your own notifiers for other systems.
[ "visual-studio", "build-process" ]
19
14
7,786
8
0
2008-09-01T09:41:14.777000
2008-09-01T09:50:26.143000
37,692
39,989
Eclipse Plugin Dev: How do I get the paths for the currently selected project?
I'm writing a plugin that will parse a bunch of files in a project. But for the moment I'm stuck searching through the Eclipse API for answers. The plugin works like this: Whenever I open a source file I let the plugin parse the source's corresponding build file (this could be further developed with caching the parse result). Getting the file is simple enough: public void showSelection(IWorkbenchPart sourcePart) { // Gets the currently selected file from the editor IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class); if (file!= null) { String path = file.getProjectRelativePath(); /** Snipped out: Rip out the source path part * and replace with build path * Then parse it. */ } } The problem I have is I have to use hard coded strings for the paths where the source files and build files go. Anyone know how to retrieve the build path from Eclipse? (I'm working in CDT by the way). Also is there a simple way to determine what the source path is (e.g. one file is under the "src" directory) of a source file?
You should take a look at ICProject, especially the getOutputEntries and getAllSourceRoots operations. This tutorial has some brief examples too. I work with JDT so thats pretty much what I can do. Hope it helps:)
Eclipse Plugin Dev: How do I get the paths for the currently selected project? I'm writing a plugin that will parse a bunch of files in a project. But for the moment I'm stuck searching through the Eclipse API for answers. The plugin works like this: Whenever I open a source file I let the plugin parse the source's corresponding build file (this could be further developed with caching the parse result). Getting the file is simple enough: public void showSelection(IWorkbenchPart sourcePart) { // Gets the currently selected file from the editor IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class); if (file!= null) { String path = file.getProjectRelativePath(); /** Snipped out: Rip out the source path part * and replace with build path * Then parse it. */ } } The problem I have is I have to use hard coded strings for the paths where the source files and build files go. Anyone know how to retrieve the build path from Eclipse? (I'm working in CDT by the way). Also is there a simple way to determine what the source path is (e.g. one file is under the "src" directory) of a source file?
TITLE: Eclipse Plugin Dev: How do I get the paths for the currently selected project? QUESTION: I'm writing a plugin that will parse a bunch of files in a project. But for the moment I'm stuck searching through the Eclipse API for answers. The plugin works like this: Whenever I open a source file I let the plugin parse the source's corresponding build file (this could be further developed with caching the parse result). Getting the file is simple enough: public void showSelection(IWorkbenchPart sourcePart) { // Gets the currently selected file from the editor IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class); if (file!= null) { String path = file.getProjectRelativePath(); /** Snipped out: Rip out the source path part * and replace with build path * Then parse it. */ } } The problem I have is I have to use hard coded strings for the paths where the source files and build files go. Anyone know how to retrieve the build path from Eclipse? (I'm working in CDT by the way). Also is there a simple way to determine what the source path is (e.g. one file is under the "src" directory) of a source file? ANSWER: You should take a look at ICProject, especially the getOutputEntries and getAllSourceRoots operations. This tutorial has some brief examples too. I work with JDT so thats pretty much what I can do. Hope it helps:)
[ "java", "eclipse", "eclipse-api" ]
6
1
4,065
1
0
2008-09-01T10:06:42.407000
2008-09-02T16:38:17.777000
37,696
37,761
Concatenate several fields into one with SQL
I have three tables tag, page, pagetag With the data below page ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 tag ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 pagetag ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output. ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 Is this possible with SQL? I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.
Sergio del Amo: However, I am not getting the pages without tags. I guess i need to write my query with left outer joins. SELECT pagetag.id, page.name, group_concat(tag.name) FROM ( page LEFT JOIN pagetag ON page.id = pagetag.pageid ) LEFT JOIN tag ON pagetag.tagid = tag.id GROUP BY page.id; Not a very pretty query, but should give you what you want - pagetag.id and group_concat(tag.name) will be null for page 4 in the example you've posted above, but the page shall appear in the results.
Concatenate several fields into one with SQL I have three tables tag, page, pagetag With the data below page ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 tag ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 pagetag ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output. ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 Is this possible with SQL? I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.
TITLE: Concatenate several fields into one with SQL QUESTION: I have three tables tag, page, pagetag With the data below page ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 tag ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 pagetag ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output. ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 Is this possible with SQL? I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible. ANSWER: Sergio del Amo: However, I am not getting the pages without tags. I guess i need to write my query with left outer joins. SELECT pagetag.id, page.name, group_concat(tag.name) FROM ( page LEFT JOIN pagetag ON page.id = pagetag.pageid ) LEFT JOIN tag ON pagetag.tagid = tag.id GROUP BY page.id; Not a very pretty query, but should give you what you want - pagetag.id and group_concat(tag.name) will be null for page 4 in the example you've posted above, but the page shall appear in the results.
[ "sql", "mysql" ]
5
3
6,039
6
0
2008-09-01T10:16:45.003000
2008-09-01T11:17:34.483000
37,702
37,707
True random number generator
Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it. Does anybody know about that article?
I believe that was on thedailywtf.com - ie. not something that you want to do. It is not possible to get a truly random number from pseudorandom numbers, no matter how many times you call randomize(). You can get "true" random numbers from special hardware. You could also collect entropy from mouse movements and things like that.
True random number generator Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it. Does anybody know about that article?
TITLE: True random number generator QUESTION: Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it. Does anybody know about that article? ANSWER: I believe that was on thedailywtf.com - ie. not something that you want to do. It is not possible to get a truly random number from pseudorandom numbers, no matter how many times you call randomize(). You can get "true" random numbers from special hardware. You could also collect entropy from mouse movements and things like that.
[ "algorithm", "language-agnostic", "random", "prng" ]
25
17
25,265
11
0
2008-09-01T10:25:46.090000
2008-09-01T10:30:54.780000
37,731
37,768
To use views or not to use views
I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this: $draw = new Draw; $nav = $draw->wideHeaderBox(). $draw->left(). $draw->image(). Image::get($image,60,array('id'=>'header_image')). $draw->imageEnd(). $draw->leftEnd(). $draw->left(10). ' '. self::defaultSectionText(). ' '. $draw->leftEnd(). and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.
HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a new Draw just doesn't sound very natural. Furthermore, wideHeaderBox and left will only have significance to someone who intimately knows the system. And what if there is a redesign, like your co-worker muses? What if the wideHeaderBox becomes very narrow? Will you change the markup (and styles, presumable) generated by the PHP method but leave a very inaccurate method name to call the code? If you guys just have to use HTML generation, you should use it interspersed in view files, and you should use it where it's really necessary/useful, such as something like this: HTML::link("Wikipedia", "http://en.wikipedia.org"); HTML::bulleted_list(array( HTML::list_item("Dogs"), HTML::list_item("Cats"), HTML::list_item("Armadillos") )); In the above example, the method names actually make sense to people who aren't familiar with your system. They'll also make more sense to you guys when you go back into a seldom-visited file and wonder what the heck you were doing.
To use views or not to use views I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this: $draw = new Draw; $nav = $draw->wideHeaderBox(). $draw->left(). $draw->image(). Image::get($image,60,array('id'=>'header_image')). $draw->imageEnd(). $draw->leftEnd(). $draw->left(10). ' '. self::defaultSectionText(). ' '. $draw->leftEnd(). and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand.
TITLE: To use views or not to use views QUESTION: I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits. He proposes a system that PHP looks something like this: $draw = new Draw; $nav = $draw->wideHeaderBox(). $draw->left(). $draw->image(). Image::get($image,60,array('id'=>'header_image')). $draw->imageEnd(). $draw->leftEnd(). $draw->left(10). ' '. self::defaultSectionText(). ' '. $draw->leftEnd(). and so on (this is in the controller btw). Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method? I mean besides not having to retype HTML by hand. ANSWER: HTML time-savers are useful, but they're only useful when they're intuitive and easy-to-understand. Having to instantiate a new Draw just doesn't sound very natural. Furthermore, wideHeaderBox and left will only have significance to someone who intimately knows the system. And what if there is a redesign, like your co-worker muses? What if the wideHeaderBox becomes very narrow? Will you change the markup (and styles, presumable) generated by the PHP method but leave a very inaccurate method name to call the code? If you guys just have to use HTML generation, you should use it interspersed in view files, and you should use it where it's really necessary/useful, such as something like this: HTML::link("Wikipedia", "http://en.wikipedia.org"); HTML::bulleted_list(array( HTML::list_item("Dogs"), HTML::list_item("Cats"), HTML::list_item("Armadillos") )); In the above example, the method names actually make sense to people who aren't familiar with your system. They'll also make more sense to you guys when you go back into a seldom-visited file and wonder what the heck you were doing.
[ "php", "model-view-controller" ]
5
5
440
5
0
2008-09-01T10:55:18
2008-09-01T11:23:44.920000
37,732
37,767
What is the regex pattern for datetime (2008-09-01 12:35:45 )?
What is the RegEx pattern for DateTime (2008-09-01 12:35:45 )? I get this error: No ending delimiter '^' found Using: preg_match('(?n:^(?=\d)((? 31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(? [/.-])(? 0?[1-9]|1[012])\2(? (1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(? ((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); Gives this error: Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19
@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed. It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed: (\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) If you're using perl, then you can get the values out with something like this: $year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.
What is the regex pattern for datetime (2008-09-01 12:35:45 )? What is the RegEx pattern for DateTime (2008-09-01 12:35:45 )? I get this error: No ending delimiter '^' found Using: preg_match('(?n:^(?=\d)((? 31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(? [/.-])(? 0?[1-9]|1[012])\2(? (1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(? ((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); Gives this error: Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19
TITLE: What is the regex pattern for datetime (2008-09-01 12:35:45 )? QUESTION: What is the RegEx pattern for DateTime (2008-09-01 12:35:45 )? I get this error: No ending delimiter '^' found Using: preg_match('(?n:^(?=\d)((? 31(?!(.0?[2469]|11))|30(?!.0?2)|29(?(.0?2)(?=.{3,4}(1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(16|[2468][048]|[3579][26])00))|0?[1-9]|1\d|2[0-8])(? [/.-])(? 0?[1-9]|1[012])\2(? (1[6-9]|[2-9]\d)\d{2})(?:(?=\x20\d)\x20|$))?(? ((0?[1-9]|1[012])(:[0-5]\d){0,2}(?i:\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$)', '2008-09-01 12:35:45'); Gives this error: Warning: preg_match() [function.preg-match]: Compilation failed: nothing to repeat at offset 0 in E:\www\index.php on line 19 ANSWER: @Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed. It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed: (\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2}) If you're using perl, then you can get the values out with something like this: $year = $1; $month = $2; $day = $3; $hour = $4; $minute = $5; $second = $6; Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.
[ "php", "regex", "datetime" ]
71
91
185,336
14
0
2008-09-01T10:58:24.607000
2008-09-01T11:23:07.433000
37,743
37,750
SQL query to get the top "n" scores out of a list
I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. I'm making an example to clarify. Let's say that this is the Users table, with the points earned: UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 6 - 25 If I want the top 3 scores, the result will be: UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.
Untested, but should work: select * from users where points in (select distinct top 3 points from users order by points desc)
SQL query to get the top "n" scores out of a list I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. I'm making an example to clarify. Let's say that this is the Users table, with the points earned: UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 6 - 25 If I want the top 3 scores, the result will be: UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.
TITLE: SQL query to get the top "n" scores out of a list QUESTION: I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores. I'm making an example to clarify. Let's say that this is the Users table, with the points earned: UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 6 - 25 If I want the top 3 scores, the result will be: UserId - Points 1 - 100 2 - 75 3 - 50 4 - 50 5 - 50 This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine. ANSWER: Untested, but should work: select * from users where points in (select distinct top 3 points from users order by points desc)
[ "sql", "sql-server", "puzzle" ]
7
11
24,223
11
0
2008-09-01T11:03:34.907000
2008-09-01T11:07:41.993000
37,759
37,762
How do you prevent the IIS default site web.config file being inherited by virtual directories?
I have the following code in a web.config file of the default IIS site. Then when I setup and browse to a virtual directory I get this error Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified. The virtual directory is inheriting the modules from the default web.config. How do you stop this inheritance?
I've found the answer. Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to false. Now any virtual directories will not inherit the settings in this location section. @GateKiller This isn't another website, its a virtual directory so inheritance does occur. @petrich I've had hit and miss results using. I have to remember to add it to every virtual directory which is a pain.
How do you prevent the IIS default site web.config file being inherited by virtual directories? I have the following code in a web.config file of the default IIS site. Then when I setup and browse to a virtual directory I get this error Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified. The virtual directory is inheriting the modules from the default web.config. How do you stop this inheritance?
TITLE: How do you prevent the IIS default site web.config file being inherited by virtual directories? QUESTION: I have the following code in a web.config file of the default IIS site. Then when I setup and browse to a virtual directory I get this error Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified. The virtual directory is inheriting the modules from the default web.config. How do you stop this inheritance? ANSWER: I've found the answer. Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to false. Now any virtual directories will not inherit the settings in this location section. @GateKiller This isn't another website, its a virtual directory so inheritance does occur. @petrich I've had hit and miss results using. I have to remember to add it to every virtual directory which is a pain.
[ ".net", "asp.net", "configuration", "configuration-files" ]
17
20
7,761
3
0
2008-09-01T11:15:11.557000
2008-09-01T11:19:03.607000
37,783
83,332
Are there any guidelines for designing user interface for mobile devices?
I am creating an application for a Windows Mobile computer. The catch is that the device ( Motorola MC17 ) does not have a touch screen or universal keys - there are only six programmable hardware keys. Fitt's law is not applicable here, most Microsoft guidelines are also moot. For now I'm mimicking Nokia's S60 keyboard layout as close as possible, since it's the most popular phone platform among my target audience. Are there any guidelines for creating a simple, discoverable user interface on such a constrained device? What fonts and colours should I use to make my UI readable? How do I measure if the items on-screen are big enough? What conventions should I follow?
Microsoft has an official set of Guidelines for getting the "Designed for Windows Mobile" logo. These are a reasonable start as they not only cover one-handed (no touchscreen) operation, they also help your app to maintain familiarity for users. Some other resources discussing the topic: The WinMo team blog entry on one-handed navigation Mark Arteaga's article on stylus-free apps
Are there any guidelines for designing user interface for mobile devices? I am creating an application for a Windows Mobile computer. The catch is that the device ( Motorola MC17 ) does not have a touch screen or universal keys - there are only six programmable hardware keys. Fitt's law is not applicable here, most Microsoft guidelines are also moot. For now I'm mimicking Nokia's S60 keyboard layout as close as possible, since it's the most popular phone platform among my target audience. Are there any guidelines for creating a simple, discoverable user interface on such a constrained device? What fonts and colours should I use to make my UI readable? How do I measure if the items on-screen are big enough? What conventions should I follow?
TITLE: Are there any guidelines for designing user interface for mobile devices? QUESTION: I am creating an application for a Windows Mobile computer. The catch is that the device ( Motorola MC17 ) does not have a touch screen or universal keys - there are only six programmable hardware keys. Fitt's law is not applicable here, most Microsoft guidelines are also moot. For now I'm mimicking Nokia's S60 keyboard layout as close as possible, since it's the most popular phone platform among my target audience. Are there any guidelines for creating a simple, discoverable user interface on such a constrained device? What fonts and colours should I use to make my UI readable? How do I measure if the items on-screen are big enough? What conventions should I follow? ANSWER: Microsoft has an official set of Guidelines for getting the "Designed for Windows Mobile" logo. These are a reasonable start as they not only cover one-handed (no touchscreen) operation, they also help your app to maintain familiarity for users. Some other resources discussing the topic: The WinMo team blog entry on one-handed navigation Mark Arteaga's article on stylus-free apps
[ "user-interface", "windows-mobile", "usability" ]
2
3
1,583
2
0
2008-09-01T11:33:31.120000
2008-09-17T13:41:18.183000
37,785
38,825
Can a fixture be changed dynamically between test methods in CakePHP?
Is it possible to have a fixture change between test methods? If so, how can I do this? My syntax for this problem: In the cakephp framework i am building tests for a behavior that is configured by adding fields to the table. This is intended to work in the same way that adding the "created" and "modified" fields will auto-populate these fields on save. To test this I could create dozens of fixtures/model combos to test the different setups, but it would be a hundred times better, faster and easier to just have the fixture change "shape" between test methods. If you are not familiar with the CakePHP framework, you can maybe still help me as it uses SimpleTest Edit: rephrased question to be more general
I'm not familiar specifically with CakePHP, but this kind of thing seems to happen anywhere with fixtures. There is no built in way in rails at least for this to happen, and I imagine not in cakePHP or anywhere else either because the whole idea of a fixture, is that it is fixed There are 2 'decent' workarounds I'm aware of Write a changefixture method, and just before you do your asserts/etc, run it with the parameters of what to change. It should go and update the database or whatever needs to be done. Don't use fixtures at all, and use some kind of object factory or object generator to create your objects each time
Can a fixture be changed dynamically between test methods in CakePHP? Is it possible to have a fixture change between test methods? If so, how can I do this? My syntax for this problem: In the cakephp framework i am building tests for a behavior that is configured by adding fields to the table. This is intended to work in the same way that adding the "created" and "modified" fields will auto-populate these fields on save. To test this I could create dozens of fixtures/model combos to test the different setups, but it would be a hundred times better, faster and easier to just have the fixture change "shape" between test methods. If you are not familiar with the CakePHP framework, you can maybe still help me as it uses SimpleTest Edit: rephrased question to be more general
TITLE: Can a fixture be changed dynamically between test methods in CakePHP? QUESTION: Is it possible to have a fixture change between test methods? If so, how can I do this? My syntax for this problem: In the cakephp framework i am building tests for a behavior that is configured by adding fields to the table. This is intended to work in the same way that adding the "created" and "modified" fields will auto-populate these fields on save. To test this I could create dozens of fixtures/model combos to test the different setups, but it would be a hundred times better, faster and easier to just have the fixture change "shape" between test methods. If you are not familiar with the CakePHP framework, you can maybe still help me as it uses SimpleTest Edit: rephrased question to be more general ANSWER: I'm not familiar specifically with CakePHP, but this kind of thing seems to happen anywhere with fixtures. There is no built in way in rails at least for this to happen, and I imagine not in cakePHP or anywhere else either because the whole idea of a fixture, is that it is fixed There are 2 'decent' workarounds I'm aware of Write a changefixture method, and just before you do your asserts/etc, run it with the parameters of what to change. It should go and update the database or whatever needs to be done. Don't use fixtures at all, and use some kind of object factory or object generator to create your objects each time
[ "unit-testing", "cakephp", "fixture" ]
2
0
1,120
2
0
2008-09-01T11:33:49.343000
2008-09-02T04:38:23.357000
37,791
89,454
How do you manage SQL Queries
At the moment my code (PHP) has too many SQL queries in it. eg... // not a real example, but you get the idea... $results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid"); if ($results) { // Do something } I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns.. I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?
The best course of action for you will depend on how you are approaching your data access. There are three approaches you can take: Use stored procedures Keep the queries in the code (but put all your queries into functions and fix everything to use PDO for parameters, as mentioned earlier) Use an ORM tool If you want to pass your own raw SQL to the database engine then stored procedures would be the way to go if all you want to do is get the raw SQL out of your PHP code but keep it relatively unchanged. The stored procedures vs raw SQL debate is a bit of a holy war, but K. Scott Allen makes an excellent point - albeit a throwaway one - in an article about versioning databases: Secondly, stored procedures have fallen out of favor in my eyes. I came from the WinDNA school of indoctrination that said stored procedures should be used all the time. Today, I see stored procedures as an API layer for the database. This is good if you need an API layer at the database level, but I see lots of applications incurring the overhead of creating and maintaining an extra API layer they don't need. In those applications stored procedures are more of a burden than a benefit. I tend to lean towards not using stored procedures. I've worked on projects where the DB has an API exposed through stored procedures, but stored procedures can impose some limitations of their own, and those projects have all, to varying degrees, used dynamically generated raw SQL in code to access the DB. Having an API layer on the DB gives better delineation of responsibilities between the DB team and the Dev team at the expense of some of the flexibility you'd have if the query was kept in the code, however PHP projects are less likely to have sizable enough teams to benefit from this delineation. Conceptually, you should probably have your database versioned. Practically speaking, however, you're far more likely to have just your code versioned than you are to have your database versioned. You are likely to be changing your queries when you are making changes to your code, but if you are changing the queries in stored procedures stored against the database then you probably won't be checking those in when you check the code in and you lose many of the benefits of versioning for a significant area of your application. Regardless of whether or not you elect not to use stored procedures though, you should at the very least ensure that each database operation is stored in an independent function rather than being embedded into each of your page's scripts - essentially an API layer for your DB which is maintained and versioned with your code. If you're using stored procedures, this will effectively mean you have two API layers for your DB, one with the code and one with the DB, which you may feel unnecessarily complicates things if your project does not have separate teams. I certainly do. If the issue is one of code neatness, there are ways to make code with SQL jammed in it more presentable, and the UserManager class shown below is a good way to start - the class only contains queries which relate to the 'user' table, each query has its own method in the class and the queries are indented into the prepare statements and formatted as you would format them in a stored procedure. // UserManager.php: class UserManager { function getUsers() { $pdo = new PDO(...); $stmt = $pdo->prepare(' SELECT u.userId as id, u.userName, g.groupId, g.groupName FROM user u INNER JOIN group g ON u.groupId = g.groupId ORDER BY u.userName, g.groupName '); // iterate over result and prepare return value } function getUser($id) { // db code here } } // index.php: require_once("UserManager.php"); $um = new UserManager; $users = $um->getUsers(); foreach ($users as $user) echo $user['name']; However, if your queries are quite similar but you have huge numbers of permutations in your query conditions like complicated paging, sorting, filtering, etc, an Object/Relational mapper tool is probably the way to go, although the process of overhauling your existing code to make use of the tool could be quite complicated. If you decide to investigate ORM tools, you should look at Propel, the ActiveRecord component of Yii, or the king-daddy PHP ORM, Doctrine. Each of these gives you the ability to programmatically build queries to your database with all manner of complicated logic. Doctrine is the most fully featured, allowing you to template your database with things like the Nested Set tree pattern out of the box. In terms of performance, stored procedures are the fastest, but generally not by much over raw sql. ORM tools can have a significant performance impact in a number of ways - inefficient or redundant querying, huge file IO while loading the ORM libraries on each request, dynamic SQL generation on each query... all of these things can have an impact, but the use of an ORM tool can drastically increase the power available to you with a much smaller amount of code than creating your own DB layer with manual queries. Gary Richardson is absolutely right though, if you're going to continue to use SQL in your code you should always be using PDO's prepared statements to handle the parameters regardless of whether you're using a query or a stored procedure. The sanitisation of input is performed for you by PDO. // optional $attrs = array(PDO::ATTR_PERSISTENT => true); // create the PDO object $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass", $attrs); // also optional, but it makes PDO raise exceptions instead of // PHP errors which are far more useful for debugging $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO venue(venueName, regionId) VALUES(:venueName,:regionId)'); $stmt->bindValue(":venueName", "test"); $stmt->bindValue(":regionId", 1); $stmt->execute(); $lastInsertId = $pdo->lastInsertId(); var_dump($lastInsertId); Caveat: assuming that the ID is 1, the above script will output string(1) "1". PDO->lastInsertId() returns the ID as a string regardless of whether the actual column is an integer or not. This will probably never be a problem for you as PHP performs casting of strings to integers automatically. The following will output bool(true): // regular equality test var_dump($lastInsertId == 1); but if you have code that is expecting the value to be an integer, like is_int or PHP's "is really, truly, 100% equal to" operator: var_dump(is_int($lastInsertId)); var_dump($lastInsertId === 1); you could run into some issues. Edit: Some good discussion on stored procedures here
How do you manage SQL Queries At the moment my code (PHP) has too many SQL queries in it. eg... // not a real example, but you get the idea... $results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid"); if ($results) { // Do something } I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns.. I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database?
TITLE: How do you manage SQL Queries QUESTION: At the moment my code (PHP) has too many SQL queries in it. eg... // not a real example, but you get the idea... $results = $db->GetResults("SELECT * FROM sometable WHERE iUser=$userid"); if ($results) { // Do something } I am looking into using stored procedures to reduce this and make things a little more robust, but I have some concerns.. I have hundreds of different queries in use around the web site, and many of them are quite similar. How should I manage all these queries when they are removed from their context (the code that uses the results) and placed in a stored procedure on the database? ANSWER: The best course of action for you will depend on how you are approaching your data access. There are three approaches you can take: Use stored procedures Keep the queries in the code (but put all your queries into functions and fix everything to use PDO for parameters, as mentioned earlier) Use an ORM tool If you want to pass your own raw SQL to the database engine then stored procedures would be the way to go if all you want to do is get the raw SQL out of your PHP code but keep it relatively unchanged. The stored procedures vs raw SQL debate is a bit of a holy war, but K. Scott Allen makes an excellent point - albeit a throwaway one - in an article about versioning databases: Secondly, stored procedures have fallen out of favor in my eyes. I came from the WinDNA school of indoctrination that said stored procedures should be used all the time. Today, I see stored procedures as an API layer for the database. This is good if you need an API layer at the database level, but I see lots of applications incurring the overhead of creating and maintaining an extra API layer they don't need. In those applications stored procedures are more of a burden than a benefit. I tend to lean towards not using stored procedures. I've worked on projects where the DB has an API exposed through stored procedures, but stored procedures can impose some limitations of their own, and those projects have all, to varying degrees, used dynamically generated raw SQL in code to access the DB. Having an API layer on the DB gives better delineation of responsibilities between the DB team and the Dev team at the expense of some of the flexibility you'd have if the query was kept in the code, however PHP projects are less likely to have sizable enough teams to benefit from this delineation. Conceptually, you should probably have your database versioned. Practically speaking, however, you're far more likely to have just your code versioned than you are to have your database versioned. You are likely to be changing your queries when you are making changes to your code, but if you are changing the queries in stored procedures stored against the database then you probably won't be checking those in when you check the code in and you lose many of the benefits of versioning for a significant area of your application. Regardless of whether or not you elect not to use stored procedures though, you should at the very least ensure that each database operation is stored in an independent function rather than being embedded into each of your page's scripts - essentially an API layer for your DB which is maintained and versioned with your code. If you're using stored procedures, this will effectively mean you have two API layers for your DB, one with the code and one with the DB, which you may feel unnecessarily complicates things if your project does not have separate teams. I certainly do. If the issue is one of code neatness, there are ways to make code with SQL jammed in it more presentable, and the UserManager class shown below is a good way to start - the class only contains queries which relate to the 'user' table, each query has its own method in the class and the queries are indented into the prepare statements and formatted as you would format them in a stored procedure. // UserManager.php: class UserManager { function getUsers() { $pdo = new PDO(...); $stmt = $pdo->prepare(' SELECT u.userId as id, u.userName, g.groupId, g.groupName FROM user u INNER JOIN group g ON u.groupId = g.groupId ORDER BY u.userName, g.groupName '); // iterate over result and prepare return value } function getUser($id) { // db code here } } // index.php: require_once("UserManager.php"); $um = new UserManager; $users = $um->getUsers(); foreach ($users as $user) echo $user['name']; However, if your queries are quite similar but you have huge numbers of permutations in your query conditions like complicated paging, sorting, filtering, etc, an Object/Relational mapper tool is probably the way to go, although the process of overhauling your existing code to make use of the tool could be quite complicated. If you decide to investigate ORM tools, you should look at Propel, the ActiveRecord component of Yii, or the king-daddy PHP ORM, Doctrine. Each of these gives you the ability to programmatically build queries to your database with all manner of complicated logic. Doctrine is the most fully featured, allowing you to template your database with things like the Nested Set tree pattern out of the box. In terms of performance, stored procedures are the fastest, but generally not by much over raw sql. ORM tools can have a significant performance impact in a number of ways - inefficient or redundant querying, huge file IO while loading the ORM libraries on each request, dynamic SQL generation on each query... all of these things can have an impact, but the use of an ORM tool can drastically increase the power available to you with a much smaller amount of code than creating your own DB layer with manual queries. Gary Richardson is absolutely right though, if you're going to continue to use SQL in your code you should always be using PDO's prepared statements to handle the parameters regardless of whether you're using a query or a stored procedure. The sanitisation of input is performed for you by PDO. // optional $attrs = array(PDO::ATTR_PERSISTENT => true); // create the PDO object $pdo = new PDO("mysql:host=localhost;dbname=test", "user", "pass", $attrs); // also optional, but it makes PDO raise exceptions instead of // PHP errors which are far more useful for debugging $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $pdo->prepare('INSERT INTO venue(venueName, regionId) VALUES(:venueName,:regionId)'); $stmt->bindValue(":venueName", "test"); $stmt->bindValue(":regionId", 1); $stmt->execute(); $lastInsertId = $pdo->lastInsertId(); var_dump($lastInsertId); Caveat: assuming that the ID is 1, the above script will output string(1) "1". PDO->lastInsertId() returns the ID as a string regardless of whether the actual column is an integer or not. This will probably never be a problem for you as PHP performs casting of strings to integers automatically. The following will output bool(true): // regular equality test var_dump($lastInsertId == 1); but if you have code that is expecting the value to be an integer, like is_int or PHP's "is really, truly, 100% equal to" operator: var_dump(is_int($lastInsertId)); var_dump($lastInsertId === 1); you could run into some issues. Edit: Some good discussion on stored procedures here
[ "php", "sql", "mysql" ]
16
31
7,490
10
0
2008-09-01T11:38:36.773000
2008-09-18T02:23:58.567000
37,799
38,317
GCOV for multi-threaded apps
Is it possible to use gcov for coverage testing of multi-threaded applications? I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started.
We've certainly used gcov to get coverage information on our multi-threaded application. You want to compile with gcc 4.3 which can do coverage on dynamic code. You compile with the -fprofile-arcs -ftest-coverage options, and the code will generate.gcda files which gcov can then process. We do a separate build of our product, and collect coverage on that, running unit tests and regression tests. Finally we use lcov to generate HTML results pages.
GCOV for multi-threaded apps Is it possible to use gcov for coverage testing of multi-threaded applications? I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started.
TITLE: GCOV for multi-threaded apps QUESTION: Is it possible to use gcov for coverage testing of multi-threaded applications? I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started. ANSWER: We've certainly used gcov to get coverage information on our multi-threaded application. You want to compile with gcc 4.3 which can do coverage on dynamic code. You compile with the -fprofile-arcs -ftest-coverage options, and the code will generate.gcda files which gcov can then process. We do a separate build of our product, and collect coverage on that, running unit tests and regression tests. Finally we use lcov to generate HTML results pages.
[ "c++", "testing", "code-coverage" ]
6
8
4,230
3
0
2008-09-01T11:44:09.113000
2008-09-01T19:19:56.383000
37,804
38,359
Link to samba shares in html
First off if you're unaware, samba or smb == Windows file sharing, \\computer\share etc. I have a bunch of different files on a bunch of different computers. It's mostly media and there is quite a bit of it. I'm looking into various ways of consolidating this into something more manageable. Currently there are a few options I'm looking at, the most insane of which is some kind of samba share indexer that would generate a list of things shared on the various samba servers I tell it about and upload them to a website which could then be searched and browsed. It's a cheap solution, OK? Ignoring the fact that the idea is obviously a couple of methods short of a class, do you chaps know of any way to link to samba file shares in html in a cross-browser way? In windows one does \\computer\share, in linux one does smb://computer/share, neither of which work afaik from browsers that aren't also used as file managers (e.g. any browser that isn't Internet Explorer). Some Clarifications The computers used to access this website are a mixture of WIndows (XP) and Linux (Ubuntu) with a mixture of browsers (Opera and Firefox). In linux entering smb://computer/share only seems to work in Nautilus (and presumably Konqueror / Dolphin for you KDE3.5/4 people). It doesn't work in Firefox or Opera (Firefox does nothing, Opera complains the URL is invalid). I don't have a Windows box handy atm so I'm unsure if \\computer\share works in anything apart from IE (e.g. Firefox / Opera). If you have a better idea for consolidating a bunch of random samba shares (it certainly can't get much worse than mine;-)) it's worth knowing that there is no guarantee that any of the servers I would be wanting to index / consolidate would be up at any particular moment. Moreover, I wouldn't want the knowledge of what they have shared lost or hidden just because they weren't available. I would want to know that they share 'foo' but they are currently down.
Hmm, protocol handlers look interesting. As Mark said, in Windows protocol handlers can be dealt with at the OS level Protocol handlers can also be done at the browser level (which is preferred, as it is cross platform and doesn't involve installing anything). Summary of how it works in Firefox Summary of how it works in Opera
Link to samba shares in html First off if you're unaware, samba or smb == Windows file sharing, \\computer\share etc. I have a bunch of different files on a bunch of different computers. It's mostly media and there is quite a bit of it. I'm looking into various ways of consolidating this into something more manageable. Currently there are a few options I'm looking at, the most insane of which is some kind of samba share indexer that would generate a list of things shared on the various samba servers I tell it about and upload them to a website which could then be searched and browsed. It's a cheap solution, OK? Ignoring the fact that the idea is obviously a couple of methods short of a class, do you chaps know of any way to link to samba file shares in html in a cross-browser way? In windows one does \\computer\share, in linux one does smb://computer/share, neither of which work afaik from browsers that aren't also used as file managers (e.g. any browser that isn't Internet Explorer). Some Clarifications The computers used to access this website are a mixture of WIndows (XP) and Linux (Ubuntu) with a mixture of browsers (Opera and Firefox). In linux entering smb://computer/share only seems to work in Nautilus (and presumably Konqueror / Dolphin for you KDE3.5/4 people). It doesn't work in Firefox or Opera (Firefox does nothing, Opera complains the URL is invalid). I don't have a Windows box handy atm so I'm unsure if \\computer\share works in anything apart from IE (e.g. Firefox / Opera). If you have a better idea for consolidating a bunch of random samba shares (it certainly can't get much worse than mine;-)) it's worth knowing that there is no guarantee that any of the servers I would be wanting to index / consolidate would be up at any particular moment. Moreover, I wouldn't want the knowledge of what they have shared lost or hidden just because they weren't available. I would want to know that they share 'foo' but they are currently down.
TITLE: Link to samba shares in html QUESTION: First off if you're unaware, samba or smb == Windows file sharing, \\computer\share etc. I have a bunch of different files on a bunch of different computers. It's mostly media and there is quite a bit of it. I'm looking into various ways of consolidating this into something more manageable. Currently there are a few options I'm looking at, the most insane of which is some kind of samba share indexer that would generate a list of things shared on the various samba servers I tell it about and upload them to a website which could then be searched and browsed. It's a cheap solution, OK? Ignoring the fact that the idea is obviously a couple of methods short of a class, do you chaps know of any way to link to samba file shares in html in a cross-browser way? In windows one does \\computer\share, in linux one does smb://computer/share, neither of which work afaik from browsers that aren't also used as file managers (e.g. any browser that isn't Internet Explorer). Some Clarifications The computers used to access this website are a mixture of WIndows (XP) and Linux (Ubuntu) with a mixture of browsers (Opera and Firefox). In linux entering smb://computer/share only seems to work in Nautilus (and presumably Konqueror / Dolphin for you KDE3.5/4 people). It doesn't work in Firefox or Opera (Firefox does nothing, Opera complains the URL is invalid). I don't have a Windows box handy atm so I'm unsure if \\computer\share works in anything apart from IE (e.g. Firefox / Opera). If you have a better idea for consolidating a bunch of random samba shares (it certainly can't get much worse than mine;-)) it's worth knowing that there is no guarantee that any of the servers I would be wanting to index / consolidate would be up at any particular moment. Moreover, I wouldn't want the knowledge of what they have shared lost or hidden just because they weren't available. I would want to know that they share 'foo' but they are currently down. ANSWER: Hmm, protocol handlers look interesting. As Mark said, in Windows protocol handlers can be dealt with at the OS level Protocol handlers can also be done at the browser level (which is preferred, as it is cross platform and doesn't involve installing anything). Summary of how it works in Firefox Summary of how it works in Opera
[ "html", "samba", "smb" ]
18
6
37,796
3
0
2008-09-01T11:49:00.570000
2008-09-01T20:06:51.463000
37,805
37,810
Filter linq list on property value
I have a List and a List. The customObject class has an ID property. How can I get a List containing only the objects where the ID property is in the List using LINQ? Edit: I accepted Konrads answer because it is easier/more intuitive to read.
var result = from o in objList where intList.Contains(o.ID) select o
Filter linq list on property value I have a List and a List. The customObject class has an ID property. How can I get a List containing only the objects where the ID property is in the List using LINQ? Edit: I accepted Konrads answer because it is easier/more intuitive to read.
TITLE: Filter linq list on property value QUESTION: I have a List and a List. The customObject class has an ID property. How can I get a List containing only the objects where the ID property is in the List using LINQ? Edit: I accepted Konrads answer because it is easier/more intuitive to read. ANSWER: var result = from o in objList where intList.Contains(o.ID) select o
[ ".net", "linq", "linq-to-objects" ]
20
17
43,693
6
0
2008-09-01T11:49:07.620000
2008-09-01T11:56:21.190000
37,808
37,824
Examples of using semantic web technologies in real world applications
Are you working on a (probably commercial) product which uses RDF/OWL/SPARQL technologies? If so, can you please describe your product?
O'Reilly's Practical RDF has a chatper titled Commercial Uses of RDF/XML. The table at the left lists the subsections: Chandler, RDF Gateway, Seamark, and Adobe's XMP stuff.
Examples of using semantic web technologies in real world applications Are you working on a (probably commercial) product which uses RDF/OWL/SPARQL technologies? If so, can you please describe your product?
TITLE: Examples of using semantic web technologies in real world applications QUESTION: Are you working on a (probably commercial) product which uses RDF/OWL/SPARQL technologies? If so, can you please describe your product? ANSWER: O'Reilly's Practical RDF has a chatper titled Commercial Uses of RDF/XML. The table at the left lists the subsections: Chandler, RDF Gateway, Seamark, and Adobe's XMP stuff.
[ "rdf", "semantic-web" ]
23
6
8,383
11
0
2008-09-01T11:55:27.560000
2008-09-01T12:05:56.893000
37,809
37,880
How do I generate a Friendly URL in C#?
How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow? For example how can I convert: How do I generate a Friendly URL in C#? Into how-do-i-generate-a-friendly-url-in-C
There are several things that could be improved in Jeff's solution, though. if (String.IsNullOrEmpty(title)) return ""; IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all. // remove any leading or trailing spaces left over … muuuch later: // remove trailing dash, if there is one Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue. // replace spaces with single dash title = Regex.Replace(title, @"\s+", "-"); // if we end up with multiple dashes, collapse to single dash title = Regex.Replace(title, @"\-{2,}", "-"); Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one. Off the top of my head, without any testing whatsoever, this would be an equivalent solution: // make it all lower case title = title.ToLower(); // remove entities title = Regex.Replace(title, @"&\w+;", ""); // remove anything that is not letters, numbers, dash, or space title = Regex.Replace(title, @"[^a-z0-9\-\s]", ""); // replace spaces title = title.Replace(' ', '-'); // collapse dashes title = Regex.Replace(title, @"-{2,}", "-"); // trim excessive dashes at the beginning title = title.TrimStart(new [] {'-'}); // if it's too long, clip it if (title.Length > 80) title = title.Substring(0, 79); // remove trailing dashes title = title.TrimEnd(new [] {'-'}); return title; Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.
How do I generate a Friendly URL in C#? How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow? For example how can I convert: How do I generate a Friendly URL in C#? Into how-do-i-generate-a-friendly-url-in-C
TITLE: How do I generate a Friendly URL in C#? QUESTION: How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow? For example how can I convert: How do I generate a Friendly URL in C#? Into how-do-i-generate-a-friendly-url-in-C ANSWER: There are several things that could be improved in Jeff's solution, though. if (String.IsNullOrEmpty(title)) return ""; IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all. // remove any leading or trailing spaces left over … muuuch later: // remove trailing dash, if there is one Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue. // replace spaces with single dash title = Regex.Replace(title, @"\s+", "-"); // if we end up with multiple dashes, collapse to single dash title = Regex.Replace(title, @"\-{2,}", "-"); Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one. Off the top of my head, without any testing whatsoever, this would be an equivalent solution: // make it all lower case title = title.ToLower(); // remove entities title = Regex.Replace(title, @"&\w+;", ""); // remove anything that is not letters, numbers, dash, or space title = Regex.Replace(title, @"[^a-z0-9\-\s]", ""); // replace spaces title = title.Replace(' ', '-'); // collapse dashes title = Regex.Replace(title, @"-{2,}", "-"); // trim excessive dashes at the beginning title = title.TrimStart(new [] {'-'}); // if it's too long, clip it if (title.Length > 80) title = title.Substring(0, 79); // remove trailing dashes title = title.TrimEnd(new [] {'-'}); return title; Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.
[ "c#", "friendly-url" ]
29
47
17,473
4
0
2008-09-01T11:55:57.620000
2008-09-01T12:35:51.173000
37,812
37,891
MSMQ monitoring
Is there anything which can help with msmq monitoring? I'd like to get some event/monit when a message appears in queue and the same on leave.
Check out the Windows Management Performance counters. If you look in your Administrative Tools and find "Performance Counters", you will be able to dig through there and find detailed metrics on what is happening on each message queue. This can also work for remote servers. Should you wish to create some sort of automation around the monitoring, check out the.NET libraries for reading these performance counters. There is a very rich and comprehensive API which should give you everything you need!
MSMQ monitoring Is there anything which can help with msmq monitoring? I'd like to get some event/monit when a message appears in queue and the same on leave.
TITLE: MSMQ monitoring QUESTION: Is there anything which can help with msmq monitoring? I'd like to get some event/monit when a message appears in queue and the same on leave. ANSWER: Check out the Windows Management Performance counters. If you look in your Administrative Tools and find "Performance Counters", you will be able to dig through there and find detailed metrics on what is happening on each message queue. This can also work for remote servers. Should you wish to create some sort of automation around the monitoring, check out the.NET libraries for reading these performance counters. There is a very rich and comprehensive API which should give you everything you need!
[ "monitoring", "msmq" ]
5
6
7,587
2
0
2008-09-01T11:59:03.587000
2008-09-01T12:58:28.267000
37,821
38,114
Viewing event log via a web interface
I'd like to be able to view the event log for a series of asp.net websites running on IIS. Can I do this externally, for example, through a web interface?
No, but there are two solutions I would recommend: Adiscon EventLogger is a third-party product that will send your Windows EventLog to a SQL database. You can either send all events or create filters. Of course, once the events are in a SQL database, you can use any of the usual tools to create a web interface. You can use ASP.NET's HealthMonitoring configuration section to configure.NET to send all ASP.NET-related events directly to a SQL database. This covers exceptions, heartbeats, and a host of other event types. The SqlWebEventProvider is a cinch to setup.
Viewing event log via a web interface I'd like to be able to view the event log for a series of asp.net websites running on IIS. Can I do this externally, for example, through a web interface?
TITLE: Viewing event log via a web interface QUESTION: I'd like to be able to view the event log for a series of asp.net websites running on IIS. Can I do this externally, for example, through a web interface? ANSWER: No, but there are two solutions I would recommend: Adiscon EventLogger is a third-party product that will send your Windows EventLog to a SQL database. You can either send all events or create filters. Of course, once the events are in a SQL database, you can use any of the usual tools to create a web interface. You can use ASP.NET's HealthMonitoring configuration section to configure.NET to send all ASP.NET-related events directly to a SQL database. This covers exceptions, heartbeats, and a host of other event types. The SqlWebEventProvider is a cinch to setup.
[ "asp.net", "iis", "logging", "monitoring" ]
4
2
2,556
2
0
2008-09-01T12:05:22.887000
2008-09-01T16:23:29.333000
37,823
37,852
Good reasons NOT to use a relational database?
Can you please point to alternative data storage tools and give good reasons to use them instead of good-old relational databases? In my opinion, most applications rarely use the full power of SQL--it would be interesting to see how to build an SQL-free application.
Plain text files in a filesystem Very simple to create and edit Easy for users to manipulate with simple tools (i.e. text editors, grep etc) Efficient storage of binary documents XML or JSON files on disk As above, but with a bit more ability to validate the structure. Spreadsheet / CSV file Very easy model for business users to understand Subversion (or similar disk based version control system) Very good support for versioning of data Berkeley DB (Basically, a disk based hashtable) Very simple conceptually (just un-typed key/value) Quite fast No administration overhead Supports transactions I believe Amazon's Simple DB Much like Berkeley DB I believe, but hosted Google's App Engine Datastore Hosted and highly scalable Per document key-value storage (i.e. flexible data model) CouchDB Document focus Simple storage of semi-structured / document based data Native language collections (stored in memory or serialised on disk) Very tight language integration Custom (hand-written) storage engine Potentially very high performance in required uses cases I can't claim to know anything much about them, but you might also like to look into object database systems.
Good reasons NOT to use a relational database? Can you please point to alternative data storage tools and give good reasons to use them instead of good-old relational databases? In my opinion, most applications rarely use the full power of SQL--it would be interesting to see how to build an SQL-free application.
TITLE: Good reasons NOT to use a relational database? QUESTION: Can you please point to alternative data storage tools and give good reasons to use them instead of good-old relational databases? In my opinion, most applications rarely use the full power of SQL--it would be interesting to see how to build an SQL-free application. ANSWER: Plain text files in a filesystem Very simple to create and edit Easy for users to manipulate with simple tools (i.e. text editors, grep etc) Efficient storage of binary documents XML or JSON files on disk As above, but with a bit more ability to validate the structure. Spreadsheet / CSV file Very easy model for business users to understand Subversion (or similar disk based version control system) Very good support for versioning of data Berkeley DB (Basically, a disk based hashtable) Very simple conceptually (just un-typed key/value) Quite fast No administration overhead Supports transactions I believe Amazon's Simple DB Much like Berkeley DB I believe, but hosted Google's App Engine Datastore Hosted and highly scalable Per document key-value storage (i.e. flexible data model) CouchDB Document focus Simple storage of semi-structured / document based data Native language collections (stored in memory or serialised on disk) Very tight language integration Custom (hand-written) storage engine Potentially very high performance in required uses cases I can't claim to know anything much about them, but you might also like to look into object database systems.
[ "sql", "database", "nosql" ]
139
147
21,914
21
0
2008-09-01T12:05:52.010000
2008-09-01T12:19:14.193000
37,830
37,878
How do I implement a chromeless window with WPF?
I want to show a chromeless modal window with a close button in the upper right corner. Is this possible?
You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this: That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration.
How do I implement a chromeless window with WPF? I want to show a chromeless modal window with a close button in the upper right corner. Is this possible?
TITLE: How do I implement a chromeless window with WPF? QUESTION: I want to show a chromeless modal window with a close button in the upper right corner. Is this possible? ANSWER: You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this: That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration.
[ "wpf", "user-interface" ]
25
34
15,259
3
0
2008-09-01T12:07:38.903000
2008-09-01T12:34:31.363000
37,832
37,853
UI and event testing
So I know that unit testing is a must. I get the idea that TDD is the way to go when adding new modules. Even if, in practice, I don't actually do it. A bit like commenting code, really. The real thing is, I'm struggling to get my head around how to unit-test the UI and more generally objects that generate events: user controls, asynchronous database operations, etc. So much of my code relates to UI events that I can't quite see how to even start the unit testing. There must be some primers and starter docs out there? Some hints and tips? I'm generally working in C# (2.0 and 3.5) but I'm not sure that this is strictly relevant to the question.
the thing to remember is that unit testing is about testing the units of code you write. Your unit tests shouldn't test that clicking a button raises an event, but that the code being executed by that click event does as it's supposed to. What you're really wanting to do is test the underlying code does what it should so that your UI layers can execute that code with confidence.
UI and event testing So I know that unit testing is a must. I get the idea that TDD is the way to go when adding new modules. Even if, in practice, I don't actually do it. A bit like commenting code, really. The real thing is, I'm struggling to get my head around how to unit-test the UI and more generally objects that generate events: user controls, asynchronous database operations, etc. So much of my code relates to UI events that I can't quite see how to even start the unit testing. There must be some primers and starter docs out there? Some hints and tips? I'm generally working in C# (2.0 and 3.5) but I'm not sure that this is strictly relevant to the question.
TITLE: UI and event testing QUESTION: So I know that unit testing is a must. I get the idea that TDD is the way to go when adding new modules. Even if, in practice, I don't actually do it. A bit like commenting code, really. The real thing is, I'm struggling to get my head around how to unit-test the UI and more generally objects that generate events: user controls, asynchronous database operations, etc. So much of my code relates to UI events that I can't quite see how to even start the unit testing. There must be some primers and starter docs out there? Some hints and tips? I'm generally working in C# (2.0 and 3.5) but I'm not sure that this is strictly relevant to the question. ANSWER: the thing to remember is that unit testing is about testing the units of code you write. Your unit tests shouldn't test that clicking a button raises an event, but that the code being executed by that click event does as it's supposed to. What you're really wanting to do is test the underlying code does what it should so that your UI layers can execute that code with confidence.
[ "visual-studio", "unit-testing", "user-interface", "tdd" ]
2
2
455
4
0
2008-09-01T12:09:10.553000
2008-09-01T12:19:14.367000
37,843
37,870
What exactly is WPF?
I have seen lots of questions recently about WPF... What is it? What does it stand for? How can I begin programming WPF?
WPF is a new technology that will supersede Windows Forms. WPF stands for Windows Presentation Foundation Here are some useful topics on SO: What WPF books would you recommend What real world WPF applications are out there From my practice I can say that WPF is a truly amazing technology however it takes some time to get used to because it's totally different from the WinForms. I would recommend you to take a look at this demo.
What exactly is WPF? I have seen lots of questions recently about WPF... What is it? What does it stand for? How can I begin programming WPF?
TITLE: What exactly is WPF? QUESTION: I have seen lots of questions recently about WPF... What is it? What does it stand for? How can I begin programming WPF? ANSWER: WPF is a new technology that will supersede Windows Forms. WPF stands for Windows Presentation Foundation Here are some useful topics on SO: What WPF books would you recommend What real world WPF applications are out there From my practice I can say that WPF is a truly amazing technology however it takes some time to get used to because it's totally different from the WinForms. I would recommend you to take a look at this demo.
[ "wpf", "windows" ]
17
10
9,191
8
0
2008-09-01T12:15:14.687000
2008-09-01T12:31:39.610000
37,851
37,884
Application Control Scripts on Unix
I'm looking for some software that allows me to control a server based application, that is, there are bunch of interdependent processes that I'd like to be able to start up, shut down and monitor in a controller manner. I've come across programs like Autosys, but that's expensive and very much over the top for what I want. I've also seen AppCtl, but that seems not to handle dependencies. Maybe it would be possible to repurpose the init scripts? Oh, and as an added complication it should be able to run on a Solaris 10 or Linux box without installing any new binaries. On the boxes I've seen recently, that means shell scripts and Perl but not Python. Do any such programs exist or do I need to dust off my copy of Programming Perl?
Try Supervise, which is what qmail uses to keep track of it's services/startup applications: http://cr.yp.to/daemontools/supervise.html
Application Control Scripts on Unix I'm looking for some software that allows me to control a server based application, that is, there are bunch of interdependent processes that I'd like to be able to start up, shut down and monitor in a controller manner. I've come across programs like Autosys, but that's expensive and very much over the top for what I want. I've also seen AppCtl, but that seems not to handle dependencies. Maybe it would be possible to repurpose the init scripts? Oh, and as an added complication it should be able to run on a Solaris 10 or Linux box without installing any new binaries. On the boxes I've seen recently, that means shell scripts and Perl but not Python. Do any such programs exist or do I need to dust off my copy of Programming Perl?
TITLE: Application Control Scripts on Unix QUESTION: I'm looking for some software that allows me to control a server based application, that is, there are bunch of interdependent processes that I'd like to be able to start up, shut down and monitor in a controller manner. I've come across programs like Autosys, but that's expensive and very much over the top for what I want. I've also seen AppCtl, but that seems not to handle dependencies. Maybe it would be possible to repurpose the init scripts? Oh, and as an added complication it should be able to run on a Solaris 10 or Linux box without installing any new binaries. On the boxes I've seen recently, that means shell scripts and Perl but not Python. Do any such programs exist or do I need to dust off my copy of Programming Perl? ANSWER: Try Supervise, which is what qmail uses to keep track of it's services/startup applications: http://cr.yp.to/daemontools/supervise.html
[ "linux", "unix", "solaris", "scripting" ]
1
1
1,359
4
0
2008-09-01T12:19:13.943000
2008-09-01T12:53:37.793000
37,882
38,259
How can you easily reorder columns in LINQ to SQL designer?
When designing LINQ classes using the LINQ to SQL designer I've sometimes needed to reorder the classes for the purposes of having the resultant columns in a DataGridView appear in a different order. Unfortunately this seems to be exceedingly difficult; you need to cut and paste properties about, or delete them and re-insert them manually. I know you can reorder columns fairly easily in a DataGridView, however that would result in a lot of hardcoding and I want the designer to match up to the grid. Does anyone know of any easier way of achieving this or is cutting/pasting the only available method? I tried manually editing the.designer.cs file, but reordering properties there doesn't appear to do anything! Edit: Just to make it clear - I want to reorder what's in the LINQ to SQL designer, not what's in the table. I haven't made an error in ordering requiring a reversion to the original table layout; rather I have a table which I want to possess a different ordering in Visual Studio than in SQL Server.
Using Linq-to-Sql, you can have columns in the DataGridView appear different than in the original table by: In your Linq query, extract the columns that you want, in the order than you want, and store them in a var. Then the autogenerate columns should show them in that order in the DataGridView Use Template columns in your DataGridView Do not use drag-and-drop on the Linq-to-Sql design surface to create your entities. Rather, create them by hand and associate them with the database table using table and column properties As far as I know, there is no drag-and-drop column reorder in the designer itself
How can you easily reorder columns in LINQ to SQL designer? When designing LINQ classes using the LINQ to SQL designer I've sometimes needed to reorder the classes for the purposes of having the resultant columns in a DataGridView appear in a different order. Unfortunately this seems to be exceedingly difficult; you need to cut and paste properties about, or delete them and re-insert them manually. I know you can reorder columns fairly easily in a DataGridView, however that would result in a lot of hardcoding and I want the designer to match up to the grid. Does anyone know of any easier way of achieving this or is cutting/pasting the only available method? I tried manually editing the.designer.cs file, but reordering properties there doesn't appear to do anything! Edit: Just to make it clear - I want to reorder what's in the LINQ to SQL designer, not what's in the table. I haven't made an error in ordering requiring a reversion to the original table layout; rather I have a table which I want to possess a different ordering in Visual Studio than in SQL Server.
TITLE: How can you easily reorder columns in LINQ to SQL designer? QUESTION: When designing LINQ classes using the LINQ to SQL designer I've sometimes needed to reorder the classes for the purposes of having the resultant columns in a DataGridView appear in a different order. Unfortunately this seems to be exceedingly difficult; you need to cut and paste properties about, or delete them and re-insert them manually. I know you can reorder columns fairly easily in a DataGridView, however that would result in a lot of hardcoding and I want the designer to match up to the grid. Does anyone know of any easier way of achieving this or is cutting/pasting the only available method? I tried manually editing the.designer.cs file, but reordering properties there doesn't appear to do anything! Edit: Just to make it clear - I want to reorder what's in the LINQ to SQL designer, not what's in the table. I haven't made an error in ordering requiring a reversion to the original table layout; rather I have a table which I want to possess a different ordering in Visual Studio than in SQL Server. ANSWER: Using Linq-to-Sql, you can have columns in the DataGridView appear different than in the original table by: In your Linq query, extract the columns that you want, in the order than you want, and store them in a var. Then the autogenerate columns should show them in that order in the DataGridView Use Template columns in your DataGridView Do not use drag-and-drop on the Linq-to-Sql design surface to create your entities. Rather, create them by hand and associate them with the database table using table and column properties As far as I know, there is no drag-and-drop column reorder in the designer itself
[ "c#", "linq", "linq-to-sql" ]
0
1
1,540
3
0
2008-09-01T12:37:30.500000
2008-09-01T18:34:08.193000
37,929
37,934
How to test java application for performance bottlenecks?
I am reviewing a big java application to see if there are any performance bottlenecks. The real problem is that I cannot pinpoint the performance issues to any single module. The whole application is slow as such. Is there some tool/technique I can use to help me out in this?
Try using a profiler on your running code. It should help you identify the bottlenecks. Try jprofiler or Netbeans profiler
How to test java application for performance bottlenecks? I am reviewing a big java application to see if there are any performance bottlenecks. The real problem is that I cannot pinpoint the performance issues to any single module. The whole application is slow as such. Is there some tool/technique I can use to help me out in this?
TITLE: How to test java application for performance bottlenecks? QUESTION: I am reviewing a big java application to see if there are any performance bottlenecks. The real problem is that I cannot pinpoint the performance issues to any single module. The whole application is slow as such. Is there some tool/technique I can use to help me out in this? ANSWER: Try using a profiler on your running code. It should help you identify the bottlenecks. Try jprofiler or Netbeans profiler
[ "java", "performance" ]
11
8
19,539
6
0
2008-09-01T13:22:19.033000
2008-09-01T13:25:22.100000
37,936
37,951
Handling XSD Dataset ConstraintExceptions
Does anyone have any tips for dealing with ConstraintExceptions thrown by XSD datasets? This is the exception with the cryptic message: System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
A couple of tips that I've found lately. It's much better to use the TableAdapter FillByDataXXXX() methods instead of GetDataByXXXX() methods because the DataTable passed into the fill method can be interrogated for clues: DataTable.GetErrors() returns an array of DataRow instances in error DataRow.RowError contains a description of the row error DataRow.GetColumnsInError() returns an array of DataColumn instances in error Recently, I wrapped up some interrogation code into a subclass of ConstraintException that's turned out to be a useful starting point for debugging. C# Example usage: Example.DataSet.fooDataTable table = new DataSet.fooDataTable(); try { tableAdapter.Fill(table); } catch (ConstraintException ex) { // pass the DataTable to DetailedConstraintException to get a more detailed Message property throw new DetailedConstraintException("error filling table", table, ex); } Output: DetailedConstraintException: table fill failed Errors reported for ConstraintExceptionHelper.DataSet+fooDataTable [foo] Columns in error: [1] [PRODUCT_ID] - total rows affected: 1085 Row errors: [4] [Column 'PRODUCT_ID' is constrained to be unique. Value '1' is already present.] - total rows affected: 1009 [Column 'PRODUCT_ID' is constrained to be unique. Value '2' is already present.] - total rows affected: 20 [Column 'PRODUCT_ID' is constrained to be unique. Value '4' is already present.] - total rows affected: 34 [Column 'PRODUCT_ID' is constrained to be unique. Value '6' is already present.] - total rows affected: 22 ----> System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. I don't know if this is too much code to include in a Stack Overflow answer but here's the C# class in full. Disclaimer: this works for me, please feel free to use/modify as appropriate. using System; using System.Collections.Generic; using System.Text; using System.Data; namespace ConstraintExceptionHelper { /// /// Subclass of ConstraintException that explains row and column errors in the Message property /// public class DetailedConstraintException: ConstraintException { private const int InitialCountValue = 1; /// /// Initialises a new instance of DetailedConstraintException with the specified string and DataTable /// /// exception message /// DataTable in error public DetailedConstraintException(string message, DataTable erroredTable): base(message) { ErroredTable = erroredTable; } /// /// Initialises a new instance of DetailedConstraintException with the specified string, DataTable and inner Exception /// /// exception message /// DataTable in error /// the original exception public DetailedConstraintException(string message, DataTable erroredTable, Exception inner): base(message, inner) { ErroredTable = erroredTable; } private string buildErrorSummaryMessage() { if (null == ErroredTable) { return "No errored DataTable specified"; } if (!ErroredTable.HasErrors) { return "No Row Errors reported in DataTable=[" + ErroredTable.TableName + "]"; } foreach (DataRow row in ErroredTable.GetErrors()) { recordColumnsInError(row); recordRowsInError(row); } StringBuilder sb = new StringBuilder(); appendSummaryIntro(sb); appendErroredColumns(sb); appendRowErrors(sb); return sb.ToString(); } private void recordColumnsInError(DataRow row) { foreach (DataColumn column in row.GetColumnsInError()) { if (_erroredColumns.ContainsKey(column.ColumnName)) { _erroredColumns[column.ColumnName]++; continue; } _erroredColumns.Add(column.ColumnName, InitialCountValue); } } private void recordRowsInError(DataRow row) { if (_rowErrors.ContainsKey(row.RowError)) { _rowErrors[row.RowError]++; return; } _rowErrors.Add(row.RowError, InitialCountValue); } private void appendSummaryIntro(StringBuilder sb) { sb.AppendFormat("Errors reported for {1} [{2}]{0}", Environment.NewLine, ErroredTable.GetType().FullName, ErroredTable.TableName); } private void appendErroredColumns(StringBuilder sb) { sb.AppendFormat("Columns in error: [{1}]{0}", Environment.NewLine, _erroredColumns.Count); foreach (string columnName in _erroredColumns.Keys) { sb.AppendFormat("\t[{1}] - rows affected: {2}{0}", Environment.NewLine, columnName, _erroredColumns[columnName]); } } private void appendRowErrors(StringBuilder sb) { sb.AppendFormat("Row errors: [{1}]{0}", Environment.NewLine, _rowErrors.Count); foreach (string rowError in _rowErrors.Keys) { sb.AppendFormat("\t[{1}] - rows affected: {2}{0}", Environment.NewLine, rowError, _rowErrors[rowError]); } } /// /// Get the DataTable in error /// public DataTable ErroredTable { get { return _erroredTable; } private set { _erroredTable = value; } } /// /// Get the original ConstraintException message with extra error information /// public override string Message { get { return base.Message + Environment.NewLine + buildErrorSummaryMessage(); } } private readonly SortedDictionary _rowErrors = new SortedDictionary (); private readonly SortedDictionary _erroredColumns = new SortedDictionary (); private DataTable _erroredTable; } }
Handling XSD Dataset ConstraintExceptions Does anyone have any tips for dealing with ConstraintExceptions thrown by XSD datasets? This is the exception with the cryptic message: System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
TITLE: Handling XSD Dataset ConstraintExceptions QUESTION: Does anyone have any tips for dealing with ConstraintExceptions thrown by XSD datasets? This is the exception with the cryptic message: System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. ANSWER: A couple of tips that I've found lately. It's much better to use the TableAdapter FillByDataXXXX() methods instead of GetDataByXXXX() methods because the DataTable passed into the fill method can be interrogated for clues: DataTable.GetErrors() returns an array of DataRow instances in error DataRow.RowError contains a description of the row error DataRow.GetColumnsInError() returns an array of DataColumn instances in error Recently, I wrapped up some interrogation code into a subclass of ConstraintException that's turned out to be a useful starting point for debugging. C# Example usage: Example.DataSet.fooDataTable table = new DataSet.fooDataTable(); try { tableAdapter.Fill(table); } catch (ConstraintException ex) { // pass the DataTable to DetailedConstraintException to get a more detailed Message property throw new DetailedConstraintException("error filling table", table, ex); } Output: DetailedConstraintException: table fill failed Errors reported for ConstraintExceptionHelper.DataSet+fooDataTable [foo] Columns in error: [1] [PRODUCT_ID] - total rows affected: 1085 Row errors: [4] [Column 'PRODUCT_ID' is constrained to be unique. Value '1' is already present.] - total rows affected: 1009 [Column 'PRODUCT_ID' is constrained to be unique. Value '2' is already present.] - total rows affected: 20 [Column 'PRODUCT_ID' is constrained to be unique. Value '4' is already present.] - total rows affected: 34 [Column 'PRODUCT_ID' is constrained to be unique. Value '6' is already present.] - total rows affected: 22 ----> System.Data.ConstraintException: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints. I don't know if this is too much code to include in a Stack Overflow answer but here's the C# class in full. Disclaimer: this works for me, please feel free to use/modify as appropriate. using System; using System.Collections.Generic; using System.Text; using System.Data; namespace ConstraintExceptionHelper { /// /// Subclass of ConstraintException that explains row and column errors in the Message property /// public class DetailedConstraintException: ConstraintException { private const int InitialCountValue = 1; /// /// Initialises a new instance of DetailedConstraintException with the specified string and DataTable /// /// exception message /// DataTable in error public DetailedConstraintException(string message, DataTable erroredTable): base(message) { ErroredTable = erroredTable; } /// /// Initialises a new instance of DetailedConstraintException with the specified string, DataTable and inner Exception /// /// exception message /// DataTable in error /// the original exception public DetailedConstraintException(string message, DataTable erroredTable, Exception inner): base(message, inner) { ErroredTable = erroredTable; } private string buildErrorSummaryMessage() { if (null == ErroredTable) { return "No errored DataTable specified"; } if (!ErroredTable.HasErrors) { return "No Row Errors reported in DataTable=[" + ErroredTable.TableName + "]"; } foreach (DataRow row in ErroredTable.GetErrors()) { recordColumnsInError(row); recordRowsInError(row); } StringBuilder sb = new StringBuilder(); appendSummaryIntro(sb); appendErroredColumns(sb); appendRowErrors(sb); return sb.ToString(); } private void recordColumnsInError(DataRow row) { foreach (DataColumn column in row.GetColumnsInError()) { if (_erroredColumns.ContainsKey(column.ColumnName)) { _erroredColumns[column.ColumnName]++; continue; } _erroredColumns.Add(column.ColumnName, InitialCountValue); } } private void recordRowsInError(DataRow row) { if (_rowErrors.ContainsKey(row.RowError)) { _rowErrors[row.RowError]++; return; } _rowErrors.Add(row.RowError, InitialCountValue); } private void appendSummaryIntro(StringBuilder sb) { sb.AppendFormat("Errors reported for {1} [{2}]{0}", Environment.NewLine, ErroredTable.GetType().FullName, ErroredTable.TableName); } private void appendErroredColumns(StringBuilder sb) { sb.AppendFormat("Columns in error: [{1}]{0}", Environment.NewLine, _erroredColumns.Count); foreach (string columnName in _erroredColumns.Keys) { sb.AppendFormat("\t[{1}] - rows affected: {2}{0}", Environment.NewLine, columnName, _erroredColumns[columnName]); } } private void appendRowErrors(StringBuilder sb) { sb.AppendFormat("Row errors: [{1}]{0}", Environment.NewLine, _rowErrors.Count); foreach (string rowError in _rowErrors.Keys) { sb.AppendFormat("\t[{1}] - rows affected: {2}{0}", Environment.NewLine, rowError, _rowErrors[rowError]); } } /// /// Get the DataTable in error /// public DataTable ErroredTable { get { return _erroredTable; } private set { _erroredTable = value; } } /// /// Get the original ConstraintException message with extra error information /// public override string Message { get { return base.Message + Environment.NewLine + buildErrorSummaryMessage(); } } private readonly SortedDictionary _rowErrors = new SortedDictionary (); private readonly SortedDictionary _erroredColumns = new SortedDictionary (); private DataTable _erroredTable; } }
[ "xsd", "dataset", "constraintexception" ]
7
20
4,523
1
0
2008-09-01T13:27:08.633000
2008-09-01T13:34:35.777000
37,944
37,963
How popular is WPF as a technology?
I had a discussion with some colleagues mentioning that there are not too many projects that we do which make use of WPF for creating UI for a windows application (we almost always use Windows Forms instead). Are your experiences the same - i.e. there is not too much adoption of this technology? Why do you think that is? And will we have a time when we see much more of WPF?
Have a look at this survey it was done by a Windows Forms Contol Vendor in Australia. Personally I have worked on two commercial projects in the last year that were using WPF to varying degrees. The adoption of WPF is on the rise. Microsoft I believe is putting all their eggs into the WPF basket.
How popular is WPF as a technology? I had a discussion with some colleagues mentioning that there are not too many projects that we do which make use of WPF for creating UI for a windows application (we almost always use Windows Forms instead). Are your experiences the same - i.e. there is not too much adoption of this technology? Why do you think that is? And will we have a time when we see much more of WPF?
TITLE: How popular is WPF as a technology? QUESTION: I had a discussion with some colleagues mentioning that there are not too many projects that we do which make use of WPF for creating UI for a windows application (we almost always use Windows Forms instead). Are your experiences the same - i.e. there is not too much adoption of this technology? Why do you think that is? And will we have a time when we see much more of WPF? ANSWER: Have a look at this survey it was done by a Windows Forms Contol Vendor in Australia. Personally I have worked on two commercial projects in the last year that were using WPF to varying degrees. The adoption of WPF is on the rise. Microsoft I believe is putting all their eggs into the WPF basket.
[ "wpf" ]
20
10
5,852
9
0
2008-09-01T13:32:22.927000
2008-09-01T13:39:49.383000
37,956
38,017
C++ : What's the easiest library to open video file
I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx ), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected... [...] hr = pGrabber->SetOneShot(TRUE); hr = pGrabber->SetBufferSamples(TRUE); pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. // Find the required buffer size. long cbBuffer = 0; hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL); for( int i = 0; i < 25; ++i ) { pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. char *pBuffer = new char[cbBuffer]; hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer); AM_MEDIA_TYPE mt; hr = pGrabber->GetConnectedMediaType(&mt); VIDEOINFOHEADER *pVih; pVih = (VIDEOINFOHEADER*)mt.pbFormat; [...] } [...] Is there somebody, with video software experience, who can advise me about code or other simpler library? Thanks Edit: Msdn links seems not to work ( see the bug )
Currently these are the most popular video frameworks available on Win32 platforms: Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed. DirectShow: standard WinXP framework, it can basically load all formats you can play with Windows Media Player. Rather difficult to use. Ffmpeg: more precisely libavcodec and libavformat that comes with Ffmpeg open- source multimedia utility. It is extremely powerful and can read a lot of formats (almost everything you can play with VLC ) even if you don't have the codec installed on the system. It's quite complicated to use but you can always get inspired by the code of ffplay that comes shipped with it or by other implementations in open-source software. Anyway I think it's still much easier to use than DS (and much faster). It needs to be comipled by MinGW on Windows, but all the steps are explained very well here (in this moment the link is down, hope not dead). QuickTime: the Apple framework is not the best solution for Windows platform, since it needs QuickTime app to be installed and also the proper QuickTime codec for every format; it does not support many formats, but its quite common in professional field (so some codec are actually only for QuickTime). Shouldn't be too difficult to implement. Gstreamer: latest open source framework. I don't know much about it, I guess it wraps over some of the other systems (but I'm not sure). All of this frameworks have been implemented as backend in OpenCv Highgui, except for DirectShow. The default framework for Win32 OpenCV is using VFW (and thus able only to open some AVI files), if you want to use the others you must download the CVS instead of the official release and still do some hacking on the code and it's anyway not too complete, for example FFMPEG backend doesn't allow to seek in the stream. If you want to use QuickTime with OpenCV this can help you.
C++ : What's the easiest library to open video file I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx ), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected... [...] hr = pGrabber->SetOneShot(TRUE); hr = pGrabber->SetBufferSamples(TRUE); pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. // Find the required buffer size. long cbBuffer = 0; hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL); for( int i = 0; i < 25; ++i ) { pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. char *pBuffer = new char[cbBuffer]; hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer); AM_MEDIA_TYPE mt; hr = pGrabber->GetConnectedMediaType(&mt); VIDEOINFOHEADER *pVih; pVih = (VIDEOINFOHEADER*)mt.pbFormat; [...] } [...] Is there somebody, with video software experience, who can advise me about code or other simpler library? Thanks Edit: Msdn links seems not to work ( see the bug )
TITLE: C++ : What's the easiest library to open video file QUESTION: I would like to open a small video file and map every frames in memory (to apply some custom filter). I don't want to handle the video codec, I would rather let the library handle that for me. I've tried to use Direct Show with the SampleGrabber filter (using this sample http://msdn.microsoft.com/en-us/library/ms787867(VS.85).aspx ), but I only managed to grab some frames (not every frames!). I'm quite new in video software programming, maybe I'm not using the best library, or I'm doing it wrong. I've pasted a part of my code (mainly a modified copy/paste from the msdn example), unfortunately it doesn't grabb the 25 first frames as expected... [...] hr = pGrabber->SetOneShot(TRUE); hr = pGrabber->SetBufferSamples(TRUE); pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. // Find the required buffer size. long cbBuffer = 0; hr = pGrabber->GetCurrentBuffer(&cbBuffer, NULL); for( int i = 0; i < 25; ++i ) { pControl->Run(); // Run the graph. pEvent->WaitForCompletion(INFINITE, &evCode); // Wait till it's done. char *pBuffer = new char[cbBuffer]; hr = pGrabber->GetCurrentBuffer(&cbBuffer, (long*)pBuffer); AM_MEDIA_TYPE mt; hr = pGrabber->GetConnectedMediaType(&mt); VIDEOINFOHEADER *pVih; pVih = (VIDEOINFOHEADER*)mt.pbFormat; [...] } [...] Is there somebody, with video software experience, who can advise me about code or other simpler library? Thanks Edit: Msdn links seems not to work ( see the bug ) ANSWER: Currently these are the most popular video frameworks available on Win32 platforms: Video for Windows: old windows framework coming from the age of Win95 but still widely used because it is very simple to use. Unfortunately it supports only AVI files for which the proper VFW codec has been installed. DirectShow: standard WinXP framework, it can basically load all formats you can play with Windows Media Player. Rather difficult to use. Ffmpeg: more precisely libavcodec and libavformat that comes with Ffmpeg open- source multimedia utility. It is extremely powerful and can read a lot of formats (almost everything you can play with VLC ) even if you don't have the codec installed on the system. It's quite complicated to use but you can always get inspired by the code of ffplay that comes shipped with it or by other implementations in open-source software. Anyway I think it's still much easier to use than DS (and much faster). It needs to be comipled by MinGW on Windows, but all the steps are explained very well here (in this moment the link is down, hope not dead). QuickTime: the Apple framework is not the best solution for Windows platform, since it needs QuickTime app to be installed and also the proper QuickTime codec for every format; it does not support many formats, but its quite common in professional field (so some codec are actually only for QuickTime). Shouldn't be too difficult to implement. Gstreamer: latest open source framework. I don't know much about it, I guess it wraps over some of the other systems (but I'm not sure). All of this frameworks have been implemented as backend in OpenCv Highgui, except for DirectShow. The default framework for Win32 OpenCV is using VFW (and thus able only to open some AVI files), if you want to use the others you must download the CVS instead of the official release and still do some hacking on the code and it's anyway not too complete, for example FFMPEG backend doesn't allow to seek in the stream. If you want to use QuickTime with OpenCV this can help you.
[ "c++", "windows", "video" ]
28
29
55,956
8
0
2008-09-01T13:35:41.937000
2008-09-01T14:53:38.503000
37,969
41,164
Tool for posting test messages onto a JMS queue?
Can anyone recommend a tool for quickly posting test messages onto a JMS queue? Description: The tool should allow the user to enter some data, perhaps an XML payload, and then submit it to a queue. I should be able to test consumer without producer.
This answer doesn't apply to all JMS brokers, but if you happen to be using Apache ActiveMQ, the web-based admin console (by default at http://localhost:8161/admin ) allows you to manually send text messages to topics or queues. It's handy for debugging.
Tool for posting test messages onto a JMS queue? Can anyone recommend a tool for quickly posting test messages onto a JMS queue? Description: The tool should allow the user to enter some data, perhaps an XML payload, and then submit it to a queue. I should be able to test consumer without producer.
TITLE: Tool for posting test messages onto a JMS queue? QUESTION: Can anyone recommend a tool for quickly posting test messages onto a JMS queue? Description: The tool should allow the user to enter some data, perhaps an XML payload, and then submit it to a queue. I should be able to test consumer without producer. ANSWER: This answer doesn't apply to all JMS brokers, but if you happen to be using Apache ActiveMQ, the web-based admin console (by default at http://localhost:8161/admin ) allows you to manually send text messages to topics or queues. It's handy for debugging.
[ "jms", "messaging", "tooling" ]
23
19
80,580
12
0
2008-09-01T13:46:41.113000
2008-09-03T04:19:36.640000
37,976
38,224
How do I change XML indentation in IntelliJ IDEA?
By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?
Sure there is. This is all you need to do: Go to File -> Settings -> Global Code Style -> General Disable the checkbox next to 'Use same settings for all file types' The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.
How do I change XML indentation in IntelliJ IDEA? By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor?
TITLE: How do I change XML indentation in IntelliJ IDEA? QUESTION: By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files. The project I'm working on uses 2 spaces as indentation in all it's XML. Is there a way to configure the indentation in IntelliJ's editor? ANSWER: Sure there is. This is all you need to do: Go to File -> Settings -> Global Code Style -> General Disable the checkbox next to 'Use same settings for all file types' The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.
[ "java", "xml", "ide", "intellij-idea" ]
12
19
13,065
3
0
2008-09-01T13:52:35.700000
2008-09-01T17:59:26.997000
37,979
38,077
Recommendations for implementations of ActiveRecord
Does anyone have any recommendations for implementations of ActiveRecord in PHP? I've been using CBL ActiveRecord, but I was wondering if there were any viable alternatives.
Depends!;) For example there is ADODB's Active Record implementation, then there is Zend_Db_DataTable and Doctrine. Those are the ones I know of, I am sure there are more implementations. Out of those three I'd recommend Doctrine. Last time I checked Adodb carried a lot of extra weight for PHP4 and Zend_Db_* is generally not known to be the best in terms of completeness and performance (most likely due to its young age). Doctrine aside from Active Table and the general database abstraction thing (aka DBAL) has so many things (e.g. migrations) which make it worth checking out, so if you haven't set your mind on a DBAL yet, you need to check it out.
Recommendations for implementations of ActiveRecord Does anyone have any recommendations for implementations of ActiveRecord in PHP? I've been using CBL ActiveRecord, but I was wondering if there were any viable alternatives.
TITLE: Recommendations for implementations of ActiveRecord QUESTION: Does anyone have any recommendations for implementations of ActiveRecord in PHP? I've been using CBL ActiveRecord, but I was wondering if there were any viable alternatives. ANSWER: Depends!;) For example there is ADODB's Active Record implementation, then there is Zend_Db_DataTable and Doctrine. Those are the ones I know of, I am sure there are more implementations. Out of those three I'd recommend Doctrine. Last time I checked Adodb carried a lot of extra weight for PHP4 and Zend_Db_* is generally not known to be the best in terms of completeness and performance (most likely due to its young age). Doctrine aside from Active Table and the general database abstraction thing (aka DBAL) has so many things (e.g. migrations) which make it worth checking out, so if you haven't set your mind on a DBAL yet, you need to check it out.
[ "php" ]
2
1
994
5
0
2008-09-01T13:58:49.650000
2008-09-01T15:53:57.050000
37,991
38,587
Using MS Access & ODBC to connect to a remote PostgreSQL
I currently have an MS Access application that connects to a PostgreSQL database via ODBC. This successfully runs on a LAN with 20 users (each running their own version of Access). Now I am thinking through some disaster recovery scenarios, and it seems that a quick and easy method of protecting the data is to use log shipping to create a warm-standby. This lead me to think about putting this warm-standby at a remote location, but then I have the question: Is Access connecting to a remote database via ODBC usable? I.e. the remote database is maybe in the same country with ok ping times and I have a 1mbit SDSL line.
onnodb, The PostgreSQL ODBC driver is actively developed and an Access front-end combined with PostgreSQL server, in my opinion makes a great option on a LAN for rapid development. I have been involved in a reasonably big system (100+ PostgreSQL tables, 200+ Access forms, 1000+ Access queries & reports) and it has run excellently for a few years, with ~20 users. Any queries running slow because Access is doing something stupid can generally just be solved by using views, and any really data-intensive code can easily be moved into PostgreSQL functions and then called from Access. The only main ODBC-related issue we have is that there is no way to kill a slow running query from Access, so we do often get users just killing Access and then massive queries are just left executing on the server.
Using MS Access & ODBC to connect to a remote PostgreSQL I currently have an MS Access application that connects to a PostgreSQL database via ODBC. This successfully runs on a LAN with 20 users (each running their own version of Access). Now I am thinking through some disaster recovery scenarios, and it seems that a quick and easy method of protecting the data is to use log shipping to create a warm-standby. This lead me to think about putting this warm-standby at a remote location, but then I have the question: Is Access connecting to a remote database via ODBC usable? I.e. the remote database is maybe in the same country with ok ping times and I have a 1mbit SDSL line.
TITLE: Using MS Access & ODBC to connect to a remote PostgreSQL QUESTION: I currently have an MS Access application that connects to a PostgreSQL database via ODBC. This successfully runs on a LAN with 20 users (each running their own version of Access). Now I am thinking through some disaster recovery scenarios, and it seems that a quick and easy method of protecting the data is to use log shipping to create a warm-standby. This lead me to think about putting this warm-standby at a remote location, but then I have the question: Is Access connecting to a remote database via ODBC usable? I.e. the remote database is maybe in the same country with ok ping times and I have a 1mbit SDSL line. ANSWER: onnodb, The PostgreSQL ODBC driver is actively developed and an Access front-end combined with PostgreSQL server, in my opinion makes a great option on a LAN for rapid development. I have been involved in a reasonably big system (100+ PostgreSQL tables, 200+ Access forms, 1000+ Access queries & reports) and it has run excellently for a few years, with ~20 users. Any queries running slow because Access is doing something stupid can generally just be solved by using views, and any really data-intensive code can easily be moved into PostgreSQL functions and then called from Access. The only main ODBC-related issue we have is that there is no way to kill a slow running query from Access, so we do often get users just killing Access and then massive queries are just left executing on the server.
[ "ms-access", "postgresql", "odbc" ]
8
11
15,468
4
0
2008-09-01T14:14:53.417000
2008-09-01T23:09:50.183000
38,002
38,041
How to get your network support team behind click-once?
I'm trying to make the case for click-once and smart client development but my network support team wants to keep with web development for everything. What is the best way to convince them that click-once and smart client development have a place in the business?
We use ClickOnce where I work; in terms of comparison to a web release I would base the case around the need for providing users with a rich client app, otherwise it might well actually be better to use web applications. In terms of releasing a rich client app ClickOnce is fantastic; you can set it up to enforce updates on startup thus enforcing a version throughout the network. You can make the case that ClickOnce gives you the same benefit of having a single deployment point that web deployment possesses. Personally I've found ClickOnce to be unbelievably useful. If you're developing rich client.net apps (in Windows, though let's face it the vast majority of real.net development is in Windows) and want to deploy it across a network nothing else compares.
How to get your network support team behind click-once? I'm trying to make the case for click-once and smart client development but my network support team wants to keep with web development for everything. What is the best way to convince them that click-once and smart client development have a place in the business?
TITLE: How to get your network support team behind click-once? QUESTION: I'm trying to make the case for click-once and smart client development but my network support team wants to keep with web development for everything. What is the best way to convince them that click-once and smart client development have a place in the business? ANSWER: We use ClickOnce where I work; in terms of comparison to a web release I would base the case around the need for providing users with a rich client app, otherwise it might well actually be better to use web applications. In terms of releasing a rich client app ClickOnce is fantastic; you can set it up to enforce updates on startup thus enforcing a version throughout the network. You can make the case that ClickOnce gives you the same benefit of having a single deployment point that web deployment possesses. Personally I've found ClickOnce to be unbelievably useful. If you're developing rich client.net apps (in Windows, though let's face it the vast majority of real.net development is in Windows) and want to deploy it across a network nothing else compares.
[ "smartclient" ]
3
1
186
5
0
2008-09-01T14:33:43.340000
2008-09-01T15:11:26.137000
38,005
38,716
How to use LINQ To SQL in an N-Tier Solution?
Now that LINQ to SQL is a little more mature, I'd like to know of any techniques people are using to create an n-tiered solution using the technology, because it does not seem that obvious to me.
LINQ to SQL doesn't really have a n-tier story that I've seen, since the objects that it creates are created in the class with the rest of it, you don't really have an assembly that you can nicely reference through something like Web Services, etc. The only way I'd really consider it is using the datacontext to fetch data, then fill an intermediary data model, passing that through, and referencing it on both sides, and using that in your client side - then passing them back and pushing the data back into a new Datacontext or intellgently updating rows after you refetch them. That's if I'm understanding what you're trying to get at:\ I asked ScottGu the same question on his blog when I first started looking at it - but I haven't seen a single scenario or app in the wild that uses LINQ to SQL in this way. Websites like Rob Connery's Storefront are closer to the provider.
How to use LINQ To SQL in an N-Tier Solution? Now that LINQ to SQL is a little more mature, I'd like to know of any techniques people are using to create an n-tiered solution using the technology, because it does not seem that obvious to me.
TITLE: How to use LINQ To SQL in an N-Tier Solution? QUESTION: Now that LINQ to SQL is a little more mature, I'd like to know of any techniques people are using to create an n-tiered solution using the technology, because it does not seem that obvious to me. ANSWER: LINQ to SQL doesn't really have a n-tier story that I've seen, since the objects that it creates are created in the class with the rest of it, you don't really have an assembly that you can nicely reference through something like Web Services, etc. The only way I'd really consider it is using the datacontext to fetch data, then fill an intermediary data model, passing that through, and referencing it on both sides, and using that in your client side - then passing them back and pushing the data back into a new Datacontext or intellgently updating rows after you refetch them. That's if I'm understanding what you're trying to get at:\ I asked ScottGu the same question on his blog when I first started looking at it - but I haven't seen a single scenario or app in the wild that uses LINQ to SQL in this way. Websites like Rob Connery's Storefront are closer to the provider.
[ "linq-to-sql", "n-tier-architecture" ]
15
1
4,480
7
0
2008-09-01T14:37:40.163000
2008-09-02T02:30:49.857000
38,010
38,011
C# string concatenation and string interning
When performing string concatentation of an existing string in the intern pool, is a new string entered into the intern pool or is a reference returned to the existing string in the intern pool? According to this article, String.Concat and StringBuilder will insert new string instances into the intern pool? http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx Can anyone explain how concatenation works with the intern pool?
If you create new strings, they will not automatically be put into the intern pool, unless you concatenate constants compile-time, in which case the compiler will create one string result and intern that as part of the JIT process.
C# string concatenation and string interning When performing string concatentation of an existing string in the intern pool, is a new string entered into the intern pool or is a reference returned to the existing string in the intern pool? According to this article, String.Concat and StringBuilder will insert new string instances into the intern pool? http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx Can anyone explain how concatenation works with the intern pool?
TITLE: C# string concatenation and string interning QUESTION: When performing string concatentation of an existing string in the intern pool, is a new string entered into the intern pool or is a reference returned to the existing string in the intern pool? According to this article, String.Concat and StringBuilder will insert new string instances into the intern pool? http://community.bartdesmet.net/blogs/bart/archive/2006/09/27/4472.aspx Can anyone explain how concatenation works with the intern pool? ANSWER: If you create new strings, they will not automatically be put into the intern pool, unless you concatenate constants compile-time, in which case the compiler will create one string result and intern that as part of the JIT process.
[ "c#", ".net", "string" ]
4
4
1,478
2
0
2008-09-01T14:41:59.797000
2008-09-01T14:44:11.210000
38,014
38,050
Referencing same table name in different schemas
I am facing problem with an Oracle Query in a.net 2.0 based windows application. I am using System.Data.OracleClient to connect to oracle database. Name of database is myDB. Below the the connection string I am using: Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL))); User ID=myDB;Password=myDB;Unicode=True If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB): SELECT ID, NAME FROM MyTempTable WHERE ID IN (10780, 10760, 11890) But if I append the database name along with it the it is giving correct result: SELECT ID, NAME FROM "myDB".MyTempTable WHERE ID IN (10780, 10760, 11890) My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.
This looks like an issue with name resolution, try creating a public synonym on the table: CREATE PUBLIC SYNONYM MyTempTable for MyTempTable; Also, what exactly do you mean by wrong result, incorrect data, error message? Edit: What is the name of the schema that the required table belongs to? It sounds like the table that you are trying to select from is in a different schema to the one that belongs to the user you are connecting as.
Referencing same table name in different schemas I am facing problem with an Oracle Query in a.net 2.0 based windows application. I am using System.Data.OracleClient to connect to oracle database. Name of database is myDB. Below the the connection string I am using: Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL))); User ID=myDB;Password=myDB;Unicode=True If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB): SELECT ID, NAME FROM MyTempTable WHERE ID IN (10780, 10760, 11890) But if I append the database name along with it the it is giving correct result: SELECT ID, NAME FROM "myDB".MyTempTable WHERE ID IN (10780, 10760, 11890) My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help.
TITLE: Referencing same table name in different schemas QUESTION: I am facing problem with an Oracle Query in a.net 2.0 based windows application. I am using System.Data.OracleClient to connect to oracle database. Name of database is myDB. Below the the connection string I am using: Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP) (HOST = 172.16.0.24)(PORT = 1522)))(CONNECT_DATA =(SERVICE_NAME = ORCL))); User ID=myDB;Password=myDB;Unicode=True If I run the below query then it will given me wrong result (here wrong result means incorrect data. The data doesn't belongs to myDB): SELECT ID, NAME FROM MyTempTable WHERE ID IN (10780, 10760, 11890) But if I append the database name along with it the it is giving correct result: SELECT ID, NAME FROM "myDB".MyTempTable WHERE ID IN (10780, 10760, 11890) My limitation is that I cannot append the database name as this is a generic application and can run with any database on run time. Please help. ANSWER: This looks like an issue with name resolution, try creating a public synonym on the table: CREATE PUBLIC SYNONYM MyTempTable for MyTempTable; Also, what exactly do you mean by wrong result, incorrect data, error message? Edit: What is the name of the schema that the required table belongs to? It sounds like the table that you are trying to select from is in a different schema to the one that belongs to the user you are connecting as.
[ ".net", "sql", "oracle" ]
3
2
1,729
5
0
2008-09-01T14:51:30.693000
2008-09-01T15:18:49.380000
38,019
48,001
What's the best approach to naming classes?
Coming up with good, precise names for classes is notoriously difficult. Done right, it makes code more self-documenting and provides a vocabulary for reasoning about code at a higher level of abstraction. Classes which implement a particular design pattern might be given a name based on the well known pattern name (e.g. FooFactory, FooFacade), and classes which directly model domain concepts can take their names from the problem domain, but what about other classes? Is there anything like a programmer's thesaurus that I can turn to when I'm lacking inspiration, and want to avoid using generic class names (like FooHandler, FooProcessor, FooUtils, and FooManager)?
I'll cite some passages from Implementation Patterns by Kent Beck: Simple Superclass Name "[...] The names should be short and punchy. However, to make the names precise sometimes seems to require several words. A way out of this dilemma is picking a strong metaphor for the computation. With a metaphor in mind, even single words bring with them a rich web of associations, connections, and implications. For example, in the HotDraw drawing framework, my first name for an object in a drawing was DrawingObject. Ward Cunningham came along with the typography metaphor: a drawing is like a printed, laid-out page. Graphical items on a page are figures, so the class became Figure. In the context of the metaphor, Figure is simultaneously shorter, richer, and more precise than DrawingObject." Qualified Subclass Name "The names of subclasses have two jobs. They need to communicate what class they are like and how they are different. [...] Unlike the names at the roots of hierarchies, subclass names aren’t used nearly as often in conversation, so they can be expressive at the cost of being concise. [...] Give subclasses that serve as the roots of hierarchies their own simple names. For example, HotDraw has a class Handle which presents figure- editing operations when a figure is selected. It is called, simply, Handle in spite of extending Figure. There is a whole family of handles and they most appropriately have names like StretchyHandle and TransparencyHandle. Because Handle is the root of its own hierarchy, it deserves a simple superclass name more than a qualified subclass name. Another wrinkle in subclass naming is multiple-level hierarchies. [...] Rather than blindly prepend the modifiers to the immediate superclass, think about the name from the reader’s perspective. What class does he need to know this class is like? Use that superclass as the basis for the subclass name." Interface Two styles of naming interfaces depend on how you are thinking of the interfaces. Interfaces as classes without implementations should be named as if they were classes ( Simple Superclass Name, Qualified Subclass Name ). One problem with this style of naming is that the good names are used up before you get to naming classes. An interface called File needs an implementation class called something like ActualFile, ConcreteFile, or (yuck!) FileImpl (both a suffix and an abbreviation). In general, communicating whether one is dealing with a concrete or abstract object is important, whether the abstract object is implemented as an interface or a superclass is less important. Deferring the distinction between interfaces and superclasses is well >supported by this style of naming, leaving you free to change your mind later if that >becomes necessary. Sometimes, naming concrete classes simply is more important to communication than hiding the use of interfaces. In this case, prefix interface names with “I”. If the interface is called IFile, the class can be simply called File. For more detailed discussion, buy the book! It's worth it!:)
What's the best approach to naming classes? Coming up with good, precise names for classes is notoriously difficult. Done right, it makes code more self-documenting and provides a vocabulary for reasoning about code at a higher level of abstraction. Classes which implement a particular design pattern might be given a name based on the well known pattern name (e.g. FooFactory, FooFacade), and classes which directly model domain concepts can take their names from the problem domain, but what about other classes? Is there anything like a programmer's thesaurus that I can turn to when I'm lacking inspiration, and want to avoid using generic class names (like FooHandler, FooProcessor, FooUtils, and FooManager)?
TITLE: What's the best approach to naming classes? QUESTION: Coming up with good, precise names for classes is notoriously difficult. Done right, it makes code more self-documenting and provides a vocabulary for reasoning about code at a higher level of abstraction. Classes which implement a particular design pattern might be given a name based on the well known pattern name (e.g. FooFactory, FooFacade), and classes which directly model domain concepts can take their names from the problem domain, but what about other classes? Is there anything like a programmer's thesaurus that I can turn to when I'm lacking inspiration, and want to avoid using generic class names (like FooHandler, FooProcessor, FooUtils, and FooManager)? ANSWER: I'll cite some passages from Implementation Patterns by Kent Beck: Simple Superclass Name "[...] The names should be short and punchy. However, to make the names precise sometimes seems to require several words. A way out of this dilemma is picking a strong metaphor for the computation. With a metaphor in mind, even single words bring with them a rich web of associations, connections, and implications. For example, in the HotDraw drawing framework, my first name for an object in a drawing was DrawingObject. Ward Cunningham came along with the typography metaphor: a drawing is like a printed, laid-out page. Graphical items on a page are figures, so the class became Figure. In the context of the metaphor, Figure is simultaneously shorter, richer, and more precise than DrawingObject." Qualified Subclass Name "The names of subclasses have two jobs. They need to communicate what class they are like and how they are different. [...] Unlike the names at the roots of hierarchies, subclass names aren’t used nearly as often in conversation, so they can be expressive at the cost of being concise. [...] Give subclasses that serve as the roots of hierarchies their own simple names. For example, HotDraw has a class Handle which presents figure- editing operations when a figure is selected. It is called, simply, Handle in spite of extending Figure. There is a whole family of handles and they most appropriately have names like StretchyHandle and TransparencyHandle. Because Handle is the root of its own hierarchy, it deserves a simple superclass name more than a qualified subclass name. Another wrinkle in subclass naming is multiple-level hierarchies. [...] Rather than blindly prepend the modifiers to the immediate superclass, think about the name from the reader’s perspective. What class does he need to know this class is like? Use that superclass as the basis for the subclass name." Interface Two styles of naming interfaces depend on how you are thinking of the interfaces. Interfaces as classes without implementations should be named as if they were classes ( Simple Superclass Name, Qualified Subclass Name ). One problem with this style of naming is that the good names are used up before you get to naming classes. An interface called File needs an implementation class called something like ActualFile, ConcreteFile, or (yuck!) FileImpl (both a suffix and an abbreviation). In general, communicating whether one is dealing with a concrete or abstract object is important, whether the abstract object is implemented as an interface or a superclass is less important. Deferring the distinction between interfaces and superclasses is well >supported by this style of naming, leaving you free to change your mind later if that >becomes necessary. Sometimes, naming concrete classes simply is more important to communication than hiding the use of interfaces. In this case, prefix interface names with “I”. If the interface is called IFile, the class can be simply called File. For more detailed discussion, buy the book! It's worth it!:)
[ "naming" ]
103
67
61,733
6
0
2008-09-01T14:55:47.453000
2008-09-07T01:05:59.813000
38,021
38,028
How do I find the authoritative name-server for a domain name?
How can I find the origins of conflicting DNS records?
You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available nslookup command line tool: command line> nslookup > set querytype=soa > stackoverflow.com Server: 217.30.180.230 Address: 217.30.180.230#53 Non-authoritative answer: stackoverflow.com origin = ns51.domaincontrol.com # ("primary name server" on Windows) mail addr = dns.jomax.net # ("responsible mail addr" on Windows) serial = 2008041300 refresh = 28800 retry = 7200 expire = 604800 minimum = 86400 Authoritative answers can be found from: stackoverflow.com nameserver = ns52.domaincontrol.com. stackoverflow.com nameserver = ns51.domaincontrol.com. The origin (or primary name server on Windows) line tells you that ns51.domaincontrol is the main name server for stackoverflow.com. At the end of output all authoritative servers, including backup servers for the given domain, are listed.
How do I find the authoritative name-server for a domain name? How can I find the origins of conflicting DNS records?
TITLE: How do I find the authoritative name-server for a domain name? QUESTION: How can I find the origins of conflicting DNS records? ANSWER: You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available nslookup command line tool: command line> nslookup > set querytype=soa > stackoverflow.com Server: 217.30.180.230 Address: 217.30.180.230#53 Non-authoritative answer: stackoverflow.com origin = ns51.domaincontrol.com # ("primary name server" on Windows) mail addr = dns.jomax.net # ("responsible mail addr" on Windows) serial = 2008041300 refresh = 28800 retry = 7200 expire = 604800 minimum = 86400 Authoritative answers can be found from: stackoverflow.com nameserver = ns52.domaincontrol.com. stackoverflow.com nameserver = ns51.domaincontrol.com. The origin (or primary name server on Windows) line tells you that ns51.domaincontrol is the main name server for stackoverflow.com. At the end of output all authoritative servers, including backup servers for the given domain, are listed.
[ "dns" ]
363
468
551,858
12
0
2008-09-01T14:57:16.967000
2008-09-01T15:04:19.757000
38,026
38,129
How can I improve my support of Novell networks when I don't have a Novell network?
I work for a.NET/MSSQL shop that has trouble supporting customers running Novell, partially because we don't have Novell (or the money for it) and partially because we have no one with Novell experience. This question could easily be expanded to "How can we improve our support of technology X when we don't have technology X?" Obviously, I expect someone to say "it is easy to acquire the technology or someone with that kind of experience," but keep in mind I'm just a developer, not the development manager or someone with power over the purse strings. I looked for a Novell server virtual appliance (though I'm not sure "Novell server" is what I should be looking for) but didn't find much on VMware's website.
There is a 60 day evaluation trial of Open Enterprise Server 2 available (requires free registration). If you install it in a VM, there's nothing stopping you from reinstalling it after 60 days (well except licence). But you will need someone good with Linux to handle this (and preferably good with this precise technology). In a MS shop this might be a problem. The easiest solution would be to outsource this - have some external techs test your software for compatibility. If you find out you are paying too much - hire someone who knows this software stack. You can't support something if you don't test against it. And you can't test against something you don't know.
How can I improve my support of Novell networks when I don't have a Novell network? I work for a.NET/MSSQL shop that has trouble supporting customers running Novell, partially because we don't have Novell (or the money for it) and partially because we have no one with Novell experience. This question could easily be expanded to "How can we improve our support of technology X when we don't have technology X?" Obviously, I expect someone to say "it is easy to acquire the technology or someone with that kind of experience," but keep in mind I'm just a developer, not the development manager or someone with power over the purse strings. I looked for a Novell server virtual appliance (though I'm not sure "Novell server" is what I should be looking for) but didn't find much on VMware's website.
TITLE: How can I improve my support of Novell networks when I don't have a Novell network? QUESTION: I work for a.NET/MSSQL shop that has trouble supporting customers running Novell, partially because we don't have Novell (or the money for it) and partially because we have no one with Novell experience. This question could easily be expanded to "How can we improve our support of technology X when we don't have technology X?" Obviously, I expect someone to say "it is easy to acquire the technology or someone with that kind of experience," but keep in mind I'm just a developer, not the development manager or someone with power over the purse strings. I looked for a Novell server virtual appliance (though I'm not sure "Novell server" is what I should be looking for) but didn't find much on VMware's website. ANSWER: There is a 60 day evaluation trial of Open Enterprise Server 2 available (requires free registration). If you install it in a VM, there's nothing stopping you from reinstalling it after 60 days (well except licence). But you will need someone good with Linux to handle this (and preferably good with this precise technology). In a MS shop this might be a problem. The easiest solution would be to outsource this - have some external techs test your software for compatibility. If you find out you are paying too much - hire someone who knows this software stack. You can't support something if you don't test against it. And you can't test against something you don't know.
[ ".net", "sql-server", "vmware", "novell" ]
2
2
463
3
0
2008-09-01T15:01:39.327000
2008-09-01T16:29:57.023000
38,027
38,033
Why does Splint (the C code checker) give an error when comparing a float to an int?
Both are mathematical values, however the float does have more precision. Is that the only reason for the error - the difference in precision? Or is there another potential (and more serious) problem?
It's because the set of integer values does not equal the set of float values for the 'int' and 'float' types. For example, the float value 0.5 has no equal in the integer set and the integer value 4519245367 might not exist in the set of values a float can store. So, the checker flags this as an issue to be checked by the programmer.
Why does Splint (the C code checker) give an error when comparing a float to an int? Both are mathematical values, however the float does have more precision. Is that the only reason for the error - the difference in precision? Or is there another potential (and more serious) problem?
TITLE: Why does Splint (the C code checker) give an error when comparing a float to an int? QUESTION: Both are mathematical values, however the float does have more precision. Is that the only reason for the error - the difference in precision? Or is there another potential (and more serious) problem? ANSWER: It's because the set of integer values does not equal the set of float values for the 'int' and 'float' types. For example, the float value 0.5 has no equal in the integer set and the integer value 4519245367 might not exist in the set of values a float can store. So, the checker flags this as an issue to be checked by the programmer.
[ "c", "lint", "splint" ]
4
8
502
6
0
2008-09-01T15:02:39.900000
2008-09-01T15:06:30.377000
38,035
2,509,444
Selecting X words from a text field in MySQL
I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?
You can do it all in the query using SUBSTRING_INDEX CONCAT_WS( ' ', -- 20 words before TRIM( SUBSTRING_INDEX( SUBSTRING(field, 1, INSTR(field, 'word') - 1 ), ' ', -20 ) ), -- your word 'word', -- 20 words after TRIM( SUBSTRING_INDEX( SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ), ' ', 20 ) ) )
Selecting X words from a text field in MySQL I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well?
TITLE: Selecting X words from a text field in MySQL QUESTION: I'm building a basic search functionality, using LIKE (I'd be using fulltext but can't at the moment) and I'm wondering if MySQL can, on searching for a keyword (e.g. WHERE field LIKE '%word%') return 20 words either side of the keyword, as well? ANSWER: You can do it all in the query using SUBSTRING_INDEX CONCAT_WS( ' ', -- 20 words before TRIM( SUBSTRING_INDEX( SUBSTRING(field, 1, INSTR(field, 'word') - 1 ), ' ', -20 ) ), -- your word 'word', -- 20 words after TRIM( SUBSTRING_INDEX( SUBSTRING(field, INSTR(field, 'word') + LENGTH('word') ), ' ', 20 ) ) )
[ "mysql" ]
1
2
3,845
4
0
2008-09-01T15:08:13.070000
2010-03-24T16:28:03.290000
38,037
38,413
C++: How to extract a string from RapidXml
In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a std::string ). RapidXml has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.) Thank you.
Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml: #include #include #include "rapidxml/rapidxml.hpp" #include "rapidxml/rapidxml_print.hpp" int main(int argc, char* argv[]) { char xml[] = " " " " " "; //Parse the original document rapidxml::xml_document<> doc; doc.parse<0>(xml); std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n"; //Insert something rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe"); doc.first_node()->append_node(node); std::stringstream ss; ss <<*doc.first_node(); std::string result_xml = ss.str(); std::cout <
C++: How to extract a string from RapidXml In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a std::string ). RapidXml has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.) Thank you.
TITLE: C++: How to extract a string from RapidXml QUESTION: In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a std::string ). RapidXml has been recommended to me, but I can't see how to retrieve the XML back as a text string. (I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.) Thank you. ANSWER: Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml: #include #include #include "rapidxml/rapidxml.hpp" #include "rapidxml/rapidxml_print.hpp" int main(int argc, char* argv[]) { char xml[] = " " " " " "; //Parse the original document rapidxml::xml_document<> doc; doc.parse<0>(xml); std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n"; //Insert something rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe"); doc.first_node()->append_node(node); std::stringstream ss; ss <<*doc.first_node(); std::string result_xml = ss.str(); std::cout <
[ "c++", "xml", "rapidxml" ]
15
11
18,250
8
0
2008-09-01T15:10:13.800000
2008-09-01T20:52:45.223000
38,039
38,064
How can I get the DateTime for the start of the week?
How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#? Something like: DateTime.Now.StartWeek(Monday);
Use an extension method: public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-1 * diff).Date; } } Which can be used as follows: DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday); DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
How can I get the DateTime for the start of the week? How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#? Something like: DateTime.Now.StartWeek(Monday);
TITLE: How can I get the DateTime for the start of the week? QUESTION: How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#? Something like: DateTime.Now.StartWeek(Monday); ANSWER: Use an extension method: public static class DateTimeExtensions { public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek) { int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7; return dt.AddDays(-1 * diff).Date; } } Which can be used as follows: DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday); DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
[ "c#", "datetime" ]
585
942
386,101
33
0
2008-09-01T15:10:38.527000
2008-09-01T15:45:54.697000
38,056
38,230
How to check if a process is still running using Python on Linux?
The only nice way I've found is: import sys import os try: os.kill(int(sys.argv[1]), 0) print "Running" except: print "Not running" ( Source ) But is this reliable? Does it work with every process and every distribution?
Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable: >>> import os.path >>> os.path.exists("/proc/0") False >>> os.path.exists("/proc/12") True
How to check if a process is still running using Python on Linux? The only nice way I've found is: import sys import os try: os.kill(int(sys.argv[1]), 0) print "Running" except: print "Not running" ( Source ) But is this reliable? Does it work with every process and every distribution?
TITLE: How to check if a process is still running using Python on Linux? QUESTION: The only nice way I've found is: import sys import os try: os.kill(int(sys.argv[1]), 0) print "Running" except: print "Not running" ( Source ) But is this reliable? Does it work with every process and every distribution? ANSWER: Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable: >>> import os.path >>> os.path.exists("/proc/0") False >>> os.path.exists("/proc/12") True
[ "python", "linux", "unix", "process" ]
39
56
104,961
9
0
2008-09-01T15:20:52.277000
2008-09-01T18:06:42.690000
38,057
53,448
Why @OneToMany does not work with inheritance in Hibernate
@Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Problem { @ManyToOne private Person person; } @Entity @DiscriminatorValue("UP") public class UglyProblem extends Problem {} @Entity public class Person { @OneToMany(mappedBy="person") private List< UglyProblem > problems; } I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")". All I found is this. I was not able to find the post by Emmanuel Bernard explaining reasons behind this. Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored." Well I think this means that if I have these two classes: public class A { private int foo; } @Entity public class B extens A { } then field foo will not be mapped for class B. Which makes sense. But if I have something like this: @Entity public class Problem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity public class UglyProblem extends Problem { private int levelOfUgliness; public int getLevelOfUgliness() { return levelOfUgliness; } public void setLevelOfUgliness(int levelOfUgliness) { this.levelOfUgliness = levelOfUgliness; } } I expect the class UglyProblem to have fileds id and name and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table: CREATE TABLE "problem" ( "DTYPE" varchar(31) NOT NULL, "id" bigint(20) NOT NULL auto_increment, "name" varchar(255) default NULL, "levelOfUgliness" int(11) default NULL, PRIMARY KEY ("id") ) AUTO_INCREMENT=2; Going back to my question: I expect @ManyToOne person to be inherited by UglyProblem class. I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships. Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why...":). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked. I want to find out the motivation of this design decision. (if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)
I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works.:) Let's try to understand the problem. I think your concepts are "lying". First you say that many Problem s are associated to People. But, then you say that one Person have many UglyProblem s (and does not relate to other Problem s). Something is wrong with that design. Imagine how it's going to be mapped to the database. You have a single table inheritance, so: _____________ |__PROBLEMS__| |__PEOPLE__| |id | | | |person | -------->| | |problemType | |_________ | -------------- How is hibernate going to enforce the database to make Problem only relate to People if its problemType is equal UP? That's a very difficult problem to solve. So, if you want this kind of relation, every subclass must be in it's own table. That's what @MappedSuperclass does. PS.: Sorry for the ugly drawing:D
Why @OneToMany does not work with inheritance in Hibernate @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Problem { @ManyToOne private Person person; } @Entity @DiscriminatorValue("UP") public class UglyProblem extends Problem {} @Entity public class Person { @OneToMany(mappedBy="person") private List< UglyProblem > problems; } I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")". All I found is this. I was not able to find the post by Emmanuel Bernard explaining reasons behind this. Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored." Well I think this means that if I have these two classes: public class A { private int foo; } @Entity public class B extens A { } then field foo will not be mapped for class B. Which makes sense. But if I have something like this: @Entity public class Problem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity public class UglyProblem extends Problem { private int levelOfUgliness; public int getLevelOfUgliness() { return levelOfUgliness; } public void setLevelOfUgliness(int levelOfUgliness) { this.levelOfUgliness = levelOfUgliness; } } I expect the class UglyProblem to have fileds id and name and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table: CREATE TABLE "problem" ( "DTYPE" varchar(31) NOT NULL, "id" bigint(20) NOT NULL auto_increment, "name" varchar(255) default NULL, "levelOfUgliness" int(11) default NULL, PRIMARY KEY ("id") ) AUTO_INCREMENT=2; Going back to my question: I expect @ManyToOne person to be inherited by UglyProblem class. I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships. Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why...":). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked. I want to find out the motivation of this design decision. (if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)
TITLE: Why @OneToMany does not work with inheritance in Hibernate QUESTION: @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) public class Problem { @ManyToOne private Person person; } @Entity @DiscriminatorValue("UP") public class UglyProblem extends Problem {} @Entity public class Person { @OneToMany(mappedBy="person") private List< UglyProblem > problems; } I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")". All I found is this. I was not able to find the post by Emmanuel Bernard explaining reasons behind this. Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored." Well I think this means that if I have these two classes: public class A { private int foo; } @Entity public class B extens A { } then field foo will not be mapped for class B. Which makes sense. But if I have something like this: @Entity public class Problem { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Entity public class UglyProblem extends Problem { private int levelOfUgliness; public int getLevelOfUgliness() { return levelOfUgliness; } public void setLevelOfUgliness(int levelOfUgliness) { this.levelOfUgliness = levelOfUgliness; } } I expect the class UglyProblem to have fileds id and name and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table: CREATE TABLE "problem" ( "DTYPE" varchar(31) NOT NULL, "id" bigint(20) NOT NULL auto_increment, "name" varchar(255) default NULL, "levelOfUgliness" int(11) default NULL, PRIMARY KEY ("id") ) AUTO_INCREMENT=2; Going back to my question: I expect @ManyToOne person to be inherited by UglyProblem class. I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships. Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why...":). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked. I want to find out the motivation of this design decision. (if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...) ANSWER: I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works.:) Let's try to understand the problem. I think your concepts are "lying". First you say that many Problem s are associated to People. But, then you say that one Person have many UglyProblem s (and does not relate to other Problem s). Something is wrong with that design. Imagine how it's going to be mapped to the database. You have a single table inheritance, so: _____________ |__PROBLEMS__| |__PEOPLE__| |id | | | |person | -------->| | |problemType | |_________ | -------------- How is hibernate going to enforce the database to make Problem only relate to People if its problemType is equal UP? That's a very difficult problem to solve. So, if you want this kind of relation, every subclass must be in it's own table. That's what @MappedSuperclass does. PS.: Sorry for the ugly drawing:D
[ "java", "hibernate", "inheritance", "orm" ]
11
8
30,830
6
0
2008-09-01T15:21:01.310000
2008-09-10T05:06:10.240000
38,068
38,102
Generics in Java
Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible: Typedef myGenDef = < Object1, Object2 >; HashMap< myGenDef > hm = new HashMap< myGenDef >(); for (Entry< myGenDef > ent: hm..entrySet()) {... }
There's the pseudo-typedef antipattern... class StringList extends ArrayList { } Good stuff, drink up!;-) As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types.
Generics in Java Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible: Typedef myGenDef = < Object1, Object2 >; HashMap< myGenDef > hm = new HashMap< myGenDef >(); for (Entry< myGenDef > ent: hm..entrySet()) {... }
TITLE: Generics in Java QUESTION: Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible: Typedef myGenDef = < Object1, Object2 >; HashMap< myGenDef > hm = new HashMap< myGenDef >(); for (Entry< myGenDef > ent: hm..entrySet()) {... } ANSWER: There's the pseudo-typedef antipattern... class StringList extends ArrayList { } Good stuff, drink up!;-) As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types.
[ "java", "generics" ]
10
12
2,576
5
0
2008-09-01T15:49:48.713000
2008-09-01T16:17:14.823000
38,074
40,159
Best way to handle LOBs in Oracle distributed databases
If you create an Oracle dblink you cannot directly access LOB columns in the target tables. For instance, you create a dblink with: create database link TEST_LINK connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID'; After this you can do stuff like: select column_a, column_b from data_user.sample_table@TEST_LINK Except if the column is a LOB, then you get the error: ORA-22992: cannot use LOB locators selected from remote tables This is a documented restriction. The same page suggests you fetch the values into a local table, but that is... kind of messy: CREATE TABLE tmp_hello AS SELECT column_a from data_user.sample_table@TEST_LINK Any other ideas?
Yeah, it is messy, I can't think of a way to avoid it though. You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table) One thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables.
Best way to handle LOBs in Oracle distributed databases If you create an Oracle dblink you cannot directly access LOB columns in the target tables. For instance, you create a dblink with: create database link TEST_LINK connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID'; After this you can do stuff like: select column_a, column_b from data_user.sample_table@TEST_LINK Except if the column is a LOB, then you get the error: ORA-22992: cannot use LOB locators selected from remote tables This is a documented restriction. The same page suggests you fetch the values into a local table, but that is... kind of messy: CREATE TABLE tmp_hello AS SELECT column_a from data_user.sample_table@TEST_LINK Any other ideas?
TITLE: Best way to handle LOBs in Oracle distributed databases QUESTION: If you create an Oracle dblink you cannot directly access LOB columns in the target tables. For instance, you create a dblink with: create database link TEST_LINK connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID'; After this you can do stuff like: select column_a, column_b from data_user.sample_table@TEST_LINK Except if the column is a LOB, then you get the error: ORA-22992: cannot use LOB locators selected from remote tables This is a documented restriction. The same page suggests you fetch the values into a local table, but that is... kind of messy: CREATE TABLE tmp_hello AS SELECT column_a from data_user.sample_table@TEST_LINK Any other ideas? ANSWER: Yeah, it is messy, I can't think of a way to avoid it though. You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table) One thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables.
[ "sql", "oracle", "distributed-transactions", "dblink" ]
14
5
52,370
6
0
2008-09-01T15:52:32.277000
2008-09-02T17:53:52.493000
38,081
38,087
How to implement mouse dragging in Visual Basic?
I need to create a quick-n-dirty knob control in Visual Basic 2005 Express, the value of which is incremented/decremented by "grabbing" it with the mouse and moving the cursor up/down. Because the knob itself doesn't move, I need to keep tracking the mouse movement outside of the rectangle of the control. I use a Label with an ImageList to implement this (I have a list of 127 bitmaps representing the knob in various positions). Which events should I react to?
You need the control to handle three events: Mouse Down, Mouse Move and Mouse Up. On the Mouse Down event, you will need to capture the mouse. This means the mouse messages are sent to the control that has the capture. In the mouse move event, if the input is captured then update the displayed image depending on the amount the mouse moved. In the mouse up event, release the capture if the input is captured. The boolean jjnguy suggests is unnecessary as the Capture property of a Control is readable so it's possible to determine if the capture has been set.
How to implement mouse dragging in Visual Basic? I need to create a quick-n-dirty knob control in Visual Basic 2005 Express, the value of which is incremented/decremented by "grabbing" it with the mouse and moving the cursor up/down. Because the knob itself doesn't move, I need to keep tracking the mouse movement outside of the rectangle of the control. I use a Label with an ImageList to implement this (I have a list of 127 bitmaps representing the knob in various positions). Which events should I react to?
TITLE: How to implement mouse dragging in Visual Basic? QUESTION: I need to create a quick-n-dirty knob control in Visual Basic 2005 Express, the value of which is incremented/decremented by "grabbing" it with the mouse and moving the cursor up/down. Because the knob itself doesn't move, I need to keep tracking the mouse movement outside of the rectangle of the control. I use a Label with an ImageList to implement this (I have a list of 127 bitmaps representing the knob in various positions). Which events should I react to? ANSWER: You need the control to handle three events: Mouse Down, Mouse Move and Mouse Up. On the Mouse Down event, you will need to capture the mouse. This means the mouse messages are sent to the control that has the capture. In the mouse move event, if the input is captured then update the displayed image depending on the amount the mouse moved. In the mouse up event, release the capture if the input is captured. The boolean jjnguy suggests is unnecessary as the Capture property of a Control is readable so it's possible to determine if the capture has been set.
[ "vb.net", "user-controls", "drag-and-drop" ]
0
0
1,748
2
0
2008-09-01T15:54:46.873000
2008-09-01T16:01:22.070000
38,090
39,031
How to prevent Write Ahead Logging on just one table in PostgreSQL?
I am considering log-shipping of Write Ahead Logs (WAL) in PostgreSQL to create a warm-standby database. However I have one table in the database that receives a huge amount of INSERT/DELETEs each day, but which I don't care about protecting the data in it. To reduce the amount of WALs produced I was wondering, is there a way to prevent any activity on one table from being recorded in the WALs?
Unfortunately, I don't believe there is. The WAL logging operates on the page level, which is much lower than the table level and doesn't even know which page holds data from which table. In fact, the WAL files don't even know which pages belong to which database. You might consider moving your high activity table to a completely different instance of PostgreSQL. This seems drastic, but I can't think of another way off the top of my head to avoid having that activity show up in your WAL files.
How to prevent Write Ahead Logging on just one table in PostgreSQL? I am considering log-shipping of Write Ahead Logs (WAL) in PostgreSQL to create a warm-standby database. However I have one table in the database that receives a huge amount of INSERT/DELETEs each day, but which I don't care about protecting the data in it. To reduce the amount of WALs produced I was wondering, is there a way to prevent any activity on one table from being recorded in the WALs?
TITLE: How to prevent Write Ahead Logging on just one table in PostgreSQL? QUESTION: I am considering log-shipping of Write Ahead Logs (WAL) in PostgreSQL to create a warm-standby database. However I have one table in the database that receives a huge amount of INSERT/DELETEs each day, but which I don't care about protecting the data in it. To reduce the amount of WALs produced I was wondering, is there a way to prevent any activity on one table from being recorded in the WALs? ANSWER: Unfortunately, I don't believe there is. The WAL logging operates on the page level, which is much lower than the table level and doesn't even know which page holds data from which table. In fact, the WAL files don't even know which pages belong to which database. You might consider moving your high activity table to a completely different instance of PostgreSQL. This seems drastic, but I can't think of another way off the top of my head to avoid having that activity show up in your WAL files.
[ "postgresql" ]
8
6
4,013
4
0
2008-09-01T16:03:55.463000
2008-09-02T08:34:37.220000
38,107
38,128
Cross Page Postback doesn't work for client-side enabled button
I am using a cross page postback for Page A to pass data to Page B. The button that causes the postback has its postbackurl set but is disabled until the user selects a value from a DDL at which point the button is enable using javascript. However this prevents the cross page postback from occurring, Page A just postbacks to itself. If the button is never disabled it works fine. Anyone know how to solve this?
It looks like when the button is disabled.Net doesn't bother adding the necessary bits to handle the cross page postback on the client, so they will be missing when the button is enable client-side. I guess one solution would be to have the button enabled to start with (so that.Net adds the cross page postback controls) and then disable it using javascript as soon as the control loads on the client. But this sounds a bit clunky.
Cross Page Postback doesn't work for client-side enabled button I am using a cross page postback for Page A to pass data to Page B. The button that causes the postback has its postbackurl set but is disabled until the user selects a value from a DDL at which point the button is enable using javascript. However this prevents the cross page postback from occurring, Page A just postbacks to itself. If the button is never disabled it works fine. Anyone know how to solve this?
TITLE: Cross Page Postback doesn't work for client-side enabled button QUESTION: I am using a cross page postback for Page A to pass data to Page B. The button that causes the postback has its postbackurl set but is disabled until the user selects a value from a DDL at which point the button is enable using javascript. However this prevents the cross page postback from occurring, Page A just postbacks to itself. If the button is never disabled it works fine. Anyone know how to solve this? ANSWER: It looks like when the button is disabled.Net doesn't bother adding the necessary bits to handle the cross page postback on the client, so they will be missing when the button is enable client-side. I guess one solution would be to have the button enabled to start with (so that.Net adds the cross page postback controls) and then disable it using javascript as soon as the control loads on the client. But this sounds a bit clunky.
[ "asp.net", "postback" ]
3
2
951
1
0
2008-09-01T16:20:44.550000
2008-09-01T16:29:49.630000
38,125
38,189
Strategies for keeping a Lucene Index up to date with domain model changes
Was looking to get peoples thoughts on keeping a Lucene index up to date as changes are made to the domain model objects of an application. The application in question is a Java/J2EE based web app that uses Hibernate. The way I currently have things working is that the Hibernate mapped model objects all implement a common "Indexable" interface that can return a set of key/value pairs that are recorded in Lucene. Whenever a CRUD operation is performed involving such an object I send it via JMS queue into a message driven bean that records in Lucene the primary key of the object and the key/value pairs returned from the index( ) method of the Indexable object that was provided. My main worries about this scheme is if the MDB gets behind and can't keep up with the indexing operations that are coming in or if some sort of error/exception stops an object from being index. The result is an out-of-date index for either a sort, or long, period of time. Basically I was just wondering what kind of strategies others had come up with for this sort of thing. Not necessarily looking for one correct answer but am imagining a list of "whiteboard" sort of ideas to get my brain thinking about alternatives.
Change the message: just provide the primary key and the current date, not the key/value pairs. Your mdb fetches the entity by primary key and calls index(). After indexing you set a value "updated" in your index to the message date. You update your index only if the message date is after the "updated" field of the index. This way you can't get behind because you always fetch the current key/value pairs first. As an alternative: have a look at http://www.compass-project.org.
Strategies for keeping a Lucene Index up to date with domain model changes Was looking to get peoples thoughts on keeping a Lucene index up to date as changes are made to the domain model objects of an application. The application in question is a Java/J2EE based web app that uses Hibernate. The way I currently have things working is that the Hibernate mapped model objects all implement a common "Indexable" interface that can return a set of key/value pairs that are recorded in Lucene. Whenever a CRUD operation is performed involving such an object I send it via JMS queue into a message driven bean that records in Lucene the primary key of the object and the key/value pairs returned from the index( ) method of the Indexable object that was provided. My main worries about this scheme is if the MDB gets behind and can't keep up with the indexing operations that are coming in or if some sort of error/exception stops an object from being index. The result is an out-of-date index for either a sort, or long, period of time. Basically I was just wondering what kind of strategies others had come up with for this sort of thing. Not necessarily looking for one correct answer but am imagining a list of "whiteboard" sort of ideas to get my brain thinking about alternatives.
TITLE: Strategies for keeping a Lucene Index up to date with domain model changes QUESTION: Was looking to get peoples thoughts on keeping a Lucene index up to date as changes are made to the domain model objects of an application. The application in question is a Java/J2EE based web app that uses Hibernate. The way I currently have things working is that the Hibernate mapped model objects all implement a common "Indexable" interface that can return a set of key/value pairs that are recorded in Lucene. Whenever a CRUD operation is performed involving such an object I send it via JMS queue into a message driven bean that records in Lucene the primary key of the object and the key/value pairs returned from the index( ) method of the Indexable object that was provided. My main worries about this scheme is if the MDB gets behind and can't keep up with the indexing operations that are coming in or if some sort of error/exception stops an object from being index. The result is an out-of-date index for either a sort, or long, period of time. Basically I was just wondering what kind of strategies others had come up with for this sort of thing. Not necessarily looking for one correct answer but am imagining a list of "whiteboard" sort of ideas to get my brain thinking about alternatives. ANSWER: Change the message: just provide the primary key and the current date, not the key/value pairs. Your mdb fetches the entity by primary key and calls index(). After indexing you set a value "updated" in your index to the message date. You update your index only if the message date is after the "updated" field of the index. This way you can't get behind because you always fetch the current key/value pairs first. As an alternative: have a look at http://www.compass-project.org.
[ "indexing", "lucene" ]
6
4
1,165
2
0
2008-09-01T16:29:10.520000
2008-09-01T17:26:13.630000
38,158
38,179
What is a good maintainability index using Visual Studio 2008 code analysis?
My company recently purchased TFS and I have started looking into the code analysis tools to help drive up code quality and noticed a good looking metric "maintainability index". Is anyone using this metric for code reviews/checkins/etc? If so, what is an acceptable index for developers to work toward?
The maintainability index is not as much a fixed value you look at, it's more of an indication that code is hard to understand, test and/or debug. I usually try to keep high-level code (basically anything except for the real plumbing code) above 80, where 90+ would be good. It adds a competitive element to programming as maintainable as possible to me. The code analysis tool really shines in the area of dependencies and the number of branches within a method though. More branches mean harder testing, which makes it more error-prone. Dependencies, same thing. In other people's code, I use the maintainability index to spot possible bad parts in the code, so I know where to review it. Also, methods/classes with a high number of lines are an indication of poor code to me (unless it can't be avoided, again, the plumbing works). In the end, I think it mainly depends on how often your code will change. Code that's expected to change a lot has to score higher in maintainability than your typical 'write once' code.
What is a good maintainability index using Visual Studio 2008 code analysis? My company recently purchased TFS and I have started looking into the code analysis tools to help drive up code quality and noticed a good looking metric "maintainability index". Is anyone using this metric for code reviews/checkins/etc? If so, what is an acceptable index for developers to work toward?
TITLE: What is a good maintainability index using Visual Studio 2008 code analysis? QUESTION: My company recently purchased TFS and I have started looking into the code analysis tools to help drive up code quality and noticed a good looking metric "maintainability index". Is anyone using this metric for code reviews/checkins/etc? If so, what is an acceptable index for developers to work toward? ANSWER: The maintainability index is not as much a fixed value you look at, it's more of an indication that code is hard to understand, test and/or debug. I usually try to keep high-level code (basically anything except for the real plumbing code) above 80, where 90+ would be good. It adds a competitive element to programming as maintainable as possible to me. The code analysis tool really shines in the area of dependencies and the number of branches within a method though. More branches mean harder testing, which makes it more error-prone. Dependencies, same thing. In other people's code, I use the maintainability index to spot possible bad parts in the code, so I know where to review it. Also, methods/classes with a high number of lines are an indication of poor code to me (unless it can't be avoided, again, the plumbing works). In the end, I think it mainly depends on how often your code will change. Code that's expected to change a lot has to score higher in maintainability than your typical 'write once' code.
[ "visual-studio", "code-analysis" ]
16
22
7,020
1
0
2008-09-01T16:46:46.500000
2008-09-01T17:04:33.837000
38,160
881,450
Parallelize Bash script with maximum number of processes
Lets say I have a loop in Bash: for foo in `some-command` do do-something $foo done do-something is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 do-something 's at once. The naive approach seems to be: for foo in `some-command` do do-something $foo & done This will run all do-something s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing all at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the do-something s are finished. How would you write this loop so there are always X do-something s running at once?
Depending on what you want to do xargs also can help (here: converting documents with pdf2ps): cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w ) find. -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps From the docs: --max-procs=max-procs -P max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done.
Parallelize Bash script with maximum number of processes Lets say I have a loop in Bash: for foo in `some-command` do do-something $foo done do-something is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 do-something 's at once. The naive approach seems to be: for foo in `some-command` do do-something $foo & done This will run all do-something s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing all at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the do-something s are finished. How would you write this loop so there are always X do-something s running at once?
TITLE: Parallelize Bash script with maximum number of processes QUESTION: Lets say I have a loop in Bash: for foo in `some-command` do do-something $foo done do-something is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 do-something 's at once. The naive approach seems to be: for foo in `some-command` do do-something $foo & done This will run all do-something s at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing all at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the do-something s are finished. How would you write this loop so there are always X do-something s running at once? ANSWER: Depending on what you want to do xargs also can help (here: converting documents with pdf2ps): cpus=$( ls -d /sys/devices/system/cpu/cpu[[:digit:]]* | wc -w ) find. -name \*.pdf | xargs --max-args=1 --max-procs=$cpus pdf2ps From the docs: --max-procs=max-procs -P max-procs Run up to max-procs processes at a time; the default is 1. If max-procs is 0, xargs will run as many processes as possible at a time. Use the -n option with -P; otherwise chances are that only one exec will be done.
[ "bash" ]
102
71
53,491
16
0
2008-09-01T16:47:53.377000
2009-05-19T07:50:04.573000
38,181
38,256
When should I mock?
I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario here.
A unit test should test a single codepath through a single method. When the execution of a method passes outside of that method, into another object, and back again, you have a dependency. When you test that code path with the actual dependency, you are not unit testing; you are integration testing. While that's good and necessary, it isn't unit testing. If your dependency is buggy, your test may be affected in such a way to return a false positive. For instance, you may pass the dependency an unexpected null, and the dependency may not throw on null as it is documented to do. Your test does not encounter a null argument exception as it should have, and the test passes. Also, you may find its hard, if not impossible, to reliably get the dependent object to return exactly what you want during a test. That also includes throwing expected exceptions within tests. A mock replaces that dependency. You set expectations on calls to the dependent object, set the exact return values it should give you to perform the test you want, and/or what exceptions to throw so that you can test your exception handling code. In this way you can test the unit in question easily. TL;DR: Mock every dependency your unit test touches.
When should I mock? I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario here.
TITLE: When should I mock? QUESTION: I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario here. ANSWER: A unit test should test a single codepath through a single method. When the execution of a method passes outside of that method, into another object, and back again, you have a dependency. When you test that code path with the actual dependency, you are not unit testing; you are integration testing. While that's good and necessary, it isn't unit testing. If your dependency is buggy, your test may be affected in such a way to return a false positive. For instance, you may pass the dependency an unexpected null, and the dependency may not throw on null as it is documented to do. Your test does not encounter a null argument exception as it should have, and the test passes. Also, you may find its hard, if not impossible, to reliably get the dependent object to return exactly what you want during a test. That also includes throwing expected exceptions within tests. A mock replaces that dependency. You set expectations on calls to the dependent object, set the exact return values it should give you to perform the test you want, and/or what exceptions to throw so that you can test your exception handling code. In this way you can test the unit in question easily. TL;DR: Mock every dependency your unit test touches.
[ "unit-testing", "language-agnostic", "mocking" ]
184
168
85,800
6
0
2008-09-01T17:07:24.440000
2008-09-01T18:27:57.177000
38,190
38,213
How do I read a disk directly with .NET?
Is it possible to read a disk directly with.NET? By directly, I mean via the device bypassing the file system. I think I would go about this by opening the device some way "\Device\Ide\IdeDeviceP2T0L0-1" for example. If I can't open the device with a.NET API, knowing which Win32 API to use would be helpful.
CreateFile has support for direct disk access. Read the notes under "Physical Disks and Volumes". You should be able to P/Invoke the call. Note that Vista and Server 2008 have severely restricted this.
How do I read a disk directly with .NET? Is it possible to read a disk directly with.NET? By directly, I mean via the device bypassing the file system. I think I would go about this by opening the device some way "\Device\Ide\IdeDeviceP2T0L0-1" for example. If I can't open the device with a.NET API, knowing which Win32 API to use would be helpful.
TITLE: How do I read a disk directly with .NET? QUESTION: Is it possible to read a disk directly with.NET? By directly, I mean via the device bypassing the file system. I think I would go about this by opening the device some way "\Device\Ide\IdeDeviceP2T0L0-1" for example. If I can't open the device with a.NET API, knowing which Win32 API to use would be helpful. ANSWER: CreateFile has support for direct disk access. Read the notes under "Physical Disks and Volumes". You should be able to P/Invoke the call. Note that Vista and Server 2008 have severely restricted this.
[ ".net", "winapi", "disk" ]
15
6
14,070
4
0
2008-09-01T17:27:43.843000
2008-09-01T17:53:24.187000
38,193
38,209
Determine if a ruby script is already running
Is there an easy way to tell if a ruby script is already running and then handle it appropriately? For example: I have a script called really_long_script.rb. I have it cronned to run every 5 minutes. When it runs, I want to see if the previous run is still running and then stop the execution of the second script. Any ideas?
The ps is a really poor way of doing that and probably open to race conditions. The traditional Unix/Linux way would be to write the PID to a file (typically in /var/run) and check to see if that file exists on startup. e.g. the pidfile being located at /var/run/myscript.pid then you'd check to see if that exists before running the program. There are a few tricks to avoid race conditions involving using O_EXCL (exclusing locking) to open the file and symbolic links. However unlikely, you should try to code to avoid race conditions by using atomic operations on the filesystem. To save re-inventing the wheel, you might want to look at http://rubyforge.org/projects/pidify/
Determine if a ruby script is already running Is there an easy way to tell if a ruby script is already running and then handle it appropriately? For example: I have a script called really_long_script.rb. I have it cronned to run every 5 minutes. When it runs, I want to see if the previous run is still running and then stop the execution of the second script. Any ideas?
TITLE: Determine if a ruby script is already running QUESTION: Is there an easy way to tell if a ruby script is already running and then handle it appropriately? For example: I have a script called really_long_script.rb. I have it cronned to run every 5 minutes. When it runs, I want to see if the previous run is still running and then stop the execution of the second script. Any ideas? ANSWER: The ps is a really poor way of doing that and probably open to race conditions. The traditional Unix/Linux way would be to write the PID to a file (typically in /var/run) and check to see if that file exists on startup. e.g. the pidfile being located at /var/run/myscript.pid then you'd check to see if that exists before running the program. There are a few tricks to avoid race conditions involving using O_EXCL (exclusing locking) to open the file and symbolic links. However unlikely, you should try to code to avoid race conditions by using atomic operations on the filesystem. To save re-inventing the wheel, you might want to look at http://rubyforge.org/projects/pidify/
[ "ruby" ]
6
9
3,027
4
0
2008-09-01T17:34:06.590000
2008-09-01T17:52:38.153000
38,197
38,222
Why is the subprocess.Popen class not named Subprocess?
The primary class in the subprocess module is name Popen, and represents a subprocess. Popen sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like, say, Subprocess?
Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it. Originally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune time to rename them, but I guess that keeping Popen makes it easier to find in the docs for those who have a long history with python or even to the venerable posix functions. From its earliest posix incarnation, Popen has always been meant to open a Process and allow you to read and write from its stdio like a file. Thus the mnemonic for Popen is that it is short for ProcessOpen in an attempt to kind of, sorta, look like open.
Why is the subprocess.Popen class not named Subprocess? The primary class in the subprocess module is name Popen, and represents a subprocess. Popen sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like, say, Subprocess?
TITLE: Why is the subprocess.Popen class not named Subprocess? QUESTION: The primary class in the subprocess module is name Popen, and represents a subprocess. Popen sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like, say, Subprocess? ANSWER: Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it. Originally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune time to rename them, but I guess that keeping Popen makes it easier to find in the docs for those who have a long history with python or even to the venerable posix functions. From its earliest posix incarnation, Popen has always been meant to open a Process and allow you to read and write from its stdio like a file. Thus the mnemonic for Popen is that it is short for ProcessOpen in an attempt to kind of, sorta, look like open.
[ "python", "subprocess" ]
4
8
721
3
0
2008-09-01T17:40:52.220000
2008-09-01T17:57:42.633000
38,198
38,207
Why does this C code produce a double instead of a float?
celsius = (5.0/9.0) * (fahr-32.0); Is it just a development choice that the C developers decided upon or is there a reason to this? I believe a float is smaller than a double, so it might be to prevent overflows caused by not knowing what decimal format to use. Is that the reason, or am I overlooking something?
I think the reason is to ensure that any result can be encompassed. so the natural choice is double as it is the largest data type.
Why does this C code produce a double instead of a float? celsius = (5.0/9.0) * (fahr-32.0); Is it just a development choice that the C developers decided upon or is there a reason to this? I believe a float is smaller than a double, so it might be to prevent overflows caused by not knowing what decimal format to use. Is that the reason, or am I overlooking something?
TITLE: Why does this C code produce a double instead of a float? QUESTION: celsius = (5.0/9.0) * (fahr-32.0); Is it just a development choice that the C developers decided upon or is there a reason to this? I believe a float is smaller than a double, so it might be to prevent overflows caused by not knowing what decimal format to use. Is that the reason, or am I overlooking something? ANSWER: I think the reason is to ensure that any result can be encompassed. so the natural choice is double as it is the largest data type.
[ "c", "types" ]
5
3
907
5
0
2008-09-01T17:43:49.717000
2008-09-01T17:51:13.553000
38,235
38,384
IronRuby performance?
While I know IronRuby isn't quite ready for the world to use it, I was wondering if anyone here tried it and tested how well it faired against the other Rubies out there in terms of raw performance? If so, what are the results, and how did you go about measuring the performance (which benchmarks etc)? Edit: The IronRuby team maintains a site on how they compare to Ruby MRI 1.8 at http://ironruby.info/. Below the spec pass rate table, they also have some information on how IronRuby performs on these specs. This table is not continuously updated, but I assume they update it often enough (you can see the last update at the top of the page).
According to this article http://www.iunknown.com/2008/05/ironruby-and-rails.html. In may performance was nowhere near where they expected it to be. I heard in http://altnetpodcast.com/episodes/9-state-of-ironruby (3 days ago) that they're still working on performance. I guess they put compatability first and are now trying to get the performance up to par with other ruby implementations out there. As far as I understand they're not nearly as performant as Iron Python that is developed by the same team. I don't know if this is because Iron Ruby is using the DLR a lot more and that still needs to be optimized or if they need to optimize the Iron Ruby implementation itself more. But I guess it is good news because they can get it a lot faster. So if you're already happy with performance you'll get a lot happier.
IronRuby performance? While I know IronRuby isn't quite ready for the world to use it, I was wondering if anyone here tried it and tested how well it faired against the other Rubies out there in terms of raw performance? If so, what are the results, and how did you go about measuring the performance (which benchmarks etc)? Edit: The IronRuby team maintains a site on how they compare to Ruby MRI 1.8 at http://ironruby.info/. Below the spec pass rate table, they also have some information on how IronRuby performs on these specs. This table is not continuously updated, but I assume they update it often enough (you can see the last update at the top of the page).
TITLE: IronRuby performance? QUESTION: While I know IronRuby isn't quite ready for the world to use it, I was wondering if anyone here tried it and tested how well it faired against the other Rubies out there in terms of raw performance? If so, what are the results, and how did you go about measuring the performance (which benchmarks etc)? Edit: The IronRuby team maintains a site on how they compare to Ruby MRI 1.8 at http://ironruby.info/. Below the spec pass rate table, they also have some information on how IronRuby performs on these specs. This table is not continuously updated, but I assume they update it often enough (you can see the last update at the top of the page). ANSWER: According to this article http://www.iunknown.com/2008/05/ironruby-and-rails.html. In may performance was nowhere near where they expected it to be. I heard in http://altnetpodcast.com/episodes/9-state-of-ironruby (3 days ago) that they're still working on performance. I guess they put compatability first and are now trying to get the performance up to par with other ruby implementations out there. As far as I understand they're not nearly as performant as Iron Python that is developed by the same team. I don't know if this is because Iron Ruby is using the DLR a lot more and that still needs to be optimized or if they need to optimize the Iron Ruby implementation itself more. But I guess it is good news because they can get it a lot faster. So if you're already happy with performance you'll get a lot happier.
[ ".net", "ruby", "performance", "ironruby" ]
3
2
2,185
4
0
2008-09-01T18:15:21.123000
2008-09-01T20:27:03.680000
38,238
38,276
What is the purpose of class methods?
I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions. I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them. Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?
Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions. If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.
What is the purpose of class methods? I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions. I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them. Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?
TITLE: What is the purpose of class methods? QUESTION: I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions. I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them. Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used? ANSWER: Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions. If you have a class MyClass, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a classmethod. Then it'll be available to subclasses.
[ "python", "class-method" ]
295
208
158,121
18
0
2008-09-01T18:16:41.107000
2008-09-01T18:45:56.807000
38,280
38,298
Best browser for web application
I am in a position where I can choose the client browser for my web app. The app is being used internally, and we are installing each client "manually".I would like to find a better solution for the browser,so: What is a good browser that I can use as a client to a web application? General functionalities I would like to have: opening the browser from a shortcut, directly to the application's URL ability to restrict navigation to a set of allowed URLs fullscreen mode, no menu, no address bar javascript good CSS support ability to cancel Back button (or at least solve the "Webpage has expired" IE problem) IE7 and FireFox are good candidates, but each seem to have it's own problems and issues.
Mozilla Prism seems ideal for your purposes. It shares code with Firefox but is designed to run web applications without the usual Browser interface to make them appear more like desktop applications. So no back button or address bar to worry about. Edit: Google Chrome has Application Shortcuts so that may now be a better option.
Best browser for web application I am in a position where I can choose the client browser for my web app. The app is being used internally, and we are installing each client "manually".I would like to find a better solution for the browser,so: What is a good browser that I can use as a client to a web application? General functionalities I would like to have: opening the browser from a shortcut, directly to the application's URL ability to restrict navigation to a set of allowed URLs fullscreen mode, no menu, no address bar javascript good CSS support ability to cancel Back button (or at least solve the "Webpage has expired" IE problem) IE7 and FireFox are good candidates, but each seem to have it's own problems and issues.
TITLE: Best browser for web application QUESTION: I am in a position where I can choose the client browser for my web app. The app is being used internally, and we are installing each client "manually".I would like to find a better solution for the browser,so: What is a good browser that I can use as a client to a web application? General functionalities I would like to have: opening the browser from a shortcut, directly to the application's URL ability to restrict navigation to a set of allowed URLs fullscreen mode, no menu, no address bar javascript good CSS support ability to cancel Back button (or at least solve the "Webpage has expired" IE problem) IE7 and FireFox are good candidates, but each seem to have it's own problems and issues. ANSWER: Mozilla Prism seems ideal for your purposes. It shares code with Firefox but is designed to run web applications without the usual Browser interface to make them appear more like desktop applications. So no back button or address bar to worry about. Edit: Google Chrome has Application Shortcuts so that may now be a better option.
[ "browser", "web-applications" ]
1
7
4,783
9
0
2008-09-01T18:48:22.433000
2008-09-01T19:03:56.453000