q:
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

[A]
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.


q:
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.

[A]
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.

s: huggingface

c: devops

d: intermediate


q:
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?

[A]
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.


q:
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

[A]
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


q: 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?

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
@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


q:
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)

[A]
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.


q:
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.

[A]
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


q:
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.

[A]
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);
   }
}
```
```


q: 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?

[A]
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.


q: 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)?

[A]
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
.


q:
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

[A]
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.


q:
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?

[A]
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
```


q:
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);

[A]
```
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
.


q:
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?

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


q:
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.

[A]
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.


q: 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.

[A]
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)


q: 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.

[A]
```
```
Tools->Options->Addin/Macro Security
```
```
Change Paths there.


q:
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!

[A]
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.


q:
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.

[A]
Putting it in double quotes should work:
```
```
$myText = "$myVar";
```
```


q:
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 ?

[A]
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.


q:
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.

[A]
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.


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

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

Thanks

[A]
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.


q: 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?

[A]
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.


q:
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.

[A]
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.


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

[A]
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.


q:
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?

[A]
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.


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

[A]
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
```


q:
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?

[A]
```
```
System.getProperty("user.dir")
```
```
gets the directory the Java VM was started from.


q:
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?

[A]
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
```
```


q: 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?

[A]
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).


q:
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):
    ....

[A]
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


q:
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?

[A]
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.


q:
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

[A]
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.


q:
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);

[A]
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).


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

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

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

[A]
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.


q:
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

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


q:
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?

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


q:
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?

[A]
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


q:
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.

[A]
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.


q:
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?

[A]
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.


q:
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?

[A]
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();
```
```


q:
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);

[A]
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.


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

[A]
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.


q:
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)

[A]
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.


q:
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.

[A]
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


q: 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.

[A]
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.


q:
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.

[A]
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.


q: 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.

[A]
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.


q:
Related to my CouchDB question.

Can anyone explain MapReduce in terms a numbnuts could understand?

[A]
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)
.


q:
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,

[A]
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>
```
```


q:
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.

[A]
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.


q:
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.

[A]
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.


q: 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?

[A]
You can use
```
expect
```
command to populate the username/password info.


q:
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.

[A]
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.


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

[A]
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".


q:
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.

[A]
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
```
.


q:
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.

[A]
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 &
```
```


q:
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.

[A]
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).


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

[A]
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.


q:
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?

[A]
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)
```
```


q:
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?

[A]
```
```
import java.util.HashMap;

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


q:
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.

[A] 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.


q:
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.)

[A] 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.


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

[A]
'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/


q:
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

[A]
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! ;-)


q:
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}

[A]
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.


q: 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?

[A]
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
.


q: 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?

[A]
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


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

[A]
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);
```
```


q:
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.)

[A]
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.


q:
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

[A]
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)


q:
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.


q:
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.

[A]
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.


q:
On Windows I can do:

HANDLE hCurrentProcess = GetCurrentProcess();

SetPriorityClass(hCurrentProcess, ABOVE_NORMAL_PRIORITY_CLASS);

How can I do the same thing on *nix?

[A]
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.)


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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.

[A]
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.


q:
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)

[A]
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.


q: 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) ?

[A]
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!


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

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


q:
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?

[A]
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


q:
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.

[A]
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");
```
```


q:
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...

[A]
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.


q:
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...

[A]
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.


q:
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.

[A]
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
```
```


q:
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.

[A]
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
;)


q:
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.

[A]
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,...).


q:
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


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

[A]
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.


q:
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.

[A]
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


q:
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?

[A]
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.


q:
The default Python install on OS X 10.5 is 2.5.1 with a FAT 32 bit (Intel and PPC) client. I want to setup apache and mysql to run django. In the past, I have run Apache and MySQL to match this install in 32 bit mode (even stripping out the 64 bit stuff from Apache to make it work).

I want to upgrade Python to 64 bit. I am completely comfortable with compiling it from source with one caveat. How do I match the way that the default install is laid out? Especially, with regards to site-packages being in /Library/Python/2.5/ and not the one in buried at the top of the framework once I compile it.

[A] Not sure I entirely understand your question, but can't you simply build and install a 64 bit version and then create symbolic links so that /Library/Python/2.5 and below point to your freshly built version of python?


q:
I need to match and remove all tags using a regular expression in Perl.  I have the following:

<\\??(?!p).+?>

But this still matches with the closing </p> tag.  Any hint on how to match with the closing tag as well?

Note, this is being performed on xhtml.

[A]
Assuming that this will work in PERL as it does in languages that claim to use PERL-compatible syntax:
```
/<\/?[^p][^>]*>/
```
EDIT:
But that won't match a
```
<pre>
```
or
```
<param>
```
tag, unfortunately.
This, perhaps?
```
```
/<\/?(?!p>|p )[^>]+>/
```
```
That should cover
```
<p>
```
tags that have attributes, too.


q:
I run a game and the running is done by hand, I have a few scripts that help me but essentially it's me doing the work. I am at the moment working on web app that will allow the users to input directly some of their game actions and thus save me a lot of work.

The problem is that I'm one man working on a moderately sized (upwards of 20 tables) project, the workload isn't the issue, it's that bugs will have slipped in even though I test as I write. So my question is thus two-fold.

Beta testing, I love open beta's but would a closed beta be somehow more effective and give better results?

How should I bring in the app? Should I one turn drop it in and declare it's being used or should I use it alongside the normal construct of the game?

[A]
I don't understand what you mean by "bring in the app" and "one turn drop it". By "bring in the app" do you mean deploy? As for "One turn drop", I totally don't understand it.
As for open betas, that depends on your audience, really. Counterstrike, for example, apparently run a few closed betas before doing open betas, so here's my suggestion:
Set up a forum in some free forumboard, or set up a topic in a popular gaming forum.
Look for people (whether or not they are in those forums) that you trust, and let them in in a closed beta. This will allow you to iron out serious kinks at first.
If your closed group isn't reporting as much bugs any more, release it to open beta, pointing out ways on how they could give feedback to you.
This is similar to the approach StackOverflow took, but this being a game setting it up on a gaming forum will give the dual benefit of advertising your game
and
getting some interested beta testers.


q:
You have multiple network adapters.

Bind a UDP socket to an local port, without specifying an address.

Receive packets on one of the adapters.

How do you get the local ip address of the adapter which received the packet?

The question is, "What is the ip address from the receiver adapter?" not the address from the sender which we get in the

receive_from( ..., &senderAddr, ... );

call.

[A]
```
ssize_t
     recvfrom(int socket, void *restrict buffer, size_t length, int flags,
         struct sockaddr *restrict address, socklen_t *restrict address_len);

     ssize_t
     recvmsg(int socket, struct msghdr *message, int flags);

[..]
     If address is not a null pointer and the socket is not connection-oriented, the
     source address of the message is filled in.
```
Actual code:
```
int nbytes = recvfrom(sock, buf, MAXBUFSIZE, MSG_WAITALL, (struct sockaddr *)&bindaddr, &addrlen);
```
fprintf(stdout, "Read %d bytes on local address %s\n", nbytes, inet_ntoa(bindaddr.sin_addr.s_addr));
hope this helps.


q:
My automated script for starting and stopping VMWare Server virtual machines has stopped working. vmware-cmd has started raising the error:

The ordinal 3288 could not be located in the dynamic link library LIBEAY32.dll.

I am not aware of any specific change or update when this started happening.

I have found a bunch of other people reporting this problem (or very similar) but no solution.

Do you know what caused this error, and/or how to fix this?

[A]
I would have said that something must have updated either the LIBEAY32.dll or another dll that depends on it. You may find some helpful information using the
depends tool
. If you use this to open up the perl.exe then it should highlight the dependency path that produces the problem. You can compare this with other machines on which perl runs.
The ordinal is effectively a function that is expected by perl or a dll, but is not present in the verision of LIBEAY32.dll that you have. The depends tool makes this quite clear.


q: Setting up an integration server, I’m in doubt about the best approach regarding using multiple tasks to complete the build. Is the best way to set all in just one big-job or make small dependent ones?

[A]
I use TeamCity with an nant build script. TeamCity makes it easy to setup the CI server part, and nant build script makes it easy to do a number of tasks as far as report generation is concerned.
Here is an article I wrote about using CI with CruiseControl.NET, it has a nant build script in the comments that can be re-used across projects:
Continuous Integration with CruiseControl


q:
I have the following html code:

<h3 id="headerid"><span onclick="expandCollapse('headerid')">&uArr;</span>Header title</h3>

I would like to toggle between up arrow and down arrow each time the user clicks the span tag.

function expandCollapse(id) {
    var arrow = $("#"+id+" span").html(); // I have tried with .text() too
    if(arrow == "&dArr;") {
        $("#"+id+" span").html("&uArr;");
    } else {
        $("#"+id+" span").html("&dArr;");
    }
}

My function is going always the else path. If I make a javacript:alert of arrow variable I am getting the html entity represented as an arrow. How can I tell jQuery to interpret the  arrow variable as a string and not as html.

[A]
Check out the
.toggle()
effect.
Here is something similar i was playing with earlier.
HTML:
```
```

Hello World!

<input id="myNewTxt" type="text" />
<input id="myOk" type="button" value="OK" />
<input id="myX" type="button" value="X" />

```
```
SCRIPT:
```
```
$("#myStatic").bind("click", function(){
      $("#myNewTxt").val($("#myStatic").text());
      $("#myStatic,#myEdit").toggle();
 });
 $("#myOk").click(function(){
      $("#myStatic").text($("#myNewTxt").val());
      $("#myStatic,#myEdit").toggle();
 });
 $("#myX").click(function(){
      $("#myStatic,#myEdit").toggle();
 });
```
```


q:
I have to load a PDF within a page.

Ideally I would like to have a loading animated gif which is replaced once the PDF has loaded.

[A]
Have you tried:
```
```
$("#iFrameId").on("load", function () {
    // do something once the iframe is loaded
});
```
```


q:
How can I use XPath to select an XML-node based on its content?

If I e.g. have the following xml and I want to select the <author>-node that contains Ritchie to get the author's full name:

<books>
    <book isbn='0131103628'>
        <title>The C Programming Language</title>
        <authors>
            <author>Ritchie, Dennis M.</author>
            <author>Kernighan, Brian W.</author>
        </authors>
    </book>
    <book isbn='1590593898'>
        <title>Joel on Software</title>
        <authors>
            <author>Spolsky, Joel</author>
        </authors>
    </book>
</books>

[A]
The XPath for this is:
```
```
/books/book/authors/author[contains(., 'Ritchie')]
```
```
In C# the following code would return "Ritchie, Dennis M.":
```
```
xmlDoc.SelectSingleNode("/books/book/authors/author[contains(., 'Ritchie')]").InnerText;
```
```


q: Is there some way to do multi-threading in JavaScript?

[A]
In raw Javascript, the best that you can do is using the few asynchronous calls (xmlhttprequest), but that's not really threading and very limited.
Google Gears
adds a number of APIs to the browser, some of which can be used for threading support.


q:
The Apple Developer Documentation (link is dead now) explains that if you place a link in a web page and then click it whilst using Mobile Safari on the iPhone, the Google Maps application that is provided as standard with the iPhone will launch.

How can I launch the same Google Maps application with a specific address from within my own native iPhone application (i.e. not a web page through Mobile Safari) in the same way that tapping an address in Contacts launches the map?

NOTE:  THIS ONLY WORKS ON THE DEVICE ITSELF.  NOT IN THE SIMULATOR.

[A]
For iOS 5.1.1 and lower, use the
```
openURL
```
method of
```
UIApplication
```
. It will perform the normal iPhone magical URL reinterpretation. so
```
```
[someUIApplication openURL:[NSURL URLWithString:@"http://maps.google.com/maps?q=London"]]
```
```
should invoke the Google maps app.
From iOS 6, you'll be invoking Apple's own Maps app. For this, configure an
```
MKMapItem
```
object with the location you want to display, and then send it the
```
openInMapsWithLaunchOptions
```
message. To start at the current location, try:
```
```
[[MKMapItem mapItemForCurrentLocation] openInMapsWithLaunchOptions:nil];
```
```
You'll need to be linked against MapKit for this (and it will prompt for location access, I believe).


q:
I'm looking for a way to redirect all the stderr streams in interactive bash (ideally to its calling parent process).

I don't want to redirect stderr stream from each individual command, which I could do by appending 2> a_file to each command.

By default, these stderr streams are redirected to the stdout of an interactive bash. I would like to get them on the stderr of this interactive bash process in order to prevent my stdout to be polluted by error messages and be able to treat them separatly.

Any ideas?

I still haven't found an answer ... But maybe it's actually a tty parameter. Does anybody knows something about tty/interactive shell responsibility for handling stderr ?

[A]
You could launch a new bash process redirecting the stderr of that process:
```
```
$ bash -i 2> stderr.log
  $
```
```


q: I have two points (a line segment) and a rectangle. I would like to know how to calculate if the line segment intersects the rectangle.

[A]
Do
http://mathworld.wolfram.com/Line-LineIntersection.html
for the line and each side of the rectangle.
Or:
http://mathworld.wolfram.com/Line-PlaneIntersection.html


q:
In my browsings amongst the Internet, I came across this post, which includes this

"(Well written) C++ goes to great
  lengths to make stack automatic
  objects work "just like" primitives,
  as reflected in Stroustrup's advice to
  "do as the ints do". This requires a
  much greater adherence to the
  principles of Object Oriented
  development: your class isn't right
  until it "works like" an int,
  following the "Rule of Three" that
  guarantees it can (just like an int)
  be created, copied, and correctly
  destroyed as a stack automatic."

I've done a little C, and C++ code, but just in passing, never anything serious, but I'm just curious, what it means exactly?

Can someone give an example?

[A]
Variables in C++ can either be declared on the stack or the heap. When you declare a variable in C++, it automatically goes onto the stack, unless you explicitly use the new operator (it goes onto the heap).
```
```
MyObject x = MyObject(params); // onto the stack

MyObject * y = new MyObject(params); // onto the heap
```
```
This makes a big difference in the way the memory is managed. When a variable is declared on the stack, it will be deallocated when it goes out of scope. A variable on the heap will not be destroyed until delete is explicitly called on the object.