Question: What issues / pitfalls must be considered when overriding equals and hashCode?

Answer:
The theory (for the language lawyers and the mathematically inclined):
```
equals()
```
(
javadoc
) must define an equivalence relation (it must be
reflexive
,
symmetric
, and
transitive
). In addition, it must be
consistent
(if the objects are not modified, then it must keep returning the same value). Furthermore,
```
o.equals(null)
```
must always return false.
```
hashCode()
```
(
javadoc
) must also be
consistent
(if the object is not modified in terms of
```
equals()
```
, it must keep returning the same value).
The
relation
between the two methods is:
Whenever
```
a.equals(b)
```
, then
```
a.hashCode()
```
must be same as
```
b.hashCode()
```
.
In practice:
If you override one, then you should override the other.
Use the same set of fields that you use to compute
```
equals()
```
to compute
```
hashCode()
```
.
Use the excellent helper classes
EqualsBuilder
and
HashCodeBuilder
from the
Apache Commons Lang
library. An example:
```
```
public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}
```
```
Also remember:
When using a hash-based
Collection
or
Map
such as
HashSet
,
LinkedHashSet
,
HashMap
,
Hashtable
, or
WeakHashMap
, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable,
which has also other benefits
.


Question:
I've deployed some Managed Beans on WebSphere 6.1 and I've managed to invoke them through a standalone client, but when I try to use the application "jconsole" distributed with the standard JDK can can't make it works.

Has anyone achieved to connect the jconsole with WAS 6.1?

IBM WebSphere 6.1 it's supossed to support JSR 160 JavaTM Management Extensions (JMX) Remote API. Furthermore, it uses the MX4J implementation (http://mx4j.sourceforge.net). But I can't make it works with neither "jconsole" nor "MC4J".

I have the Classpath and the JAVA_HOME correctly setted, so the issue it's not there.

Answer:
I have successfully connected to ActiveMQ and ServiceMix using the JConsole. Does WAS 6.1 use Java Management Extension (JMX) technology? JMX is required for JConsole.
If your path is set correctly it should work fine. On windows you go to System Properties -> Advanced Tab -> Environment Variables. Have your JAVA_HOME System variable set to the path of your JDK or JRE and your Path variable with %JAVA_HOME%/bin added somewhere in there. Then all you need to do is go to Start->Run->JConsole. Select the correct Process Name and your done.
Where are you having problems at? I hope this helps.
Edit:
Here is the Java Doc's on
JConsole
.


Question:
Let's say I have a list of server names stored in a vector, and I would like to contact them one at a time until one has successfully responded. I was thinking about using STL's find_if algorithm in the following way:

find_if(serverNames.begin(), serverNames.end(), ContactServer());

Where ContactServer is a predicate function object.

On one hand, there's a problem since the predicate will not always return the same result for the same server name (because of server downtime, network problems, etc...). However, the same result will be returned regardless of which copy of the predicate is used (i.e. the predicate has no real state), so the original problem with state-keeping predicates is not relevant in this case.

What do you say?

Answer:
I think I would go for it.
The only thing I would worry about is the readability (and therefore maintainability) of it. To me, it reads something like "Find the first server I can contact", which makes perfect sense.
You might want to rename
```
ContactServer
```
to indicate that it is a predicate;
```
CanContactServer
```
? (But then people would complain about hidden side effects. Hmm...)


Question:
On the UNIX bash shell (specifically Mac OS X Leopard) what would be the simplest way to copy every file having a specific extension from a folder hierarchy (including subdirectories) to the same destination folder (without subfolders)?

Obviously there is the problem of having duplicates in the source hierarchy. I wouldn't mind if they are overwritten.

Example: I need to copy every .txt file in the following hierarchy

/foo/a.txt
/foo/x.jpg
/foo/bar/a.txt
/foo/bar/c.jpg
/foo/bar/b.txt

To a folder named 'dest' and get:

/dest/a.txt
/dest/b.txt

Answer:
In bash:
```
```
find /foo -iname '*.txt' -exec cp \{\} /dest/ \;
```
```
```
find
```
will find all the files under the path
```
/foo
```
matching the wildcard
```
*.txt
```
, case insensitively (That's what
```
-iname
```
means). For each file,
```
find
```
will execute
```
cp {} /dest/
```
, with the found file in place of
```
{}
```
.


Question:
The TRACE macro can be used to output diagnostic messages to the debugger when the code is compiled in Debug mode. I need the same messages while in Release mode. Is there a way to achieve this?

(Please do not waste your time discussing why I should not be using TRACE in Release mode :-)

Answer:
In MFC, TRACE is defined as ATLTRACE. And in release mode that is defined as:
```
```
#define ATLTRACE            __noop
```
```
So, using the out-the-box TRACE from MFC, you won't actually be able to read any TRACE text, because it won't even be written out. You could write your own TRACE function instead, then re-define the TRACE macro. You could do something like this:
```
```
void MyTrace(const CString& text)
{
  ::OutputDebugString(text); // Outputs to console, same as regular TRACE
  // TODO: Do whatever output you need here. Write to event log / write to text file / write to pipe etc.
}
```
```


Question:
We currently maintain a suit of MFC applications that are fairly well designed, however the user interface is beginning to look tired and a lot of the code is in need quite a bit of refactoring to tidy up some duplication and/or performance problems.  We make use of quite a few custom controls that handle all their own drawing (all written using MFC).

Recently I've been doing more research into Qt and the benefits it provides (cross-platform and supports what you might call a more "professional" looking framework for UI development).

My question is - what would be the best approach to perhaps moving to the Qt framework?  Does Qt play nice with MFC?  Would it be better to start porting some of our custom controls to Qt and gradually integrate more and more into our existing MFC apps? (is this possible?).

Any advice or previous experience is appreciated.

Answer:
(This doesn't really answer your specific questions but...)
I haven't personally used Qt, but it's not free for commercial Windows development.
Have you looked at
wxWindows
which is free? Nice article
here
. Just as an aside, if you wanted a single code base for all platforms, then you may have to migrate away from MFC - I am pretty sure (someone will correct if wrong) that MFC only targets Windows.
One other option would be to look at the
Feature Pack update
to MFC in SP1 of VS2008 - it includes access to new controls, including the Office style ribbon controls.


Question:
I'm having a problem obtaining the total row count for items displayed in a Gridview using Paging and with a LinqDataSource as the source of data.

I've tried several approaches:

protected void GridDataSource_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    totalLabel.Text = e.TotalRowCount.ToString();
}

returns -1 every time.

protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    System.Collections.Generic.List<country> lst  = e.Result as System.Collections.Generic.List<country>;
    int count = lst.Count;
}

only gives me the count for the current page, and not the total.

Any other suggestions?

Answer:
The LinqDataSourceEventArgs returned in those events return -1 on these occasions:
-1 if the LinqDataSourceStatusEventArgs object was created during a data modification operation; -1 if you enabled customized paging by setting AutoPage to true and by setting RetrieveTotalRowCount to false.
Check here for more information
- the table towards the bottom, shows different properties to set to get the rowcount back, but it looks like you either have to set AutoPage and AllowPage properties to either both true or both false.
Judging by the table in the link above and the example you provide you have Autopage set to false, but AllowPaging set to true, therefore it is returning the amount of rows in the page.
HTH


Question: I completely understand the concept of expression trees, but I am having a hard time trying to find situations in which they are useful. Is there a specific instance in which expression trees can be applied? Or is it only useful as a transport mechanism for code? I feel like I am missing something here. Thanks!

Answer:
Some unit test mocking frameworks make use of expression trees in order to set up strongly typed expectations/verifications. Ie:
```
```
myMock.Verify(m => m.SomeMethod(someObject)); // tells moq to verify that the method
                                              // SomeMethod was called with
                                              // someObject as the argument
```
```
Here, the expression is never actually executed, but the expression itself holds the interesting information. The alternative without expression trees would be
```
```
myMock.Verify("SomeMethod", someObject) // we've lost the strong typing
```
```


Question:
An app I'm writing always crashes on a clients computer, but I don't get an exception description, or a stack trace.

The only thing I get is a crash report that windows wants to send to Microsoft.

I would like to get that dump file and investigate it myself, but I cannot find it.

When I "View the contents of the error report" I can see the different memory dumps, but I cannot copy it or save it.

Answer:
You can use the
Windows debugging tools
to view the crash dump. To get the most use out of it, you'll need an exact copy of the symbols for that application (i.e. same version).
Have a look at
Tess's blog
for tutorials on how to use the Windows debugging tools. I refer to her blog constantly whenever I'm in need of analysing crash dumps.


Question:
Given the URL (single line):

http://test.example.com/dir/subdir/file.html

How can I extract the following parts using regular expressions:

The Subdomain (test)

The Domain (example.com)

The path without the file (/dir/subdir/)

The file (file.html)

The path with the file (/dir/subdir/file.html)

The URL without the path (http://test.example.com)

(add any other that you think would be useful)

The regex should work correctly even if I enter the following URL:

http://example.example.com/example/example/example.html

Answer:
A single regex to parse and breakup a
  full URL including query parameters
  and anchors e.g.
https://www.google.com/dir/1/2/search.html?arg=0-a&arg1=1-b&arg3-c#hash
```
^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$
```
RexEx positions:
url: RegExp['$&'],
protocol:RegExp.$2,
host:RegExp.$3,
path:RegExp.$4,
file:RegExp.$6,
query:RegExp.$7,
hash:RegExp.$8
you could then further parse the host ('.' delimited) quite easily.
What
I
would do is use something like this:
```
```
/*
    ^(.*:)//([A-Za-z0-9\-\.]+)(:[0-9]+)?(.*)$
*/
proto $1
host $2
port $3
the-rest $4
```
```
the further parse 'the rest' to be as specific as possible. Doing it in one regex is, well, a bit crazy.


Question:
I am storing a PNG as an embedded resource in an assembly.  From within the same assembly I have some code like this:

Bitmap image = new Bitmap(typeof(MyClass), "Resources.file.png");

The file, named "file.png" is stored in the "Resources" folder (within Visual Studio), and is marked as an embedded resource.

The code fails with an exception saying:

Resource MyNamespace.Resources.file.png cannot be found in class MyNamespace.MyClass

I have identical code (in a different assembly, loading a different resource) which works. So I know the technique is sound. My problem is I end up spending a lot of time trying to figure out what the correct path is. If I could simply query (eg. in the debugger) the assembly to find the correct path, that would save me a load of headaches.

Answer:
I'm guessing that your class is in a different namespace. The canonical way to solve this would be to use the resources class and a strongly typed resource:
```
```
ProjectNamespace.Properties.Resources.file
```
```
Use the IDE's resource manager to add resources.


Question:
Effectively I want to give numeric scores to alphabetic grades and sum them. In Excel, putting the LOOKUP function into an array formula works:

{=SUM(LOOKUP(grades, scoringarray))}

With the VLOOKUP function this does not work (only gets the score for the first grade). Google Spreadsheets does not appear to have the LOOKUP function and VLOOKUP fails in the same way using:

=SUM(ARRAYFORMULA(VLOOKUP(grades, scoresarray, 2, 0)))

or

=ARRAYFORMULA(SUM(VLOOKUP(grades, scoresarray, 2, 0)))

Is it possible to do this (but I have the syntax wrong)? Can you suggest a method that allows having the calculation in one simple cell like this rather than hiding the lookups somewhere else and summing them afterwards?

Answer:
I'm afraid I think the answer is no. From the help text on
http://docs.google.com/support/spreadsheets/bin/answer.py?answer=71291&query=arrayformula&topic=&type=
The real power of ARRAYFORMULA comes when you take the result from one of those computations and wrap it inside a formula that does take array or range arguments: SUM, MAX, MIN, CONCATENATE,
As vlookup takes a single cell to lookup (in the first argument) I don't think you can get it to work, without using a separate range of lookups.


Question:
I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine.

Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing.

Is there any way to see debug output from GraphBuilder when it assembles a graph?

Is there a way to dump a working graph to see how it was put together?

Any other ideas for unraveling the mystery that lives in the DirectShow box?

Thanks!
-Z

Answer:
You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph...
In order to find your graph in the list, you have to register it in the running object table:
```
```
void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister )
{
    IMoniker* pMoniker;
    IRunningObjectTable* pROT;
    GetRunningObjectTable( 0, &pROT );

    WCHAR wsz[256];
    swprintf_s( wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() );
    CreateItemMoniker( L"!", wsz, &pMoniker );

    pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister );

    // Clean up any COM stuff here ...
}
```
```
After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke


Question: Is there a Box Plot graph, or box and whisker graph available for Reporting Services 2005? From the looks of the documentation there doesn't seem to be one out of the box; so I am wondering if there is a third party that has the graph, or a way to build my own?

Answer:
There definitely isn't a Box Plot built into SSRS 2005, though it's possible that 2008 has one.  SSRS 2005 does have a robust extension model.  If you can implement a chart in System.Drawing/GDI+, you can make it into a
custom report item
for SSRS.
There are a few third-party vendors with fairly feature-rich products, but the only one I've ever evaluated was
Dundas Chart
, which isn't cheap, but gives you about 100x more charting capability than SSRS 2005 built in (for SSRS 2008, Microsoft incorporated a great deal of Dundas's charting technology).  I can't say from experience that I know Dundas Chart supports the Box Plot, but this
support forum post
says so.


Question:
So far I have encountered adjacency list, nested sets and nested intervals as models for storing tree structures in a database. I know these well enough and have migrated trees from one to another.

What are other popular models? What are their characteristics? What are good resources (books, web, etc) on this topic?

I'm not only looking for db storage but would like to expand my knowledge on trees in general. For example, I understand that nested sets/intervals are especially favorable for relational database storage and have asked myself, are they actually a bad choice in other contexts?

Answer:
A variation is where you use a direct hierarchical representation (ie. parent link in node), but also store a path value.
ie. for a directory tree consisting of the following:
```
```
C:\
   Temp
   Windows
       System32
```
```
You would have the following nodes
```
```
Key     Name     Parent     Path
1       C:                  *1*
2       Temp       1        *1*2*
3       Windows    1        *1*3*
4       System32   3        *1*3*4*
```
```
Path is indexed, and will allow you to quickly do a query that picks up a node and all its children, without having to manipulate ranges.
ie. to find C:\Temp and all its children:
```
```
WHERE Path LIKE '*1*2*%'
```
```
This representation is the only place I can think of where storing
id's
in a string like this is ok.


Question:
In SQL Server 2005, we can create temp tables one of two ways:

declare @tmp table (Col1 int, Col2 int);

or

create table #tmp (Col1 int, Col2 int);

What are the differences between these two?  I have read conflicting opinions on whether @tmp still uses tempdb, or if everything happens in memory.

In which scenarios does one out-perform the other?

Answer:
@wcm - actually to nit pick the Table Variable isn't Ram only - it can be partially stored on disk.
A temp table can have indexes, whereas a table variable can only have a primary index. If speed is an issue Table variables can be faster, but obviously if there are a lot of records, or the need to search the temp table of a clustered index, then a Temp Table would be better.
Good background article


Question:
The DOI system places basically no useful limitations on what constitutes a reasonable identifier. However, being able to pull DOIs out of PDFs, web pages, etc. is quite useful for citation information, etc.

Is there a reliable way to identify a DOI in a block of text without assuming the 'doi:' prefix? (any language acceptable, regexes preferred, and avoiding false positives a must)

Answer:
The following regex should do the job (Perl regex syntax):
```
```
/(10\.\d+\/\d+)/
```
```
You could do some additional sanity checking by opening the urls
```
```
http://hdl.handle.net/<doi>
```
```
and
```
```
http://dx.doi.org/<doi>
```
```
where  is the candidate doi,
and testing that you a) get a 200 OK http status, and b) the returned page is not the "DOI not found" page for the service.


Question:
What tools are people using for testing SQL Server databases?

By this I mean all parts of the database:

configuration

tables

column type

stored procedures

constraints

Most likely, there is not one tool to do it all.

Answer:
I personally use NHibernate with SqlCe, this provides a "throw-away" database that doesn't need any specialized tear down after the tests are run.
It also provides a good way to test your nhibernate mappings if applicable.
Here is a link to an article I wrote awhile ago on how to accomplish this:
http://www.codeproject.com/KB/database/TDD_and_SqlCE.aspx?display=Print


Question:
Story:  The user uploads an image that will be added to a photo gallery.  As part of the upload process, we need to A) store the image on the web server's hard drive and B) store a thumbnail of the image on the web server's hard drive.

"Best" here is defined as

Relatively easy to implement, understand, and maintain

Results in a thumbnail of reasonable quality

Performance and high-quality thumbnails are secondary.

Answer:
I suppose your best solution would be using the
GetThumbnailImage
from the .NET
Image
class.
```
```
// Example in C#, should be quite alike in ASP.NET
// Assuming filename as the uploaded file
using ( Image bigImage = new Bitmap( filename ) )
{
   // Algorithm simplified for purpose of example.
   int height = bigImage.Height / 10;
   int width = bigImage.Width / 10;

   // Now create a thumbnail
   using ( Image smallImage = image.GetThumbnailImage( width,
                                                       height,
                                                       new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero) )
   {
      smallImage.Save("thumbnail.jpg", ImageFormat.Jpeg);
   }
}
```
```


Question: My goals are focused on software application development, and maybe web application development, but most likely desktop applications. I'm embarking on a path to becoming more familiar with C/C++, but should I go much lower than that, into assembly? Or would I not have a benefit for my long-term goals?

Answer:
I wouldn't start learning ASM. If you want to learn C/C++ then start with that. As the quality of your code matures, you may find you have a need for ASM. 99% of the time you won't, but every now and then you might need it.
Also, it does help to know ASM in terms of understanding what C/C++ is doing behind the scenes. But again, until you get more advanced, you probably won't have a need for it.


Question: Basically what I want to do it this: a pdb file contains a location of source files (e.g. C:\dev\proj1\helloworld.cs). Is it possible to modify that pdb file so that it contains a different location (e.g. \more\differenter\location\proj1\helloworld.cs)?

Answer:
If you're looking to be more generic about the paths embedded in a pdb file, you could first use the MS-DOS
```
subst
```
command to map a particular folder to a drive letter.
```
```
subst N: <MyRealPath>
```
```
Then open your project relative to the N: drive and rebuild it.  Your PDB files will reference the source files on N:.  Now it doesn't matter where you place that particular set of source files, so long as you subsequently call the root directory "N:" like you did when you built it.
This practice is recommended by John Robbins in his excellent book,
Debugging Applications for Microsoft .NET and Microsoft Windows
.


Question:
I have a table of tags and want to get the highest count tags from the list.

Sample data looks like this

id (1) tag ('night')
id (2) tag ('awesome')
id (3) tag ('night')

using

SELECT COUNT(*), `Tag` from `images-tags`
GROUP BY `Tag`

gets me back the data I'm looking for perfectly. However, I would like to organize it, so that the highest tag counts are first, and limit it to only send me the first 20 or so.

I tried this...

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20

and I keep getting an "Invalid use of group function - ErrNr 1111"

What am I doing wrong?

I'm using MySQL 4.1.25-Debian

Answer:
MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.
You can get around this limit with the deprecated syntax:
```
```
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20
```
```
1, since it's the first column you want to group on.


Question:
Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a DLL with accessible functions I just export them using the standard __declspec(dllexport) directive.  Then access them either dynamically via LoadLibrary() or at compile time with a header and lib file.

How do you do this when you want to export an entire class (and all it's public methods and properties)?

Is it possible to dynamically load that class at runtime and if so, how?

How would you do it with a header and lib for compile time linking?

Answer:
I use some macros to mark the code for import or export
```
#ifdef ISDLL
#define DLL __declspec(dllexport)
#endif

#ifdef USEDLL
#define DLL __declspec(dllimport)
#endif
```
Then declare the class in a header file:
```
class DLL MyClassToExport { ... }
```
Then
```
#define ISDLL
```
in the libary, and
```
USEDLL
```
before including the header file in the place you want to use the class.
I don't know if you might need to do anything differently for working with
```
LoadLibrary
```


Question:
I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e.

MyClass *m = (MyClass *)ptr;

all over the place, but there seem to be two other types of casts, and I don't know the difference. What's the difference between the following lines of code?

MyClass *m = (MyClass *)ptr;
MyClass *m = static_cast<MyClass *>(ptr);
MyClass *m = dynamic_cast<MyClass *>(ptr);

Answer:
```
dynamic_cast
```
has runtime type checking and only works with references and pointers, whereas
```
static_cast
```
does not offer runtime type checking. For complete information, see the MSDN article
static_cast Operator
.


Question:
I have a large database and would like to select table names that have a certain column name. I have done something like this in MySQL, but can't find any info on SQL Server.

I want to do something like:

select [table]
from [db]
where table [has column 'classtypeid']

How can I do something like this?

Answer:
Use the ANSI information_schema views, this will also work in MySQL
```
```
select table_name
from information_schema.columns
where column_name = 'classtypeid'
```
```


Question:
How do you determine when to use table clusters? There are two types, index and hash, to use for different cases. In your experience, have the introduction and use of table clusters paid off?

If none of your tables are set up this way, modifying them to use table clusters would add to the complexity of the set up. But would the expected performance benefits outweight the cost of increased complexity in future maintenance work?

Do you have any favorite online references or books that describe table clustering well and give good implementation examples?

//Oracle tips greatly appreciated.

Answer:
I haven't used Oracle's table clusters myself, but I understand that its index table clusters are very much like MS SQL Server's clustered indexes. That is, the row data is physically organized by the clustered index's key.
That makes one ideal for a heavily-accessed column that has a reasonably small number of possible values (compared to the total number of rows), where most queries want to retrieve all rows with a particular value. Because all such rows are physically stored together, disk I/O, particularly seek time, is reduced.
"Reasonably small" is not easily defined, but postal or zip codes in an address table seems reasonable if you're often querying for all addresses in a single code's region. Province/state/territory codes are likely too small a selection for a country-wide address table.
So, you don't want to use them on columns with few possible values (e.g., M/F for gender) because then the clustering doesn't buy you anything and likely costs you for insertions. You also never want to use clustering on "autonumber" surrogate key columns (from sequences in Oracle) because that will create a "hot spot" in the last extent of the table as all insertions must physically happen there. You also don't want to apply clustering to a column value that will be updated because the RDBMS will have to physically move the record to maintain the clustered ordering.


Question: Working with dates in ruby and rails on windows, I'm having problems with pre-epoch dates (before 1970) throwing out of range exceptions. I tried using both Time and DateTime objects, but still have the same problems.

Answer:
If you only need dates (no times), the
```
Date
```
class in ruby should handle dates before 1970. But it has only a resolution of days. I don't know if there are solutions, if you also need times before 1970
(source)


Question: How can I have it so Visual Studio doesn't keep re-creating this folder that I never use. It's annoying ot keep looking and unnecessary.

Answer:
```
```
Tools->Options->Addin/Macro Security
```
```
Change Paths there.


Question:
I have a ListBox that has a style defined for ListBoxItems.  Inside this style, I have some labels and a button.  One that button, I want to define a click event that can be handled on my page (or any page that uses that style).  How do I create an event handler on my WPF page to handle the event from my ListBoxItems style?

Here is my style (affected code only):

<Style x:Key="UsersTimeOffList"  TargetType="{x:Type ListBoxItem}">
...
<Grid>
<Button x:Name="btnRemove" Content="Remove" Margin="0,10,40,0" Click="btnRemove_Click" />
</Grid>
</Style>

Thanks!

Answer:
You could create a user control (.ascx) to house the listbox. Then add a public event for the page.
```
```
Public Event btnRemove()
```
```
Then on the button click event in the usercontrol
```
```
RaiseEvent btnRemove()
```
```
You can also pass objects through the event just like any other method. This will allow your user control to tell your page what to delete.


Question:
How do I convert the value of a PHP variable to string?

I was looking for something better than concatenating with an empty string:

$myText = $myVar . '';

Like the ToString() method in Java or .NET.

Answer:
Putting it in double quotes should work:
```
```
$myText = "$myVar";
```
```


Question:
We would like to have user defined formulas in our c++ program.
e.g. The value v = x + ( y - (z - 2)) / 2. Later in the program the user would define x,y and z -> the program should return the result of the calculation.
Somewhen later the formula may get changed, so the next time the program should parse the formula and add the  new values.

 Any ideas / hints how to do something like this ?

 So far I just came to the solution to write a parser to calculate these formulas - maybe any ideas about that ?

Answer:
Using
Spirit
(for example) to parse (and the 'semantic actions' it provides to construct an expression tree that you can then manipulate, e.g., evaluate) seems like quite a simple solution. You can find a grammar for arithmetic expressions
there
for example, if needed... (it's quite simple to come up with your own).
Note: Spirit is
very
simple to learn, and quite adapted for such tasks.


Question:
Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly.

Do you have an Ant template that can be easily ported in a new project? Any tips/sites for making one?

Thank you.

Answer:
I used to do exactly the same thing.... then I switched to
maven
.  Maven relies on a simple xml file to configure your build and a simple repository to manage your build's dependencies (rather than checking these dependencies into your source control system with your code).
One feature I really like is how easy it is to version your jars - easily keeping previous versions available for legacy users of your library.  This also works to your benefit when you want to upgrade a library you use - like junit.  These dependencies are stored as separate files (with their version info) in your maven repository so old versions of your code always have their specific dependencies available.
It's a better Ant.


Question:
Can I get a 'when to use' for these and others?

<% %>
<%# EVAL() %>

Thanks

Answer:
Check out the
Web Forms Syntax Reference
on MSDN.
For basics,
<% %> is used for pure code blocks.  I generally only use this for if statements

is used to add text into your markup; that is, it equates to
<div class='<%= IsLoggedIn ? "authenticated" : "unauthenticated" %>'>
<%# Expression %> is very similar to the above, but it is evaluated in a DataBinding scenario.  One thing that this means is that you can use these expressions to set values of runat="server" controls, which you can't do with the <%= %> syntax.  Typically this is used inside of a template for a databound control, but you can also use it in your page, and then call Page.DataBind() (or Control.DataBind()) to cause that code to evaluate.
The others mentioned in the linked article are less common, though certainly have their uses, too.


Question: Using JDeveloper, I started developing a set of web pages for a project at work. Since I didn't know much about JDev at the time, I ran over to Oracle to follow some tutorials. The JDev tutorials recommended doing JSPX instead of JSP, but didn't really explain why. Are you developing JSPX pages? Why did you decide to do so? What are the pros/cons of going the JSPX route?

Answer:
Hello fellow JDeveloper developer!
I have been working with JSPX pages for over two years and I never had any problems with them being JSPX opposed to JSP. The choice for me to go with JSPX was kinda forced since I use JHeadstart to automatically generate ADF Faces pages and by default, JHeadstart generates everything in JSPX.
JSPX specifies that the document has to be a well-formed XML document. This allows stuff to properly and efficiently parse it. I have heard developers say that this helps your pages be more 'future proof' opposed to JSP.


Question:
I've been looking for a tool to extract exception information from a C++ program. The most wanted feature I'm looking for: I want to know all the exceptions that can be thrown from a function (which would include all the function that is called from that function recursively).

I've always thought that documenting errors and exceptions in particular is very hard (and takes a lot of effort to keep up to date). But if there is some way to automate that, it would be very helpful.

A tool for windows and Visual Studio would be preferred but not necessary, I could always work around that.

Answer:
PC-Lint
claims to do static exception analysis of C++ code.
Coverity
is another static C++ code analysis tool that apparently informs you of unhandled exceptions.
AQtime
claims to have exception tracing as part of its code analysis. Plus, they advertise Visual Studio integration.
Here
is a list of several static code analysis tools.


Question: What are the most user-friendly color combinations for Web 2.0 websites, such as background, button colors, etc.?

Answer:
search for color on useit
search for color on boxesandarrows
There has been loads of research on this sort of stuff and most of it is conflicting a couple of good jump off points are listed above.
Generally lighter backgrounds and good contrast are favoured by all researchers but the details get niggly.


Question:
Has anybody managed to get the Android Emulator working behind a proxy that requires authentication?

I've tried setting the -http-proxy argument to

http://DOMAIN/USERNAME:PASSWORD@IP:PORT

but am having no success.

I've tried following the docs to no avail. I've also tried the -verbose-proxy setting but this no longer seems to exist.

Any pointers?

Answer:
I've not used the Android Emulator but I have set the $http_proxy environment variable for perl and wget and a few cygwin tools on windows. That might work for you for android, but the slash in the domain name seems like a potential problem.
I know I tried having my domain "GLOBAL" in there, but ended up taking it out and sticking with:
```
http://$USER:password@www-proxy.company.com:80
```
One problem I run into a lot though is programs that cannot be told to use the proxy for DNS queries too. In cases where they don't I always get a host name not found. I'd like to find a local dns resolver that can use the proxy for all the programs that won't.


Question: How do you pass $_POST values to a page using cURL?

Answer:
Should work fine.
```
```
$data = array('name' => 'Ross', 'php_master' => true);

// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)
```
```
We have two options here,
```
CURLOPT_POST
```
which turns HTTP POST on, and
```
CURLOPT_POSTFIELDS
```
which contains an array of our post data to submit. This can be used to submit data to
```
POST
```
```
<form>
```
s.
It is important to note that
```
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
```
takes the $data in two formats, and that this determines how the post data will be encoded.
```
$data
```
as an
```
array()
```
: The data will be sent as
```
multipart/form-data
```
which is not always accepted by the server.
```
```
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
```
```
```
$data
```
as url encoded string: The data will be sent as
```
application/x-www-form-urlencoded
```
, which is the default encoding for submitted html form data.
```
```
$data = array('name' => 'Ross', 'php_master' => true);
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
```
```
I hope this will help others save their time.
See:
```
curl_init
```
```
curl_setopt
```


Question:
I want to bring up a file dialog in Java that defaults to the application installation directory.

What's the best way to get that information programmatically?

Answer:
```
```
System.getProperty("user.dir")
```
```
gets the directory the Java VM was started from.


Question:
I recently asked a question about IIf vs. If and found out that there is another function in VB called If which basically does the same thing as IIf but is a short-circuit.

Does this If function perform better than the IIf function?  Does the If statement trump the If and IIf functions?

Answer:
Damn, I really thought you were talking about the operator all along. ;-) Anyway …
Does this If function perform better than the IIf function?
Definitely. Remember, it's built into the language. Only one of the two conditional arguments has to be evaluated, potentially saving a costly operation.
Does the If statement trump the If and IIf functions?
I think you can't compare the two because they do different things. If your code semantically performs an assignment you should emphasize this, instead of the decision-making. Use the
```
If
```
operator here instead of the statement. This is especially true if you can use it in the initialization of a variable because otherwise the variable will be default initialized, resulting in slower code:
```
```
Dim result = If(a > 0, Math.Sqrt(a), -1.0)

' versus

Dim result As Double ' Redundant default initialization!
If a > 0 Then
    result = Math.Sqrt(a)
Else
    result = -1
End If
```
```


Question: What open source licenses are more corporate-friendly, i.e., they can be used in commercial products without the need to open source the commercial product?

Answer:
The two most commonly used licenses that allow what you want are the
BSD License
and
MIT License
. (see also the full
list of licenses
considered Open Source by the OSI).


Question:
What's the best Python idiom for this C construct?

while ((x = next()) != END) {
    ....
}

I don't have the ability to recode next().

update:  and the answer from seems to be:

for x in iter(next, END):
    ....

Answer:
Maybe it's not terribly idiomatic, but I'd be inclined to go with
```
```
x = next()
while x != END:
    do_something_with_x
    x = next()
```
```
... but that's because I find that sort of thing easy to read


Question:
A discussion about Singletons in PHP has me thinking about this issue more and more. Most people instruct that you shouldn't make a bunch of DB connections in one request, and I'm just curious as to what your reasoning is. My first thought is the expense to your script of making that many requests to the DB, but then I counter myself with the question: wouldn't multiple connections make concurrent querying more efficient?

How about some answers (with evidence, folks) from some people in the know?

Answer:
It is the cost of setting up the connection, transferring the data and then tearing it down.  It will eat up your performance.
Evidence is harder to come by but consider the following...
Let's say it takes x microseconds to make a connection.
Now you want to make several requests and get data back and forth.  Let's say that the difference in transport time is negligable between one connection and many (just ofr the sake of argument).
Now let's say it takes y microseconds to close the connection.
Opening one connection will take x+y microseconds of overhead.  Opening many will take n * (x+y).  That will delay your execution.


Question:
I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either:

learn the ins and out of C in Visual Studio

recommend a better C IDE + compiler

Edit: See also: https://stackoverflow.com/questions/951516/a-good-c-ide

Answer:
Some people say that a smaller IDE is better for learning. Take a look at
Code::Blocks
. It's generally true that beginning C in an IDE is hard because not many books explain enough to control the IDE. Perhaps starting in a console and a basic text editor with syntax highlighting would be better – at least under Linux. Since Windows' console is far from great, I'd not recommend using it.
/EDIT: Dev-C++ used to be the best freely available IDE for Windows. However, it's development has been discontinued years ago and the most recent version unfortunately is full of bugs.


Question:
I need to find a bottleneck and need to accurately as possible measure time.

Is the following code snippet the best way to measure the performance?

DateTime startTime = DateTime.Now;

// Some execution process

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);

Answer:
The
stopwatch
functionality would be better (higher precision).  I'd also recommend just downloading one of the popular profilers, though (
DotTrace
and
ANTS
are the ones I've used the most... the free trial for DotTrace is fully functional and doesn't nag like some of the others).


Question:
I have a web service that I created in C# and a test harness that was provided by my client. Unfortunately my web service doesn't seem to be parsing the objects created by the test harness. I believe the problem lies with serializing the soap packet.

Using TCPTrace I was able to get the soap packet passed to the web service but only on a remote machine so I can't debug it there. Is there a way of calling my local webservice with the soap packet generated rather than my current test harness where I manually create objects and call the web service through a web reference?

[edit] The machine that I got the soap packet was on a vm so I can't link it to my machine. I suppose I'm looking for a tool that I can paste the soap packet into and it will in turn call my web service

Answer:
By default, .Net will not allow you to connect a packet analyzer like TCPTrace or Fiddler (which I prefer) to localhost or 127.0.0.1 connections (for reasons that I forget now..)
Best way would be to reference your web services via a full IP address or FQDN where possible.  That will allow you to trace the calls in the tool of your choice.


Question:
Is there a simple way of getting a HTML textarea and an input type="text" to render with (approximately) equal width (in pixels), that works in different browsers?

A CSS/HTML solution would be brilliant. I would prefer not to have to use Javascript.

Thanks
/Erik

Answer:
You should be able to use
```
```
.mywidth {
  width: 100px;
}
```
```
```
```
<input class="mywidth">
<br>
<textarea class="mywidth"></textarea>
```
```


Question:
Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection?

Possible with LINQ or Lambda?

Answer:
In any case, you have to loop through it. Linq offers the
```
Count
```
method:
```
```
var result = myenum.Count();
```
```


Question:
I have been doing some java development lately and have started using Eclipse.  For the most part, I think it is great, but being a C/C++ guy used to doing all of his editing in vim, I find myself needlessly hitting the Esc key over and over.

It would be really nice if I got all the nice features of Eclipse, but still could do basic editing the same way I can in vim.  Anyone know of any Eclipse pluggins that would help with this?

Answer:
There is this plugin that costs $20+
http://satokar.com/viplugin/
I use it and it works great, you've got basic vi movement commands and a set of others.
Here is an open source, free plugin but i've never been able to get it working (i'm on a mac).
http://sourceforge.net/projects/vimplugin/
You can also go the other way and get eclipse code completion inside vim.
http://eclim.sourceforge.net/
You basically run an instance of Eclipse and you will be working inside vim. They just released a version compatible with Eclipse 3.4.
New plugin I've started using
https://marketplace.eclipse.org/content/viable-vim-eclipse


Question:
I have a bunch of classes I want to rename.  Some of them have names that are small and that name is reused in other class names, where I don't want that name changed.  Most of this lives in Python code, but we also have some XML code that references class names.

Simple search and replace only gets me so far.  In my case, I want to rename AdminAction to AdminActionPlug and AdminActionLogger to AdminActionLoggerPlug, so the first one's search-and-replace would also hit the second, wrongly.

Does anyone have experience with Python refactoring tools ? Bonus points if they can fix class names in the XML documents too.

Answer:
In the meantime, I've tried it two tools that have some sort of integration with vim.
The first is
Rope
, a python refactoring library that comes with a Vim (and emacs) plug-in.  I tried it for a few renames, and that definitely worked as expected.  It allowed me to preview the refactoring as a diff, which is nice.  It is a bit text-driven, but that's alright for me, just takes longer to learn.
The second is
Bicycle Repair Man
which I guess wins points on name.  Also plugs into vim and emacs.  Haven't played much with it yet, but I remember trying it a long time ago.
Haven't played with both enough yet, or tried more types of refactoring, but I will do some more hacking with them.


Question:
We have a number of users with Windows Mobile 6 and need to apply minor changes. eg. update a registry setting. One option is push and execute an executable file using our device management software.

I'd like this to be a little more friendly for the admins who are familiar with scripting in VBScript/JScript etc. What are the options for scripting on Windows Mobile devices?

Answer:
I work on windows mobile full time and have never really come across a good Windows Mobile scripting implementation unfortunately.  For some reason MS has never seen the need for it.  For example, even though you can actually get a command console on WM, it does not support running batch files, even though all the commands are still there and it would be relatively easy.  There is definitely not a VBScript engine I've ever heard of nor JScript.  There is
PythonCE
but the WM specific support is minimal and you don't get access to a lot of WM only things.
Also, I've done a lot of work with a company called
SOTI
which has a product called MobiControl that does incorporate a basic scripting engine. Though most of the commands are specific to their system and actually have to be run from a desktop-side management console.
Given all of the times I have tried to find a good scripting engine for WM myself you would think I would've just written one ;)
So, sorry, but the basic answer is
no
, there is not a scripting engine available for VB in the context that you specified.


Question:
If I call finalize() on an object from my program code, will the JVM still run the method again when the garbage collector processes this object?

This would be an approximate example:

MyObject m = new MyObject();

m.finalize();

m = null;

System.gc()

Would the explicit call to finalize() make the JVM's garbage collector not to run the finalize() method on object m?

Answer:
The finalize method is never invoked more than once by a JVM for any given object. You shouldn't be relying on finalize anyway because there's no guarantee that it will be invoked. If you're calling finalize because you need to execute clean up code then better to put it into a separate method and make it explicit, e.g:
```
```
public void cleanUp() {
  .
  .
  .
}

myInstance.cleanUp();
```
```


Question:
I'm translating my C# code for YouTube video comments into PHP. In order to properly nest comment replies, I need to re-arrange XML nodes. In PHP I'm using DOMDocument and DOMXPath which closely corresponds to C# XmlDocument. I've gotten pretty far in my translation but now I'm stuck on getting the parent node of a DOMElement. A DOMElement does not have a parent_node() property, only a DOMNode provides that property.

After determining that a comment is a reply to a previous comment based in the string "in-reply-to" in a link element, I need to get its parent node in order to nest it beneath the comment it is in reply to:

// Get the parent entry node of this link element
$importnode = $objReplyXML->importNode($link->parent_node(), true);

Answer:
DOMElement
is a subclass of
DOMNode
, so it does have parent_node property. Just use $domNode->parentNode; to find the parent node.
In your example, the parent node of $importnode is null, because it has been imported into the document, and therefore does not have a parent yet. You need to attach it to another element before it has a parent.


Question: Using the same sort command with the same input produces different results on different machines.  How do I fix that?

Answer:
This can be the result of locale differences:
```
```
$ echo 'CO2_
CO_' | env LC_ALL=C sort
CO2_
CO_

$ echo 'CO2_
CO_' | env LC_ALL=en_US sort
CO_
CO2_
```
```
Setting the LC_ALL environment variable to the same value should correct the problem.


Question:
What is the the best JavaScript compressor available? I'm looking for a tool that:

is easy to use

has a high compression rate

Produce reliable end results (doesn't mess up the code)

Answer:
YUI Compressor
is the way to go. It has a great compression rate, is well tested and is in use among many top sites, and, well, personally recommended by me.
I've used it for my projects without a single JavaScript error or hiccup.  And it has nice documentation.
I've never used its CSS compression capabilities, but they exist as well.
CSS compression works just as well.
Note: Although Dean Edwards's /
packer
/ achieves a better compression rate than YUI Compressor, I ran into a few JavaScript errors when using it.


Question:
Hey everyone, I'm using Virtual PC and working with a virtual hard disk (*.vhd) that is only sized at 8.2 GB. I would like to double the size to something like 16-20GB. I see options for compacting the VHD but nothing to expand it. It's set to "dynamically expand" but I'm installing some software and it doesn't seem to resize itself to a larger space.

Thanks much.

Answer:
Never worked with Virtual PC but from other virtualization software I know I guess that dynamically expand means that initially the .vhd file will take less space in the HD than the specified and will dynamically grow as you keep installing programs or adding files into the virtual drive UP TO the specified size.
For what you want I guess that you will have to modify the specified size in the virtual hard drive from Virtual PC's setup window.
A bit offtopic but give a go to Virtual Box: www.virtualbox.org


Question: Does anyone have links to documentation or guides on making the decision between REST vs. SOAP? I understand both of these but am looking for some references on the key decision points, eg, security, which may make you lean towards one or the other.

Answer:
Google first hit
seems pretty comprehensive.
I think the problem here is there are too many advocates of one or the other, may be better of googling and getting more of a handle of the pro's/con's yourself and making your own decision.
I know that sounds kinda lame, but ultimately these sort of design decisions fall down to the developer/architect working on it, and
99% of the time, the problem domain will be the deciding factor
(or at least it should be), not a guide on the net.


Question:
Is it possible to get a breakdown of CPU utilization by database?

I'm ideally looking for a Task Manager type interface for SQL server, but instead of looking at the CPU utilization of each PID (like taskmgr) or each SPID (like spwho2k5), I want to view the total CPU utilization of each database. Assume a single SQL instance.

I realize that tools could be written to collect this data and report on it, but I'm wondering if there is any tool that lets me see a live view of which databases are contributing most to the sqlservr.exe CPU load.

Answer:
SQL Server (starting with 2000) will install performance counters (viewable from Performance Monitor or Perfmon).
One of the counter categories (from a SQL Server 2005 install is:)
 - SQLServer:Databases
With one instance for each database.  The counters available however do not provide a CPU % Utilization counter or something similar, although there are some rate counters, that you could use to get a good estimate of CPU.  Example would be, if you have 2 databases, and the rate measured is 20 transactions/sec on database A and 80 trans/sec on database B --- then you would know that A contributes roughly to 20% of the total CPU, and B contributes to other 80%.
There are some flaws here, as that's assuming all the work being done is CPU bound, which of course with databases it's not.  But that would be a start I believe.


Question: I've followed the CouchDB project with interest over the last couple of years, and see it is now an Apache Incubator project. Prior to that, the CouchDB web site was full of do not use for production code type disclaimers, so I'd done no more than keep an eye on it. I'd be interested to know your experiences if you've been using CouchDB either for a live project, or a technology pilot.

Answer:
I got to know one of the people (Jan) working on it a while ago (like 6 months) and have been playing with it ever since. I found the community around CouchDB to be both very knowledgable and helpful so that whenever I ran into an issue it was resolved in a matter of minutes or hours at least.
We just kicked off a project the other week which basically requires us to store data in the non-relational way and due to CouchDB's document oriented store we selected it as one of the technologies to use. So this is actually the first time that I will run it in production, but I'm still pretty confident about it. :)
Just an update here (2009-10-25):
Our first CouchDB install is 20 GB, it hosts 40 million records. It's been running in production since January 2009, and it's been great. Read (
```
GET
```
) speed is outstanding and we use it as a store for complex data, and then it's just pull.
Our second couchdb installment has two databases, one is 160,000,000+ documents (210 GB), and growing between 150,000-300,000 documents a day. The other is
only
35,000,000 documents (7 GB). This setup has a lot more reads and writes and initial tests are performing very well.
View building on the 160,000,000 document database took roughly a week, but since then we upgraded to a larger Amazon EC2 instance and we are also getting ready to update to CouchDB
```
0.10.x
```
(from
```
0.9.1
```
) as this release includes a lot of performance improvements in view building.


Question:
Related to my CouchDB question.

Can anyone explain MapReduce in terms a numbnuts could understand?

Answer:
Take a bunch of data
Perform some kind of transformation that converts every datum to another kind of datum
Combine those new data into yet simpler data
Step 2 is Map. Step 3 is Reduce.
For example,
Get time between two impulses on a pair of pressure meters on the road
Map those times into speeds based upon the distance of the meters
Reduce those speeds to an average speed
The reason MapReduce is split between Map and Reduce is because different parts can easily be done in parallel. (Especially if Reduce has certain mathematical properties.)
For a complex but good description of MapReduce, see:
Google's MapReduce Programming Model -- Revisited (PDF)
.


Question:
Sometimes I need to quickly extract some arbitrary data from XML files to put into a CSV format. What's your best practices for doing this in the Unix terminal? I would love some code examples, so for instance how can I get the following problem solved?

Example XML input:

<root>
    <myel name="Foo" />
    <myel name="Bar" />
</root>

My desired CSV output:

Foo,
Bar,

Answer:
Use a command-line XSLT processor such as
xsltproc
,
saxon
or
xalan
to parse the XML and generate CSV. Here's
an example
, which for your case is the stylesheet:
```
```
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>

    <xsl:template match="root">
        <xsl:apply-templates select="myel"/>
    </xsl:template>

    <xsl:template match="myel">
        <xsl:for-each select="@*">
            <xsl:value-of select="."/>
            <xsl:value-of select="','"/>
        </xsl:for-each>
        <xsl:text>
</xsl:text>
    </xsl:template>
</xsl:stylesheet>
```
```


Question:
I have

class Foo < ActiveRecord::Base
  named_scope :a, lambda { |a| :conditions => { :a => a } }
  named_scope :b, lambda { |b| :conditions => { :b => b } }
end

I'd like

class Foo < ActiveRecord::Base
  named_scope :ab, lambda { |a,b| :conditions => { :a => a, :b => b } }
end

but I'd prefer to do it in a DRY fashion.  I can get the same effect by using

 Foo.a(something).b(something_else)

but it's not particularly lovely.

Answer:
Well I'm still new to rails and I'm not sure exactly what you're going for here, but if you're just going for code reuse why not use a regular class method?
```
```
def self.ab(a, b)
            a(a).b(b)
        end
```
```
You could make that more flexible by taking *args instead of a and b, and then possibly make one or the other optional.  If you're stuck on named_scope, can't you extend it to do much the same thing?
Let me know if I'm totally off base with what you're wanting to do.


Question:
I have one table "orders" with a foreing key "ProductID".

I want to show the orders in a grid with the product name, without LazyLoad for better performance, but I if use DataLoadOptions it retrieves all Product fields, which seams like a overkill.

Is there a way to retrieve only the Product name in the first query?
Can I set some attribute in the DBML?

In this table says that "Foreign-key values" are "Visible" in Linq To SQL, but don't know what this means.

Edit: Changed the title, because I'm not really sure the there is no solution.

Can't believe no one has the same problem, it is a very common scenario.

Answer:
If you select only the columns you want in the linq query, and then call .ToList() on the query, it will be immedietly executed, and will only bring back the columns you are interested in. For example if you do this:
```
```
var q = from p in dataContext.products select p.ProductName;
var results = q.ToList();
```
```
You will get back a list of product names stored in results, and when the query executes on the server it will only bring back the ProductName column.


Question: When I try to use an ssh command in a shell script, the command just sits there.  Do you have an example of how to use ssh in a shell script?

Answer:
You can use
```
expect
```
command to populate the username/password info.


Question:
I have a repeater that is bound to some data.

I bind to the ItemDataBound event, and I am attempting to programmatically create a UserControl:

In a nutshell:

void rptrTaskList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    CCTask task = (CCTask)e.Item.DataItem;

    if (task is ExecTask)
    {
        ExecTaskControl foo = new ExecTaskControl();
        e.Item.Controls.Add(foo);
    }
}

The problem is that while the binding works, the user control is not rendered to the main page.

Answer:
Eh, figured out one way to do it:
```
```
ExecTaskControl foo = (ExecTaskControl)LoadControl("tasks\\ExecTaskControl.ascx");
```
```
It seems silly to have a file depedancy like that, but maybe thats how UserControls must be done.


Question: What is the difference between a Group and a Match in .NET's RegEx?

Answer:
A
Match
is an object that indicates a particular regular expression matched (a portion of) the target text. A
Group
indicates a portion of a match, if the original regular expression contained group markers (basically a pattern in parentheses). For example, with the following code:
```
```
string text = "One car red car blue car";
string pat = @"(\w+)\s+(car)";
Match m = r.Match(text);
```
```
```
m
```
would be match object that contains two groups - group 1, from
```
(\w+)
```
, and that captured "One", and group 2 (from
```
(car)
```
) that matched, well, "car".


Question:
Can anyone suggest a good implementation of a generic collection class that implements the IBindingListView & IBindingList interfaces and provides Filtering and Searching capabilities?

I see my current options as:

Using a class that someone else has written and tested

Inheriting from BindingList<T>, and implementing the IBindingListView interfaces

Write a custom collection from scratch, implementing IBindingListView and IBindingList.

Obviously, the first option is my preferred choice.

Answer:
A couple of solutions I can think of:
The
SubSonic Project
has a pretty nice implementation of
```
BindlingList<T>
```
which is open source. Although this might require using the entire SubSonic binary to use their implementation.
I enjoy using the classes from the
Power Collections
project. It is fairly simple to inherit from one of the base collections there and implement
```
IBindingListView
```
.


Question:
This is a follow-on question to the How do you use ssh in a shell script? question.  If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return?  When I try to just include the ampersand (&) at the end of the command it just hangs.  The exact form of the command looks like this:

ssh user@target "cd /some/directory; program-to-execute &"

Any ideas?  One thing to note is that logins to the target machine always produce a text banner and I have SSH keys set up so no password is required.

Answer:
I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on
nohup
, copied here for your convenience.
Nohuping backgrounded jobs is for
  example useful when logged in via SSH,
  since backgrounded jobs can cause the
  shell to hang on logout due to a race
  condition [2]. This problem can also
  be overcome by redirecting all three
  I/O streams:
```
```
nohup myprogram > foo.out 2> foo.err < /dev/null &
```
```


Question:
I've always used Subversion or CVS for version control, which use a 'merge' methodology.  One of my friends raves about Perforce and how great it is with its change lists and check-out methodology.

While I'm sure a lot of it comes down to experience & personal preference, I was wondering if any research had been done into which method of version control is more efficient to work in?

EDIT: To clarify, I know both Perforce & SVN allow locking & merging, but SVN 'encourages' a liberal edit & merge method, whereas as I understand it, Perforce encourages a checkout-checkin method.

Answer:
Merge is more efficient. For the simple reason that changes to the same file simultaneously tends to be common, and merge allows you to recover from that. In contrast, single checkout prevents that little bit of extra work but it does so at the cost of huge inefficiencies in scheduling. Typically it takes a short amount of time to merge two changes to the same file (e.g. minutes), whereas it takes a significant amount of time to make changes to a file (e.g. many hours or days) so that preventing access to editing a file is a huge inefficiency.
Note that Perforce does not force the checkout methodology, it allows concurrent checkouts (equivalent to merge).


Question: What are the differences between delegates and an events? Don't both hold references to functions that can be executed?

Answer:
An
Event
declaration adds a layer of abstraction and protection on the
delegate
instance.  This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.


Question:
Here is my sample code:

from xml.dom.minidom import *
def make_xml():
    doc = Document()
    node = doc.createElement('foo')
    node.innerText = 'bar'
    doc.appendChild(node)
    return doc
if __name__ == '__main__':
    make_xml().writexml(sys.stdout)

when I run the above code I get this:

<?xml version="1.0" ?>
<foo/>

I would like to get:

<?xml version="1.0" ?>
<foo>bar</foo>

I just guessed that there was an innerText property, it gives no compiler error, but does not seem to work... how do I go about creating a text node?

Answer:
Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "
```
node.noSuchAttr = 'bar'
```
" would also not give an error).
Unless you need a specific feature of
```
minidom
```
, I would look at
```
ElementTree
```
:
```
```
import sys
from xml.etree.cElementTree import Element, ElementTree

def make_xml():
    node = Element('foo')
    node.text = 'bar'
    doc = ElementTree(node)
    return doc

if __name__ == '__main__':
    make_xml().write(sys.stdout)
```
```


Question:
What is the most straightforward way to create a hash table (or associative array...) in Java?  My google-fu has turned up a couple examples, but is there a standard way to do this?

And is there a way to populate the table with a list of key->value pairs without individually calling an add method on the object for each pair?

Answer:
```
```
import java.util.HashMap;

Map map = new HashMap();
```
```


Question:
I have a project to build a voting desktop application for a class in Java. While security isn't the focus of the project, I would like to be as realistic as I can. What are some of the primary tools to integrate security into a Java application.

Edit: I'm not primarily worried about physical security, we are simply building an application not a whole system. I want to ensure votes are recorded correctly and not able to be changed or read by someone else.

Answer: It really depends on what kind of security you are looking to integrate.  Do you want security to ensure that the user isn't running any debuggers or such to flip bits in your application to change the votes?  Do you want to ensure that the user doesn't install logging software to keep track of who voted for who?  Do you want to ensure that the person who is supposed to be voting is actually voting?  Security is a very broad subject, and it's hard to give an answer without knowing what exactly you are looking for.


Question:
I'm working on building a development tool that is written in JavaScript.

This will not be an open source project and will be sold (hopefully) as a commercial product.

I'm looking for the best way to protect my investment. Is using an obfuscator (code mangler) enough to reasonably secure the code?

Are there other alternatives that I am not aware of?

(I'm not sure if obfuscator is the right word, it's one of the apps that takes your code and makes it very unreadable.)

Answer: That's probably about the best you can do.  Just be aware that anybody with enough dedication, can probably de-obfuscate your program.   Just make sure you're comfortable with that before embarking on your project.  I think the biggest problem with this would be to control who's using it on their site.    If somebody goes to a site with your code on it, and likes what it does, it doesn't matter that they don't understand what the code does, or can't read it, when they can just copy the code, and use it on their own site.


Question: I'm looking for a good GUI designer for swing in eclipse. My preference is for a free/open-source plugin.

Answer:
'Jigloo' is a very cool GUI designer.  It is not free for commercial use however.
It auto-generates code and allows for custom editing of the code it creates.
http://www.cloudgarden.com/jigloo/


Question:
I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?

Code:

Assembly a = Assembly.LoadFrom("my.dll");
Type t = a.GetType("type info here");
// All ok so far, assembly loads and I can get my type

string s = "Pass me to the constructor of Type t";
MyObj o = Activator.CreateInstance(t); // throws MissMethodException

Answer:
See if this works for you (untested):
```
```
Type t = a.GetType("type info here");
var ctors = t.GetConstructors();
string s = "Pass me to the ctor of t";
MyObj o = ctors[0].Invoke(new[] { s }) as MyObj;
```
```
If the type has more than one constructor then you may have to do some fancy footwork to find the one that accepts your string parameter.
Edit: Just tested the code, and it works.
Edit2:
Chris' answer
shows the fancy footwork I was talking about! ;-)


Question:
I want to shift the contents of an array of bytes by 12-bit to the left.

For example, starting with this array of type uint8_t shift[10]:

{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xBC}

I'd like to shift it to the left by 12-bits resulting in:

{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAB, 0xC0, 0x00}

Answer:
Lets make it the best way to shift
```
N
```
bits in the array of 8 bit integers.
```
```
N            - Total number of bits to shift
F = (N / 8) - Full 8 bit integers shifted
R = (N % 8) - Remaining bits that need to be shifted
```
```
I guess from here you would have to find the most optimal way to make use of this data to move around ints in an array.  Generic algorithms would be to apply the full integer shifts by starting from the right of the array and moving each integer
```
F
```
indexes.  Zero fill the newly empty spaces.  Then finally perform an
```
R
```
bit shift on all of the indexes, again starting from the right.
In the case of shifting
```
0xBC
```
by
```
R
```
bits you can calculate the overflow by doing a bitwise AND, and the shift using the bitshift operator:
```
```
// 0xAB shifted 4 bits is:
(0xAB & 0x0F) >> 4   // is the overflow      (0x0A)
0xAB << 4            // is the shifted value (0xB0)
```
```
Keep in mind that the 4 bits is just a simple mask: 0x0F or just 0b00001111.  This is easy to calculate, dynamically build, or you can even use a simple static lookup table.
I hope that is generic enough.  I'm not good with C/C++ at all so maybe someone can clean up my syntax or be more specific.
Bonus:  If you're crafty with your C you might be able to fudge multiple array indexes into a single 16, 32, or even 64 bit integer and perform the shifts.  But that is prabably not very portable and I would recommend against this.  Just a possible optimization.


Question: I know I can programatically make the taskbar item for a particular window start flashing when something changes, but is there any way I can stop it from flashing either programatically after a certain period of time or at least is there a keyboard shortcur I can give to my users to somehow stop the flashing?

Answer:
The
FlashWindowEx
function which controls the flashing takes a
FLASHWINFO
struct which has a uCount field to control how many times it flashes.  Also, a possible value for the dwFlags field is FLASHW_STOP to cause the flashing to stop.
EDIT: Forgot was a C# tagged question ... so
P/Invoke goodness found here
.


Question: I'd like to write a game for the Nintendo Wii. How do I go about obtaining an SDK and/or any other tools necessary for writing a game?

Answer:
You would have to get in contact with Nintendo of America and obtain a developer kit from them. Be prepared to spend a wad of dough though.
Check this out:
http://www.nintendo.com/corp/developer.jsp


Question: How do I cast an int to an enum in C#?

Answer:
From an int:
```
```
YourEnum foo = (YourEnum)yourInt;
```
```
From a string:
```
```
YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
    throw new InvalidOperationException(
        $"{yourString} is not an underlying value of the YourEnum enumeration."
    );
}
```
```
From a number:
```
```
YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);
```
```


Question:
If all you see is the ugly no-char boxes, what tools or strategies do you use to figure out what went wrong?

(The specific scenario I'm facing is no-char boxes within a <select> when it should be showing Japanese chars.)

Answer:
Firstly, "ugly no-char boxes" might not be an encoding problem, they might just be a sign you don't have a font installed that can display the glyphs in the page.
Most character encoding problems happen when strings are being passed from one system to another. For webapps, this is usually between the browser and the application, between the application and the filesystem and between the application and the database.
So you need to check where the mis-encoded data is coming from, what character encoding it has at the source, and what encoding it is being received as. The best way is to send through characters you know the system is having problems with, and examine them at each level of the app. What do they look like inside the app? In the database? When you get them back from the database? When they're displayed in the browser?
Sorry to be so general, but the question doesn't give much more to work with.


Question:
The log4j network adapter sends events as a serialised java object. I would like to be able to capture this object and deserialise it in a different language (python). Is this possible?

NOTE The network capturing is easy; its just a TCP socket and reading in a stream. The difficulty is the deserialising part

Answer:
Generally, no.
The stream format for Java serialization is defined
in this document
, but you need access to the original class definitions (and a Java runtime to load them into) to turn the stream data back into something approaching the original objects. For example, classes may define writeObject() and readObject() methods to customise their own serialized form.
(
edit:
lubos hasko suggests having a little java program to deserialize the objects in front of Python, but the problem is that for this to work, your "little java program" needs to load the same versions of all the same classes that it might deserialize. Which is tricky if you're receiving log messages from one app, and really tricky if you're multiplexing more than one log stream. Either way, it's not going to be a little program any more.
edit2:
I could be wrong here, I don't know what gets serialized. If it's just log4j classes you should be fine. On the other hand, it's possible to log arbitrary exceptions, and if they get put in the stream as well my point stands.)
It would be much easier to customise the log4j network adapter and replace the raw serialization with some more easily-deserialized form (for example you could use XStream to turn the object into an XML representation)


Question:
In Ruby, trying to print out the individual elements of a String is giving me trouble. Instead of seeing each character, I'm seeing their ASCII values instead:

>> a = "0123"
=> "0123"
>> a[0]
=> 48

I've looked online but can't find any way to get the original "0" back out of it. I'm a little new to Ruby to I know it has to be something simple but I just can't seem to find it.

Answer:
You want
```
a[0,1]
```
instead of
```
a[0]
```
.


Question:
Can anyone tell me what is the memory usage overhead associated with PHP opcode cache?

I've seen a lot of reviews of opcode cache but all of them only concentrate on the performance increase. I have a small entry level VPS and memory limits are a concern for me.

Answer:
Most of the memory overhead will come from the opcode cache size. Each opcode cacher has their own default(e.g. 30MB for APC) which you can change through the config file.
Other than the cache size, the actual memory overhead of the cacher itself is negligible.


Question:
On Windows I can do:

HANDLE hCurrentProcess = GetCurrentProcess();

SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS);

How can I do the same thing on *nix?

Answer:
Try:
```
```
#include <sys/time.h>
#include <sys/resource.h>

int main(){
    setpriority(PRIO_PROCESS, 0, -20);
}
```
```
Note that you must be running as superuser for this to work.
(for more info, type 'man setpriority' at a prompt.)


Question:
I've writen an Excel-based, database reporting tool. Currentely, all the VBA code is associated with a single XLS file. The user generates the report by clicking a button on the toolbar. Unfortunately, unless the user has saved the file under another file name, all the reported data gets wiped-out.

When I have created similar tools in Word, I can put all the code in a template (.dot) file and call it from there. If I put the template file in the Office startup folder, it will launch everytime I start Word. Is there a similar way, to package and distribute my code in Excel? I've tried using Add-ins, but I didn't find a way to call the code from the application window.

Answer:
You can modify the user's personal.xls file, stored in the excel startup directory (varies between Office versions). If you have lots of users though, that can be fiddly.
An alternative way to get over your problem is to store the macro in a template (.xlt) file. Then when the users opens it they can't save it back over the original file, but have to specify a new filename to save it as. The disadvantage of this method is that you then get multiple copies of your original code all over the place with each saved file. If you modify the original .xlt and someone reruns the old macro in a previously-saved .xls file then things can get out of step.


Question:
Okay, here's the scenario. I have a utility that processes tons of records, and enters information to the Database accordingly.

It works on these records in multi-threaded batches. Each such batch writes to the same log file for creating a workflow trace for each record. Potentially, we could be making close to a million log writes in a day.

Should this log be made into a database residing on another server? Considerations:

The obvious disadvantage of multiple threads writing to the same log file is that the log messages are shuffled amongst each other. In the database, they can be grouped by batch id.

Performance - which would slow down the batch processing more? writing to a local file or sending log data to a database on another server on the same network. Theoretically, the log file is faster, but is there a gotcha here?

Are there any optimizations that can be done on either approach?

Thanks.

Answer:
I think it depends greatly on what you are doing with the log files afterwards.
Of the two operations writing to the log file will be faster - especially as you are suggesting writing to a database on another server.
However if you are then trying to process and search the log files on a regular basis then the best place to do this would be a database.
If you use a logging framework like log4net they often provide simple config file based ways of redirecting input to file or database.


Question:
I have a few lines of PowerShell code that I would like to use as an automated script. The way I would like it to be able to work is to be able to call it using one of the following options:

One command line that opens PowerShell, executes script and closes PowerShell (this would be used for a global build-routine)

A file that I can double-click to run the above (I would use this method when manually testing components of my build process)

I have been going through PowerShell documentation online, and although I can find lots of scripts, I have been unable to find instructions on how to do what I need. Thanks for the help.

Answer:
Save your script as a .ps1 file and launch it using powershell.exe, like this:
```
```
powershell.exe .\foo.ps1
```
```
Make sure you specify the full path to the script, and make sure you have set your execution policy level to at least "RemoteSigned" so that unsigned local scripts can be run.


Question:
I have two machines in two different domains. On both I have VS 2005 installed. I want remote debug between them. Without authentication it is possible but I want to debug managed code. I don't want to debug directly since it is really crappy machine.

When I try to attach with debugger I get message "The trust relationship between this workstation and primary domain failed." Any idea how to overcome this ? I tried tricks with adding same local username on both machines but with no luck.

EDIT: I have same local users on both machines. I started both VS2005 and Debugging monitor with RunAs using local users. I turned Windows Auditing on debug machine and I see that local user from VS2005 machine is trying to logon. But he fails with error 0xC000018D (ERROR_TRUSTED_RELATIONSHIP_FAILURE)

Answer:
I seem to remember that I have sometimes found it useful to use RunAs when you run msvcmon (or whatever it's called this week - the remote debugging stub anyway), to force it to start as the user which you have set up to be the same on both machines.
I would guess that on the machine you're running VS on, you will also need to log in as the local user rather than a domain user (or start VS with RunAs).
I have never understood why this needed to be so hard, given that unmanaged debugging is so much easier, and must expose every security hole that managed debugging could.


Question: What should I do if I want to release a .net assembly but wish to keep its internals detailed in the manifest private (from a utility such as ildasm.exe) ?

Answer:
I think what you're talking about is "obfuscation".
There are lots of articles about it on the net:
http://en.wikipedia.org/wiki/Obfuscation
The "standard" tool for obfuscation on .NET is by Preemptive Solutions:
http://www.preemptive.com/obfuscator.html
They have a community edition that ships with Visual Studio which you can use.
You mentioned ILDasm, have you looked at the .NET Reflector?
http://aisto.com/roeder/dotnet/
It gives you an even better idea as to what people can see if you release a manifest!


Question: How do you stop the designer from auto generating code that sets the value for public properties on a user control?

Answer:
Add the following attributes to the property in your control:
```
```
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
```
```


Question:
I am using jQuery and trying to find a cross browser way to get the pixel coordinates of the caret in <textarea>s and input boxes such that I can place an absolutely positioned div around this location.

Is there some jQuery plugin? Or JavaScript snippet to do just that?

Answer:
Note: this answer describes how to get the
character co-ordinates
of the text-cursor/caret. To find the pixel-co-ordinates, you'll need to extend this further.
The first thing to remember is that the cursor can be in three states
a regular insertion cursor at a specific position
a text selection that has a certain bounded area
not active: textarea does not have focus. Has not been used.
The IE model uses the Object
document.selection
, from this we can get a
TextRange
object which gives us access to the selection and thus the cursor position(s).
The FF model/Opera uses the handy variables [input].selectionStart and selectionEnd.
Both models represent a regular ative cursor as a zero-width selection, with the left bound being the cursor position.
If the input field does not have focus, you may find that neither is set.
I have had good success with the following code to insert a piece of text at the current cursor location, also replacing the current selection, if present.
Depending on the exact browser, YMMV.
```
```
function insertAtCursor(myField, myValue) {

/* selecion model - ie */
if (document.selection) {
  myField.focus();
  sel = document.selection.createRange();
  sel.text = myValue;
}

/* field.selectionstart/end  firefox */
else if (myField.selectionStart || myField.selectionStart == '0' ) {

  var startPos = myField.selectionStart;
  var endPos = myField.selectionEnd;
  myField.value = myField.value.substring(0, startPos)
    + myValue
    + myField.value.substring(endPos, myField.value.length);

  myField.selectionStart = startPos + myValue.length;
  myField.selectionEnd = startPos + myValue.length;
  myField.focus();
}

// cursor not active/present
else {
  myField.value += myValue;
}
```
```
Bug Note: links are not being correctly marked up in the top para.
Selection object:
http://msdn.microsoft.com/en-us/library/ms535869(VS.85).aspx
TextRange object:
http://msdn.microsoft.com/en-us/library/ms535872(VS.85).aspx


Question:
I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case).

If that is the case then the question becomes what is the best way to sort a DataTable?

The combo box bindings are set in the designer initialize using

myCombo.DataSource = this.typedDataSet;
myCombo.DataMember = "Table1";
myCombo.DisplayMember = "ColumnB";
myCombo.ValueMember = "ColumnA";

I have tried setting

this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC";

But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.

Answer:
Does the data need to be in a DataTable?
Using a SortedList and binding that to a combo box would be a simpler way.
If you need to use a DataTable you can use the Select method to retrieve a DataView and pass in a sort parameter.
```
```
DataView dv = myDataTable.Select("filter expression", "sort");
```
```


Question:
We're living in a golden age of databases, with numerous high quality commercial and free databases.  This is great, but the downside is there's not a simple obvious choice for someone who needs a database for his next project.

What are the constraints/criteria you use for selecting a database?

How well do the various databases you've used meet those constraints/criteria?

What special features do the databases have?

Which databases do you feel comfortable recommending to others?

etc...

Answer:
I would think first on what the system requirements are for data access, data security, scalability, performance, disconnected scenarios, data transformation, data sizing.
On the other side, consider also the experience and background of developers, operators, platform administrators.
You should also think on what constraints you have regarding programming languages, operating systems, memory footprint, network bandwidth, hardware.
Last, but not least, you have to think about business issues like budget for licences, support, operation.
After all those considerations you should end up with just a couple of options and the selection should be easier.
In other words, select the technology that suits the best the constraints and needs of your organization and project.
I certainly think that you are right on saying that it is not an obvious choice given the wide number of alternatives, but this is the only way I think you can narrow them to the ones that are really feasible for your project.


Question:
This seems to be an overlooked area that could really use some insight.  What are your best practices for:

making an upgrade procedure

backing out in case of errors

syncing code and database changes

testing prior to deployment

mechanics of modifying the table

etc...

Answer:
In general my rule is: "The application should manage it's own schema."
This means schema upgrade scripts  are part of any upgrade package for the application and run automatically when the application starts.  In case of errors the application fails to start and the upgrade script transaction is not committed.  The downside to this is that the application has to have full modification access to the schema (this annoys DBAs).
I've had great success using Hibernates SchemaUpdate feature to manage the table structures. Leaving the upgrade scripts to only handle actual data initialization and occasional removing of columns (SchemaUpdate doesn't do that).
Regarding testing, since the upgrades are part of the application, testing them becomes part of the test cycle for the application.
Afterthought: Taking on board some of the criticism in other posts here, note the rule says "it's own". It only really applies where the application
owns
the schema as is generally the case with software sold as a product. If your software is sharing a database with other software, use other methods.


Question:
I'm looking for something that will show me the size of each folder within my main folder recursively.

This is a LAMP server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin.

My hosting company does not provide an interface for me to see which folders are consuming the most amount of space.  I don't know of anything on the Internet and did a few searches however I came up with no results.

Something implementing graphs (GD/ImageMagick) would be best but not required.

My host supports only Perl in the CGI-BIN.

Answer:
Strange, I came up on Google with
many relevant results
and
this one
is probably the most complete.
The function "getDirectorySize" will
  ignore link/shorcuts to
  files/directory. The function
  "sizeFormat" will suffix the size with
  bytes,KB,MB or GB accordingly.
Code
```
```
function getDirectorySize($path)
{
  $totalsize = 0;
  $totalcount = 0;
  $dircount = 0;
  if ($handle = opendir ($path))
  {
    while (false !== ($file = readdir($handle)))
    {
      $nextpath = $path . '/' . $file;
      if ($file != '.' && $file != '..' && !is_link ($nextpath))
      {
        if (is_dir ($nextpath))
        {
          $dircount++;
          $result = getDirectorySize($nextpath);
          $totalsize += $result['size'];
          $totalcount += $result['count'];
          $dircount += $result['dircount'];
        }
        elseif (is_file ($nextpath))
        {
          $totalsize += filesize ($nextpath);
          $totalcount++;
        }
      }
    }
  }
  closedir ($handle);
  $total['size'] = $totalsize;
  $total['count'] = $totalcount;
  $total['dircount'] = $dircount;
  return $total;
}

function sizeFormat($size)
{
    if($size<1024)
    {
        return $size." bytes";
    }
    else if($size<(1024*1024))
    {
        $size=round($size/1024,1);
        return $size." KB";
    }
    else if($size<(1024*1024*1024))
    {
        $size=round($size/(1024*1024),1);
        return $size." MB";
    }
    else
    {
        $size=round($size/(1024*1024*1024),1);
        return $size." GB";
    }

}
```
```
Usage
```
```
$path="/httpd/html/pradeep/";
$ar=getDirectorySize($path);

echo "
Details for the path : $path
";
echo "Total size : ".sizeFormat($ar['size'])."
";
echo "No. of files : ".$ar['count']."
";
echo "No. of directories : ".$ar['dircount']."
";
```
```
Output
```
```
Details for the path : /httpd/html/pradeep/
Total size : 2.9 MB
No. of files : 196
No. of directories : 20
```
```


Question:
I use my mobile phone for connection to the internet on my laptop, I also have a wired connection to a LAN which doesn't have internet conectivity, it just has our TFS server on it.

The problem is that I can't use the internet (from the phone) with the LAN cable plugged in. Is there a way to set the default route to my phone?

I'm running Windows XP.

Answer:
There's many OS specific ways to force routing over specific interfaces. What OS are you using? XP? Vista? *nix?
The simplest way is to configure your network card with a static IP and NO GATEWAY, the only gateway (ie. internet access) your laptop will find is then via the mobile.
The disadvantage of this method is that you'll need to access your TFS server by IP address (or netbios name) as all DNS requests will be going out over the internet and not through your private LAN.
EDIT: If you can't use the phone when the LAN is plugged in, that's because you've got it setup for DHCP and the DHCP server is advertising (incorrectly for you) that it will accept and route internet traffic. As previously mentioned, setup with a static IP and no gateway... if you insist on using DHCP you'll need to learn the ROUTE command in DOS, find the IP address of your phone (assuming it's acting as a router) set that as the default route, and remove whatever default route was assigned from the DHCP server.
EDIT2: @dan - you can't use the internet from your phone directly (eg. mobile browser), or you can't make your laptop use your phone for internet when the cable is plugged in? (ie. routing issues) ... if it's the former, then your phone is probably configuring a PAN with your phone and trying to route internet back over the LAN
EDIT @Jorge - IP routing is the responsibility of the network layer, not the application.  Go review the
OSI model
;)


Question:
What are the strategies for versioning of a web application/ website?

I notice that here in the Beta there is an svn revision number in the footer and that's ideal for an application that uses svn over one repository. But what if you use externals or a different source control application that versions separate files?

It seems easy for a Desktop app, but I can't seem to find a suitable way of versioning for an asp.net web application.

NB I'm not sure that I have been totally clear with my question.

What I want to know is how to build and auto increment a version number for an asp.net application.

I'm not interested in how to link it with svn.

Answer:
For my big apps I just use a incrementing version number id (1.0, 1.1, ...) that i store in a comment of the main file (usually index.php).
For just websites I usually just have a revision number (1,2,3,...).


Question:
I know the colours are changed in Environment > Fonts and Colors but I haven't found out which Display Item the object is.

Can someone please tell how I can colour the following code:

lblMessage.Text = "You have successfully answered my question!"

I have the string coloured pink, I would like the lblMessage purple and the .Text a light green.

For me the darker the colour the less it will "change". I won't often change object names, I'll more often change properties and am always changing strings - although I have another question about this that I'll post later.

Thanks

Answer:
For my big apps I just use a incrementing version number id (1.0, 1.1, ...) that i store in a comment of the main file (usually index.php).
For just websites I usually just have a revision number (1,2,3,...).


Question: What's needed to succesfully make a crossdomain call from Silverlight?

Answer:
If I understand your question correctly you would need to have a clientaccesspolicy.xml file in the domain web root of the server that you wish to call (ie www.example.com/clientaccesspolicy.xml) that defines that it is ok for services from other domains to call services on that domain.
Read the
How to Make a Service Available Across Domain Boundaries
MSDN article for more detailed information.


Question:
Around here we have been working with a bunch of Visual Source Safe repositories for about 10 years or so.

Now I want to get rid of sourcesafe and move on to Team Foundation Server.

Do you have any tips or tricks for me before I embark on this migration? What are the things I have to be careful about?

I am sure this migration will mean that our working habits have to be modified in some way. Do you think that these changes could be a problem for the organization? Think about a group of about 20 .NET developers in a single site.

Answer:
I just googled, but
this walkthrough
seems like a good reference, and it mentions the tool VSSConverter which should help you make the migration as painless as possible.
I would like to recommend one thing though: Backup. Backup everything before you do this. Should anything go wrong it's better to be safe than sorry.
My links aren't showing up. This is the address:
http://msdn.microsoft.com/en-us/library/ms181247(VS.80).aspx


Question:
I have an application on which I am implementing localization.

I now need to dynamically reference a name in the resouce file.

assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world"

normally, I will refer as:
String result =Login.foo;
and result=="hello";

my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz".

I need something like:

Login["foo"];

Does anyone know if there is any way to dynamically reference a string in a resource file?

Answer:
You'll need to instance a
```
ResourceManager
```
for the
```
Login.resx
```
:
```
```
var resman = new System.Resources.ResourceManager(
    "RootNamespace.Login",
    System.Reflection.Assembly.GetExecutingAssembly()
)
var text = resman.GetString("resname");
```
```
It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager.