Question:
I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.

Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?

Answer:
A single image alone doesn't give the browser the semantic information on the logos within. You could use an
image map
to supply the coordinates. To achieve tooltips, just apply a
```
title
```
attribute to each link. For more sophisticated tooltips (such as with styling, multiple lines, etc.), you'll need something non-standard, such as
UniTip
.


Question:
I've used the PHP MVC framework Symfony to build an on-demand web app.

It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as this one did not help me.

I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future.

Has anyone been there and solved it? I would be most grateful for a hint or two!

Answer:
The company I work for has been using Symfony and the workaround that we've used is to trigger a warning with javascript before the user gets logged out. I suspect that there is a a way to make 'heartbeat' ajax calls to the server to trigger the timer to reset, but that may be a lot of trouble. I think that there may not be a full fix that's suitable for you though, except maybe re-writing the session handler.
Sorry I couldn't be more specific, if I get the chance, I'll ask our Symfony devs if they know of a better solution.


Question:
I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:

15, 'QHS', '20', '2008-08-24 13:36:33.465567-04'
15, 'QHE', '8', '2008-08-24 12:07:08.660519-04'
15, 'QHS', '21', '2008-08-24 09:44:44.39354-04'
15, 'QHE', '10', '2008-08-24 08:47:57.672058-04'

I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.

Answer:
I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes...
One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy.
The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity.
Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'.
You might be interested in taking a look at the Wikipedia entry on
temporal databases
and the article
A consensus glossary of temporal database concepts
.


Question:
I have a couple of files containing a value in each line.

EDIT :

I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.

I was trying to do:

paste -d ',' file1 file2 file 3 file 4 > file5.csv

and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things.

Answer:
you probably need to clarify or retag your question but as it stands the answer is below.
joining two files under Linux
```
```
cat filetwo >> fileone
```
```


Question:
What's the best way to make an element of 100% minimum height across a
  wide range of browsers ?

In particular if you have a layout with a header and footer of fixed height,

how do you make the middle content part fill 100% of the space in between with the footer fixed to the bottom ?

Answer:
I am using the following one:
CSS Layout - 100 % height
Min-height
The #container element of this page has a min-height of 100%. That
  way, if the content requires more height than the viewport provides,
  the height of #content forces #container to become longer as well.
  Possible columns in #content can then be visualised with a background
  image on #container; divs are not table cells, and you don't need (or
  want) the physical elements to create such a visual effect. If you're
  not yet convinced; think wobbly lines and gradients instead of
  straight lines and simple color schemes.
Relative positioning
Because #container has a relative position, #footer will always remain
  at its bottom; since the min-height mentioned above does not prevent
  #container from scaling, this will work even if (or rather especially when) #content forces #container to become longer.
Padding-bottom
Since it is no longer in the normal flow, padding-bottom of #content
  now provides the space for the absolute #footer. This padding is
  included in the scrolled height by default, so that the footer will
  never overlap the above content.
Scale the text size a bit or resize your browser window to test this
  layout.
```
```
html,body {
    margin:0;
    padding:0;
    height:100%; /* needed for container min-height */
    background:gray;

    font-family:arial,sans-serif;
    font-size:small;
    color:#666;
}

h1 {
    font:1.5em georgia,serif;
    margin:0.5em 0;
}

h2 {
    font:1.25em georgia,serif;
    margin:0 0 0.5em;
}
    h1, h2, a {
        color:orange;
    }

p {
    line-height:1.5;
    margin:0 0 1em;
}

div#container {
    position:relative; /* needed for footer positioning*/
    margin:0 auto; /* center, not in IE5 */
    width:750px;
    background:#f0f0f0;

    height:auto !important; /* real browsers */
    height:100%; /* IE6: treaded as min-height*/

    min-height:100%; /* real browsers */
}

div#header {
    padding:1em;
    background:#ddd url("../csslayout.gif") 98% 10px no-repeat;
    border-bottom:6px double gray;
}
    div#header p {
        font-style:italic;
        font-size:1.1em;
        margin:0;
    }

div#content {
    padding:1em 1em 5em; /* bottom padding for footer */
}
    div#content p {
        text-align:justify;
        padding:0 1em;
    }

div#footer {
    position:absolute;
    width:100%;
    bottom:0; /* stick to bottom */
    background:#ddd;
    border-top:6px double gray;
}
div#footer p {
    padding:1em;
    margin:0;
}
```
```
Works fine for me.


Question: How do you unit test a HttpModule in asp.net given that HttpApplication and HttpContext do no implement an interface ?

Answer:
In the past before moving to ASP.NET MVC, I used
this library
Phil Haack created for Unit Testing anything that used the HttpApplication and HttpContext.  It in turned used a
Duck Typing library
.
Unfortunately, this was the best way to do it.  ASP.NET was not made to be easily testable.  When they worked on ASP.NET MVC, one of the goals is to get rid of these headaches by making the framework more testable.


Question:
Has anybody out there used the SWIG library with C#?  If you have, what pitfalls did you find and what is the best way to use the library?  I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my .NET application.

Edit:  Some clarification on target OS's.

I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG.  P/Invoke is not an option.

Answer:
I did attempt to use SWIG to wrap a project C++ for using in .NET a few years ago.
I didn't get very far as it was a massive giant pain to produce the configuration that SWIG required. At the time I just wanted a solution, not to learn another language/api/etc. SWIG may be easier to use these days, I couldn't tell you.
We ended up using Managed C++ to wrap the C++ project. It worked really well.
If you're just invoking functions straight out of a dll, I'd suggest not worrying about either of the above, and just using
P/Invoke


Question:
There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used.

The official response was:

not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you?

So, is there a way?

There are a number of resources on it I can find, but I am not an expert.

Answer:
As far as I've seen, it is
not
possible to do AND when using FREETEXT() under SQL 2005 (nor 2008, afaik).
A FREETEXT query ignores Boolean, proximity, and wildcard operators by design. However you could do this:
```
```
WHERE FREETEXT('You gotta love MS-SQL') > 0
 AND FREETEXT('You gotta love MySQL too...') >  0
```
```
Or that's what I think :)
-- The idea is make it evaluate to Boolean, so you can use boolean operators. Don't know if this would give an error or not. I think it
should
work. But reference material is pointing to the fact that this is not possible by design.
The use of CONTAINS() instead of FREETEXT() could help.


Question:
I would like to use as and is as members of an enumeration. I know that this is possible in VB.NET to write it like this:

Public Enum Test
    [as] = 1
    [is] = 2
End Enum

How do I write the equivalent statement in C#?
The following code does not compile:

public enum Test
{
    as = 1,
    is = 2
}

Answer:
Prefixing reserved words in C# is done with @.
```
```
public enum Test
{
    @as = 1,
    @is = 2
}
```
```


Question:
I'm looking for an existing library to summarize or paraphrase content (I'm aiming at blog posts) - any experience with existing natural language processing libraries?

I'm open to a variety of languages, so I'm more interested in the abilities & accuracy.

Answer:
Your getting into really far out AI type domain. I have done extensive work in text transformation into machine knowledge mainly using Attempto Controlled English (see:
http://attempto.ifi.uzh.ch/site/
), it is a natural language (english) that is completely computer processable into several different ontologies, such as OWLDL.
Seems like that would we way overkill though...
Is there a reason for not just taking the first few sentences of your blog post and then appending an ellipse for your summary?


Question:
I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer.

I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source.

Does one exist or are all products based on recording mouse and keyboard presses?

Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison.

Answer:
AutomatedQA's TestComplete
is a good testing application to automate GUI testing.  It supports more than just Windows Forms also, so you can reuse it for other applications.  It is not open source and this is the best that I have found.  I haven't seen an open source equivalent to WatiN.  It does have a free trial, for you decide if you like it or not.  The main reason I went with it, is that it really is cost effective, compared to other testing applications.


Question:
I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma.

What would be, in your opinion, the best way to do this using C#.NET 2.0?

Answer:
The best way is the builtin way: Use
```
string.Replace
```
. Why do you need alternatives?


Question: Does .NET come with a class capable of representing extremely large integers, such as 100 factorial?  If not, what are some good third party libraries to accomplish this?

Answer:
.NET has a BigInteger class, but it is internal, unfortunately. However, several places have their own. You can grab an implementation from IronPython, or the one from CodeProject, or from Visual J#. I have to say, I've not tried these myself, so I don't know which one is the best.
http://www.codeplex.com/IronPython
http://www.codeproject.com/KB/cs/biginteger.aspx
http://msdn.microsoft.com/en-us/magazine/cc163696.aspx


Question:
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions?

They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer?

Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.

Answer:
Lambdas bring functional programing to C#.
They are anonymous functions that can be passed as values to certain other functions.  Used most in LINQ.
Here is a contrived example:
```
```
List<int> myInts = GetAll();
IEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0);
```
```
Now when you foreach through evenNumbers the lamda
```
```
x=> x % 2 == 0
```
```
is then applied as a filter to myInts.
They become really useful in increasing readability to complicated algorithms that would have many nested IF conditionals and loops.


Question:
Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier.

Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc.

Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole?

Answer:
What I found works best is to really learn CSS. I mean
really
learn CSS.
It can be a confusing language to learn, but if you read enough about it and practice, eventually you'll learn the best way to do things.
The key is to do it enough that it comes natural. CSS can be very elegant if you know what you want to do before you start and you have enough experience to do it.
Granted, it is also a major PITA to do sometimes, but even cross-browser issues aren't so bad if you
really
practice at it and learn what works and what doesn't, and how to get around problems.
All it takes is practice and in time you can become good at it.


Question:
I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering...

For those who have used reflection in applications, have you measured performance hits and, is it really so bad?

Answer:
It is. But that depends on what you're trying to do.
I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application.
However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code :)
For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by .NET, so I don't see why you shouldn't give it a try.


Question:
Is it possible to call a stored procedure from another stored procedure asynchronously?

Edit: Specifically I'm working with a DB2 database.

Answer:
Executive summary:  Yes, if your database has a message queue service.
You can push a message onto a queue and the queue processor will consume it asynchronously.
Oracle: queues
Sql Server: service broker
DB2: event broker
For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have.
However, if your database has a queuing mechanism, you can use that to get the same result.


Question:
What would be the Master Pages equivalent in the Java web development world?  I've heard of Tiles, Tapestry and Velocity but don't know anything about them.  Are they as easy to use as Master Pages?

I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages.

Any examples would be great!!

Answer:
First, the equivalent of ASP.Net in Java is going to be a web framework, such as the ones you mention (Tiles, Tapestry and Velocity).
Master pages give the ability to define pages in terms of content slotted into a master template.
Master pages are a feature of ASP.Net (the .Net web framework), so you are looking for a feature similar to master pages in a Java web framework.
http://tiles.apache.org/framework/tutorial/basic/pages.html
gives some basic examples using Tiles and JSP to implement something similar with Struts, a Java web framework.  In this case, the Master Pages functionality is a plugin on top of Struts.
Velocity is a generic templating engine, not specialized for web pages and definitely more complicated than you need.  (I've seen it used for code generation.)
Tapestry is more of a full featured web stack than Tile, and is probably good for your purposes.  Its templating functionality involves creating a component and putting all common markup in that.  An example is at
http://www.infoq.com/articles/tapestry5-intro
.
The specifics of this differ based on which Java web framework you choose.


Question: Is there a way to shutdown a computer using a built-in Java method?

Answer:
Create your own function to execute an OS command through the
command line
?
For the sake of an example. But know where and why you'd want to use this as others note.
```
```
public static void main(String arg[]) throws IOException{
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("shutdown -s -t 0");
    System.exit(0);
}
```
```


Question: I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?

Answer:
The NSFont class has a method that can give you the size of a rectangle that would enclose a specific attributed string.  Get the font used by your text view, create a string that serves as a reasonable example of what will be in the text view, and use that to inform your frame height.  (The frame height will need to be some number of points larger than the actual rectangle the string would be displayed in.)
Alternately, you can get the various metrics from the font and attempt to calculate a reasonable frame from that.  That might or might not work; for example, a font like Apple Chancery has a huge amount of variation depending on the glyphs that are being rendered, where they are in a word, and so on; I don't know that you can calculate what the needed size would be in advance without knowing exactly what you were going to render.


Question:
Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?

For instance, I can currently set the display name of a column like this:

[DisplayName("Last name")]
public object Last_name { get; set; }

Is there a similar way to hide a column?

Edit: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-)

Answer:
Had no idea what ASP.NET Dynamic Data was so you promted me to so some research :)
Looks like the property you are looking for is
```
```
[ScaffoldColumn(false)]
```
```
There is also a similar property for tables
```
```
[ScaffoldTable(false)]
```
```
source


Question: Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?

Answer:
There are several scopes that are available to any portion of your code: Session, Client, Cookie, Application, and Request. Some are inadvisable to use in certain ways (i.e. using Request or Application scope inside your Custom Tags or CFC's; this is
coupling
, violates encapsulation principles, and is considered a bad practice), and some have special purposes: Cookie is persisted on the client machine as physical cookies, and Session scoped variables are user-specific and expire with the user's session on the website.
If a variable is extremely unlikely to change (constant for all intents and purposes) and can simply be initialized on application startup and never written again, generally you should put it into Application scope because this persists it between every user and every session. When properly implemented it is written once and read N times.
A proper implementation of Application variables in Application.cfm might look like this:
```
```
<cfif not structKeyExists(application, "dsn")>
    <cflock scope="application" type="exclusive" timeout="30">
        <cfif not structKeyExists(application, "dsn")>
            <cfset application.dsn = "MyDSN" />
            <cfset foo = "bar" />
            <cfset x = 5 />
        </cfif>
    </cflock>
</cfif>
```
```
Note that the existence of the variable in the application scope is checked before and after the lock, so that if two users create a race condition at application startup, only one of them will end up setting the application variables.
The benefit of this approach is that it won't constantly refresh these stored variables on every request, wasting the user's time and the server's processing cycles. The trade-off is that it is a little verbose and complex.
This was greatly simplified with the addition of Application.cfc. Now, you can specify which variables are created on application startup and don't have to worry about locking and checking for existence and all of that fun stuff:
```
```
<cfcomponent>
    <cfset this.name = "myApplicationName" />

    <cffunction name="onApplicationStart" returnType="boolean" output="false">
        <cfset application.dsn = "MyDSN" />
        <cfset foo = "bar" />
        <cfset x = 5 />
        <cfreturn true />
    </cffunction>
</cfcomponent>
```
```
For more information on Application.cfc including all of the various special functions available and every little detail about what and how to use it,
I recommend this post on Raymond Camden's blog
.
To summarize, request scope is available everywhere in your code, but that doesn't necessarily make it "right" to use it everywhere. Chances are that your predecessor was using it to break encapsulation, and that can be cumbersome to refactor out. You may be best off leaving it as-is, but understanding which scope is the best tool for the job will definitely make your future code better.


Question: In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?

Answer:
From Wikipedia:
Model-view-controller
(MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.
Thus, model - it holds the application and the business rules.


Question:
I'm learning objective-C and Cocoa and have come across this statement:

The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.

I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?

Answer:
Let's use C++, since my Objective C is totally non-existent.
If you stash a string into a constant variable:
```
```
const std::string mystring = "my string";
```
```
Now when you call methods, you use my_string, you're using a string constant:
```
```
someMethod(mystring);
```
```
Or, you can call those methods with the string literal directly:
```
```
someMethod("my string");
```
```
The reason, presumably, that they encourage you to use string constants is because Objective C doesn't do "interning"; that is, when you use the same string literal in several places, it's actually a different pointer pointing to a separate copy of the string.
For dictionary keys, this makes a huge difference, because if I can see the two pointers are pointing to the same thing, that's much cheaper than having to do a whole string comparison to make sure the strings have equal value.
Edit:
Mike, in C# strings are immutable, and literal strings with identical values all end pointing at the same string value. I imagine that's true for other languages as well that have immutable strings. In Ruby, which has mutable strings, they offer a new data-type: symbols ("foo" vs. :foo, where the former is a mutable string, and the latter is an immutable identifier often used for Hash keys).


Question:
I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods.

What's does the @ symbol mean in objective-c?

Answer:
From
Objective-C Tutorial: The @ Symbol
, the reason it is on the front of various keywords:
Using @ should make it easier to bolt an Objective-C compiler on to an existing C compiler. Because the @ isn't valid in any context in C except a string literal, the tokenizer (an early and simple step in the compiler) could be modified to simply look for the @ character outside of a string constant (the tokenizer understands string literals, so it is in a position to distinguish this). When @ is encountered the tokenizer would put the rest of the compiler in "Objective-C mode." (The Objective-C parser would be responsible for returning the compiler back to regular C mode when it detects the end of the Objective-C code).
Also when seen in front of a string literal, it makes an NSString rather than a 'char *' in C.


Question:
In a drop down list, I need to add spaces in front of the options in the list. I am trying

<select>
<option>&#32;&#32;Sample</option>
</select>

for adding two spaces but it displays no spaces. How can I add spaces before option texts?

Answer:
```
```

```
```
Can you try that? Or is it the same?


Question:
I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential.

Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...

Answer:
If your hardcoded values are just simple key-value pairs, you should look at
java.util.Properties
.  It's a lot simpler than xml, easier to use, and mind-numbingly trivial to implement.
If you are working with Java and the data you are storing or retrieving from disk is modeled as a key value pair (which it sounds like it is in your case), then I really can't imagine a better solution.
I have used properties files for simple configuration of small packages in a bigger project, and as a more global configuration for a whole project, and I have never had problems with it.
Of course this has the huge benefit of not requiring any 3rd party libraries to utilize.


Question:
Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?

To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.

And just to be clear, there's only one file present, it should never be deleted.

Answer:
Remove all but 5 (or whatever number) of the most recent files in a directory.
```
```
rm `ls -t | awk 'NR>5'`
```
```


Question:
Without local access to the server, is there any way to duplicate/clone a MySQL db (with content and without content) into another without using mysqldump?

I am currently using MySQL 4.0.

Answer:
You can duplicate a table without data by running:
```
```
CREATE TABLE x LIKE y;
```
```
(See the
MySQL CREATE TABLE
Docs)
You could write a script that takes the output from
```
SHOW TABLES
```
from one database and copies the schema to another. You should be able to reference schema+table names like:
```
```
CREATE TABLE x LIKE other_db.y;
```
```
As far as the data goes, you can also do it in MySQL, but it's not necessarily fast. After you've created the references, you can run the following to copy the data:
```
```
INSERT INTO x SELECT * FROM other_db.y;
```
```
If you're using MyISAM, you're better off to copy the table files; it'll be much faster. You should be able to do the same if you're using INNODB with
per table table spaces
.
If you do end up doing an
```
INSERT INTO SELECT
```
, be sure to temporarily
turn off indexes
with
```
ALTER TABLE x DISABLE KEYS
```
!
EDIT
Maatkit
also has some scripts that may be helpful for syncing data. It may not be faster, but you could probably run their syncing scripts on live data without much locking.


Question:
If I have Python code

class A():
    pass
class B():
    pass
class C(A, B):
    pass

and I have class C, is there a way to iterate through it's super classed (A and B)? Something like pseudocode:

>>> magicGetSuperClasses(C)
(<type 'A'>, <type 'B'>)

One solution seems to be inspect module and getclasstree function.

def magicGetSuperClasses(cls):
    return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type]

but is this a "Pythonian" way to achieve the goal?

Answer:
```
C.__bases__
```
is an array of the super classes, so you could implement your hypothetical function like so:
```
```
def magicGetSuperClasses(cls):
  return cls.__bases__
```
```
But I imagine it would be easier to just reference
```
cls.__bases__
```
directly in most cases.


Question:
I have seen Solutions created in Visual Studio 2008 cannot be opened in Visual Studio 2005 and tried workaround 1. Yet to try the workaround 2.

But as that link was bit old and out of desperation asking here: Is there any convertor available?

I dont have VS2008 yet and i wanted to open an opensource solution which was done in vs2008.

Guess i have to fiddle around or wait till the vs2008 is shipped.

Answer:
I'd say you should restore your 2005 version from source control, assuming you have source control and a 2005 copy of the file.
Otherwise, there are plenty of pages on the net that details the changes, but unfortunately no ready-made converter program that will do it for you.
Be aware that as soon as you open the file in 2008 again, it'll be upgraded once more.
Perhaps the solution (no pun intended) is to keep separate copy of the project and solution files for 2005 and 2008?
Why do you want to open it in 2005 anyway?


Question: How do you get the maximum number of bytes that can be passed to a sendto(..) call for a socket opened as a UDP port?

Answer:
As UDP is not connection oriented there's no way to indicate that two packets belong together. As a result you're limited by the maximum size of a single IP packet (65535). The data you can send is somewhat less that that, because the IP packet size also includes the IP header (usually 20 bytes) and the UDP header (8 bytes).
Note that this IP packet can be fragmented to fit in smaller packets (eg. ~1500 bytes for ethernet).
I'm not aware of any OS restricting this further.
Bonus
```
SO_MAX_MSG_SIZE
```
of UDP packet
IPv4: 65,507 bytes
IPv6: 65,527 bytes


Question:
I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: http://diymacserver.com/installing-apache/compiling-apache-on-leopard/ But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.

Any help is appreciated

Cheers

Answer:
Add this to your ~/.bash_profile which means that your architecture is 64-bit ant you’d like to compile Universal binaries.
```
```
export CFLAGS="-arch x86_64"
```
```


Question:
My good friend, Wikipedia, didn't give me a very good response to that question. So:

What are language bindings?

How do they work?

Specifically accessing functions from code written in language X of a library written in language Y.

Answer:
In Flex (Actionscript 3).
Source
A data binding copies the value of a property in one object to a property in another object. You can bind the properties of following objects: Flex components, Flex data models, and Flex data services.
The object property that provides the data is known as the source property. The object property that receives the data is known as the destination property.
The following example binds the text property of a TextInput component (the source property) to the text property of a Label component (the destination property) so that text entered in the TextInput component is displayed by the Label component:
```
```
<mx:TextInput id="LNameInput"></mx:TextInput>
...
<mx:Label text="{LNameInput.text}"></mx:Label>
```
```
Data binding is usually a simple way to bind a model to user interface components. For example, you have a class with a FirstName property. In flex you could easily bind that property to a textbox by setting the value of the textbox to {Object.FirstName}. Then, every time that FirstName property changes, the textbox will be updated without requiring you to write any code to monitor that property for changes.
Hope that helps.
Matt


Question:
We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:

error initializing safe control - Assembly: ...

The assembly actually loads fine. Additionally, it is correctly listed in the web.config and GAC.

Any ideas about how to stop these (Phantom?) errors would be appreciated.

Answer:
You need to add a safecontrol entry to the web,config file, have a look at the following:
```
```
<SafeControls>
  <SafeControl
    Assembly = "Text"
    Namespace = "Text"
    Safe = "TRUE" | "FALSE"
    TypeName = "Text"/>
  ...
</SafeControls>
```
```
http://msdn.microsoft.com/en-us/library/ms413697.aspx


Question:
Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name.

Are there any good modern day equivalents?

Answer:
I used to have a lot of fun coding my own robot with
Robocode
in college.
It is Java based, the API is detailled and it's pretty easy to get a challenging robot up and running.
Here is an example :
```
```
public class MyFirstRobot extends Robot {
     public void run() {
         while (true) {
             ahead(100);
             turnGunRight(360);
             back(100);
             turnGunRight(360);
         }
     }

     public void onScannedRobot(ScannedRobotEvent e) {
         fire(1);
     }
 }
```
```


Question:
I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).

Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?

Answer:
Try:
```
```
INSERT INTO table1 ( column1 )
SELECT  col1
FROM    table2
```
```
This is standard ANSI SQL and should work on any DBMS
It definitely works for:
Oracle
MS SQL Server
MySQL
Postgres
SQLite v3
Teradata
DB2
Sybase
Vertica
HSQLDB
H2
AWS RedShift
SAP HANA
Google Spanner


Question:
Is there an easy way to iterate over an associative array of this structure in PHP:

The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two).

Thoughts on doing this in a way that's nice, neat, and understandable?

Answer:
You should be able to use a nested foreach statment
from the
php manual
```
```
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}
```
```


Question: I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?

Answer:
There is a list of Sqlite wrappers for .Net at
http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers
. From what I've heard
http://sqlite.phxsoftware.com/
is quite good. This particular one lets you access Sqlite through ADO.Net just like any other database.


Question:
I'm starting to develop a browser-based game (and by this I mean text-based, no Flash or similar stuff on it) and I'm struggling to decide on which development framework to use.

As far as requirements are concerned, the most important thing that I can think of right now is the ability to translate it to several languages. A good object-relational mapping and a way to generate forms from logical objects would also be very good, as I've noticed that I always spend lots of time solving the problems that come up when I change any of those things.

The programming language is kind of unimportant. I have some experience in PHP and C#, but I don't mind, and I would even like to use this as an excuse, learning some new thing like Python or Ruby. What I do want is something with a good and thriving community and lots of samples and tutorials online to help me.

Answer:
I would reccomend sticking to what you know - PHP is more than capable.
I used to play a game called
Hyperiums
- a text based browser game like yours - which is created using Java (it's web-based quivalent is JSP?) and servlets. It works fairly well (it has had downtime issues but those were more related to it's running on a pretty crap server).
As for which framework to use - why not create your own? Spend a good amount of time pre-coding deciding how you're going to handle various things - such as langauge support: you could use a phrase system or seperate langauge-specific templates. Third party frameworks are probably better tested than one you make but they're not created for a specific purpose, they're created for a wide range of purposes.


Question:
I have an Access database in which I drop the table and then create the table afresh.  However, I need to be able to test for the table in case the table gets dropped but not created (i.e. when someone stops the DTS package just after it starts -roll-eyes- ).  If I were doing this in the SQL database I would just do:

IF (EXISTS (SELECT * FROM sysobjects WHERE name = 'Table-Name-to-look-for'))
BEGIN
drop table 'Table-Name-to-look-for'
END

But how do I do that for an Access database?

Optional answer: is there a way to have the DTS package ignore the error and just go to the next step rather than checking to see if it exists?

SQL Server 2000

Answer:
I would reccomend sticking to what you know - PHP is more than capable.
I used to play a game called
Hyperiums
- a text based browser game like yours - which is created using Java (it's web-based quivalent is JSP?) and servlets. It works fairly well (it has had downtime issues but those were more related to it's running on a pretty crap server).
As for which framework to use - why not create your own? Spend a good amount of time pre-coding deciding how you're going to handle various things - such as langauge support: you could use a phrase system or seperate langauge-specific templates. Third party frameworks are probably better tested than one you make but they're not created for a specific purpose, they're created for a wide range of purposes.


Question:
What strategies have you used with Model Based Testing?

Do you use it exclusively for
integration testing, or branch it
out to other areas
(unit/functional/system/spec verification)?

Do you build focused "sealed" models  or do you evolve complex onibus models over time?

When in the product cycle do you invest in creating MBTs?

What sort of base test libraries do you exclusively create for  MBTs?

What difference do you make in your functional base test libraries to better support MBTs?

Answer:
We haven't done any/much I&T and use unit testing almost exclusively, seasoned with a bit of system testing. But our focus is clearly on unit testing. I'm pretty strict on the APIs we build/provide, so the assumption is, if it works by itself, it will work in conjunction and there hasn't been much wrong in it yet.
Our models are focused on a single purpose/module with as little dependencies as possible.
The focus is always to start as early as possible (TDD-kinda), but unfortunately we don't always get to it. The problem is, you always have to sell it to management and then it's hard because while testing improves stability (overall QA), the people from the outside (outside of tech) can't really relate to what that means until something bad happened.
Since we use PHP, we employ PHPUnit for the unit tests. All in all, we do CI with various different tools. :)


Question:
I have a couple of questions regarding VBScript and ASP Classic:

What is the preferred way to access an MS SQL Server database in VBScript/ASP?

What are best practices in regards to separating model from view from controller?

Any other things I should know about either VBScript or ASP?

If you haven't noticed, I'm new at VBScript coding.  I realize numbers 2 & 3 are kind of giant "black hole" questions that are overly general, so don't think that I'm expecting to learn everything there is to know about those two questions from here.

Answer:
ADO is an excellent way to access a database in VBScript/Classic ASP.
```
```
Dim db: Set db = Server.CreateObject("ADODB.Connection")
db.Open "yourconnectionstring -> see connectionstrings.com"
Dim rs: Set rs = db.Execute("SELECT firstName from Employees")
While Not rs.EOF
    Response.Write rs("firstName")
    rs.MoveNext
Wend
rs.Close
```
```
More info here:
http://www.technowledgebase.com/2007/06/12/vbscript-how-to-create-an-ado-connection-and-run-a-query/
One caveat is that if you are returning a MEMO field in a recordset, be sure you only select ONE MEMO field at a time, and make sure it is the LAST column in your query.  Otherwise you will run into problems.
(Reference:
http://lists.evolt.org/archive/Week-of-Mon-20040329/157305.html
)


Question:
C++ 0x has template aliases (sometimes referred to as template typedefs). See here. Current spec of C++ does not.

What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ?

Answer:
What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?
The canonical way is to use a metafunction like thus:
```
```
template <typename T>
struct my_string_map {
    typedef std::map<std::string, T> type;
};

// Invoke:

my_string_map<int>::type my_str_int_map;
```
```
This is also used in the STL (
```
allocator::rebind<U>
```
) and in many libraries including Boost. We use it extensively in a
bioinformatical library
.
It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.
(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)


Question:
I've always wanted to be able to get a reasonably elegant way of getting vimdiff to work with a CVS controlled file. I've found numerous (somewhat hacky) scripts around the internet (best example here) that basically check out the file you are editing from CVS to a temp file, and vimdiff the two. None of these take into account branches, and always assume you're working from MAIN, which for me is completely useless.

So, my question is this: has anyone out there found a decent solution for this that does more than this script?

Or failing that, does anyone have any ideas of how they would implement this, or suggestions for what features you would consider vital for something that does this? My intention is that, if no one can suggest an already built solution to either use or build from, we start building one from here.

Answer:
You could change the call to
```
cvs
```
to take branches into account. That shouldn't be to hard. It bit harder would to change the whole function and make the branch your working a variable (argument, session, global or otherwise).


Question:
I am looking for a very fast way to filter down a collection in C#.  I am currently using generic List<object> collections, but am open to using other structures if they perform better.

Currently, I am just creating a new List<object> and looping thru the original list.  If the filtering criteria matches, I put a copy into the new list.

Is there a better way to do this?  Is there a way to filter in place so there is no temporary list required?

Answer:
If you're using C# 3.0 you can use linq, which is way better and way more elegant:
```
```
List<int> myList = GetListOfIntsFromSomewhere();

// This will filter ints that are not > 7 out of the list; Where returns an
// IEnumerable<T>, so call ToList to convert back to a List<T>.
List<int> filteredList = myList.Where(x => x > 7).ToList();
```
```
If you can't find the
```
.Where
```
, that means you need to import
```
using System.Linq;
```
at the top of your file.


Question:
Do you know if I can use Visio to forward-engineer a sequence diagram into code (c#)?

Can it be done with Visio alone or do I need a plugin?

What about other diagrams?

Answer:
To the best of my knowledge, Visio can only forward-engineer code from class models.
As sequence diagrams only really show paths of communication between objects, I suspect that they do not contain the necessary information, except perhaps in trivial cases, for generating code.
Objects with any sort of complex behaviour patterns are likely to involve changing run-time states, of which sequence diagrams aren't really capable of capturing.


Question: Over the last few months/years, I have shared a folder or two with numerous people on my domain. How do I easily revoke those shares to keep access to my system nice and tidy?

Answer:
On Windows XP, go to:
```
```
Administrative Tools > Computer Management > System Tools > Shared Folders > Shares
```
```
This page lists all shares and lets you remove them easily, in one place.


Question: Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.

Answer:
System.Net.WebClient
From MSDN:
```
```
using System;
using System.Net;
using System.IO;

public class Test
{
    public static void Main (string[] args)
    {
        if (args == null || args.Length == 0)
        {
            throw new ApplicationException ("Specify the URI of the resource to retrieve.");
        }
        WebClient client = new WebClient ();

        // Add a user agent header in case the
        // requested URI contains a query.

        client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

        Stream data = client.OpenRead (args[0]);
        StreamReader reader = new StreamReader (data);
        string s = reader.ReadToEnd ();
        Console.WriteLine (s);
        data.Close ();
        reader.Close ();
    }
}
```
```


Question: What JavaScript keywords (function names, variables, etc) are reserved?

Answer:
We should be linking to the actual sources of info, rather than just the top google hit.
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Reserved_Words
JScript 8.0:
http://msdn.microsoft.com/en-us/library/ttyab5c8.aspx


Question: I want to be able to play sound files in my program. Where should I look?

Answer:
A bad example:
```
```
import  sun.audio.*;    //import the sun.audio package
import  java.io.*;

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);

// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);

// Similarly, to stop the audio.
AudioPlayer.player.stop(as);
```
```


Question:
C#: What is a good Regex to parse hyperlinks and their description?

Please consider case insensitivity, white-space and use of single quotes (instead of double quotes) around the HREF tag.

Please also consider obtaining hyperlinks which have other tags within the <a> tags such as <b> and <i>.

Answer:
I found this
but apparently
these guys
had some problems with it.
Edit:
(It works!)
I have now done my own testing and found that it works, I don't know C# so I can't give you a C# answer but I do know PHP and here's the matches array I got back from running it on this:
```
```
Text

array(3) { [0]=> string(52) "Text" [1]=> string(15) "pages/index.php" [2]=> string(4) "Text" }
```
```


Question:
I've found an article on this subject by a Microsoft employee, but has anyone implemented a more robust framework for this? Is there a lightweight framework for WinForms that could be ported easily? I'd like to get up to speed fairly quickly and avoid producing a framework/library of my own to handle this when someone smarter has already done this.

I haven't looked at the Mobile Software Factory from the P&P group, but I suspect it's kind of heavy. Is it worth a look?

Edit: I'm not looking for information on the ASP.NET MVC project. I'm asking about the compact framework 'WinForms' implementation, and how to implement MVC with that.

Answer:
Edit: The above posters are correct.  I saw MVC and immediately thought of web forms.  My apologies.  Feel free to disregard this.  I'll leave my original message in place just in case anyone who
is
interested in web forms MVC needs the links. :-)
There are a couple MVC frameworks out there, neither of which are very "lightweight", but MVC is a pretty big shift away from web forms so that is expected:
ASP.NET MVC
- This is Microsoft's attempt at an MVC framework.  It is still in preview mode so use it at your own discretion, but several people are already using it in their production applications.  You will find ample documentation on this with a simple Google search as it is becoming very popular amongst the .NET crowd.
Castle MonoRail
- The MonoRail framework is an open-source MVC framework that has been around for quite some time and is in use on several production applications.  It is definitely more flushed out than the ASP.NET MVC framework, but considering the amount of effort Microsoft is throwing at their MVC offering, I think will change relatively soon.


Question: Do you know where I could find some useful third party (free) code snippets for VS 2008?

Answer:
http://gotcodesnippets.com/
http://www.codekeep.net/
has a VS add-in for their snippets, too


Question:
Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?

Doing session.contains(obj) seems to only return true if the session contains that exact object, not another object with the same ID.

Using merge(obj) throws an exception if the object is new

Answer:
Have you tried calling .SaveOrUpdateCopy()?
It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).
Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object.
This should be easy enough to do:
```
```
IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);
```
```
Although the above code could probably do with some null checking for the .Get() call.


Question:
Do you use Design by Contract professionally? Is it something you have to do from the beginning of a project, or can you change gears and start to incorporate it into your software development lifecycle? What have you found to be the pros/cons of the design approach?

I came across the Design by Contract approach in a grad school course. In the academic setting, it seemed to be a pretty useful technique. But I don't currently use Design by Contract professionally, and I don't know any other developers that are using it. It would be good to hear about its actual usage from the SO crowd.

Answer:
I can't recommend it highly enough.  It's particularly nice if you have a suite that takes inline documentation contract specifications, like so:
```
```
// @returns null iff x = 0
public foo(int x) {
  ...
}
```
```
and turns them into generated unit tests, like so:
```
```
public test_foo_returns_null_iff_x_equals_0() {
  assertNull foo(0);
}
```
```
That way, you can actually see the tests you're running, but they're auto-generated.  Generated tests shouldn't be checked into source control, by the way.


Question:
I have a ComboBox that I bind to a standard HTTPService, I would like to add an event listener so that I can run some code after the ComboBox is populated from the data provider.

How can I do this?

Answer:
You can use
```
BindingUtils
```
to get notified when the
```
dataProvider
```
property of the combo box changes:
```
```
BindingUtils.bindSetter(comboBoxDataProviderChanged, comboBox, "dataProvider");
```
```
```
BindingUtils
```
lives in the
```
mx.binding.utils
```
package.
I have a longer description of how to work with
```
BindingUtils
```
here:
Does painless programmatic data binding exist?


Question:
I have a habit of keeping my variable usage to a bare minimum.  So I'm wondering if there is any advantage to be gained by the following:

$query = $mysqli->query('SELECT * FROM `people` ORDER BY `name` ASC LIMIT 0,30');

// Example 1
$query = $query->fetch_assoc();

// Example 2
$query_r = $query->fetch_assoc();
$query->free();

Now if I'm right Example 1 should be more efficient as $query is unset when I reassign it  which should free any memory associated with it. However there is a method (MySQLi_Result::free()) which frees associated memory - is this the same thing?

If I don't call ::free() to free any memory associated with the result but unset it by reassigning the variable am I doing the same thing? I don't know how to log this sort of thing - does anyone have some ideas?

Answer:
The
manual
seems to suggest that you should still be using
```
free()
```
to release the memory. I believe the reasoning is that
```
free()
```
is freeing the memory in
MySQL
, not in PHP. Since PHP can't garbage-collect for MySQL, you need to call
```
free()
```
.


Question:
My coworker and I have encountered a nasty situation where we have to use an active X control to manipulate a web camera on a page.

Is it possible to assign a javascript event handler to a button in the active x control so that it would fire an action on the page when clicked, or do we have to create a button on the html page itself that manipulates the Active X Control and then can fire any necessary actions on the page?

Answer:
Yes! You can throw events in C++/ActiveX land which makes the JavaScript code run an event handler function. I was even able to make an entire invisible ActiveX control (same color as page background) with no buttons or visual feedback that did all of its GUI work through JavaScript and CSS.
edit: Frank's advice is right on.
Here's the link on scripting events.
My strategy was to call a C++ function called MyUpdate (which implements IConnectionPoint) when I wanted to force updates in the browser.
(Also, I made sure to pump Windows messages in the Fire_MyUpdate method because sometimes JavaScript code would call back into C++ land by calling methods on the ActiveX control; this avoids freezing up the browser and ensures that the JavaScript GUI stays responsive, e.g. for a Cancel button.)
On the browser side, the JavaScript code has the global variable referencing the object, followed by "::", followed by the method name:
```
```
function Uploader::MyUpdate()
{
    // ... code to fetch the current state of various
    // properties from the Uploader object and do something with it
    // for example check Uploader.IsActive and show or hide an HTML div
}
```
```


Question:
Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?

Basic detection can be done with the URL itself, such as “http://myblog.blogger.com” etc. But what if it's self hosted?

I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.

Answer:
Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this.
You'll have to be careful how you detect it though, Google surprised me with this line:
```
```
<meta content='blogger' name='generator'/>
```
```
Single quotes are blasphemy.


Question:
I need to pass an ID and a password to a batch file at the time of running rather than hardcoding them into the file.

Here's what the command line looks like:

test.cmd admin P@55w0rd > test-log.txt

Answer:
Yep, and just don't forget to use variables like
```
%%1
```
when using
```
if
```
and
```
for
```
and the gang.
If you forget the double
```
%
```
, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.


Question: What are the advantages and disadvantages of turning NOCOUNT off in SQL server queries?

Answer:
From SQL BOL:
SET NOCOUNT ON prevents the sending of
  DONE_IN_PROC messages to the client
  for each statement in a stored
  procedure. For stored procedures that
  contain several statements that do not
  return much actual data,
setting SET
  NOCOUNT to ON can provide a
  significant performance boost
, because
  network traffic is greatly reduced.
See
http://msdn.microsoft.com/en-us/library/ms189837.aspx
for more details.
Also, this article on SQLServerCentral is great on this subject:
Performance Effects of NOCOUNT


Question: I know there are a lot of positive things mod-rewrite accomplishes. But are there any negative? Obviously if you have poorly written rules your going to have problems.  But what if you have a high volume site and your constantly using mod-rewrite, is it going to have a significant impact on performance? I did a quick search for some benchmarks on Google and didn't find much.

Answer:
I've used mod_rewrite on sites that get millions/hits/month without any significant performance issues. You do have to know which rewrites get applied first depending on your rules.
Using mod_rewrite is most likely faster than parsing the URL with your current language.
If you are really worried about performance, don't use
```
.htaccess
```
files, those are slow. Put all your rewrite rules in your Apache config, which is only read once on startup.
```
.htaccess
```
files get re-parsed on every request, along with
every
```
.htaccess
```
file in parent folders.


Question: What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?

Answer:
I haven't tried this in a while, but a quick google search shows some possibilities:
Java Sketchbook: The HTML Renderer Shootout, Part 1
Cobra: Java HTML Renderer & Parser
Are you trying to do this in an applet, or an application?  If it's an application (or signed applet) you could potentially instantiate IE or Firefox within your application.
Webrenderer
acts as a Swing wrapper for this.


Question:
Is there any difference between:

if foo is None: pass

and

if foo == None: pass

The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter.  None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right?  Are there any circumstances in which it might?

Answer:
```
is
```
always returns
```
True
```
if it compares the same object instance
Whereas
```
==
```
is ultimately determined by the
```
__eq__()
```
method
i.e.
```
```
>>> class Foo(object):
       def __eq__(self, other):
           return True

>>> f = Foo()
>>> f == None
True
>>> f is None
False
```
```


Question:
In my web app, I submit some form fields with jQuery's $.getJSON() method. I am having some problems with the encoding. The character-set of my app is charset=ISO-8859-1, but I think these fields are submitted with UTF-8.

How I can set encoding used in $.getJSON calls?

Answer:
I think that you'll probably have to use
```
$.ajax()
```
if you want to change the encoding, see the
```
contentType
```
param below (the
```
success
```
and
```
error
```
callbacks assume you have
```
<div id="success"></div>
```
and
```
<div id="error"></div>
```
in the html):
```
```
$.ajax({
    type: "POST",
    url: "SomePage.aspx/GetSomeObjects",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: "{id: '" + someId + "'}",
    success: function(json) {
        $("#success").html("json.length=" + json.length);
        itemAddCallback(json);
    },
    error: function (xhr, textStatus, errorThrown) {
        $("#error").html(xhr.responseText);
    }
});
```
```
I actually just had to do this about an hour ago, what a coincidence!


Question: Is there a way to make a TSQL variable constant?

Answer:
There are no such thing as "creating a constant" in database literature. Constants exist as they are and often called values. One can declare a variable and assign a value (constant) to it. From a scholastic view:
```
```
DECLARE @two INT
SET @two = 2
```
```
Here @two is a variable and 2 is a value/constant.


Question:
I found What are mvp and mvc and what is the difference but it didn't really answer this question.

I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on?

Pros

Display and Processing are seperated

Cons

None so far

Answer:
MVC is the separation of
m
odel,
v
iew and
c
ontroller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.
For example, while a table grid
view
should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the
model
) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the
controller
.
A 'save file' dialog (
view
) ultimately passes the path, once picked by the user, on to the
controller
, which then asks the
model
for the data, and does the actual saving.
This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.


Question:
How does the new Microsoft asp.net mvc implementation handle partitioning your application - for example:

--index.aspx
--about.aspx
--contact.aspx
--/feature1
--/feature1/subfeature/action
--/feature2/subfeature/action

I guess what I am trying to say is that it seems everything has to go into the root of the views/controllers folders which could get unwieldy when working on a project that if built with web forms might have lots and lots of folders and sub-folders to partition the application.

I think I get the MVC model and I like the look of it compared to web forms but still getting my head round how you would build a large project in practice.

Answer:
There isn't any issues with organizing your controllers.  You just need to setup the routes to take the organization into consideration.  The problem you will run into is finding the view for the controller, since you changed the convention.  There isn't any built in functionality for it yet, but it is easy to create a work around yourself with a ActionFilterAttribute and a custom view locator that inherits off ViewLocator.  Then when creating your controller, you just specify what ViewLocator to use, so the controller knows how to find the view.  I can post some code if needed.
This method kind of goes along with some advice I gave another person for separating their views out for a portal using ASP.NET MVC.  Here is the
link to the question
as a reference.


Question:
When creating scrollable user controls with .NET and WinForms I have repeatedly encountered situations where, for example, a vertical scrollbar pops up, overlapping the control's content, causing a horizontal scrollbar to also be needed.  Ideally the content would shrink just a bit to make room for the vertical scrollbar.

My current solution has been to just keep my controls out of the far right 40 pixels or so that the vertical scroll-bar will be taking up.  Since this is still effectively client space for the control, the horizontal scroll-bar still comes up when it gets covered by the vertical scroll-bar, even though no controls are being hidden at all.  But then at least the user doesn't actually need to use the horizontal scrollbar that comes up.

Is there a better way to make this all work?  Some way to keep the unneeded and unwanted scrollbars from showing up at all?

Answer:
If your controls are inside a panel, try setting the AutoScroll property of the Panel to False.  This will hide the scrollbars.  I hope this points you in the right direction.
```
```
myPanel.AutoScroll = False
```
```


Question:
<servlet>
    <servlet-name>myservlet</servlet-name>
    <servlet-class>workflow.WDispatcher</servlet-class>
    <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>myservlet</servlet-name>
    <url-pattern>*NEXTEVENT*</url-pattern>
</servlet-mapping>

Above is the snippet from Tomcat's web.xml. The URL pattern *NEXTEVENT* on start up throws

java.lang.IllegalArgumentException: Invalid <url-pattern> in servlet mapping

It will be greatly appreciated if someone can hint at the error.

Answer:
```
```
<url-pattern>*NEXTEVENT*</url-pattern>
```
```
The URL pattern is not valid. It can either end in an asterisk or start with one (to denote a file extension mapping).
The url-pattern specification:
A string beginning with a ‘/’ character and ending with a ‘/*’
  suffix is used for path mapping.
A string beginning with a ‘*.’ prefix is used as an extension
  mapping.
A string containing only the ’/’ character indicates the "default"
  servlet of the application. In this
  case the servlet path is the request
  URI minus the context path and the
  path info is null.
All other strings are used for exact matches only.
See section 12.2 of the
Java Servlet Specification
Version 3.1 for more details.


Question:
Using reflection, how can I get all types that implement an interface with C# 3.0/.NET 3.5 with the least code, and minimizing iterations?

This is what I want to re-write:

foreach (Type t in this.GetType().Assembly.GetTypes())
    if (t is IMyInterface)
        ; //do stuff

Answer:
loop through all loaded assemblies, loop through all their types, and check if they implement the interface.
something like:
```
```
Type ti = typeof(IYourInterface);
foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) {
    foreach (Type t in asm.GetTypes()) {
        if (ti.IsAssignableFrom(t)) {
            // here's your type in t
        }
    }
}
```
```


Question: I have some strings of xxh:yym format where xx is hours and yy is minutes like "05h:30m". What is an elegant way to convert a string of this type to TimeSpan?

Answer:
This seems to work, though it is a bit hackish:
```
```
TimeSpan span;

if (TimeSpan.TryParse("05h:30m".Replace("m","").Replace("h",""), out span))
            MessageBox.Show(span.ToString());
```
```


Question: How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible?

Answer:
All important files are in version control (Subversion)
My subversion layout generally matches the file layout on my web server so I can just do a checkout and all of my library files and things are in the correct places.
Twice-daily backups to an external hard drive
Nightly rsync backups to a remote server.
This means that I send stuff on my home server over to my webhost and all files & databases on my webhost back home so I'm not screwed if I lose either my house or my webhost.


Question:
I'm using XPath in .NET to parse an XML document, along the lines of:

XmlNodeList lotsOStuff = doc.SelectNodes("//stuff");

foreach (XmlNode stuff in lotsOStuff) {
   XmlNode stuffChild = stuff.SelectSingleNode("//stuffChild");
   // ... etc
}

The issue is that the XPath Query for stuffChild is always returning the child of the first stuff element, never the rest. Can XPath not be used to query against an individual XMLElement?

Answer:
```
//
```
at the beginning of an XPath expression starts from the document root.  Try ".//stuffChild".  . is shorthand for self::node(), which will set the context for the search, and // is shorthand for the descendant axis.
So you have:
```
```
XmlNode stuffChild = stuff.SelectSingleNode(".//stuffChild");
```
```
which translates to:
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant-or-self::stuffChild");
```
```
In the case where the child node could have the same name as the parent, you would want to use the slightly more verbose syntax that follows, to ensure that you don't re-select the parent:
```
```
xmlNode stuffChild = stuff.SelectSingleNode("self::node()/descendant::stuffChild");
```
```
Also note that if "stuffChild" is a direct descendant of "stuff", you can completely omit the prefixes, and just select "stuffChild".
```
```
XmlNode stuffChild = stuff.SelectSingleNode("stuffChild");
```
```
The
W3Schools
tutorial has helpful info in an easy to digest format.


Question:
I frequently have problems dealing with DataRows returned from SqlDataAdapters. When I try to fill in an object using code like this:

DataRow row = ds.Tables[0].Rows[0];
string value = (string)row;

What is the best way to deal with DBNull's in this type of situation.

Answer:
Nullable types are good, but only for types that are not nullable to begin with.
To make a type "nullable" append a question mark to the type, for example:
```
```
int? value = 5;
```
```
I would also recommend using the "
```
as
```
" keyword instead of casting. You can only use the "as" keyword on nullable types, so make sure you're casting things that are already nullable (like strings) or you use nullable types as mentioned above. The reasoning for this is
If a type is nullable, the "
```
as
```
" keyword returns
```
null
```
if a value is
```
DBNull
```
.
It's
ever-so-slightly faster than casting
though
only in certain cases
. This on its own is never a good enough reason to use
```
as
```
, but coupled with the reason above it's useful.
I'd recommend doing something like this
```
```
DataRow row = ds.Tables[0].Rows[0];
string value = row as string;
```
```
In the case above, if
```
row
```
comes back as
```
DBNull
```
, then
```
value
```
will become
```
null
```
instead of throwing an exception. Be aware that if your DB query changes the columns/types being returned,
using
```
as
```
will cause your code to silently fail
and make values simple
```
null
```
instead of throwing the appropriate exception when incorrect data is returned so it is recommended that you have tests in place to validate your queries in other ways to ensure data integrity as your codebase evolves.


Question: I'm currently using the module URI::URL to generate a full URL from a relative URL; however, it isn't running as fast as I'd like it to be. Does anyone know another way to do this that may be faster?

Answer:
Perhaps I got the wrong end of the stick but wouldn't,
```
```
$full_url = $base_url . $relative_url
```
```
work? IIRC Perl text processing is pretty quick.
@lennysan
Ah sure yes of course. Sorry I can't help, my Perl is pretty rusty.


Question:
Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?

Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a link/button on my site's page that will fill in those values and submit the info without having to copy/paste them across and click the submit button.

Further clarification: How do automated spam bots fill out forms and click the submit button if they were written in C#?

Answer:
The code will look something like this:
```
```
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";

byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.Length;

Stream sout = req.GetRequestStream();
sout.Write(send, 0, send.Length);
sout.Flush();
sout.Close();

WebResponse res = req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream());
string returnvalue = sr.ReadToEnd();
```
```


Question:
In C#, what is the difference (if any) between these two lines of code?

tmrMain.Elapsed += new ElapsedEventHandler(tmrMain_Tick);

and

tmrMain.Elapsed += tmrMain_Tick;

Both appear to work exactly the same. Does C# just assume you mean the former when you type the latter?

Answer:
I did this
```
```
static void Hook1()
{
    someEvent += new EventHandler( Program_someEvent );
}

static void Hook2()
{
    someEvent += Program_someEvent;
}
```
```
And then ran ildasm over the code.
The generated MSIL was exactly the same.
So to answer your question, yes they are the same thing.
The compiler is just inferring that you want
```
someEvent += new EventHandler( Program_someEvent );
```
-- You can see it creating the new
```
EventHandler
```
object in both cases in the MSIL


Question: As someone who hasn't used either technology on real-world projects I wonder if anyone knows how these two complement each other and how much their functionalities overlap?

Answer:
Can you clarify what you mean by "LINQ"?
LINQ isn't an data access technology, it's just a language feature which supports querying as a native construct. It can query any object model which supports specific interfaces (e.g. IQueryable).
Many people refer to LINQ To SQL as LINQ, but that's not at all correct. Microsoft has just released LINQ To Entities with .NET 3.5 SP1. Additionally, NHibernate has a LINQ interface, so you could use LINQ and NHibernate to get at your data.


Question:
I have been in both situations:

Creating too many custom Exceptions

Using too many general Exception class

In both cases the project started OK but soon became an overhead to maintain (and refactor).

So what is the best practice regarding the creation of your own Exception classes?

Answer:
Basically, each job deserves an own exception. When you catch exceptions, you don't distinguish different instances, like you would normally do with objects, therefore you need different subtypes. Using too many custom exceptions is a case which I see hardly occurring.
One advice would be to create exceptions as needed, and if it becomes apparent that one exception type is a duplicate of another, refactor the code by merging the two. Of course it helps if some thought goes into structuring exceptions from the beginning. But generally, use custom exceptions for all cases that have no 1:1 correspondence to existing, situation-specific exceptions.
On the other hand,
```
NullPointerException
```
s and
```
IndexOutofBoundsException
```
s might actually often be appropriate. Don't catch these, though (except for logging) as they're a programming error which means that after throwing them, the program is in an undefined state.


Question: When applying the Single Responsibility Principle and looking at a class's reason to change, how do you determine whether that reason too change is too granular, or not granular enough?

Answer:
Rewrite your code in a passing style!
Seriously, an old code base will have hundreds of errors - but that's why we have novice/intern programmers. Correcting FxCop violations is a great way to get an overview of the code base and also learn how to write conforming .NET code.
So just bite the bullet, drink lots of caffeine, and just get through it in a couple days!


Question:
So you know a lot of Mac apps use "bundles":  It looks like a single file to your application, but it's actually a folder with many files inside.

For a version control system to handle this, it needs to:

check out all the files in a directory, so the app can modify them as necessary

at checkin,

commit files which have been modified

add new files which the application has created

mark as deleted files which are no longer there (since the app deleted them)

manage this as one atomic change

Any ideas on the best way to handle this with existing version control systems?  Are any of the versioning systems more adept in this area?

Answer:
Mercurial in particular versions based on file, not directory structure.  Therefore, your working tree, which is a fully-fledged repository, doesn't spit out .svn folders at each level.
It also means that a directory that is replaced, like an Application or other Bundle, will still find it's contents with particular file names under revision control.  File names are monitored, not inodes or anything fancy like that!
Obviously, if a new file is added to the Bundle, you'll need to explicitly add this to your repository.  Similarly, removing a file from a Bundle should be done with an 'hg rm'.
There aren't any decent Mercurial GUIs for OS X yet, but if all you do is add/commit/merge, it isn't that hard to use a command line.


Question:
Do any of you know of a tool that will search for .class files and then display their compiled versions?

I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).

Answer:
It is easy enough to read the
class file signature
and get these values without a 3rd party API. All you need to do is read the first 8 bytes.
```
```
ClassFile {
    u4 magic;
    u2 minor_version;
    u2 major_version;
```
```
For class file version 51.0 (Java 7), the opening bytes are:
```
```
CA FE BA BE 00 00 00 33
```
```
...where 0xCAFEBABE are the magic bytes, 0x0000 is the minor version and 0x0033 is the major version.
```
```
import java.io.*;

public class Demo {
  public static void main(String[] args) throws IOException {
    ClassLoader loader = Demo.class.getClassLoader();
    try (InputStream in = loader.getResourceAsStream("Demo.class");
        DataInputStream data = new DataInputStream(in)) {
      if (0xCAFEBABE != data.readInt()) {
        throw new IOException("invalid header");
      }
      int minor = data.readUnsignedShort();
      int major = data.readUnsignedShort();
      System.out.println(major + "." + minor);
    }
  }
}
```
```
Walking directories (
File
) and archives (
JarFile
) looking for class files is trivial.
Oracle's
Joe Darcy's blog
lists the
class version to JDK version mappings
up to Java 7:
```
```
Target   Major.minor Hex
1.1      45.3        0x2D
1.2      46.0        0x2E
1.3      47.0        0x2F
1.4      48.0        0x30
5 (1.5)  49.0        0x31
6 (1.6)  50.0        0x32
7 (1.7)  51.0        0x33
8 (1.8)  52.0        0x34
9        53.0        0x35
```
```


Question:
I have an old C library with a function that takes a void**:

oldFunction(void** pStuff);

I'm trying to call this function from managed C++ (m_pStuff is a member of the parent ref class of type void*):

oldFunction( static_cast<sqlite3**>(  &m_pStuff ) );

This gives me the following error from Visual Studio:

error C2440: 'static_cast' : cannot convert from 'cli::interior_ptr' to 'void **'

I'm guessing the compiler is converting the void* member pointer to a cli::interior_ptr behind my back.

Any advice on how to do this?

Answer:
EDIT: Fixed answer, see below.
Really you need to know what oldFunction is going to be doing with pStuff. If pStuff is a pointer to some unmanaged data you can try wrapping the definition  of m_pStuff with:
```
```
#pragma unmanaged

void* m_pStuff

#pragma managed
```
```
This will make the pointer unmanaged which can then be passed into unmanaged functions. Of course you will not be able to assign any managed objects to this pointer directly.
Fundamentally unmanaged and managed pointers are not the same and can't be converted without some sort of glue code that copies the underlying data. Basically managed pointers point to the managed heap and since this is garbage collected the actual memory address they point to can change over time. Unmanaged pointers do not change the memory address without you explicitly doing so.
Scratch that, you can't define unmanaged / managed inside a class definition. But this test code seems to work just fine:
```
```
// TestSol.cpp : main project file.

#include "stdafx.h"

using namespace System;

#pragma unmanaged

void oldFunction(void** pStuff)
{
    return;
}

#pragma managed

ref class Test
{
public:
    void* m_test;

};

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");

    Test^ test = gcnew Test();
    void* pStuff = test->m_test;
    oldFunction(&pStuff);
    test->m_test = pStuff;

    return 0;
}
```
```
Here I copy the pointer out of the managed object first and then pass that in by to the oldFunction. Then I copy the result (probably updated by oldFunction) back into the managed object. Since the managed object is on the managed heap, the compiler won't let you pass a reference to the pointer contained in that object as it may move when the garbage collector runs.


Question: I have a bunch of perfmon files that have captured information over a period of time. Whats the best tool to crunch this information? Idealy I'd like to be able to see avg stats per hour for the object counters that have been monitored.

Answer:
Perhaps look into using
LogParser
.
It depends on how the info was logged (Perfmon doesn't lack flexibility)
If they're CSV you can even use the ODBC Text drivers and run queries against them!
(performance would be 'intriguing')
And here's the obligatory link to a
CodingHorror article
on the topic ;-)


Question: Can anyone recommend a library for chart generation (bar charts, pie charts etc.) which runs on both Java and .Net?

Answer:
Have you looking into using
JFreeChart
.
I have used it on a few Java projects and its very configurable. Its free but I think you can purchase the developers guide for $50. Its good for quick simple charts too. However performance for real-time data is not quite up to par (Check out the
FAQ
).
They also have a port to
.NET
however I have never used it.
Hope that helps.


Question:
I was wondering if I could access the iPhones Core Location framework over a website?

My goal is to build a webapp/website that the iPhone would browse to, then upload its current GPS location. This would be a simple site primary for friends/family so we could locate each other. I can have them manually enter lng/lat but its not the easiest thing to find. If the iPhone could display or upload this automatically it would be great.

I don't own a Mac yet (waiting for the new Mac Book Pro) but would like something a little more automatic right now. Once I have the mac I could download the SDK and build a better version later. For now a webapp version would be great if possible. Thanks.

Answer:
I'm pretty sure you can't do what you want directly.
The best idea I can come up with is to "reuse" an iPhone app that records location and makes it accessible on the web. Take Twitter for example. If I'm not mistaken, Tapulous' app Twinkle will grab your location and post it to your Twitter.com user profile. Here's an example of what that looks like:
From your webapp, you could then scrape the user page for each person whose location you're interested in. It's a pain in the butt, but like I said, this is the best I could come up with.
Again, if you don't want to mess with Twitter, there may be other apps out there that do this as well, but I don't personally know of any. Good luck.


Question: Can fogbugz track case dependencies?

Answer:
Yes and no. Cases can be linked to each other, but if you're looking for a tree of cases (prerequisites and such), you need FogBugz 7 or later.
If you're using FogBugz 7.3 or greater, you can now use the
Case Dependency Plugin
, which was released in April 2011.


Question:
I'm comparing between two techniques to create partitioned tables in SQL 2005.

Use partitioned views with a standard version of SQL 2005 (described here)

Use the built in partition in the Enterprise edition of SQL 2005 (described here)

Given that the enterprise edition is much more expensive, I would like to know what are the main benefits of the newer enterprise built-in implementation. Is it just an time saver for the implementation itself. Or will I gain real performance on large DBs?

I know i can adjust the constraints in the first option to keep a sliding window into the partitions. Can I do it with the built in version?

Answer:
Yes and no. Cases can be linked to each other, but if you're looking for a tree of cases (prerequisites and such), you need FogBugz 7 or later.
If you're using FogBugz 7.3 or greater, you can now use the
Case Dependency Plugin
, which was released in April 2011.


Question:
Given a select with multiple option's in jQuery.

$select = $("<select></select>");
$select.append("<option>Jason</option>") //Key = 1
       .append("<option>John</option>") //Key = 32
       .append("<option>Paul</option>") //Key = 423

How should the key be stored and retrieved?

The ID may be an OK place but would not be guaranteed unique if I had multiple select's sharing values (and other scenarios).

Thanks

and in the spirit of TMTOWTDI.

$option = $("<option></option>");
$select = $("<select></select>");
$select.addOption = function(value,text){
    $(this).append($("<option/>").val(value).text(text));
};

$select.append($option.val(1).text("Jason").clone())
       .append("<option value=32>John</option>")
       .append($("<option/>").val(423).text("Paul"))
       .addOption("321","Lenny");

Answer:
The HTML
```
<option>
```
tag has an attribute called "value", where you can store your key.
e.g.:
```
```
<option value=1>Jason</option>
```
```
I don't know how this will play with jQuery (I don't use it), but I hope this is helpful nonetheless.


Question: I'm looking for a method, or a code snippet for converting std::string to LPCWSTR

Answer:
If you are in an ATL/MFC environment, You can use the ATL conversion macro:
```
```
#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);
```
```
You can then use unicodeStr as an LPCWSTR.  The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.


Question:
What kinds of considerations are there for migrating an application from NHibernate 1.2 to 2.0? What are breaking changes vs. recommended changes?

Are there mapping issues?

Answer:
Breaking changes in NHibernate 2.0
If you have good test coverage it's busywork.
Edit: We upgraded this morning.  There is nothing major.  You have to Flush() the session after you delete.  The Expression namespace got renamed to Criterion.  All these are covered in the link above.  Mappings need no change.  It's quite transparent.  Oh, and transactions
everywhere
, but you were probably doing that already.
By the way, here's an interesting look at the changes:
http://codebetter.com/blogs/patricksmacchia/archive/2008/08/26/nhibernate-2-0-changes-overview.aspx


Question: I know that this should be easy but how do I export/save a DataGridView to excel?

Answer: Does it need to be a native XLS file? Your best bet is probably just to export the data to a CSV file, which is plain text and reasonably easy to generate. CSVs open in Excel by default for most users so they won't know the difference.


Question: I'm running MAMP 1.7.2 on a Mac and I'd like to install the extension php_gd2.  How do I do this?  I know that on Windows using WAMP I'd simply select the php_gd2 entry in the extensions menu to activate it.  How is it done when using MAMP? I know that I can do it using MacPorts but I'd prefer not to make any changes to my default OS X PHP installation.

Answer:
You shouldn't need to install the extension.  I have 1.7.2 installed and running right now and it has GD bundled (2.0.34 compatible).
From the MAMP start page, click on phpinfo and you should see a GD section.


Question:
On an 8-bit micro controller I would like to do the following:

16bit_integer = another_16bit_integer * 0.997;

with the least possible number of instructions.

Answer:
How about integer arithmetic in 32 bits?
```
```
16bit_integer = (int16_t) (another_16bit_integer * (int32_t) 997 / 1000);
```
```
32 bits will be enough to store (INT16_MAX × 997), do the sum on values 1000 times larger then divide back to your 16 bit scale.


Question:
I am working on a web application using Python (Django) and would like to know whether MySQL or PostgreSQL would be more suitable when deploying for production.

In one podcast Joel said that he had some problems with MySQL and the data wasn't consistent.

I would like to know whether someone had any such problems. Also when it comes to performance which can be easily tweaked?

Answer:
Well, I don't think you should be using a different database brand in anything past development (build, staging, prod) as that will come back to bite you.
From how I understand it PostgreSQL is a more 'correct' database implementation while mySQl is less correct (less compliant) but faster.
So if you are pretty much writing a CRUD application mySQL is the way to go. If you require certain features out of your database (if you're not sure then you don't) then you may want to look into postgreSQL.


Question:
I've learned in College that you always have to free your unused Objects but not how you actually do it. For example structuring your code right and so on.
Are there any general rules on how to handle pointers in C++?

I'm currently not allowed to use boost. I have to stick to pure c++ because the framework I'm using forbids any use of generics.

Answer:
Rules:
Wherever possible, use a
smart pointer
.  Boost has some
good ones
.
If you
can't use a smart pointer,
null out
your pointer after deleting it
.
Never work anywhere that won't let you use rule 1.
If someone disallows rule 1, remember that if you grab someone else's code, change the variable names and delete the copyright notices, no-one will ever notice.  Unless it's a school project, where they actually check for that kind of shenanigans with quite sophisticated tools.  See also,
this question
.


Question: How do I check if an object property in JavaScript is undefined?

Answer:
```
```
if (somevariable == undefined) {
  alert('the variable is not defined!');
}
```
```
You can also make it into a function, as shown
here
:
```
```
function isset(varname){
  return(typeof(window[varname]) != 'undefined');
}
```
```


Question: Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is this blog entry, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.

Answer:
you want an interpolation between the first and the second colour. Interpolating colours is easy by calculating the same interpolation for each of its components (R, G, B). There are many ways to interpolate. The easiest is to use linear interpolation: just take percentage
p
of the first colour and percentage 1 -
p
of the second:
```
```
R = firstCol.R * p + secondCol.R * (1 - p)
```
```
There's
another question
related to this.
There are other methods of interpolation that sometimes work better. For example, using a
bell-shaped (sigmoidal)
interpolation function makes the transition smoother.
/EDIT: Oops, you mean using a predefined function. OK, even easier. The blog post you linked now has an example code in Python.
In Java, you could use the
```
GradientPaint
```
.


Question: The ones that stick out and make life usefull.

Answer:
Here is one for a testClass with Nunit support.
```
```
Imports Nunit.FrameWork

    Namespace $NAMESPACE$
    '''
    ''' A TestClass
    '''
    '''
     _
    Public Class $CLASSNAME$

#Region " Setup and TearDown "
        '''
        ''' Sets up the Tests
        '''
        '''
         _
        Public Sub Setup()

            End Sub

        '''
        ''' Tears down the test. Is executed after the Test is Completed
        '''
        '''
         _
        Public Sub TearDown()

        End Sub
#End Region

#Region " Tests "
                '''
        ''' A Test
        '''
        '''
             _
            Public Sub $Test_Name$()

            End Sub
#End Region

    End Class
End Namespace
```
```


Question:
I am running oracle and have a query which pulls some results from the database. I would like to write the results as a text file. How would I go about doing this?

My prefered way would be by using UTL_FILE. Would some one have an example of how to do this?

Answer:
If you're running the query from
sqlplus
you can use the spool command:
```
spool /tmp/test.spool
```
After executing the spool command within a session, all output is sent to the sqlplus console as well as the /tmp/test.spool text file.


Question:
We've been using the 32bit linux version of the JavaServiceWrapper for quite a while now and it's working perfectly. We are now considering also using it on 64bit linux systems. There are downloads for 64bit binaries on the website, but looking into Makefile for the 64bit version I found the following comment, though:
    # This makefile is in progess. It builds, but the resulting libwrapper.so does not yet work.
    # If you know how to fix it then please help out.

Can anyone confirm, that this comment is just outdated and the resulting wrapper will work without flaws?

Answer:
From
http://wrapper.tanukisoftware.org/doc/english/introduction.html
:
Binary distributions are provided for
  the following list of platforms and
  are available on the download page.
  Only OS versions which are known to
  work have been listed.
(snip...)
linux - Linux kernels; 2.2.x 2.4.x, 2.6.x. Known to work with Debian and Red Hat, but should work with any
  distribution. Currently supported on
  both 32 and
64-bit
x86, and 64-bit ppc
  systems.


Question:
In Java (or any other language with checked exceptions), when creating your own exception class, how do you decide whether it should be checked or unchecked?

My instinct is to say that a checked exception would be called for in cases where the caller might be able to recover in some productive way, where as an unchecked exception would be more for unrecoverable cases, but I'd be interested in other's thoughts.

Answer:
From
A Java Learner
:
When an exception occurs, you have to
  either catch and handle the exception,
  or tell compiler that you can't handle
  it by declaring that your method
  throws that exception, then the code
  that uses your method will have to
  handle that exception (even it also
  may choose to declare that it throws
  the exception if it can't handle it).
Compiler will check that we have done
  one of the two things (catch, or
  declare).  So these are called Checked
  exceptions.   But Errors, and Runtime
  Exceptions are not checked for by
  compiler (even though you can choose
  to catch, or declare, it is not
  required).  So, these two are called
  Unchecked exceptions.
Errors are used to represent those
  conditions which occur outside the
  application, such as crash of the
  system.  Runtime exceptions are
  usually occur by fault in the
  application logic.  You can't do
  anything in these situations.  When
  runtime exception occur, you have to
  re-write your program code.  So, these
  are not  checked by compiler.  These
  runtime exceptions will uncover in
  development, and testing period.  Then
  we have to refactor our code to remove
  these errors.