q:
When using py2exe to distribute Python applications with wxPython, some MSVC DLLs are usually needed to make the .exe work on freshly installed machines. In particular, the two most common DLLs are msvcp71.dll and msvcr71.dll

The former can be included in the .exe using this tip. However, the latter is just placed in the dist dir by py2exe and not into the executable, even if I specifically ask to include it.

Any idea how to cause py2exe to include both inside the .exe ?

[A]
Wouldn't it fail to launch, then? You want
```
msvcr71.dll
```
in the same directory as the exe, so that the library loader will be able to find and link it into the application's memory map.
It's needed for basic operation, so you can't just let
```
py2exe
```
unpack it with the rest of the DLLs.


q: I've got a bunch of 3D vertex positions & need to generate a convex hull containing them; does anyone know of any QHull bindings for .NET? or native 3D Delaunay triangulation algorithms?

[A]
A 3d delaunay is tricky, I'm not sure it's even possible to strictly define a delaunay constraint for a 3d surface.
The normal technique if you just want to mesh a surface is to pick a direction and map that onto 2 coordinates and do a 2d delaunay. For a height map it's easy to just use x,y.
Then when you have the nodes forming each triangle you can of course use their 3d coordinates.
The best 2d code is probably
http://www.cs.cmu.edu/~quake/triangle.html
This will also give you the convex hull

s: huggingface

c: devops

d: intermediate


q:
List Comprehension is a very useful code mechanism that is found in several languages, such as Haskell, Python, and Ruby (just to name a few off the top of my head). I'm familiar with the construct.

I find myself working on an Open Office Spreadsheet and I need to do something fairly common: I want to count all of the values in a range of cells that fall between a high and low bounds. I instantly thought that list comprehension would do the trick, but I can't find anything analogous in Open Office. There is a function called "COUNTIF", and it something similar, but not quite what I need.

Is there a construct in Open Office that could be used for list comprehension?

[A]
CountIf can count values equal to one chosen. Unfortunately it seems that there is no good candidate for such function. Alternatively you can use additional column with If to display 1 or 0 if the value fits in range or not accordingly:
```
```
=If(AND({list_cell}>=MinVal; {list_cell}<=MaxVal); 1; 0)
```
```
Then only thing left is to sum up this additional column.


q: How do you generate a X.509 public and private key pair and a signing request (CSR file) to be sent to a CA for signing in C#?


q:
I'm working on a small project where for the first time I want to use XML as the one and only data source...a file based store suits the need of the project.

When writing the DAL should I have all the get methods static? to aviod and "reading while file open" errors?
Should I use CacheDependency on the file?

Thx

[A]
I think you were not as clear as you could have been. How big are these files going to be? Would it make sense for the data layer to always keep the XmlDocument in memory and dump to harddisk on every update?
How often are updates going to occur, if at all? How are you going to handle concurrency? Are updates going to be transactional across multiple xml files? How are you going to handle consistency and transactional integrity? If there are no updates, your life will be much simpler.
Methods don't have to be static. The main thing to consider is  that, in the future, you might want to change the DAL provider from XML to DB. To this end, the concrete implementation of the DAL interfaces should talk to an abstract data provider. For you, it would be an Xml provider initially, but you should be able to write a Sql Provider that implements the same interface and easily switch the implementation using dependency injection, config files or what-have-you.
One you have instances of the DAL implementations, you can just use those objects to talk to the data layer.
Hope this is a good start for you.


q:
How do you convert a numerical number to an Excel column name in C# without using automation getting the value directly from Excel.

Excel 2007 has a possible range of 1 to 16384, which is the number of columns that it supports. The resulting values should be in the form of excel column names, e.g. A, AA, AAA etc.

[A]
```
```
int nCol = 127;
string sChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol >= 26)
{
    int nChar = nCol % 26;
    nCol = (nCol - nChar) / 26;
    // You could do some trick with using nChar as offset from 'A', but I am lazy to do it right now.
    sCol = sChars[nChar] + sCol;
}
sCol = sChars[nCol] + sCol;
```
```
Update
:
Peter
's comment is right. That's what I get for writing code in the browser. :-) My solution was not compiling, it was missing the left-most letter and it was building the string in reverse order - all now fixed.
Bugs aside, the algorithm is basically converting a number from base 10 to base 26.
Update 2
:
Joel Coehoorn
is right - the code above will return AB for 27. If it was real base 26 number, AA would be equal to A and the next number after Z would be BA.
```
```
int nCol = 127;
string sChars = "0ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string sCol = "";
while (nCol > 26)
{
    int nChar = nCol % 26;
    if (nChar == 0)
        nChar = 26;
    nCol = (nCol - nChar) / 26;
    sCol = sChars[nChar] + sCol;
}
if (nCol != 0)
    sCol = sChars[nCol] + sCol;
```
```


q: We have a project with many dll files which get loaded when the application starts. The baseaddresses of the dll files do overlap so that the memory image gets relocated. Is there a possibility to assign the baseaddresses automatically or a way to calculate a "good" baseaddress for each dll file?

[A]
You can use the REBASE utility which ships with the platform SDK and with Visual studio I think to set the base addresses of a whole bunch of DLLS loaded by the appliction
You supply REBASE with a list of the DLLS that make up your program, not including system Dlls, it then performs a dummy load of all the DLLs and assigns them new base addresses.
This can be performed as part of a final build step.
There is a Dr Dobbs article on rebasing
here
and a Microsoft article on rebasing in general
here


q:
I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is
stl compatible if at all possible.

For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the goal here.

Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within.
So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable.

[A]
I am going to suggest using std::map instead of a tree.
The complexity characteristics of a tree are:
Insert:       O(ln(n))
Removal:  O(ln(n))
Find:         O(ln(n))
These are the same characteristics the std::map guarantees.
Thus as a result most implementations of std::map use a tree (Red-Black Tree) underneath the covers (though technically this is not required).


q: Let's say I have this model named Product with a field named brand. Suppose the values of brand are stored in the format this_is_a_brand. Can I define a method in the model (or anywhere else) that allows me to modify the value of brand before it is called. For example, if I call @product.brand, I want to get This is a Brand, instead of this_is_a_brand.

[A]
In your model you can override the method call
```
brand
```
.
```
```
def brand
#code to modify the value that is stored in brand
return modified_brand
end
```
```
This will allow it to be stored as this_is_a_brand.  But, it will be returned as "this is a brand".


q:
my java application has a loading task which requires two server calls which can be parallelized. So I launch a Thread t1 (doing task1) and a Thread t2 (for task2).
I want then to do a specific task, task3 when both other tasks (1 & 2) are over. Naturally I can't tell which of task1 and task2 will finish first...

Which would be for you the simplest (and safest) way to code this ?

Thank you for your help

[A]
You can
```
join
```
both
```
t1
```
and
```
t2
```
(in either order), then run task3 after the join.


q: Has anyone used Mono, the open source .NET implementation on a large or medium sized project? I'm wondering if it's ready for real world, production environments. Is it stable, fast, compatible, ... enough to use? Does it take a lot of effort to port projects to the Mono runtime, or is it really, really compatible enough to just take of and run already written code for Microsoft's runtime?

[A]
I've used it for a number of internal and commercial projects with great success.  My warnings:
Write lots of unit tests and make sure they ALL pass under Mono -- this will save you a lot of trouble.
Unless you absolutely have to, do NOT use their embedding API.  It's damn easy to use, but it's ungodly easy to garbage collect valid memory or leak all of your memory.
Don't ever, ever, ever even come close to SVN and unless there's no choice, do not compile your own.  Things change so often in SVN that it's highly likely you'll end up implementing something that doesn't work on a release version if your project is significantly large.
Don't try and figure out problems on your own for long, use the IRC channel.  The people there are helpful and you'll save yourself days upon days -- don't make the same mistake I did.
Good luck!
Edit:  The reason I say not to compile your own from source (release or SVN) is that it's easy to configure it differently than release binaries and hide bugs, for instance in the garbage collection.
Edit 2:  Forgot to answer the second part to your question.  In my case, I had no issues with porting code, but I wasn't using any MS-specific libraries (WinForms, ASP.NET, etc).  If you're only using System.* stuff, you'll be fine;  beyond that, you may run into issues.  Mono 2.0 is quite solid, though.


q:
When I add a breakpoint and hit F5 to run in the debugger (I am using my debug build), a dialog pops up telling my my web.config file does not have debug=true in it (which is does) and I get 2 choices a) run without the debugger or b) let visual studio update my web.config file. If I choose b) the web.config is updated badly and nothing will work. If I choose a) then the site appears and I can test it out, but no debugging.

I am an experienced developer, but I have never used visual studio and asp.net for web development before, so I am feeling rather frustrated by all the walls it is putting up to prevent me working.

So far I have not been able to use the debugger. Is there something totally obvious that I am missing? What would you check if it was happening to you?

[A]
Open web.config manually and make sure the following line is in there
```
```
<compilation defaultLanguage="c#" debug="true" />
```
```
Now you should be able to debug from VS. If this does not work I suggest that you recreate the project.
EDIT: perhaps from what you say it could be that web.config is screwed up, e.g.contains invalid xml, no closing tag for some element etc.


q: How do I start a process, such as launching a URL when the user clicks a button?

[A]
You can use the
System.Diagnostics.Process.Start
method to start a process. You can even pass a URL as a string and it'll kick off the default browser.


q: i need to get the color at a particular coordinate from a texture. There are 2 ways  i can do this, by getting and looking at the raw png data, or by sampling my generated opengl texture. Is it possible to sample an opengl texture to get the color (RGBA) at a given UV or XY coord? If so, how?

[A]
The most efficient way I've found to do it is to access the texture data (you should have our PNG decoded to make into a texture anyway) and interpolate between the texels yourself.  Assuming your texcoords are [0,1], multiply texwidth
u and texheight
v and then use that to find the position on the texture.  If they're whole numbers, just use the pixel directly, otherwise use the int parts to find the bordering pixels and interpolate between them based on the fractional parts.
Here's some HLSL-like psuedocode for it.  Should be fairly clear:
```
```
float3 sample(float2 coord, texture tex) {
    float x = tex.w * coord.x; // Get X coord in texture
    int ix = (int) x; // Get X coord as whole number
    float y = tex.h * coord.y;
    int iy = (int) y;

    float3 x1 = getTexel(ix, iy); // Get top-left pixel
    float3 x2 = getTexel(ix+1, iy); // Get top-right pixel
    float3 y1 = getTexel(ix, iy+1); // Get bottom-left pixel
    float3 y2 = getTexel(ix+1, iy+1); // Get bottom-right pixel

    float3 top = interpolate(x1, x2, frac(x)); // Interpolate between top two pixels based on the fractional part of the X coord
    float3 bottom = interpolate(y1, y2, frac(x)); // Interpolate between bottom two pixels

    return interpolate(top, bottom, frac(y)); // Interpolate between top and bottom based on fractional Y coord
}
```
```


q:
Often when making changes to a VS2008 ASP.net project we get a message like:

BC30560: 'mymodule_ascx' is ambiguous in the namespace 'ASP'.

This goes away after a recompile or sometimes just waiting 10 seconds and refreshing the page.

Any way to get rid of it?

[A]
I used to have this problem sometimes too.  If I remember correctly it was caused by something like the following:
```
```
<%@ Page Inherits="_Default" %>
```
```
or perhaps
```
```
<%@ Page ClassName="_Default" %>
```
```
Or something like that.  I'm not 100% sure which attribute it was (it's been a while).
But look look for something like _Default in your Page directive and replace them with actual class names in all of your files.  For some reason, ASP.Net doesn't always interpret the _Default correctly, yielding temporary ambiguous references.


q:
Is there an exact overview what has changed in the SP1 for .NET 3.5? New classes, methods, etc.

For example, I've noticed there is a new WaitOne(TimeSpan) and WaitOne(int) overloads in the WaitHandle class.

[A] What's New in the .NET Framework Version 3.5 SP1 - MSDN


q:
I've got a Java client that needs to access a remote database. It is the goal to hide database credentials from the user and not hardcode any credentials within the code. Therefore, the database access will probably have to be on the server side.

I'm restricted to use Ibatis as a data abstraction framework. Apart from that I have JBoss running on the webserver, allowing me to use data sources.

How would you design the remote database access and data serialization/deserialization. would you prefer web services of some kind of data stream over a socket? How would you realize either of both?

[A]
So you want users to be able to access the database without knowing the credentials? Your only option is server-side database access. Unfortunately there is no way of hiding the username and password in Java -- if you put it into a properties file and encrypt it, a determined attacker could still attach a debugger and see what values are being held in your code.
Also, unless you're connecting to the DB over a secure connection someone could run a packet sniffer such as tcpdump and get the credentials there.
You say that you're running a JBoss server, what might be best is to set up remote EJBs so that your client application doesn't access the database directly - it has to go via your EJB methods. (It doesn't have to be EJB, by the way, you could do something such as web services if you prefer).
The point is, your server talks to the databas directly, and your client's only access is via a limited set of interfaces you define on the server.


q:
UPDATED: on win2k it seems it works OK. Sorry for the confusion.

MS Windows Vista internal ftp client has a strange behavior.
When redirecting its output and error to a file, the errors do not show up there:

ftp -n -s:commands.txt host >output.log 2>&1

When running it from Task Scheduler inside a batch file, I don't get any error messages if connection refused. Even if echo is on or with the -d option.
Do you have a workaround for it?


q:
I once had a MySQL database table containing 25 million records, which made even a simple COUNT(*) query takes minute to execute. I ended up making partitions, separating them into a couple tables. What i'm asking is, is there any pattern or design techniques to handle this kind of problem (huge number of records)? Is MSSQL or Oracle better in handling lots of records?

P.S
the COUNT(*) problem stated above is just an example case, in reality the app does crud functionality and some aggregate query (for reporting), but nothing really complicated. It's just that it takes quite a while (minutes) to execute some these queries because of the table volume

[A]
Many performance issues around large tables relate to indexing problems, or lack of indexing all together. I'd definitely make sure you are familiar with indexing techniques and the specifics of the database you plan to use.
With regards to your slow count(*) on the huge table, i would assume you were using the InnoDB table type in MySQL. I have some tables with over 100 million records using MyISAM under MySQL and the count(*) is very quick.
With regards to MySQL in particular, there are even slight indexing differences between InnoDB and MyISAM tables which are the two most commonly used table types. It's worth understanding the pros and cons of each and how to use them.


q:
I'm trying to localize my aspx pages. I'm done with content localization using L10n features provided by .net f/w, like resource files. But I'm finding it difficult to set local data in page titles.

Most of the browsers, including IE and FF, shows content on window title with some boxes (FF will show properly localized text in tab, IE doesn't even do that). But its working fine in safari (on windows).

When I did a research it seems like this issue exits ONLY for some of the languages. For example, the Hindi version of BBC shows the title with boxes. But Arabic version shows the localized text in title.

Can somebody please tell me why this is happening? How we can solve this issue?

Note: My site is using Asp.net 2.0 / IIS

[A]
I suspect this is a typeface issue. The browser title bar and other window ornaments are usually rendered by your OS, not by the browser itself, so if you've configured Windows to use a typeface that doesn't support the additional character glyphs required for Hindi, Arabic, etc., then you'll get the boxes instead. Within your actual pages, you're probably using a typeface which does include support for all these extended characters, which is why you're only seeing the problem on the window titles.
Safari uses its own rendering engine for everything including the window chrome, which is why it doesn't look like a normal Windows app, and why your localized titles are working.
You might want to try changing your Windows "Active Title Bar" font (under Display Properties, Appearance, Advanced) to something like Arial which covers the full set of Unicode characters, and see if this resolves the problem?


q: What's the difference between absolute path & relative path when using any web server or Tomcat?

[A]
Absolute paths start with / and refer to a location from the root of the current site (or virtual host).
Relative paths do not start with / and refer to a location from the actual location of the document the reference is made.
Examples, assuming root is
http://foo.com/site/
Absolute path, no matter where we are on the site
```
```
/foo.html
```
```
will refer to
http://foo.com/site/foo.html
Relative path, assuming the containing link is located in
http://foo.com/site/part1/bar.html
```
```
../part2/quux.html
```
```
will refer to
http://foo.com/site/part2/quux.html
or
```
```
part2/blue.html
```
```
will refer to
http://foo.com/site/part1/part2/blue.html


q:
I have created a Dynamic Web Project in my Eclipse workspace. It is also a Maven project, and under SVN control. But in "Open Resource" (Ctrl+Alt+R) no file from this project appears, unless I check from the window's options (top right drop-down) "Show Derived Resources".

I have checked on some of the project's folders and they are not marked as "Derived".

I have two more (plain Java) projects in the workspace, and all the files from them are visible in "Open Resource".

Do you know what might be wrong with either Eclipse, the Maven plugin or Subclipse (the SVN plugin)?

[A]
I experienced a similar issue in Eclipse (Ganymede), when using the Maven and Subclipse plugins. I have not determined which plugin caused this problem, but I suspect that it is related to my pom.xml containing nested modules (ie. a
```
<modules><module>main-module</module><module>integration-test</module>
```
). These appear in Eclipse as nested folders with their own pom.xml files (I did not use the Multiple Projects plugin although I have installed it).
I assume that one of the plug-ins has incorrectly set the derived flag on these folders when I checked out the project by SVN and then updated the MVN dependencies and project settings.
When I right click->properties on the top-level nested module directories I can see the Derived flag is checked. By unchecking the derive flag on the module directories (and checking the derive flag on the target directories within each sub-module instead), it fixed the Open Resource functionality.
As the derived flag is inherited from directories, you may need to check all of your directories in the hierarchy to find the 'culprit'.
If it helps the plug-in authors, my top level module directories contain a hyphen '-' in their names. Maybe that is throwing out one of the plugins.


q:
According to the feedparser documentation, I can turn an RSS feed into a parsed object like this:

import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')

but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:

print d.toXML()

but there doesn't seem to be anything in feedparser for going in that direction.  Am I going to have to loop through d's various elements, or is there a quicker way?

[A]
```
```
from xml.dom import minidom

doc= minidom.parse('./your/file.xml')
print doc.toxml()
```
```
The only problem is that it do not download feeds from the internet.


q:
After discovering Clojure I have spent the last few days immersed in it.

What project types lend themselves to Java over Clojure, vice versa, and in combination?

What are examples of programs which you would have never attempted before Clojure?

[A]
Clojure lends itself well to
concurrent programming
.  It provides such wonderful tools for dealing with threading as Software Transactional Memory and mutable references.
As a demo for the Western Mass Developer's Group, Rich Hickey made an ant colony simulation in which each ant was its own thread and all of the variables were immutable. Even with a very large number of threads things worked great. This is not only because Rich is an amazing programmer, it's also because he didn't have to worry about locking while writing his code. You can check out his
presentation on the ant colony here
.


q:
What are the implications of including a set of visual components released under a Mozilla Public License in a commercial application.

Do I have any obligations?

[A]
I've found pretty good analysis on MPL (and others) by Frank Hecker here:
http://hecker.org/writings/setting-up-shop
(search for "Mozilla Public License")
This pretty much sums it up:
For MozPL-ed source code considered as
  a set of source files, modifications
  of the original source files are
  considered to also fall under the
  MozPL, as are new source files
  incorporating extracts from the
  original source files. Such modified
  or new files are required to be
  licensed under the same terms as the
  original files, and in particular must
  be made freely and publicly available
  in source form.
...
Thus an open-source product initially
  released under the MozPL may be
  extended with proprietary code to
  create new proprietary products, as
  long as the proprietary code is
  separate (i.e., in separate files) and
  interacts with the open-source code
  using a defined API.
But as usual, read it carefully and consult your lawyers.


q:
Does anyone know of a nice (and preferably free) way to integrate Prolog and C#?

Im looking to create a Prolog dll or similar to call from my managed code, and retrieve an answer once all the processing has been complete. Im looking for it to be predominantly one sided (c# calls Prolog).

I have seen this question which talks about Prologs real world usage but I was wondering if anyone had either any experience with c# & Prolog? or a nice tutorial/article?

[A]
Perhaps
P#
will be useful for you


q:
I want to disable "Alert window" that I get from login page of one HTTPS site with "untrusted certificate".

ServicePointManager is used for WebRequest/WebResponse:

> public static bool
> ValidateServerCertificate(object
> sender, X509Certificate certificate,
> X509Chain chain, SslPolicyErrors
> sslPolicyErrors) {
>     return true; }
>
> ServicePointManager.ServerCertificateValidationCallback
> = new RemoteCertificateValidationCallback(ValidateServerCertificate);

but how can I use it with Webbrowser control?

[A]
The ServicePointManager is for managed code; WebBrowser is a wrapper around shdocvw, so will almost certainly have a very different programming model.
if
you can automate this (and I'm not sure that you can), I would expect to have to reference the COM version to get the full API (see: AxWebBrowser). WebBrowser only exposes a .NET-friendly subset of the full functionality - enough to get most common jobs done.
One other option might be to get the data yourself (WebClient / WebRequest / etc), and simply push that html into the WebBrowser - but this will mess up external links etc.


q: Are there any free tools for scripting MSSQL table data?  I'll gladly write one, but am hoping it's been done, and the app matured a bit before/

[A]
A quick google and hop pointed me to a Stored proc that should be able to help you. Look at
My code library
more specifically the file
generate_inserts.txt
to see if it can help you.
Not really a tool, but the start of one! :)


q:
When working on a big C/C++ project, do you have some specific rules regarding the #include within source or header files?

For instance, we can imagine to follow one of these two excessive rules:

#include are forbidden in .h files; it is up to each .c file to include all the headers it needs

Each .h file should include all its dependancies, i.e. it should be able to compile alone without any error.

I suppose there is trade-off in between for any project, but what is yours? Do you have more specific rules? Or any link that argues for any of the solutions?

[A]
The first rule will fail as soon as there are circular dependencies. So it cannot be applied strictly.
(This can still be made to work but this shifts a whole lot of work from the programmer to the consumer of these libraries which is obviously wrong.)
I'm all in favour of rule 2 (although it might be good to include “forward declaration headers” instead of the real deal, as in
```
<iosfwd>
```
because this reduces compile time). Generally, I believe it's a kind of self-documentation if a header file “declares” what dependencies it has – and what better way to do this than to include the required files?
EDIT:
In the comments, I've been challenged that circular dependencies between headers are a sign of bad design and should be avoided.
That's not correct. In fact, circular dependencies
between classes
may be unavoidable and aren't a sign of bad design at all. Examples are abundant, let me just mention the Observer pattern which has a circular reference between the observer and the subject.
To resolve the circularity between classes, you have to employ forward declaration because the order of declaration matters in C++. Now, it is completely acceptable to handle this forward declaration in a circular manner to reduce the number of overall files and to centralize code. Admittedly, the following case doesn't merit from this scenario because there's only a single forward declaration. However, I've worked on a library where this has been much more.
```
```
// observer.hpp

class Observer; // Forward declaration.

#ifndef MYLIB_OBSERVER_HPP
#define MYLIB_OBSERVER_HPP

#include "subject.hpp"

struct Observer {
    virtual ~Observer() = 0;
    virtual void Update(Subject* subject) = 0;
};

#endif
```
```
```
```
// subject.hpp
#include <list>

struct Subject; // Forward declaration.

#ifndef MYLIB_SUBJECT_HPP
#define MYLIB_SUBJECT_HPP

#include "observer.hpp"

struct Subject {
    virtual ~Subject() = 0;
    void Attach(Observer* observer);
    void Detach(Observer* observer);
    void Notify();

private:
    std::list<Observer*> m_Observers;
};

#endif
```
```


q:
An advantage by using Windows Authentication is that I do not need to provide a username and password to log into the server as the user currently logged into Windows. But in a specific case I would like to log into the SQL Server as another user, using the same Windows Authenticated ODBC connection.

So, the question: Is it possible to log into an SQL Server using Windows Authentication, but not as the user currently logged into Windows (without a dialog asking for username and password)?

[A]
The simple answer to your question is no, without a dialog being presented, it's not possible to login to SQL Server using another Windows account.
The slightly more complex answer is; You can login as another user (WITH a dialog being presented) by right-clicking the Query Analyser icon and choosing "Run As" (Might require a CTRL or SHIFT key held down to make RUN AS appear.
There's also the RUNAS command line executable which you could look at, so you could create a shortcut that contains the RUNAS command, the credentials and the path to Query Analyser. That would eliminate being asked for a username or password on execution.


q: In certain areas in my application I need data from several tables in the database (I have  an application, the application has many attributes, each attribute has several definitions, and each definition has a value). I need the data from all these tables for an application. Should I use a view (one that would be rather large) or subqueries for selecting the records? In the case of subqueries is the optimizer able to work efficiently? I'm also interested if caching will work for subqueries.

[A]
This is an 'It depends' question.  A view might help to make the code more maintainable but complex selection predicates might confuse the optimiser.
Another option is a stored procedure that returns a record set.  If you reuse a subquery several times you may get some mileage from splitting up the query, selecting the subquery into a temporary table and combining the parts in a later step.
Without a more specific description of the problem it's hard to really give a meaningful answer.


q: I have a webpage (say www.example.com/a.asp) .. I am having an iframe in this page which loads a page from a different website (www.example.net/b.asp)... This b.asp asks few questions to the user and the results are posted to c.asp in my website (www.example.com/c.asp). This page (www.example.com/c.asp) gets loaded in the iframe. Is there any way so that I can reload the entire webpage and redirect to another wbpage when I get the response from www.example.net. Sorry if this question is confusing, Any queries please let me know.


q: How can I prevent a user from resizing GridViewColumns withing a ListView control?

[A]
i found a solution and probably it will help someone else someday ;)
you have to override the GridViewColumnHeader's ControlTemplate (default template is
here
) and remove the
PART_HeaderGripper
from the template in order to prevent resizing of your columns.
there is another solution that comes up with subclassing GridViewColumn described
here
. for representation purposes i prefer xaml only solutions though


q: I want to use a template engine in a struts application and would like to know if using TILES can be recommended instead of FREEMARKER or VELOCITY.

[A]
I've used tiles before on a project. It was good for templating, however it can't really be compared to velocity or freemarker: with Tiles you use normal JSPs and are limited to the JSP tags youv'e got.
Velocity (and probably Freemarker although I haven't used it before) provide their own tags or expression language, so you can do thinks like:
```
Hello ${name}
```
Which you can't do in plain JSPs. [updated due to comment: in JSP 2.0, EL is included so you can do things like that. However, I think Velocity or Freemarker are more powerful in terms of what you can do with it.]
If you've got a layout with lots of different components (i.e. header, sidebar, etc) and you want to define various different templates, tiles isn't a bad choice. (Although be warned - it can be quite a lot of XML!)
But if you need something more "advanced" than plain JSPs Velocity or Freemarker might be the way to go.


q:
the function addresses (Rva+Base) in my MAP-file from visual studio doesn't match the one I see in the debugger (or when I manually inspect my stack frame).

What could be causing this?

/A.B.

[A]
Is the problem in an executable or a DLL?
If it's a DLL what is its preferred load address? If this clashes with any other DLL then it will be rebased by the loader, and this can lead to what you're seeing.
As part of your build process, you should ensure that all your DLLs are rebased (there's a tool to do this) so that their address spaces don't clash (this frees up some page file space as well as improving load time).


q: When accessing an object in a DataTable retrieved from a database, are there any reasons not to cast the object into your desired type, or are there reasons to use convert? I know the rule is cast when we know what data type we're working with, and convert when attempting to change the data type to something it isn't. Presuming we know what data type is stored in a column, cast seems appropriate, but are there any DB type issues that mean we can't rely on this?

[A]
I would always cast, for the reasons you state.  The gotchas I'm aware of that you need to handle are:
You obviously need to be able to handle DBNulls (e.g. by testing with Convert.IsDBNull)
In the case of ExecuteScalar I believe you need to check for null as well as DBNull.
SQL Servers @@IDENTITY and SCOPE_IDENTITY functions return numeric (decimal) even for columns that are declared as INT.  In this case you can cast twice "(int)(decimal)value" or handle it in the T-SQL code, e.g.:
.
INSERT INTO MyTable ...
SELECT AutoIdColumn FROM MyTable WHERE AutoIdColumn = SCOPE_IDENTITY()
or
```
```
INSERT INTO MyTable ...
SELECT CAST(SCOPE_IDENTITY() AS INT)
```
```


q:
I want to put "random" output from my result set (about 1.5 mil rows) in a file in a sorted manner. I know i can use sort by command in my query but that command is "expensive".
Can you tell me is there any algorithm for writing result set rows in a file so the content would be sorted in the end and can i gain in performance with this?
I'm using java 1.6, and query has multiple joins.

[A]
Define an index for the sort criteria in your table, then you can use the order by clause without problems and write the file as it comes from the resultset.
If your query has multiple joins, create the proper indexes for the joins and for the sort criteria. You can sort the data on your program but you'd be wasting time. That time will  be a lot more valuable when employed learning how to properly tune/use your database rather than reinventing sorting algorithms already present in the database engine.
Grab your database's profiler and check the query's execution plan.


q: XP-specific answers preferred, but others are welcome too.

[A]
From
```
%windir%\System32\Shell32.dll
```


q:
Can anyone give me an example of what the Artifact paths setting defined for a build configuration could look like if I want to create two artifacts dist and source where I am using the sln 2008 build runner and building my projects using the default bin/Release?

**/Source/Code/MyProject/bin/Release/*.* => dist
**/*.* => source

I get two artifact roots dist and source but under dist I get the whole directory structure (Source/Code/MyProject/bin/Release) which I don't want and under source I get the whole thing along with obj and bin/Release which I do not want.

Can you give some advice on how to do this correctly?

Do I need to change the target location for all the projects I am building to be able to get this thing to work?

[A]
So you'll just need:
```
```
Source\Code\MyProject\bin\Release\* => dist
Source\**\* => source
```
```
This will put all the files in release into a artifact folder called dist and everything in Source into a artifact folder called source.
If you have subfolders in Release try:
```
```
Source\Code\MyProject\bin\Release\**\* => dist
```
```


q:
How do I setup a Python environment on windows computer so I can start writing and running Python scripts, is there an install bundle?  Also which database should i use?

I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?

[A]
Download the Python 2.6 Windows installer from
python.org
(
direct link
). If you're just learning, use the included SQLite library so you don't have to fiddle with database servers.
Most web development frameworks (Django, Turbogears, etc) come with a built-in webserver command that runs on the local computer without Apache.


q:
given a matrix of distances between points is there an algorithm for determining a set of n-dimensional points that has these distances? (or at least minimises the error)

sort of like a n-dimensional version of the turnpike problem.

The best I can come up with is using multidimensional scaling.

[A]
I can't edit the original, because I don't have enough rep, but I've tried to restate the problem here.
The OP has an input NxN matrix of distances. He wants to create an output array, size N, of N-dimensional coordinates representing points, where the distance between each point is stored in the input matrix.
Note that this is not solvable in the general case:
Suppose I have a matrix like this
```
A  B  C
A  x  1  2
B     x  0
C        x
```
A is 1 unit of distance (say 1 metre) away from B, and A is one metre away from C. But B and C are in the same spot.
In this particular case the minimal sum of errors is 1 metre, and there are an infinite variety of solutions which achieve that result


q:
I am interested to read and understand the 2D mesh algorithms. A search on Google reveals a lot of papers and sources, however most are too academic and not much on beginner's side.

So, would anyone here recommend any reading sources ( suitable for the beginners), or open source implementation that I can learn from the start? Thanks.

Also, compared to triangular mesh generation, I have more interest in quadrilateral mesh and mix mesh( quad and tri combined).

[A]
The first link on your Google search takes you to
Jonathan Shewchuk's
site. This is not actually a bad place to start. He has a program called
triangle
which you can download for 2D triangulation. On that page there is a
link
to references used in
creating triangle
, including a link to a description of the
triangluation algorithm
.
There are several approaches to mesh generation. One of the most common is to create a
Delaunay triangulation
. Triangulating a set of points is fairly simple and there are several algorithms which do that, including Watson's and
Rupert's
as used in triangle
When you want to create a constrained triangulation, where the edges of the triangulation match the edges of your input shape it is a bit harder, because you need to recover certain edges.
I would start by understanding Delaunay triangulation. Then maybe look at some of the other meshing algorithms.
Some of the common topics that you will find in mesh generation papers are
Robustness - that is how to deal with floating point round off errors.
Mesh quality - ensuring the shapes of the triangles/tetrahedrons are close to equilateral. Whether this is important depends on why you are creating the mesh. For analysis work it is very important,
How to choose where to insert the nodes in the mesh to give a good mesh distribution.
Meshing speed
Quadrilateral/Hexahedral mesh generation. This is harder than using triangles/tetrahedra.
3D mesh generation is much harder than 2D so a lot of the papers are on 3D generation
Mesh generation is a large topic. It would be helpful if you could give some more information on what aspects (eg 2D or 3D) that you are interested in. If you can give some idea of what you ant to do then maybe I can find some better sources of information.


q: I'm new to Spring Security. How do I add an event listener which will be called as a user logs in successfully? Also I need to get some kind of unique session ID in this listener which should be available further on. I need this ID to synchronize with another server.

[A]
You need to define a Spring Bean which implements
ApplicationListener
.
Then, in your code, do something like this:
```
```
public void onApplicationEvent(ApplicationEvent appEvent)
{
    if (appEvent instanceof AuthenticationSuccessEvent)
    {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) appEvent;
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();

        // ....
    }
}
```
```
Then, in your applicationContext.xml file, just define that bean and it will automatically start receiving events :)


q: Which Template-Engine and Ajax-Framework/-Toolkit is able to load template information from JAR-Files?


q:
So Google Analytics does not have an API that we can use to get our data, so is there an efficient way to programaticly fetch the data collected by Google, without logging it locally?

Edit:
I would prefer a Python or PHP solution but anything will work.

[A]
Well, it depends on what you want to do with the data. If you only want to process part of it, then I don't think it is difficult.
Here's a basic web search with a hit explanations from Google and someone else:
http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55561
http://blogoscoped.com/archive/2008-01-17-n73.html


q:
I'm trying to call the SQL statement below but get the following error:

System.Data.SqlClient.SqlException: Conversion failed when converting
  the varchar value '+@buildingIDs+' to data type int.

@"SELECT id, startDateTime, endDateTime
    FROM tb_bookings
   WHERE buildingID IN ('+@buildingIDs+')
     AND startDateTime <= @fromDate";

buildingID is an int type column in the db. Will I need to pass the IDs as an array of ints?

[A]
It's trying to compare an int with the string value '+@buildingsIDs+'
So it tries to convert the string to convert it to an int and fails.
So do the following:
```
buildingsIDs = "1, 5, 6";
@"SELECT id, startDateTime, endDateTime From tb_bookings WHERE buildingID IN (" + buildingIDs + ") AND startDateTime <= @fromDate";
```


q:
ModRewrite can easily handle stripping the www off the front of my domain.

In .htaccess:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

But with SSL, the certificate check comes before the .htaccess rewrite, causing certificate error.

I would rather not buy an SSL certificate for the www only to redirect it.

Can you offer me a smarter solution?
(btw EV Certificates are not available as wildcards)

[A]
You can get certificates with multiple domain names in them. Get one with
```
mydomain.com
```
and
```
www.mydomain.com
```
. I think it's also possible to buy "wildcard" certificates that will match any subdomain, but they cost much more.


q:
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.

I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :

filepath = r"c:\ttemp\FILEPA~1.EXE"
print os.path.basename(filepath)
'c:\\ttemp\\FILEPA~1.EXE']
print os.path.splitdrive(filepath)
('', 'c:\ttemp\\FILEPA~1.EXE')

WTF ?

It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".

Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.

[A]
From a
```
os.path
```
documentation:
os.path.splitdrive(path)
Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.
If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string.
If you want to solve windows paths on any platform, you can just use a simple regexp:
```
```
import re
(drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups()
```
```
```
drive
```
will be a drive letter followed by
```
:
```
(eg.
```
c:
```
,
```
u:
```
) or
```
None
```
, and
```
tail
```
the whole rest :)


q:
Is OpenID a secure method of authentication users on a website?

And, if not, what are the security risks associated with OpenID?

[A]
OpenID is inherently insecure. It works by your site redirecting the user to their open ID provider site and then accepting an ID back from that site. This provides insecurities in both directions. You have to trust the ID that comes back (as you have no way of authenticating the user yourself) and it is easy to operate a proxy to the user’s open ID provider, that allows you to steal their username and password.
OpenID is fine for something like Stack Overflow, where it doesn’t really matter if someone impersonates you. Using OpenID for sites with more serious – on a personal level – content is extremely risky. If you use OpenID for your email for example, then anyone stealing your Id can access your email. They could then in turn send password reminder requests to other sites that you use in order to get passwords for those sites. In the worst case, you could use OpenID for a bank account, or have a bank that sends password reminders to your email account...
There are numerous other security problems with OpenID. You can find more information in
"Privacy on the Internet"
.


q: How can I modify a SharePoint site so that versioning is turned on by default in Document Libraries?

[A]
Versioning is not done at the site level, but at the list level.
If you want versioning to be turn on on each new library, you'll have to either:
Use your own library template (with versioning turned on)
Use feature + event handler to programmatically activate versioning on each new list
The easiest way is probably to use your own template. To do this, create a new document library, activate versioning, then save this list as template.
When you create a new list, you will then be able to use your template and directly create a list with versioning activated.


q: I'm looking for an open-source library for editing AAC metadata in M4A files (as appearing in iTunes).  Specifically, I need to be able to add an album art tag.  It should be something similar to id3lib, which works with ID3 tags on MP3 files.

[A]
Since I hadn't find any open-source library maybe open-source program, that can read and set iTunes-style metadata tags in MPEG-4 files, will help you.
atomicparsley.sourceforge.net
There is also Known iTunes Metadata structure provided:
http://atomicparsley.sourceforge.net/mpeg-4files.html
This discussion may also turn out helpful for you:
www.hydrogenaudio.org/forums/lofiversion/index.php/t31022.html
Good Luck


q:
I have a template in word (.docx) format and want to replace some placeholders in this template with my own data, do you know where I can find the right classes for this project? It would be nice for me to know the namespace. Are there any newer classes for handling word documents in the docx format (xml) than the com classes? Thank you for all your answers, I hope someone can help me with my problem.

greets

Sebastian

[A]
The new office formats (docx, xlsx, etc) are zip files that contain a collection of xml files.  With that in mind you have a couple of approaches.
You can use the Open XML SDK located at
http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en
You can unzip the docx file, do a search and replace for your tokens, and zip it back up.
There is a website at
openxmldeveloper.org
that is just for this kind of thing.  Also, bear in mind that they are already shipping a beta version 2 of the SDK.


q:
Why can't I pass the table name to a prepared PDO statement?

$stmt = $dbh->prepare('SELECT * FROM :table WHERE 1');
if ($stmt->execute(array(':table' => 'users'))) {
    var_dump($stmt->fetchAll());
}

Is there another safe way to insert a table name into a SQL query? With safe, I mean that I don't want to do

$sql = "SELECT * FROM $table WHERE 1"

[A]
Using the former isn't inherently more safe than the latter, you need to sanitize the input whether it's part of a parameter array or a simple variable.  So I don't see anything wrong with using the latter form with
```
$table
```
, provided you make sure that the content of
```
$table
```
is safe (alphanum plus underscores?) before using it.


q:
My application runs under CF 2.0 locally and i would like to know how to connect and send something to print in the embedded printer of a http://www.milliontech.com/home/content/view/195/95/'>Bluebird BIP-1300 device.

Ideally i would like an example in C#.

Thank you in advance.

[A]
I'm not familiar with this particular device, but in general, printers in this class require you to send RAW data, as they don't have Windows drivers.
This KB article
outlines how to send data to the device using C#: whether this is useful for you depends on whether the unmanaged APIs used are available in the environment your CF app runs on.
In case the APIs are supported, what you need next are the correct escape codes for the device in order to get the on-paper results you want. These are usually well-documented in the printer manual.
If the Spooler API is not available, or you run into other issues that make this approach more trouble than it's worth, the third-party
PrinterCE.NetCF SDK
may also be worth looking into.


q:
I'm trying to serialize objects from a database that have been retrieved with Hibernate, and I'm only interested in the objects' actual data in its entirety (cycles included).

Now I've been working with XStream, which seems powerful. The problem with XStream is that it looks all too blindly on the information. It recognizes Hibernate's PersistentCollections as they are, with all the Hibernate metadata included. I don't want to serialize those.

So, is there a reasonable way to extract the original Collection from within a PersistentCollection, and also initialize all referring data the objects might be pointing to. Or can you recommend me to a better approach?

(The results from Simple seem perfect, but it can't cope with such basic util classes as Calendar. It also accepts only one annotated object at a time)

[A]
I recommend a simpler approach: user dozer:
http://dozer.sf.net
. Dozer is a bean mapper, you can use it to convert, say, a PersonEJB to an object of the same class. Dozer will recursively trigger all proxy fecthes through getter() calls, and will also convert src types to dest types (let's say java.sql.date to java.utilDate).
Here's a snippet:
```
```
MapperIF mapper = DozerBeanMapperSingletonWrapper.getInstance();
PersonEJB serializablePerson = mapper.map(myPersonInstance, PersonEJB.class);
```
```
Bear in mind, as dozer walks through your object tree it will trigger the proxy loading one by one, so if your object graph has many proxies you will see many queries, which can be expensive.


q:
Is there a way to figure out versions of modules that were loaded into the process' address space when the process crashed from a crash dump that was generated by the process calling the MiniDumpWriteDump function? In other words, is any version information stored inside a dmp file?

Thanks.

[A]
load your minidump into WinDbg, then there's a Modules item off the Debug menu that shows checksum and timestamp information. That may be enough info for your purposes.
You can get the version from all loaded modules by typing "LM v" in the command window, in WinDBG. The list is long and you get lots, including the Product and File version strings. However, I think it fetches this information from locally-stored modules that it loads, making sure its got the right ones from checksum information it uses to match them to the symbol files.


q:
What is the easiest way to check if events have been logged in the eventlog during a period of time?

I want to perform a series of automated test steps and then check if any errors were logged to the Application Event Log, ignoring a few sources that I'm not interested in. I can use System.Diagnostics.EventLog and then look at the Entries collection, but it doesn't seem very useable for this scenario. For instance Entries.Count can get smaller over time if the event log is removing old entries. I'd prefer some way to either query the log or monitor it for changes during a period of time. e.g.

DateTime start = DateTime.Now;
// do some stuff...
foreach(EventLogEntry entry in CleverSolution.EventLogEntriesSince(start, "Application"))
{
  // Now I can do stuff with entry, or ignore if its Source is one
  // that I don't care about.
  // ...
}

[A]
The
System.Diagnostics.EventLog
class really is the right way to do this.
Your main objection seems to be that the log can remove old entries in some cases.  But you say this is in a software testing scenario.  Can't you arrange to configure your test systems such that the logs are large enough to contain all entries and the removal of old entries won't occur during your tests?


q:
I've got a column in a database table (SQL Server 2005) that contains data like this:

TQ7394
SZ910284
T r1534
su8472

I would like to update this column so that the first two characters are uppercase. I would also like to remove any spaces between the first two characters. So T q1234 would become TQ1234.

The solution should be able to cope with multiple spaces between the first two characters.

Is this possible in T-SQL? How about in ANSI-92? I'm always interested in seeing how this is done in other db's too, so feel free to post answers for PostgreSQL, MySQL, et al.

[A]
```
```
update Table set Column = case when len(rtrim(substring (Column , 1 , 2))) < 2
            then UPPER(substring (Column , 1 , 1) + substring (Column , 3 , 1)) + substring(Column , 4, len(Column)
            else UPPER(substring (Column , 1 , 2)) + substring(Column , 3, len(Column) end
```
```
This works on the fact that if there is a space then the trim of that part of string would yield length less than 2 so we split the string in three and use upper on the 1st and 3rd char. In all other cases we can split the string in 2 parts and use upper to make the first two chars to upper case.


q: Internet Explorer (from versions 4 to 7, at least) limits the number of files uploaded using a single 'input type="file"' form field to one. What is the best approach to take if I want to upload more than one file in a single HTTP POST request?

[A]
You have to include multiple
```
input
```
controls, one per file to be uploaded.
If you don't know how many you want ahead of time, you can use jQuery (or plain javascript) to create them on-the-fly.


q:
I use XFire to create a webservice wrapper around my application. XFire provides the webservice interface and WSDL at runtime (or creates them at compile time, don't know exactly).

Many of our customers don't know webservices very well and additionally they simply don't read any external documentation like Javadoc. I know that it's possible to add documentation (for parameters and methods) directly to the WSDL file.

I thought about Annotations or Aegis XML files but I don't know how... Do you know a way?

Edit: I just found this JIRA issue but the last activity was 2006. Any ideas?

[A]
XFire is slowly headed for /dev/null. Use
CXF
instead. In other words, XFire is being deprecated in favor of CXF - it's pretty much the same developers.
Since you use the Java-first approach, I suggest you generate you WSDL once and for all with CXF's
```
java2wsdl
```
tool, then you put your documentation in that and tell CXF to use
that
documented WSDL instead of letting CXF generate its own (undocumented) WSDL at runtime/deploy-time.
This page
has pretty much everything you need to know about creating a web service in CXF.


q: How do I remove a trailing comma from a string in ColdFusion?

[A]
Check the rightmost char - if it's a comma, set the string to a substring of the original, with length -1.
Trimming the string ensures that spaces after the trailing comma don't interfere with this method.
```
```
<cfset myStr = "hello, goodbye,">
<cfset myStr = trim(myStr)>

<cfif right(myStr, 1) is ",">
    <cfset myStr = left(myStr, len(myStr)-1)>
</cfif>
```
```


q:
I would like TortoiseSVN (1.5.3) to ignore certain folders, their contents and certain other files wherever they might appear in my directory hierarchy but I cannot get the global ignore string right.

Whatever I do, it either adds to much or ignores too much

What is the correct 'Global ignore pattern' to ignore....

Folders : bin obj release compile
Files   : *.bak *.user *.suo

Update: To help clarify... yes I am using this on windows.

[A]
Currently I have the following in my Global Ignore Pattern:
```
```
bin obj CVS .cvsignore *.user *.suo Debug Release *.pdb test.* Thumbs.db
```
```
Works really well to ignore several hidden or temp files/folders....
So for your specific requirements:
Folders:
```
bin obj release compile
```
Files:
```
*.bak *.user *.suo
```
I would use:
```
```
bin obj release compile *.bak *.user *.suo
```
```


q: Please give me the direction of the best guidance on the Entity Framework.


q:
In applying for jobs via agents I sometimes get blocked by an agent who says do you know software package X. When I reply that I know the similar package Y they might say unless you know X I cannot put you forward.

The problem is that some of these agents don't know what they talking about, they are merely being used by their clients as a screening filter.

It would be useful to be able to say to these agents that because I know Y I can expect to become reasonably proficient in X in a given number of days/months. However not knowing X determining the required time is why I'm asking this question.

Most recently X was Oracle and Y was SQL Server.

Please can those of you who know both, express an opinion on how long is required to become reasonably proficient? NB I'm not talking about becoming a DBA!

[A]
If you're being hired as a DBA, it will take a while to switch between databases as the management of them differs (I base this on my experience with Oracle and DB2 only).
I DON'T know SQL Server but I can imagine a Microsoft program with its nice GUI management would be vastly different to managing DB2/z, for example (although you can use the fancy DB2 LUW (Linux/UNIX/Window) tools if you're that way inclined).
If you're just cutting code to use the database, the SQL differences are minor (relatively).  That shouldn't take much time at all, assuming you're already proficient with SQL.


q:
What do you use to validate an email address on a ASP.NET form. I want to make sure that it contains no XSS exploits.

This is ASP.NET 1.1

[A]
Preventing XSS is a different issue from validating input.
Regarding XSS: You should not try to check
input
for XSS or related exploits. You should prevent XSS exploits, SQL injection and so on by escaping correctly when inserting strings into a different language where some characters are "magic", eg, when inserting strings in HTML or SQL. For example a name like O'Reilly is perfectly valid input, but could cause a crash or worse if inserted unescaped into SQL. You cannot prevent that kind of problems by validating input.
Validation of user input makes sense to prevent missing or malformed data, eg. a user writing "asdf" in the zip-code field and so on. Wrt. e-mail adresses, the syntax is so complex though, that it doesnt provide much benefit to validate it using a regex. Just check that it contains a "@".


q: Is there a way to automatically apply a theme/template/style to all controls of the targettype, so I don't have to specify Template=..., Style=... on all controls?

[A]
I thought there was a way to do this by just omitting the x:Key attribute, but that doesn't seem to work anymore. Based on some googling it seems to me like you're best best is to create a custom control library of your own that has a themes/generic.xaml file that defines your custom styles. Then you can use your own elements that are styled properly (MyButton instead of Button). Either that or
stick with the Style property
.
Some example of this
here
and an alternate approach using themes
here
.
Update:
Just found a really good example of this
here
(I think you might have already seen it :).


q: I need to make a change to an ASP.NET web service written a couple years ago on 2.0.  I call this web service from an old 1.1 web site.  I need to make some changes to the web service, so am thinking, should I rewrite this into a WCF service and if so, will I still be able to use it from my 1.1 web site?

[A]
You can make a WCF service act and behave just like a traditional 1.1 ASMX web service, but is that what you want?
I think you need to ask yourself what featires of WCF are motivating you to upgrade.
Do you want to also expose the service as a REST-ful service?  Do you need to implement message level security?
If it's just to go to the latest technology for the sake of the latest technology, I'd say stick with ASMX web services if your requirements for message and protocol security aren't that high and you're working with mostly microsoft technologies.
Writing a WCF service is regrettably more difficult than a plain-old asmx web service.


q:
Sybase db tables do not have a concept of self updating row numbers. However , for one of the modules , I require the presence of rownumber corresponding to each row in the database such that max(Column) would always tell me the number of rows in the table.

I thought I'll introduce an int column and keep updating this column to keep track of the row number. However I'm having problems in updating this column in case of deletes. What sql should I use in delete trigger to update this column?

[A]
You can easily assign a unique number to each row by using an identity column. The identity can be a numeric or an integer (in ASE12+).
This will
almost
do what you require. There are certain circumstances in which you will get a gap in the identity sequence. (These are called "identity gaps", the best discussion on them is
here
). Also deletes will cause gaps in the sequence as you've identified.
Why do you need to use max(col) to get the number of rows in the table, when you could just use count(*)? If you're trying to get the last row from the table, then you can do
```
```
select * from table where column = (select max(column) from table).
```
```
Regarding the delete trigger to update a manually managed column, I think this would be a potential source of deadlocks, and many performance issues. Imagine you have 1 million rows in your table, and you delete row 1, that's 999999 rows you now have to update to subtract 1 from the id.


q:
We are developing a considerably big application using Ruby on Rails framework (CRM system) and are considering to rewrite it to use ExtJS so that Rails would just do the data handling, while ExtJS would do all the browser heavylifting in a desktop-like manner.

Anyone has some experience and hints about what would be the best approach? Is ExtJS mature enough to be used in relatively big (and complex) applications? And what about the Rails part - what would be the best approach here?

EDIT:

Just to make it clear. I would prefer to do it in such a way that all the javascript client side application code is loaded at once (at the start up of the application, optimally as one compressed js file) and then just use ajax to send data to and from Rails app. Also, it would be nice to have ERB available for dynamic generation of the Ext apliccation elements.

[A]
Ext is definitely mature enough to handle this situation. I'm currently working on a Rails project with a lot of Ext, and the hardest part has definitely been working with Rails's
```
to_json
```
to render JSON that Ext can read (for arrays, hashes, models, which failed validation, etc.)
Check out the ext_
```
scaffold
```
plugin for Rails. I started with this and hacked away at its
```
ActiveRecord
```
/
```
ActionView
```
extensions until it did what I needed it to do.


q:
Is there a best practice when it comes to setting client side "onclick" events when using ASP.Net controls?  Simply adding the onclick attribute results in a Visual Studio warning that onclick is not a valid attribute of that control.  Adding it during the Page_Load event through codebehind works, but is less clear than I'd like.

Are these the only two choices?  Is there a right way to do this that I'm missing?

Thanks!
Eric Sipple

[A]
Setting the value for
```
WebControl.Attributes["onclick"]
```
is okay. If ASP.NET needs a client-side
```
click
```
handler, it will concatenate the values, delimited by semi-colon.


q: I have a BulletedList in asp.net that is set to DisplayMode="LinkButton". I would like to trigger the first "bullet" from a javascript, can this be done? And if so, how?

[A]
Say you have the BulletedList as
```
```
<asp:BulletedList runat="server" ID="MyLovelyBulletedList" DisplayMode="LinkButton">
    <asp:ListItem Text="My Lovely Text 1" />
    <asp:ListItem Text="My Lovely Text 2" />
</asp:BulletedList>
```
```
... then you can fire the "onclick" event like this (cross-browser):
```
```
var links = document.getElementById('<%= MyLovelyBulletedList.ClientID %>').getElementsByTagName('a');

var targetLink = links[0];

if (targetLink.fireEvent)
{
    // IE
    targetLink.fireEvent("onclick");
}
else if (targetLink.dispatchEvent)
{
    // W3C
    var evt = document.createEvent("MouseEvents");

    evt.initMouseEvent("click", true, true, window,
        0, 0, 0, 0, 0, false, false, false, false, 0, null);

    targetLink.dispatchEvent(evt);
}
```
```


q:
When reading my RSS feed with the Thunderbird feed reader, some entries are duplicated. Google Reader does not have the same problem.

Here is the faulty feed:
http://plcoder.net/rss.php?rss=Blog

There is a problem, but where?

I added a GUID, but the problem remains. Other feeds do not duplicate like mine, so I will do rework on this module and replace this old good code.

Conclusion: I completely reworked the RSS generator code, and it's OK. I think I was using a very old version of RDF.

[A]
Try adding a
```
<guid>
```
tag to each item, giving it a permalink.  i.e.:
```
```
<item rdf:about="http://plcoder.net/?doc=2134&amp;titre=mon-pc-se-la-pete">
  <link>http://plcoder.net/?doc=2134&amp;titre=mon-pc-se-la-pete</link>
  <guid>http://plcoder.net/?doc=2134&amp;titre=mon-pc-se-la-pete</guid>
  ...
</item>
```
```
Without a GUID, if any of the content in the post changes, your RSS aggregator might think that it is a new post.  With the GUID, even if the content of that item changes, your RSS aggregator
should
just update the post, instead of treating it as a new item.


q:
This question is similar to my  earlier question.

I have used ASP .Net in Visual Studio 2005 about 4 years ago. How long would it take to get back up to speed with the latest versions?

[A]
Not very long. The major addition to VS 2008 is support for Linq, but you don't have to use this (or any of the new features).
The IDE is extremely similar to VS 2005.
Essentially, 2005 targets the 3.0 framework, and 2008 target the 3.5 framework, but these are both just expansions of the 2.0 framework, and not new versions (unlike the change from 1.1 to 2.0).


q:
I am trying to find all matches in a string that begins with | |.

I have tried: if ($line =~ m/^\\\|\s\\\|/) which didn't work.

Any ideas?

[A]
You are escaping the pipe one time too many, effectively escaping the backslash instead.
```
```
print "YES!" if ($line =~ m/^\|\s\|/);
```
```


q:
I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.

Example:

public class MyGenericClass<T> {
  public void doSomething() {
    // Snip...
    // Call to a 3rd party lib
    T bean = (T)someObject.create(T.class);
    // Snip...
  }
}

Clearly the example above doesn't work  and results in the following error: Illegal class literal for the type parameter T.

My question is: does someone know a good alternative or workaround for this?

[A]
Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method :
```
```
public class MyGenericClass<T> {

    private final Class<T> clazz;

    public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
        return new MyGenericClass<U>(clazz);
    }

    protected MyGenericClass(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void doSomething() {
        T instance = clazz.newInstance();
    }
}
```
```
It's ugly, but it works.


q:
I am doing .net programming in addition to c and c++ development and want more flexibility on my home machine.  I want to be able to have both Linux (probably Ubuntu) and Windows Vista on my home computer.  Is there a way I can install both and on boot be prompted for which one to start?  Is there a way to set Windows to default?

I have seen this before in CS labs in undergrad.

Also, I assume there would be no problem if I were to use Windows 32-bit along with Ubuntu 64-bit.  Any advise?

[A]
You can dual boot, but I would recommend using a Virtual Machine for what you want to do.
Look at
VMWare
and
Virtual PC
.
For more information on Virtual PC:
http://en.wikipedia.org/wiki/Microsoft_Virtual_PC
For more information on VMWare:
http://en.wikipedia.org/wiki/VMware_Workstation
You should note that dual booting Windows and Linux can be a little risky and is a bit permanent. Running in a Virtual Machine means that you can run the Linux install in a window and not worry about it affecting your development machine at all. The software will not know the difference, so your testing is not affected.
Consider that the Virtual Machine is like a sandbox, where you can try new and different things out, without fear of consequences.
Virtual machines do run with a bit of overhead, and therefore you should not expect to be playing games or anything through them. I would say it is very much like logging into a machine through Remote Desktop (good LAN connection) as far as performance goes.
EDIT: There is also
VirtualBox
that you could check out. Thanks for the helpers in my comments for that one.


q: Using JDK1.5 how does one send a binary attachemnt (such as a PDF file) easily using the JavaMail API?

[A]
If you want to do it easily I'd suggest using
Commons-Email
! It's built on the JavaMail API, but it makes it much simpler.
There is a sample in the
User Guide
on how to send email with attachments... it's much easier than using the standard JavaMail API!


q: How to unit test the windows workflows?

[A]
MS dropped the ball on making workflows easily mockable and testable.  If you want to do thorough tests on your custom activities you'll need to purchase a mocking framework that can mock sealed types such as
TypeMock.
Otherwise, you'll have to write your code around the limitations of Workflow.


q: Specifically MSSQL 2005.

[A]
Some links to possible answers:
http://www.extremeexperts.com/sql/Tips/DateTrick.aspx
http://www.devx.com/tips/Tip/14405
http://blog.sqlauthority.com/2007/08/18/sql-server-find-last-day-of-any-month-current-previous-next/
http://www.sqlservercurry.com/2008/03/find-last-day-of-month-in-sql-server.html


q:
This is a question for anyone who has the pleasure to work in both Java and C#.

Do you find that you have to make a mental context switch of some kind when you move from one to the other?

I'm working in both at the moment and because the syntax and libraries are so similar and yet subtly different I'm finding it frustrating when i move from one to the other.

This is more so than I've experienced moving between any other programming languages.

Does anyone have any tips for making your brain work differently for languages that are so similar?

[A]
Yes, I have to make a mental context switch - because LINQ isn't available in Java :(
Beyond that, there are little things like
```
foreach (X x in y)
```
vs
```
for (X x : y)
```
which often trip me up, but not a
huge
amount otherwise.
As for a tip to make your brain work differently: don't give into the temptation to use the naming conventions of the other language. I find that using camel-cased method names in Java is a good nudge to my brain, for example.
EDIT: The differences in terms of generics are important and can occasionally be brain-warping, too.


q: I need to determine the highest .NET framework version installed on a desktop machine from C\C++ code.  Looks like I can iterate the folders under %systemroot%\Microsoft.NET\Framework, but that seems kind of error prone.  Is there a better way?  Perhaps a registry key I can inspect?  Thanks.

[A]
Use the
Windows Registry
location
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
```
.


q:
im trying to locate the position of the minimum value in a vector, using STL find algorithm (and the min_element algorithm), but instead of returning the postion, its just giving me the value. E.g, if the minimum value is it, is position will be returned as 8 etc. What am I doing wrong here?

int value = *min_element(v2.begin(), v2.end());
cout << "min value at position " << *find(v2.begin(), v2.end(), value);

[A]
```
min_element
```
already gives you the iterator, no need to invoke
```
find
```
(additionally, it's inefficient because it's twice the work). Use
```
distance
```
or the
```
-
```
operator:
```
```
cout << "min value at " << min_element(v2.begin(), v2.end()) - v2.begin();
```
```


q:
I have parsed XML using both of the following two methods...

Parsing the XmlDocument using the object model and XPath queries.

XSL/T

But I have never used...

The Linq Xml object model that was new to .Net 3.5

Can anyone tell me the comparative efficiency between the three alternatives?

I realise that the particular usage would be a factor, but I just want a rough idea. For example, is the Linq option massively slower than the others?

[A]
I haven't actually tested it, but Linq is primarily a compiler code-gen type feature, and so it should be comparable to using an XmlDocument and XPath queries.
The primary value of Linq is that it provides compile-time verification of your query statements, which neither XPath nor XSLT can provide.
I would think that if performance is a concern, your decision would be based on the task at hand.  For example, retrieving a single value from an XML document might be fastest using a single XPath query, but translating XML data into an HTML page would be faster using XSLT.


q:
Files:

Website\Controls\map.ascx

Website\App_Code\map.cs

I'd like to create a strongly typed instance of map.ascx in map.cs

Normally, in an aspx, you would add a <%Register... tag to be able to instantiate in codebehind. Is this possible in an app_code class?
I'm using .NET 3.5/Visual Studio 2008

Thanks!

[A]
Normally, I'd do something like this (assuming your type is "Map" and that you have the appropriate "Inherits" declaration in your .ascx file):
```
```
Map map = (Map)LoadControl("~/Controls/map.ascx");
```
```


q:
I'm working on a free software (bsd license) project with others. We're searching for a system that check out our source code (svn) and build it also as test it (unit tests with Check / other tools).

It should have a webbased interface and generate reports.

I hope we don't have to write such a system from null by ourselves...

[A]
I don't think that there's a buildsystem that is capable of doing all this tasks - but what about combining them?
SCons
is a nice buildsystem that runs on every machine that has
Python
. It can even build directly from
SVN
. For automatic building you can try
Buildbot
.


q: I'm making a report in Access 2003 that contains a sub report of related records.  Within the sub report, I want the top two records only.  When I add "TOP 2" to the sub report's query, it seems to select the top two records before it filters on the link fields.  How do I get the top two records of only those records that apply to the corresponding link field?  Thanks.

[A]
I've got two suggestions:
1) Pass your master field (on the parent form) to the query as a parameter (you could reference a field on the parent form directly as well)
2) You could fake out rownumbers in Access and limit them to only rownum <= 2. E.g.,
```
```
SELECT o1.order_number, o1.order_date,
    (SELECT COUNT(*) FROM orders AS o2
        WHERE o2.order_date <= o1.order_date) AS RowNum
    FROM
        orders AS o1
    ORDER BY o1.order_date
```
```
(from
http://groups.google.com/group/microsoft.public.access.queries/msg/ec562cbc51f03b6e?pli=1
)
However, this kind of query might return an read only record set, so it might not be appropriated if you needed to do the same thing on a Form instead of a Report.


q:
When i deploy a rails application in production mode, it appends a date-time string as a query param to the end of all the static asset urls. This is to prevent browsers using old-out of date cahed copies of the assets after I redeploy the application.

Is there a way to make rails use the old time stamps for the assets that have not changed (and only the ones that have not changed) since the last deployment. I want to do this to prevent users having to redownload those assets that have not changed.

[A]
I think you can use ENV['RAILS_ASSET_ID'] to alter the cache-busting asset ID. Unfortunately, this is for all assets.
But if it's not set, it uses the asset's source modification time. If that file hasn't been modified since the last time you used it, it shouldn't be a problem.
If the asset ID is changing when they haven't been changed, it might be because of your deployment process altering the modification time and maybe you could look at tweaking that.
Lastly, you can always
override rails_asset_id with your own custom method
.
Hope this helps.


q:
Looking into System.Data.DbType there is no SqlVariant type there. SqlDataReader, for example, provides the GetString method for reading into string variable. What is the appropriate way to retrieve data from the database field of type sql_variant, presumably into object?

The aim is to read data stored as sql_variant type in database. Not to assign the value into variable of object type. I mentioned object type variable because I thing the sql_variant, if possible, would go into such type.

[A]
If you want to put the data into a variable of type object then (simplified):
```
```
object result = null;
result = reader["columnNameGoesHere"];
```
```
Should do the trick.
There's also a good explanation of the various different methods of retrieving the contents of a given columns current record in
this DevHood tutorial
. The summary table of data type mappings at the end may come in handy too!


q:
I have an internal web app with an image at the top of the page, currently containing some english text with drop shadows. I now need to provide localized versions of this page for various languages. My main choices are:

Have a different graphic per supported language, containing the localized text.

Use CSS to position localized text over a plain image, with a complex CSS technique to get drop shadows in most current browsers.

Are there other options? This is for an educational environment, I don't get to control the browser used by the students.

I did try both removing the drop shadows from the graphic, and also moving the text into in a header in the HTML, but neither was appealing. People said it looked like a cheap knockoff of the current page, which wounds my pride.

[A]
Personally I'm a big fan of CSS techniques for visual effects like this. The big benefit is that you are offloading the processing of the effect to the client side, saving you bandwith and content creation time (custom text images for each locale is a big order!), and making the page download faster for the user.
The only reason to avoid it is if you absolutely MUST have the drop shadows on very old (IE5) browsers with next to no CSS support.
Edit: Just thought of something - I a few cases like this where I need a specific font or some exact text effect I've used PHP to render the text, with effects, to an image and cache it server side. That way you avoid the content creation process and gain wider browser support in exchange for bandwidth and server CPU time. It's your call if the tradeoff is acceptable.


q:
I have a strange bug with WPF Interop and an Excel Addin. I'm using .Net 3.5 SP1.

I'm using Add-in Express to create a Custom Task Pane for Excel 2003. Within that taskpane I'm using ElementHost to host a WPF UserControl. The UserControl simply contains a Grid with a TextBox and ComboBox. My problem is that whilst everything displays properly, the ComboBox won't stay dropped-down unless I hold the mouse down over the down-arrow.

I don't believe this is necessarily related to Add-in Express because I've had a similar problem when I tried displaying a WPF window modelessly in Excel.

A second problem is that the ComboBox seems reluctant to give up focus. If I click it, the text area goes grey to indicate that it has focus, but I can't move focus anywhere else in the window. The only way to wrest focus away is to move the mousewheel.

Anybody else had a similar problem, and managed to fix it?

[A]
Add-in Express looked into this for me, and it turns out to have something to do with the Window style of the Task Pane that gets added to Excel. If you turn off the WS_CHILD flag in the Windows CreateParams then Combo Boxes and other popups work as expected.
They gave me this snippet of code to add to my ADXExcelTaskPane:
```
```
private const uint WS_CHILD = 0x40000000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;

private CreateParams _CreateParams = new CreateParams();
protected override CreateParams CreateParams
{
    get
    {
        _CreateParams = base.CreateParams;
        if (!DesignMode)
            _CreateParams.Style = (int)(WS_CLIPCHILDREN | WS_CLIPSIBLINGS); //| WS_CHILD

        return _CreateParams;
    }
}
```
```


q: Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?

[A]
You could try writing a
custom type
, for instance:
```
```
import sqlalchemy.types as types

class UUID(types.TypeEngine):
    def get_col_spec(self):
        return "uuid"

    def bind_processor(self, dialect):
        def process(value):
            return value
        return process

    def result_processor(self, dialect):
        def process(value):
            return value
        return process

table = Table('foo', meta,
    Column('id', UUID(), primary_key=True),
)
```
```


q:
I would like to add a BuildListener to my headless build process, which is building an Eclipse product. The docs on how to do this are, shall we say, a bit scanty. I think I need to put my custom jar in a plugin and then use the org.eclipse.ant.core.extraClasspathEntries extension point to make that jar visible to Ant. But everything I have tried results in
 [myClass] which was specified to be a build listener is not an instance of org.apache.tools.ant.BuildListener.

My class implements the BuildListener interface. Various  postings seem to indicate that this means my class is visible-to/loaded-by the Plugin classloader rather than the Ant classloader. But I thought the whole point of the extension point was to make jars visible to Ant...

Can anyone shed light on what I'm doing wrong?
Additional info: I am trying to run this build from the Eclipse IDE at the moment using the AntRunner application.

[A]
I had this problem when I had two plugins providing an
```
ant.jar
```
.
Make sure you use the
```
org.apache.ant
```
plugin and that there is no other plugin providing another
```
ant.jar
```
.
Another thing I just stumbled upon: The jar containing your contribution must not be in the plugins classpath (Runtime -> Classpath).
See
Eclipse Bug 34466
.


q: I'm a big fan of Capistrano but I need to develop an automated deployment script for a Java-only shop.  I've looked at Ant and Maven and they don't seem to be well geared towards remote administration the way Capistrano is - they seem much more focused on simply building and packaging applications.  Is there a better tool out there?

[A]
I don't think there is a Capistrano-like application for Java Web Applications, but that shouldn't really keep you from using it (or alternatives like Fabric) to deploy your applications. As you've already said, Ant is more a replacement for GNU Make while Maven is primary a buildout/dependency-management application.
Since Java Web Applications are thanks to the .war container less dependent on external libraries, you can (depending on your application server) make deploying an application as easy as running a simple HTTP PUT-request.
But if you require additional steps,
Fabric
has worked very well for me so far and I assume that Capistrano also offers generic shell-command, put and get operations. So I wouldn't look for too long for an alternative if what you already have already works :-)


q:
I have a C++ template class that gets instantiated with 3 different type parameters. There's a method that the class needs to have for only one of those types and that isn't ever called with the two other types.

Will object code for that method be generated thrice (for all types for which the template is instantiated), or is object code generated only once (for the type with which it is actually used)?

[A]
Usually, yes.
All the compiler really knows is that your program can create at least one instance of each class.  But it doesn't know what you will do with those instances.  So the code will almost certain be generated.
That said, if the methods in question are
not
virtual, and are never called, the
linker
can remove them with its normal dead code removal features.  So the generated (and compiled) code won't be in the final EXE.
Also this will largely depend on the C++ compiler being used because they're not all the same.


q:
I need to generate multiple random values under SQL Server 2005 and somehow this simply wont work

with Random(Value) as
(
    select rand() Value
        union all
    select rand() from Random

)select top 10 * from Random

Whats the preffered workaround?

[A]
I'm currently using this:
```
```
with Random(Value) as
(
    select rand(checksum(newid())) Value
        union all
    select rand(checksum(newid())) from Random
)select top 10 * from Random
```
```
but that seems overly hackish :S
Why doesnt rand get reevaluated in the first version?


q:
We are using Visual Studio 2008 as our primary development IDE.  Our security team has set up McAfee to scan files in our \Local Settings\Temp folder.  Unfortunately VS uses this directory during code builds which is slowing the developers down.  We've reached an impasse with the security team on this, and wonder if anyone knows of a configuration setting in VS where we could change the folder to where those temporary files are written.

Thanks

[A]
Maybe complain a lot that you need faster computers since the added security slows you down so much? Have hard facts ready (like "slower compile time costs me 60 minutes every day")
Usually when it comes around to spending money most businesses find other ways around a problem.


q:
What's the best way to break from nested loops in Javascript?

//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
   for (var Heading in Navigation.Headings)
   {
      for (var Item in Navigation.Headings[Heading])
      {
         if (Args[x] == Navigation.Headings[Heading][Item].Name)
         {
            document.write("<a href=\""
               + Navigation.Headings[Heading][Item].URL + "\">"
               + Navigation.Headings[Heading][Item].Name + "</a> : ");
            break; // <---HERE, I need to break out of two loops.
         }
      }
   }
}

[A]
Wrap that up in a function and then just
```
return
```
.


q:
Is it possible to make hibernate do "the right thing" for some value of "right" in this situation?

from ClassA a, ClassB b
where a.prop = b.prop

The thing is that prop is a UserType with different representation in the joined tables. In table A it is represented as an integer and in table B it is represented as a char. So the eq test translates to see if 1 == 'a' more or less, which is false but the object represented by 1 or 'a' should is the same so they should compare true.

[A]
(1) Change data-type of columns which map to "prop" to be the same. This will require "Making DBA your friend" but will result in consitent "prop" UserType usage.
(2) Handle the type differences in equals() method
```
```
public boolean equals(Object x, Object y) throws HibernateException {
    boolean retValue = false;
    if (x == y) retValue = true;

    if (x!=null && y!=null){
        Character xChar = new Character(x);
        Character yChar = new Character(y);
        if (xChar.equals(ychar)){
            retValue = true;
        }
    }

    return retValue;
}
```
```


[A]
```
```
ps aux --sort user | perl -npe 's/^(\w+)//g; if ($user ne $1) {$user=$1; print "user: " . uc($user) . "\n";}'
```
```


q:
I have unmanaged C++ calling a managed delegate via the function pointer provided by Marshal::GetFunctionPointerForDelegate.  This delegate has the potential to throw an exception.  I need to be able to properly handle this exception in my unmanaged C++ to ensure things like pointer cleanup, and potentially rethrow the exception up into more managed code.  The call stack is similar to this:

Managed Code -> Unmanaged C++ -> callback to Managed Code via delegate (exception can be thrown here).

Anyone have pointers for properly handling this situation so that the resources in unmanaged code can be cleaned up and a usable exception can be thrown out to the managed code which initiated the whole call stack?

[A]
Catching from managed code with
```
```
try
{
  throw gcnew InvalidOperationException();
}
catch(InvalidOperationException^ e)
{
  // Process e
  throw;
}
```
```
And an
```
```
[assembly:RuntimeCompatibility(WrapNonExceptionThrows = true)];
```
```
on your assembly catches managed and unmanaged exceptions


q:
I'm having some trouble with plain old JavaScript (no frameworks) in referencing my object in a callback function.

function foo(id) {
    this.dom = document.getElementById(id);
    this.bar = 5;
    var self = this;
    this.dom.addEventListener("click", self.onclick, false);
}

foo.prototype = {
    onclick : function() {
        this.bar = 7;
    }
};

Now when I create a new object (after the DOM has loaded, with a span#test)

var x = new foo('test');

The 'this' inside the onclick function points to the span#test and not the foo object.

How do I get a reference to my foo object inside the onclick function?

[A]
```
```
this.dom.addEventListener("click", function(event) {
    self.onclick(event)
}, false);
```
```


q: Passing an undimensioned array to the VB6's Ubound function will cause an error, so I want to check if it has been dimensioned yet before attempting to check its upper bound.  How do I do this?

[A]
I found this:
```
```
Dim someArray() As Integer

If ((Not someArray) = -1) Then
  Debug.Print "this array is NOT initialized"
End If
```
```
Edit
: RS Conley pointed out in his
answer
that (Not someArray) will sometimes return 0, so you have to use ((Not someArray) = -1).


q:
I have a SEAM app with some JPA/Hibernate entities. And I now wonder where to put my query, persistence methods.

The default choice seems to put them in a session bean layer with injected

@PersistenceContext(...) @Inject EntityManager entityManager;

But I think I would rather have the methods on the entities themselves. What are the pro's/con's?

Testablity?

Niceness?

Performance?

And does anyone have links to best practices for interacting with the EntityManager etc. from methods on the Entities rather than session beans?

Best,
Anders

[A]
I have no experience with SEAM, but from my experience with Java projects, I found it easiest to keep beans clear of persist methods. What we usually do:
Have beans for business objects (like "User" and "Setting" for example)
Have a DAO layer which can persist and retrieve these beans (simple CRUD)
Have a Service Layer which nows how to handle the beans, and maybe even how to build an aggregate of beans
This way, everything is pretty separated, and is easy to unittest. Performance is usually not an issue with this setup.


q:
Does Mono .NET support and compile C++ / CLI?

If not, do you know if they have any plans of supporting it?

[A]
go
here
and look under "Missing Languages".  But just because you cant compile does not mean that you cant
run
.  You can compile your C++ code using the framework sdk and try running it using mono.  Worth trying anyway.


q:
How can I add a line break to text when it is being set as an attribute i.e.:

<TextBlock Text="Stuff on line1 \n Stuff on line2" />

Breaking it out into the exploded format isn't an option for my particular situation.  What I need is some way to emulate the following:

<TextBlock>
  <TextBlock.Text>
    Stuff on line1 <LineBreak/>
    Stuff on line2
  </TextBlock.Text>
<TextBlock/>

[A]
```
```
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
```
```
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic"
```
vbCrLf
```
, then you can use
```

```
By the way, note the syntax: It's the ampersand, a pound, the letter
x
, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.


q:
I have an extremely simple routes.rb in my Rails app:

ActionController::Routing::Routes.draw do |map|
  map.resources :tags
end

Starting up my app with script/server and pointing my browser to localhost:3000/tags/ yields:

ActionController::MethodNotAllowed

Only get and post requests are allowed.

...

Starting up my app with script/server webrick, however, solves the problem.

Later: in case it matters, I'm running Mongrel 1.1.5 on OSX 10.5.5.

[A]
I have seen this happen with older versions of mongrel, but 1.1.5 is not old. I have also seen some similar problems when the browser double-posts a request to a URL. Is that happening here?
I'd need some more information to be able to help you: What browser are you using? Are you using the firebug plugin on Firefox? What does the server log say about the request, other than the MethodNotAllowed exception?


q:
How do I fix that error once and for all?  I just want to be able to do unions in MySQL.

(I'm looking for a shortcut, like an option to make MySQL ignore that issue or take it's best guess, not looking to change collations on 100s of tables ... at least not today)

[A]
Not sure about mySQL but in MSSQL you can change the collation in the query so for example if you have 2 tables with different collation and you want to join them or as in you situation crate UNION you can do
```
```
select column1 from tableWithProperCollation
union all
select column1 COLLATE SQL_Latin1_General_CP1_CI_AS from tableWithDifferentCollation
```
```
Of course SQL_Latin1_General_CP1_CI_AS is just an example of collation you want to "convert" to


q:
Is there any way to determine a removable drive speed in Windows without actually reading in a file.  And if I do have to read in a file, how much needs to be read to get a semi accurate speed (e.g. determine whether a device is USB2 or USB1)?

EDIT: Just to clarify, USB2 and USB1 were an example.  These could be Compact Flash, could be SSD, could be a removable drive.  And I am trying to determine this as fast as possible as it has a real effect on the responsiveness of the application.

EDIT:  Should also clarify, this has to be done programatically.  It will probably be done in C++.

EDIT: Boost answer is kind of what I was looking for (though I haven't written any WMI in C++).  But I need to know what properties I have to check to determine relative speed.  I don't need exact speed (like I said about the difference in speed between USB1 and USB2), but I need to know if it is going to be SLLOOOOWWW.

[A]
Several megabytes, I'd say. Transfer speeds can start out slow, and then speed up as the transfer progresses. There are also variations because of file sizes (a single 1GB file will transfer much faster than 1GB of smaller files).
Best way to do that would be to copy a file to/from the device, and time how long it takes with your code. USB1 speed is 11Mb/s (I think), and USB2 is 480Mb/s (note those are numbers for the whole bus, not each port, so multiple devices on the same bus will change the actual numbers).