Question: Is there a macro that does it? Which DTE objects to use?

Answer:
I don't know what DTE functions to use, but you could very simply record a macro that could pretty much do it:
Go to the top of the file
ctrl - shift - R (start recording)
ctrl - I (incremental search)
{ (search for the first { character).
F9 (set breakpoint)
ctrl - ] (go to matching } character)
ctrl - shift - R (stop recording)
Now just run this over and over (ctrl - shift P repeatedly) until you reach the end of the file.
If you have namespaces, then change 4. to:
( (search for "(" at the start of the function definition)
esc (stop incremental search)
ctrl - I (incremental search again)
{ (start of function body)
This kind of thing can be infinitely modified to suit your codebase


Question:
I have been adding dependency injection to my code because it makes by code much easier to Unit test through mocking.

However I am requiring objects higher up my call chain to have knowledge of objects further down the call chain.

Does this break the Law of Demeter? If so does it matter?

for example: a class A has a dependency on an interface B, The implementation of this interface to use is injected into the constructor of class A. Anyone wanting to use class A must now also have a reference to an implementation of B. And can call its methods directly meaning and has knowledge of its sub components (interface B)

Wikipedia says about the law of Demeter:  "The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents)."

Answer:
Does it break the law?
Strictly speaking, I think it does.
Does it matter?
The main danger of breaking the law is that you make your code more brittle.
If you really keep it to just the tests, it seems like that danger is not too bad.
Mitigation
My understanding of the
Law of Demeter
is that it can be followed by having "wrapper methods" which prevent directly calling down into objects.


Question:
There are a ton of drivers & famous applications that are not available in 64-bit. Adobe for instance does not provider a 64-bit Flash player plugin for Internet Explorer. And because of that, even though I am running 64-bit Vista, I have to run 32-bit IE. Microsoft Office, Visual Studio also don't ship in 64-bit AFAIK.

Now personally, I haven't had much problems building my applications in 64-bit. I just have to remember a few rules of thumb, e.g. always use SIZE_T instead of UINT32 for string lengths etc.

So my question is, what is preventing people from building for 64-bit?

Answer: Just a guess, but I would think a large part of it would be support - If Adobe compiles the 64 bit version, they have to support it.  Even though it may be a simple compile switch, they'd still have to run through a lot of testing, etc, followed by training their support staff to respond correctly, when they do run into issues fixing them either results in a new version of the 32 bit binary or a branch in the code, etc.  So while it seems simple, for a large application it can still end up costing a lot.


Question:
How do you change controls' Z-order in MFC at design time - i.e. I can't use SetWindowPos or do this at runtime - I want to see the changed z-order in the designer (even if I have to resort to direct-editing the .rc code).

I have an MFC dialog to which I am adding controls.  If there is overlap between the edges of the controls, I want to bring one to the front of the other.  In Windows Forms or WPF, etc. I can Bring to Front, Send to Back, Bring Forward, Send Back.  I don't find these options in MFC, nor can I tell how it determines what is in front, as a control just added is often behind a control that was there previously.  How can I manipulate the Z-order in MFC?  Even if I have to manipulate the .rc file code directly (i.e. end-run around the designer).

Answer:
```
```
GetDlgItem(IDC_MYCONTROL)->SetWindowPos(HWND_TOP,
                                        0, 0, 0, 0,
                                        SWP_NOMOVE | SWP_NOSIZE);
```
```


Question: What is the correct way to implement the "find as you type" behavior on a TComboBox descendant component whose style is csOwnerDrawFixed?

Answer:
Use a TTimer (let's call it timIncSearch). Set (at design time) the following properties:
Enabled:=False;
Interval:=400; //empirically found - it's the delay used in Windows Explorer
...and in OnTimer you'll wrote your searching engine. Be sure that the first line here will be timIncSearch.Enabled:=False; Also because you use csOwnerDrawFixed perhaps it's better to enforce a repaint of your control.
As an aside, - just guessing because you didn't give us many details - perhaps you must hook OnEnter and OnExit events to custom open and close the DropDown list. (Normaly, this is achieved by setting the AutoDropDown property accordingly)
In your ComboBox.KeyPress you'll write
```
with timIncSearch do
begin
Enabled:=False;
Enabled:=True;
end;
```
...also take care here, perhaps you must have a 'case Key of' construct to handle the #13 separately (or whatever).
Other hints:
depending on your situation, perhaps you must hook (also?) the OnKeyDown (if you want to process special keys like eg. BackSpace, Del, Arrows etc. -
taking
in account that the event repeats itself while the key it's pressed down) and/or OnKeyUp (if you want to do similar processing as above but
without
taking in account the keyboard's key auto-repeat feature).


Question:
I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature?

I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both static and non-static methods in the same class?

If this is not possible, is there a good way to implement something like this that can be applied generically to any situation?

EDIT

From the responses I've received, it's clear that there is no way to do this. I'm going with a different naming system to work around this problem.

Answer:
You can call static methods from instance methods without having to specify the type name:
```
```
class Foo
{
    static void Bar()
    {
    }

    void Fizz()
    {
        Bar();
    }
}
```
```
... so it makes sense that you wouldn't be allowed to have a static method and an instance method with the same signature.
What are you trying to accomplish? It's hard to suggest a workaround without knowing specifics. I'd just rename one of the methods.


Question:
C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.

    private void SetProgressBar(string text, int position, int max)
    {
        try
        {
            int percent = (100 * position) / max; //when max is 0 bug hits
            string txt = text + String.Format(". {0}%", percent);
            SetStatus(txt);
        }
        catch
        {
        }
    }

Answer:
```
```
int percent = 0
if (max != 0) percent = (100*position) / max
```
```


Question:
If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it.  In other words, if we have
$f->{$x}{$y}, I want something like

foreach ($x, $y) (deep_keys %{$f})
{
}

instead of

foreach $x (keys %f)
    {
    foreach $y (keys %{$f->{$x})
    {
    }
}

Answer:
It's easy enough if all you want to do is operate on values, but if you want to operate on keys, you need specifications of how levels will be recoverable.
a. For instance, you could specify keys as
```
"$level1_key.$level2_key.$level3_key"
```
--or any separator, representing the levels.
b. Or you could have a list of keys.
I recommend the latter.
Level can be understood by
```
@$key_stack
```
and the most local key is
```
$key_stack->[-1]
```
.
The path can be reconstructed by:
```
join( '.', @$key\_stack )
```
Code:
```
```
use constant EMPTY_ARRAY => [];
use strict;
use Scalar::Util qw<reftype>;

sub deep_keys (\%) {
    sub deeper_keys {
        my ( $key_ref, $hash_ref ) = @_;
        return [ $key_ref, $hash_ref ] if reftype( $hash_ref ) ne 'HASH';
        my @results;

        while ( my ( $key, $value ) = each %$hash_ref ) {
            my $k = [ @{ $key_ref || EMPTY_ARRAY }, $key ];
            push @results, deeper_keys( $k, $value );
        }
        return @results;
    }

    return deeper_keys( undef, shift );
}

foreach my $kv_pair ( deep_keys %$f ) {
    my ( $key_stack, $value ) = @_;
    ...
}
```
```
This has been tested in Perl 5.10.


Question:
I am trying to get the value of some ListViewSubItems, but I have no idea what values it uses for its keys.  I have some simple code:

    protected override void OnItemDrag(ItemDragEventArgs e)
    {
        base.OnItemDrag(e);
        ListViewItem item = e.Item as ListViewItem;
        string val = item.SubItems[???].ToString();
    }

The ??? part is where I am having a problem.  I cannot figure out what the keys are.  I have tried the column names of the ListView with no luck.  I would like to use this method instead of using numeric indices.

Answer:
Subitems are only ordered by column index unluckily. So you'd have to access them like:
```
```
protected override void OnItemDrag(ItemDragEventArgs e)
{
    base.OnItemDrag(e);
    ListViewItem item = e.Item as ListViewItem;
    string val = item.SubItems[0].ToString();
}
```
```


Question:
I'm trying:

import commands
print commands.getoutput("ps -u 0")

But it doesn't work on os x.
os instead of commands gives the same output:
USER   PID %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND

nothing more

Answer:
It works if you use os instead of commands:
```
```
import os
print os.system("ps -u 0")
```
```


Question:
Just that, if you embed an icon:

[Embed(source='icons/checkmark.png')]
private static var CheckMark:Class;

You end up with a dynamic class. You can pretty easily assign the icon to a button at runtime by calling the setStyle method:

var btn:Button = new Button();
btn.setStyle("icon", CheckMark);

But what if you wanted to alter the icon at runtime, like changing it's alpha value or even redrawing pixels, before assigning it to the button?

So far I can't find a satisfactory answer...

Answer:
This is the only answer I could find that seemed close:
Dynamic Icons
(example with View Source)
His solution involves a custom "DynamicIcon" class which is used in the button's icon setting, and a custom Button class which adds one method to the Button class to draw dynamic icons.
The end result is that you are able to send BitmapData to the DynamicIcon class, which will show up in the button. So, embed your image, instantiate your asset class, get the bitmapasset and modify it however you need to and send the bitmapData to the icon.
It's an interesting problem and it seems like there should be an easier solution, but this works without a lot of hassle.


Question:
I am using sybase database to query the daily transaction report. I had subquery within my script.

Here as it goes:

SELECT orders.accountid ,items.x,etc
(SELECT charges.mistotal FROM charges where items.id = charges.id)
FROM items,orders
WHERE date = '2008-10-02'

Here I am getting the error message as:

Subquery cannot return more than one values

My values are 7.50, 25.00

I want to return the 25.00, but when I use

(SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id)

My result is 7.50 but I want to return 25.00

Does anyone has any better suggestion?

Answer:
Under what criteria you choose to select the 25.00 instead of the 7.5?
If its related to the maximum value, you can try using the
MAX()
function on that field.
If its related to the chronologically last row added, try using the
MAX()
on the datetime field, if you have details on the hours and minutes it was added.


Question:
I've been playing with the .NET built in localization features and they seem to all rely on putting data in resx files.

But most systems can't rely on this because they are database driven. So how do you solve this issue? Is there a built in .NET way, or do you create a translations table in SQL and do it all manually?  And if you have to do this on the majority of your sites, is there any reason to even use the resx way of localization?

An example of this is I have an FAQ list on my site, I keep this list in the database so I can easily add/remove more, but by putting it in the database, I have no good way have translating this information into multiple languages.

Answer:
In my opinion, localizing dynamic content (e.g., your FAQ) should be done by you in your database. Depending on how your questions are stored, I would probably create a "locale" column and use that when selecting the FAQ questions from the database. I'm not sure if this would scale  very well when you started localizing lots of tables.
For static content (e.g, form field labels, static text, icons, etc) you should probably be just fine using file-based resources. If you really wanted to, however, it looks like it wouldn't be super hard to create a custom resource provider implementation that could handle this.
Here's some related links:
http://channel9.msdn.com/forums/Coffeehouse/250892-Localizing-with-a-database-or-resx-files/
http://weblogs.asp.net/scottgu/archive/2006/05/30/ASP.NET-2.0-Localization-_2800_Video_2C00_-Whitepaper_2C00_-and-Database-Provider-Support_2900_.aspx
http://www.arcencus.nl/Blogs/tabid/105/EntryID/20/Default.aspx
http://msdn.microsoft.com/en-us/library/aa905797.aspx
http://www.codeproject.com/KB/aspnet/customsqlserverprovider.aspx


Question:
In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch.

How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now".

Answer:
This will do it I think:
```
```
svn diff -r 22334:HEAD --summarize <url of the branch>
```
```


Question:
I have a rather big number of source files that I need parse and extract all string literals and put them in a file as play old java constant.

For exemple:

Label l = new Label("Cat");

Would become:

Label l = new Label(Constants.CAT);

And in Constants.java I would have:

public final static String CAT = "Cat";

I do not want the strings to be externalized in a property text file.

One reason is for consistency and code readability.

The other is that our client code uses GWT, which does not support Java property text file mechanism.

I could write some sort of parser (using ant replace task maybe)?

But I wondered if an IDE already does this sort of thing automatically.

Answer:
Eclipse does do this automatically.  Right-click the file, choose "Source", then "Externalize strings"
This doesn't do exactly what you requested (having the strings in a Constants.java file as Strings) but the method used is very powerful indeed.  It moves them into a properties file which can be loaded dynamically depending on your locale.  Having them in a separate Java source file as you suggest means you'll either have ALL languages in your application at once or you'll ship different applications depending on locale.
We use it for our applications where even the basic stuff has to ship in English and Japanese - our more complicated applications ship with 12 languages - we're not a small software development company by any means :-).
If you
do
want them in a Java file, despite the shortcomings already mentioned, it's a lot easier to write a program to morph the properties file into a Java source file than it is to try and extract the strings from free-form Java source.
All you then need to do is modify the Accessor class to use the in-built strings (in the separate class) rather than loading them at run time.


Question:
My group is a Perl shop in an organization that is very heterogenous.  Although we support the odd Java, PHP, or Python installation, we're using Perl for nearly all of our web applications and systems/data marshalling tasks.  All of our boxes are Linux, although we interface with IIS systems as well.

We're coming under some pressure from management to move to Java for at least some of our work.  I'd like to use the right tool for the right task, but for our work, and due to our collective experience, Perl seems like the right tool for everything.

My initial thought is to use Java for applications that are open to the organization at large, since there is more Java mindshare out there than Perl.

Does anyone have similar experience?  If I'm given the choice, what kinds of tasks should we start with applying Java?  What kinds of tasks should we insist on sticking with Perl?  Does it make any difference?  Why or why not?

Answer:
If your team is going to be supporting the applications, then stick with what you know.
If another team is supporting your apps then you may need to consider Java as it definetly has a greater penetration in today's corporate world.
Management are told that Java is the only way, or "real enterprises use Java", and therefore they think they have to use Java.  I know where I work they think that Java is the only language out there, and things like C# are just for 'tactical' projects and not 'strategic' - whatever that means.
You should use the best tool for the job.


Question: I'm using subversion (TortoiseSVN) and I want to remove the .svn folders from my project for deployment, is there an automated way of doing this using subversion or do I have to create a custom script for this?

Answer:
Use
```
```
svn export <url-to-repo> <dest-path>
```
```
It gets just the source, nothing else. Look in
svn export
(in
Version Control with Subversion
) for more information.


Question:
I need to get the "td" element of a table.  I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY.

I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table.

Thats what I need, maybe someone can help me out?

Answer:
```
```
$(function() {
    $("table#mytable td").mouseover(function() {
        //The onmouseover code
    }).click(function() {
        //The onclick code
    });
});
```
```


Question:
I thought people would be working on little code projects together, but I don't see them, so here's an easy one:

Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.

I wrote a little bit about zip codes in a side project on my wiki/blog:

https://benc.fogbugz.com/default.asp?W24

There is also a new, weird type of zip code.

https://benc.fogbugz.com/default.asp?W42

I can do the javascript code, but it would be interesting to see how many languages we can get here.

Answer:
Javascript Regex Literal
:
US Zip Codes:
```
/(^\d{5}$)|(^\d{5}-\d{4}$)/
```
```
```
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");
```
```
Some countries use
Postal Codes
, which would fail this pattern.


Question:
I have a Selenium test case that enters dates into a date selector made up of three pulldowns (year, month, and day).

select validity_Y label=2008
select validity_M label=08
select validity_D label=08

This part gets repeated a lot throughout the test case. I'd like to reduce it by defining my custom action "selectValidity", so that I can have less redundancy, something like

selectValidity 2008,08,08

What is the best (easiest, cleanest) way to add macros or subroutines to a test case?

Answer:
You aren't allowed to make WinForms calls from other threads.  Look at BeginInvoke in the form -- you can call a delegate to show the form from the UI thread.
Edit: From the comments (do not set CheckForIllegalCrossThreadCalls to false).
More Info
Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.


Question:
Is there a way to run some custom Javascript whenever a client-side ASP.NET validator (RequiredFieldValidator, RangeValidator, etc) is triggered?

Basically, I have a complicated layout that requires I run a custom script whenever a DOM element is shown or hidden. I'm looking for a way to automatically run this script when a validator is displayed. (I'm using validators with Display="dynamic")

Answer:
The best solution I've identified for my specific situation is this:
Create a global JS data structure mapping control IDs to a visibility state.
Register the client IDs of the validators (or anything else, for that matter) in this data structure.
Every 250 milliseconds, loop through the global data structure and compare the cached visiblity state with the element's current state. If the states are different, update the cache and run the custom resize script.
This is ugly in lots of ways, and it's only a solution for my specific scenario, not the abstract case where we want to piggyback arbitrary code onto the showing/hiding of a validator. I'd love a better suggestion!


Question:
I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness.  I much prefer to write

if (boolean1 ^ boolean2)
{
  //do it
}

than

if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
  //do it
}

but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.

I'm curious as to the best practices regarding the usage of the ^ operator.

Answer:
You can simply use
```
!=
```
instead.


Question:
I would like to create a Crystal Reports report using pre-existing LINQ classes that live in a different project than where the report lives.  I can't find a way to do this.  I'm using VS2008.

Whenever I expand the "Project Data" tree, I see only classes in my current project.  The "History" tree shows me the last 5 class in the OTHER project, but I need more than those 5.  I found the "Make New Connection" option under "ADO.NET", but it looks like it's looking for XML sources and DLLs.

Answer:
How about a private helper method in the test fixture
```
```
private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()
```
```


Question:
For my server app, I need to check if an ip address is in our blacklist.

What is the most efficient way of comparing ip addresses? Would converting the IP address to integer and comparing them efficient?

Answer:
Depends what language you're using, but an IP address is usually stored as a 32-bit unsigned integer, at least at the network layer, making comparisons quite fast. Even if it's not, unless you're designing a high performance packet switching application it's not likely to be a performance bottleneck. Avoid premature optimization - design your program for testability and scalability and if you have performance problems then you can use a profiler to see where the bottlenecks are.
Edit: to clarify, IPv4 addresses are stored as 32-bit integers, plus a netmask (which is not necessary for IP address comparisons). If you're using the newer and currently more rare IPv6, then the addresses will be 128 bits long.


Question:
Does the compiler optimize out any multiplications by 1? That is, consider:

int a = 1;
int b = 5 * a;

Will the expression 5 * a be optimized into just 5? If not, will it if a is defined as:

const int a = 1;

Answer:
It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the
```
const
```
it will be left alone.
Your first example compiles to this IL:
```
```
.maxstack 2
.locals init ([0] int32, [1] int32)

ldc.i4.1   //load 1
stloc.0    //store in 1st local variable
ldc.i4.5   //load 5
ldloc.0    //load 1st variable
mul        // 1 * 5
stloc.1    // store in 2nd local variable
```
```
The second example compiles to this:
```
```
.maxstack 1
.locals init ( [0] int32 )

ldc.i4.5 //load 5
stloc.0  //store in local variable
```
```


Question:
I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.

Answer:
Where have you seen the phrase used?
"Binding" in Python generally refers to the process by which a variable name ends up pointing to a specific object, whether by assignment or parameter passing or some other means, e.g.:
```
```
a = dict(foo="bar", zip="zap", zig="zag") # binds a to a newly-created dict object
b = a # binds b to that same dictionary

def crunch(param):
  print param

crunch(a) # binds the parameter "param" in the function crunch to that same dict again
```
```
So I would guess that "lambda binding" refers to the process of binding a lambda function to a variable name, or maybe binding its named parameters to specific objects?  There's a pretty good explanation of binding in the Language Reference, at
http://docs.python.org/ref/naming.html


Question:
I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)

I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.

Answer:
Same as C, you would do
```
```
#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;
```
```
(assuming you meant including 0 but excluding 74, which is what your Java example does)
Edit:
Feel free to substitute
```
random()
```
or
```
arc4random()
```
for
```
rand()
```
(which is, as others have pointed out, quite sucky).


Question:
We all hear a lot about scaling issues in Rails.

I was just curious what the actual costs in handling a HTTP request is in the Rails framework.  Meaning, what has to happen for each and every request which comes in?  Is there class parsing?  Configuration?  Database Connection establishment?

Answer:
That actually depends a lot on which web server you're using, and which configuration you're using, not to mention the application design itself. Configuration and design issues involved include:
Whether you're using fastcgi, old-school cgi, or some other request handling mechanism (affects whether you're going to have to rerun all of the app initialization code per request or not)
Whether you're using memcache (or an alternate caching strategy) or not (affects cost of database requests)
Whether you're using additional load balancing techniques or not
Which session persistence strategy you're using (if needed)
Whether you're using "development" mode or not, which causes code files to be reloaded whenever they're changed (as I recall; maybe it's just per-request) or not
Like most web app frameworks, there are solutions for connection pooling, caching, and process management. There are a whole bunch of ways to manage database access; the usual, default ones are not necessarily the highest performance, but it's not rocket science to adjust that strategy.
Someone who has dug into the internals more deeply can probably speak in more excruciating detail, but most apps use either FastCGI on Apache or an alternate more rails-friendly web server, which means that you only have app setup once per process.


Question: What Abstract Datatypes should be added to OpenJDK7 ?

Answer:
If you look at these two links you will see what some people feel is missing:
http://commons.apache.org/collections/
http://code.google.com/p/google-collections/
My favourite missing one is Bag... it is easy to implement, but annoying to have to implement it.
Mulimaps would also nice to have in the standard packages.


Question:
I am pretty sure I have seen this before, but I haven't found out / remembered how to do it.  I want to have a line of code that when executed from the Delphi debugger I want the debugger to pop-up like there was a break point on that line.

Something like:

FooBar := Foo(Bar);
SimulateBreakPoint; // Cause break point to occur in Delphi IDE if attached
WriteLn('Value: ' + FooBar);

Hopefully that makes sense. I know I could use an exception, but that would be a lot more overhead then I want.  It is for some demonstration code.

Thanks in advance!

Answer:
To trigger the debugger from code (supposedly, I don't have a copy of delphi handy to try):
```
```
asm int 3 end;
```
```
See this page:
http://17slon.com/blogs/gabr/2008/03/debugging-with-lazy-breakpoints.html


Question: How can I check if a given number is even or odd in C?

Answer:
I'd say just divide it by 2 and if there is a 0 remainder, it's even, otherwise it's odd.
Using the modulus (%) makes this easy.
eg.
4 % 2 = 0 therefore 4 is even
5 % 2 = 1 therefore 5 is odd


Question:
I have a function that takes a struct, and I'm trying to store its variables in array:

int detect_prm(Param prm) {
  int prm_arr[] = {prm.field1, prm.field2, prm.field3};

  return 0;
}

But with gcc -Wall -ansi -pedantic-errors -Werror I get the following error:

initializer element is not computable at load time

It looks fine to me, what's wrong?

Answer:
This is illegal in C. Initializer lists must be constant compile time expressions. Do the following instead:
```
```
int prm_arr[3];

prm_arr[0] = prm.field1;
prm_arr[1] = prm.field2;
prm_arr[2] = prm.field3;
```
```


Question:
If I have two variables:

Object obj;
String methodName = "getName";

Without knowing the class of obj, how can I call the method identified by methodName on it?

The method being called has no parameters, and a String return value. It's a getter for a Java bean.

Answer:
Use
method invocation
from reflection:
```
```
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", parameterTypes);
method.invoke(objectToInvokeOn, params);
```
```
Where:
```
"class name"
```
is the name of the class
```
objectToInvokeOn
```
is of type Object and is the object you want to invoke the method on
```
"method name"
```
is the name of the method you want to call
```
parameterTypes
```
is of type
```
Class[]
```
and declares the parameters the method takes
```
params
```
is of type
```
Object[]
```
and declares the parameters to be passed to the method


Question:
Basically I have the following class:

class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};

The methods stateA() and stateB() should be able return pointers to stateA() and stateB().
How to typedef the StateMethod?

Answer:
My philosophy is don't use raw member function pointers. I don't even really know how to do what you want using raw pointer typedef's the syntax is so horrible. I like using boost::function.
This is
almost
certainly wrong:
```
```
class X
{
  public:
    typedef const boost::function0<Method> Method;

    // some kind of mutually recursive state machine
    Method stateA()
    { return boost::bind(&X::stateB, this); }
    Method stateB()
    { return boost::bind(&X::stateA, this); }
};
```
```
This problem is definitely a lot harder than first meets the eye


Question:
In .NET is there a way to enable Assembly.Load tracing? I know while running under the debugger it gives you a nice message like "Loaded 'assembly X'" but I want to get a log of the assembly loads of my running application outside the debugger, preferably intermingled with my Debug/Trace log messages.

I'm tracing out various things in my application and I basically want to know what action triggered a particular assembly to be loaded.

Answer:
Get the AppDomain for your application and attach to the AssemblyLoad event.
Example (C#):
```
```
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(OnAssemblyLoad);
```
```


Question:
I am trying to send an email from a site I am building, but it ends up in the yahoo spam folder. It is the email that sends credentials. What can I do to legitimize it?

$header = "From: site <sales@site.com>\r\n";
$header .= "To: $name <$email>\r\n";
$header .= "Subject: $subject\r\n";
$header .= "Reply-To: site <sales@site.com>" . "\r\n";
$header .= "MIME-VERSION: 1.0\r\n";
$header .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$phpversion = phpversion();
$header .= "X-Mailer: PHP v$phpversion\r\n";
mail($email,$subject,$body,$header);

Answer:
Don't use HTML in your email.
Send it via a legitimate mail server with a static IP and reverse-DNS (PTR) that points to the machine's real host name (and matches a forward lookup).
Include a Message-ID (or ensure that the local mailer adds one for you).
Run your email through
SpamAssassin
and see which bad-scoring rules it matches. Avoid matching them.
Use
DomainKeys Identified Mail
to digitally sign your messages.


Question:
Is there a CSS editor which automatically expands one-line declarations as multi-line declarations on focus ? To clarify my thought, see example below:

Original CSS:

div#main { color: orange; margin: 1em 0; border: 1px solid black; }

But when focusing on it, editor automatically expands it to:

div#main {
  color: orange;
  margin: 1em 0;
  border: 1px solid black;
}

And when it looses focus, editor again it automatically compresses it to one-line declaration.

Thanks.

Answer:
Sorry. I don't know of any IDEs that explicitly do that.
But, there are quite a few external options:
CSSTidy
(download)
Clean CSS
(in-browser)
CSS Optimiser
(in-browser)
others...
(Google Search)


Question:
I have a form with a progress bar and a cancel button which is displayed as a process runs. The buttons "Cancel" property is set to true so pressing escape, cancels the process.

But, as the button is the only control on the form capable of taking the focus, should the user inadvertently press enter (or space bar) while the process is running it will be cancelled.

I have prevented the Space Bar from working by setting KeyPreview to true (on the form) then setting KeyAscii to 0 but this approach deson't seem to work for the enter key as the button click event fires first.

I've tried setting the button's TabStop property to "false" - no change.

Answer:
In my opinion, the Enter key
should activate
the cancel button. Or are you requiring the user to reach out for the mouse? why?
I suggest adding just a confirmation dialog after the user cancels the operation, so if anyone accidentally presses the Enter key have the chance to resume saying 'no, I don't want to cancel'.
But as a user
I would be annoyed if the Cancel button has the focus and I can't activate it pressing the Enter key
on my keyboard.
My 2 cents


Question: I would really like to use SpringSource dm Server, but our customer requires us to run our apps on their application server (Websphere). Is there a way to integrate SpringSource dm Server with other application servers? At least dm Server is build on OSGi, and many other application servers (including Websphere) are based on OSGi as well. Is it possible to run a SpringSource dm Server as a websphere component?

Answer:
Spring DM is deployed on a Knoplerfish OSGi implementation.
Websphere is deployed on an Equinox OSGi implmentation.
So the question becomes - are the two interchangeable? They both support R4, so I would say, yes, they are.
The next question would be to check dependencies, particularly with respect to things like HttpServices.
I would say this would be ok, but I think the final proof would be try deploying it. Easiest would be to drop the bundles into a Websphere deployment. You'll need your bundles and whatever spring bundles you're using.


Question:
I have a table that looks like that:

The rows are sorted by CLNDR_DATE DESC.

I need to find a CLNDR_DATE that corresponds to the highlighted row, in other words:

Find the topmost group of rows WHERE EFFECTIVE_DATE IS NOT NULL,
and return the CLNR_DATE of a last row of that group.

Normally I would open a cursor and cycle from top to bottom until I find a NULL in EFFECTIVE_DATE. Then I would know that the date I am looking for is CLNDR_DATE, obtained at the previous step.

However, I wonder if the same can be achieved with a single SQL?

Answer:
Warning: Not a DBA by any means. ;)
But, a quick, untested stab at it:
```
```
SELECT min(CLNDR_DATE) FROM [TABLE]
WHERE (EFFECTIVE_DATE IS NOT NULL)
  AND (CLNDR_DATE > (
    SELECT max(CLNDR_DATE) FROM [TABLE] WHERE EFFECTIVE_DATE IS NULL
  ))
```
```
Assuming you want the
first
CLNDR_DATE
with
EFFECTIVE_DATE after the
last without
.
If you want the
first with
after the
first without
, change the subquery to use min() instead of max().


Question:
For a right triangle specified by an equation aX + bY <= c  on integers

I want to plot each pixel(*) in the triangle once and only once, in a pseudo-random order, and without storing a list of previously hit points.

I know how to do this with a line segment between 0 and x

pick a random point'o' along the line,

     pick 'p' that is relatively prime to x

     repeat for up to x times:     Onext = (Ocur + P) MOD x

To do this for a triangle, I would

1.  Need to count the number of pixels in the triangle sans lists

2.  Map an integer 0..points into a x,y pair that is a valid pixel inside the triangle

I hope any solution could be generalized to pyramids and higher dimensional shapes.

(*) I use the CG term pixel for the pair of integer points X,Y such that the equation is satisfied.

Answer:
Since you want to guarantee visiting each pixel once and only once, it's probably better to think in terms of pixels rather than the real triangles.
You can slice the triangles horizontally and get bunch of horizontal
scan lines
. Connect the scan lines together and you have converted your "triangle" into a long line. Apply your point visiting algorithm to your long chain of scan lines.
By the way, this mapping only needs to happen on paper, all you need is a function that can return (x, y) given (t) along the virtual scan line.
Edit:
To convert two points to a line segment, you can look for
Bresenham's scan conversion
. Once you get the 3 line segments converted into series of points, you can put all points into a bucket and group all points by y. Within the same y-value, sort points by x. The smallest x within a y-value is the begin point of the scan line and the largest x within the y-value is the end point of the scan line. This is called "scan converting triangle". You can find more info if you Google.


Question:
I am currently looking at a distributed cache solution.

If money was not an issue, which would you recommend?

www.scaleoutsoftware.com

ncache

memcacheddotnet

MS Velocity

Answer:
Out of your selection I've only ever attempted to use memcached, and even then it wasn't the C#/.NET libraries.
However memcached technology is fairly well proven, just
look at the sites that use it
:
...The system is used by several very large, well-known sites including
YouTube
,
LiveJournal
,
Slashdot
,
Wikipedia
,
SourceForge
, ShowClix, GameFAQs,
Facebook
,
Digg
,
Twitter
, Fotolog, BoardGameGeek, NYTimes.com, deviantART, Jamendo, Kayak, VxV,
ThePirateBay
and Netlog.
I don't really see a reason to look at the other solution's.
Good Luck,
Brian G
.


Question: I want Netbeans 6.1 to store the .netbeans directory in another place than the default. How do I do this?

Answer:
There's config file:
```
```
<Netbeans>/etc/netbeans.conf

 netbeans_default_userdir=<dir>
```
```


Question:
We have a scenario where we want to display a list of items and indicate which is the "current" item (with a little arrow marker or a changed background colour).

ItemsControl is no good to us, because we need the context of "SelectedItem". However, we want to move the selection programattically and not allow the user to change it.

Is there a simple way to make a ListBox non-interactive? We can fudge it by deliberately swallowing mouse and keyboard events, but am I missing some fundamental property (like setting "IsEnabled" to false without affecting its visual style) that gives us what we want?

Or ... is there another WPF control that's the best of both worlds - an ItemsControl with a SelectedItem property?

Answer:
Is your ItemsControl/ListBox databound?
I'm just thinking you could make the Background Brush of each item bound to a property from the source data, or pass the property through a converter. Something like:
```
```
<ItemsControl DataContext="{Binding Source={StaticResource Things}}" ItemsSource="{Binding}" Margin="0">
    <ItemsControl.Resources>
      <local:SelectedConverter x:Key="conv"/>
    </ItemsControl.Resources>
    <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
        <local:Control Background="{Binding Path=IsSelected, Converter={StaticResource conv}}"/>
      </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
```
```


Question:
Currently I'm trying to erase a sequence of iterators from a set, however GCC's standard library seems to be broken because std::set::erase(iterator) should return the an iterator (next iterator), however in GCC it returns void (which is standard?)

Anyways I want to write:

myIter = mySet.erase(myIter);

But GCC doesn't like it...
So Is it safe to write this instead?

mySet.erase(myIter++);

Edit: And yes I'm checking against mySet.end();

Answer:
There is no problem with
```
```
mySet.erase(myIter++);
```
```
The order of operation is well-defined: myIter is copied into myTempIter, myIter is incremented, and myTempIter is then given to the erase method.
For Greg and Mark
: no, there is no way operator++ can perform operations after the call to erase. By definition, erase() is called after operator++ has returned.


Question:
I am working on an ASP site hosted using SUN One (used to be called Chillisoft) server. I am having trouble loading in an XML file, the code I am using is below

dim directory
set directory = Server.CreateObject("MSXML2.DOMDocument")

if(directory.load(Server.MapPath("directory.xml"))) then
     Response.Write("Loaded")
else
     Response.Write("NotLoaded")
    If directory.parseError.errorCode Then
        Response.Write( "Parse error" )
    end if
end if

My asp page and directory.xml are both in the same folder "/public_html/".

I think the problem might have something to do with the mappath not finding the file, but no errors are returned so not sure what to do.

Thanks

Answer:
I don't know much about Sun One but I do know it has a Bean that emulates MSXML.
Oridinarily, you would use:-
```
```
Set directory = Server.CreateObject("MSXML2.DOMDocument")
directory.async = false
directory.load(Server.MapPath("directory.xml")
```
```
Otherwise load returns immeadiately whilst the xml is loaded asynchronously.
It can't see how the code you have posted would not return something without error.
First diagnositic I would is:-
```
```
Response.Write(Server.MapPath("directory.xml"))
```
```
and then
```
```
Dim direcotory
Set directory = Server.CreateObject("MSXML.DOMDocument")
Response.Write(Not (directory Is Nothing))
```
```


Question:
Does C++ support 'finally' blocks?

What is the RAII idiom?

What is the difference between C++'s RAII idiom and C#'s 'using' statement?

Answer:
No, C++ does not support 'finally' blocks.  The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a
poor name
†
for a really useful concept.
The idea is that an object's destructor is responsible for freeing resources.  When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception.  Here is
Bjarne Stroustrup's explanation
of the topic.
A common use for RAII is locking a mutex:
```
```
// A class with implements RAII
class lock
{
    mutex &m_;

public:
    lock(mutex &m)
      : m_(m)
    {
        m.acquire();
    }
    ~lock()
    {
        m_.release();
    }
};

// A class which uses 'mutex' and 'lock' objects
class foo
{
    mutex mutex_; // mutex for locking 'foo' object
public:
    void bar()
    {
        lock scopeLock(mutex_); // lock object.

        foobar(); // an operation which may throw an exception

        // scopeLock will be destructed even if an exception
        // occurs, which will release the mutex and allow
        // other functions to lock the object and run.
    }
};
```
```
RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result.  This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to
Mike B
for pointing this out.)
For those familliar with C# or VB.NET, you may recognize that RAII is similar to
.NET deterministic destruction using IDisposable and 'using' statements
.  Indeed, the two methods are very similar.  The main difference is that RAII will deterministically release any type of resource -- including memory.  When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory.  In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.
† Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.


Question:
I am using the System.Web.Routing assembly in a WebForms application. When running the application deployed on win2008/IIS7 I got the following message.

Session state can only be used when enableSessionState is set to true, either in a configuration file or in the Page directive. Please also make sure that System.Web.SessionStateModule or a custom session state module is included in the \\ section in the application configuration.

This is only a problem when using a route I have configured. It is not a problem when directly navigating to an aspx page.

EnableSessionState has been turned on in both the web.config and the Page directive. I have added the Session entry to httpmodule of the web.config.

This is not an issue when developing using Visual Studio on my workstation. It is only a problem when trying to run the application under IIS7 on Win 2008.

Answer:
I'm having the same issue and I think I know what the problem is.
I'm trying to implement a FileNotFound page under the routing system (something I've yet to figure out is how to both give a FileNotFound page AND give a 404 response in the header)
What I've found, is that for some reason, the pages registered with BuildManager seem to be instanced without session context (the page was not actually requested, just instanced!).
At least that's what it seems to do.
I'm now less sure of my previous assertion. Apparently, requests for images also go through the routing system when they do not exist on physically. This causes an
```
IRouteHandler
```
to be called when the image path matches. I'm pretty sure the session object does not exist when an image is requested, so that may cause the problem when the page that was routed to tries to access it.


Question:
I've been using maven2 and hudson for a while to do my continuous integration, but I find that Eclipse and Maven do not play well together. Sure there's a plugin, but it's cranky to mash the maven project into something that eclipse likes and the build times and unit test are too long.
I'm considering switching back to a pure eclipse project with no ant and no maven involved. With the infinitest plugin and possible the JavaRebel agent, it would give me a very fast build-deploy-test cycle. However I'd still like to have automatic and testing as well, so:

How do I use continuous integration with an Eclipse project?

Is there a command line way to do it?

Is there a build server that already supports it natively?

Answer:
Yeah, Eclipse Maven2 plugin is crap for now. But I would suggest for you to hang in there, there is a lot of benefit to using Maven2, so it actually balances out.
What we do, is that we use Eclipse to develop and only use Maven to manage dependencies. Everything else is done by running "mvn" on command line. We keep tests in their own integration test projects (...-itest) and have continuous integration server to do build in 2 phases, first build the actual code, and second pass build and runs the -itest projects. (First pass (pure build) usually is very quick, and the integration tests build (with running of tests) usually takes quite a while.)
Here's command line to make mvn run tests:
```
mvn -o verify -Ditest
```
Of course you need to define 'itest' profile in your parent pom:
Say, like this:
```
```
<profiles>
  <profile>
    <id>integration-test</id>
    <activation>
      <property>
        <name>itest</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-surefire-plugin</artifactId>
          <executions>
            <execution>
              <id>itest</id>
            </execution>
          </executions>
          <configuration>
            <testSourceDirectory>src/main</testSourceDirectory>
            <testClassesDirectory>target/classes</testClassesDirectory>
            <forkMode>once</forkMode>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>
```
```


Question:
Hibernate has a handful of methods that, one way or another, takes your object and puts it into the database. What are the differences between them, when to use which, and why isn't there just one intelligent method that knows when to use what?

The methods that I have identified thus far are:

save()

update()

saveOrUpdate()

saveOrUpdateCopy()

merge()

persist()

Answer:
Here's my understanding of the methods.  Mainly these are based on the
API
though as I don't use all of these in practice.
saveOrUpdate
Calls either save or update depending on some checks.  E.g. if no identifier exists, save is called.  Otherwise update is called.
save
Persists an entity.  Will assign an identifier if one doesn't exist.  If one does, it's essentially doing an update.  Returns the generated ID of the entity.
update
Attempts to persist the entity using an existing identifier.  If no identifier exists, I believe an exception is thrown.
saveOrUpdateCopy
This is deprecated and should no longer be used.  Instead there is...
merge
Now this is where my knowledge starts to falter.  The important thing here is the difference between transient, detached and persistent entities.  For more info on the object states,
take a look here
.  With save & update, you are dealing with persistent objects.  They are linked to a Session so Hibernate knows what has changed.  But when you have a transient object, there is no session involved.  In these cases you need to use merge for updates and persist for saving.
persist
As mentioned above, this is used on transient objects.  It does not return the generated ID.


Question:
Is there a way of forcing a (child) class to have constructors with particular signatures or particular static methods in C# or Java?

You can't obviously use interfaces for this, and I know that it will have a limited usage. One instance in which I do find it useful is when you want to enforce some design guideline, for example:

Exceptions

They should all have the four canonical constructors, but there is no way to enforce it. You have to rely on a tool like FxCop (C# case) to catch these.

Operators

There is no contract that specifies that two classes can be summed (with operator+ in C#)

Is there any design pattern to work around this limitation?
What construct could be added to the language to overcome this limitation in future versions of C# or Java?

Answer:
Using generics you can force a type argument to have a parameterless constructor - but that's about the limit of it.
Other than in generics, it would be tricky to actually
use
these restrictions even if they existed, but it could sometimes be useful for type parameters/arguments. Allowing static members in interfaces (or possibly static interfaces) could likewise help with the "generic numeric operator" issue.
I
wrote about this
a little while ago when facing a similar problem.


Question: Should I use the GWT for a struts web application?

Answer:
I don't think GWT would integrate so well into Struts - GWT is more like a framework which you would use instead of Struts.
You could try something like
Ext JS
, which (being a pure JavaScript library) I think would be more likely to integrate into Struts.


Question:
I'm trying to run some commands in paralel, in background, using bash. Here's what I'm trying to do:

forloop {
  //this part is actually written in perl
  //call command sequence
  print `touch .file1.lock; cp bigfile1 /destination; rm .file1.lock;`;
}

The part between backticks (``) spawns a new shell and executes the commands in succession. The thing is, control to the original program returns only after the last command has been executed. I would like to execute the whole statement in background (I'm not expecting any output/return values) and I would like the loop to continue running.

The calling program (the one that has the loop) would not end until all the spawned shells finish.

I could use threads in perl to spawn different threads which call different shells, but it seems an overkill...

Can I start a shell, give it a set of commands and tell it to go to the background?

Answer:
```
```
for command in $commands
do
    "$command" &
done
wait
```
```
The ampersand at the end of the command runs it in the background, and the
```
wait
```
waits until the background task is completed.


Question:
I wrote a small web app using ruby on rails, its main purpose is to upload, store, and display results from xml(files can be up to several MB) files.  After running for about 2 months I noticed that the mongrel process was using about 4GB of memory.  I did some research on debugging ruby memory leaks and could not find much. So I have two questions.

Are there any good tools that can be used to find memory leaks in Ruby/rails?

What type of coding patterns cause memory leaks in ruby?

Answer:
Memory leak is a problem in the current ruby implementation a good place to start about this is
http://whytheluckystiff.net/articles/theFullyUpturnedBin.html
Whytheluckystiff website doesn't exist anymore but you can find the original article here:
https://viewsourcecode.org/why/hacking/theFullyUpturnedBin.html
for a more specific answer on problems with long running ruby processes see
https://just.do/2007/07/18/heap-fragmentation-in-a-long-running-ruby-process/
maybe you could give passenger (mod_rails) a try
https://web.archive.org/web/20130901072209/http://nubyonrails.com/articles/ask-your-doctor-about-mod_rails


Question: How can I create a new Word document pro grammatically using Visual Studio Tools for Office?

Answer:
For a VSTO app-level add-in, you can do something like this:
```
```
Globals.ThisAddIn.Application.Documents.Add(ref objTemplate, ref missingType, ref missingType, ref missingType);
```
```
where
```
objTemplate
```
can be a template of document
See
Documents.Add Method


Question:
We're moving a solution with 20+ projects from .net 2.0 to 3.5 and at the same time moving from Visual Studio 2005 to 2008. We're also at the same time switching from MS Entlib 2.0 to 4.0.

Is there any reasons not to let the
Visual Studio wizard convert the
solution for us?

Is 3.5 fully backwards compatible
with 2.0?

Is Entlib 4.0 fully backwards compatible
with 2.0?

Edit: I might been a bit confused when I wrote this, the backwards compatability is supposed to mean; is there anything that exists in a 2.0 project that will not work/compile in 3.5

:)

//W

Answer:
I upgraded several projects from Visual Studio 2005 to 2008 with the Wizard, and they all went painless (well... except for that C++ beast. But you're talking about .NET anyway).
Keep in mind that you don't need to upgrade the .NET version. Visual Studio 2008 supports .NET 2.0, 3.0 and 3.5. However, 3.5 is backwards-compatible anyway, since it sits on the same CLR and is, more or less, just some extra libraries. And the "old" libraries stay the same.
I don't know about Entlib.
Why don't you just try and run your unit tests? :)


Question:
I have a WinForms TreeView with one main node and several sub-nodes.

How can I hide the + (plus sign) in the main node?

Answer:
Treview Property:
```
.ShowRootLines = false
```
When
```
ShowRootLines
```
is false, the Plus/Minus sign will not be shown for the root node, but will still show when necessary on child nodes.
With the Plus/Minus sign hidden, you might consider executing the
```
Expand()
```
method of the root node once the tree is populated.  That will make sure that the root node shows all first-level child nodes.
Note: There is a
```
ShowPlusMinus
```
property on the TreeView, but it works on
all
nodes.


Question:
I have a control where I have to check in which page I am, so I can set a certain variable accordingly.

string pageName = this.Page.ToString();
switch (pageName)
{
case "ASP.foo_bar_aspx": doSomething(); break;
default: doSomethingElse(); break;
}

this works fine locally and on some developmentservers, however when I put it live, It stopped working because I don't get ASP.foo_bar_aspx but _ASP.foo_bar_aspx
(notice the underscore in the live version)
Why does it act that way, Can I set it somehow?

Answer:
That seems like a really dodgy way of getting the current request. Have you tried using
```
HttpContext.Current.Request.FilePath
```
or another
```
HttpContext.Current.Request...
```
variable instead?


Question:
I have three tables, A, B, C, where A is many to one B, and B is many to one C. I'd like a list of all C's in A.

My tables are something like this: A[id, valueA, lookupB], B[id, valueB, lookupC], C[id, valueC]. I've written a query with two nested SELECTs, but I'm wondering if it's possible to do INNER JOIN with DISTINCT somehow.

SELECT valueC
FROM C
INNER JOIN
(
    SELECT DISTINCT lookupC
    FROM B INNER JOIN
    (
        SELECT DISTINCT lookupB
        FROM A
    )
    A2 ON B.id = A2.lookupB
)
B2 ON C.id = B2.lookupC

EDIT:
The tables are fairly large, A is 500k rows, B is 10k rows and C is 100 rows, so there are a lot of uneccesary info if I do a basic inner join and use DISTINCT in the end, like this:

SELECT DISTINCT valueC
FROM
C INNER JOIN B on C.id = B.lookupB
INNER JOIN A on B.id = A.lookupB

This is very, very slow (magnitudes times slower than the nested SELECT I do above.

Answer:
Is this what you mean?
```
```
SELECT DISTINCT C.valueC
FROM
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB
```
```


Question:
I am not really familiar with Maven program but I've been using Eclipse for quite a while for Unit testing, code coverage, javadoc generation, code style checking, etc. Probably, the only main thing that I didn't really like about Eclipse is the "compilation errors" that it generates when you are running Eclipse and Ant simultaneously. So I am wondering if Maven 2 does the same thing if you are running Ant task.

Lee23

Answer:
The company I currently work for has a lot of JUnit tests which are run using Maven (1.x). We've never really had any problem and any tests that fail in maven can be debugged using the remote debugger or in Eclipse on their own.
The most important thing is that you take the time and effort to set up the environment properly so that when your tests run they are using the correct directories, variables, etc. This way you shouldn't get the 'compilation errors' that you would get when running Eclipse and Ant.
Maven has the ability to run all your tests for you during the testing cycle of compilation, this should stop the need for any Ant tasks to run the tests. However, if you still need to have scripts for other tasks (generation of code, etc) then be weary of Maven's ability to generate code and not include it in the compiled binaries (jar, war), though this may well be fixed for newer versions of Maven.
At the end of the day it would be best to evaluate Maven 2 and see if it's right for you. It sounds like you're having (sarcasm)a lot of fun (/sarcasm) with Ant and Eclipse already though. :)


Question:
In Kohana/CodeIgniter, I can have a URL in this form:

http://www.name.tld/controller_name/method_name/parameter_1/parameter_2/parameter_3 ...

And then read the parameters in my controller as follows:

class MyController
{
    public function method_name($param_A, $param_B, $param_C ...)
    {
        // ... code
    }
}

How do you achieve this in the Zend Framework?

Answer:
Take a look at the Zend_Controller_Router classes:
http://framework.zend.com/manual/en/zend.controller.router.html
These will allow you to define a Zend_Controller_Router_Route which maps to your URL in the way that you need.
An example of having 4 static params for the Index action of the Index controller is:
```
```
$router = new Zend_Controller_Router_Rewrite();

$router->addRoute(
    'index',
    new Zend_Controller_Router_Route('index/index/:param1/:param2/:param3/:param4', array('controller' => 'index', 'action' => 'index'))
);

$frontController->setRouter($router);
```
```
This is added to your bootstrap after you've defined your front controller.
Once in your action, you can then use:
```
```
$this->_request->getParam('param1');
```
```
Inside your action method to access the values.
Andrew


Question:
I'm using org.w3c XML API to open an existing XML file. I'm removing some nodes , and I'm adding others instead.

The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the XML file is valid , it is very hard for a human to examine it.

Is there anyway to add indentation , or at least a newline after each node?

Answer:
I'm assuming that you're using a
```
Transformer
```
to do the actual writing (to a
```
StreamResult
```
). In which case, do this before you call
```
transform
```
:
```
```
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
```
```


Question:
In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)?
I'm looking for something similar to C#'s 'ref' keyword.

Example:

def func(x)
    x += 1
end

a = 5
func(a)  #this should be something like func(ref a)
puts a   #should read '6'

Btw. I know I could just use:

a = func(a)

Answer:
Ruby doesn't support "pass by reference" at all. Everything is an object and the references to those objects are always passed by value. Actually, in your example you are passing a copy of the reference to the
```
Fixnum
```
Object by value.
The problem with the your code is, that
```
x += 1
```
doesn't modify the passed
```
Fixnum
```
Object but instead creates a completely new and independent object.
I think, Java programmers would call
```
Fixnum
```
objects
immutable
.


Question: How can I change the color of a DataGridView border when BorderStyle = FixedSingle?

Answer:
You cannot change the border color, it is system defined.
Instead you could try turning off the border setting and then placing the DataGridView inside a Panel. Where the DataGridView is set to Dock.Fill and the Panel has a Padding of 1 pixel on all edges. Then setting the background color of the Panel will show as a border around the contained DataGridView.


Question:
I use Visual Basic and an automation interface to retrieve strings from an external application. These strings contain simple html formatting codes (<b>, <i>, etc.).
Is there any easy function in Visual Basic for Word to insert these strings into a word document and convert the html formatting codes to word formatting?

Answer:
AFAIK there is no builtin function to do that in VBA. You will have to write it yourself, which would be not too difficult if you restirct it to parse
```
<b>, <i>, <a> and <p>,
```
for example. All other tags would have to be ignored.


Question:
I've been reading Skype4Java (java api for skype) and noticed they use jni to access the skype client.

intuitively I'd assume that there already is a standard library in java that has an  OS-sensitive jni implementation to access other processes. I set up to look for one, but couldn't find it.

Is there such a library? if not, is there a best practice to access another process in the os, not necessarily a skype client?

Answer: From Java 1.4 onwards you can use memory mapped files to exchange arbitrary information with another process. See java.nio.MappedByteBuffer for details.


Question:
Imagine the following Ruby Module:

module Foo
  def inst_method
    puts "Called Foo.inst_method"
  end
  def self.class_method
    puts "Called Foo.class_method"
  end
end

Obviously Foo.class_method can be called without any class instances. However, what's happening to Foo.inst_method? Is it possible to call Foo.inst_method without previously including/extending a class?

Disclaimer: The question isn't focused on solving a real problem. I'm just trying to improve my understanding of the Ruby object system.

Answer:
My answer would be : "no you can't call module instance methods without first extending or including that module in a class"
now knowing ruby and all the meta programming trickery it contains there probably
is
a way to call it but it would be outside the intended use of modules
```
```
module Tester
  def inst_meth
    puts "test inst meth\n"
  end

  def self.meth
    puts "test self meth\n"
  end
end

begin
  Tester.meth
rescue;
  puts $!
end
begin
  Tester.inst_meth
rescue
  puts $!
end
begin
  Tester.new.inst_meth
rescue
  puts $!
end
begin
  extend Tester
  inst_meth
rescue
  puts $!
end
begin
  include Tester
  inst_meth
rescue
  puts $!
end
```
```
gives
```
```
>ruby test.rb
test self meth
undefined method `inst_meth' for Tester:Module
undefined method `new' for Tester:Module
 test inst meth
 test inst meth
```
```


Question: What's the difference between toolkits and frameworks? Do you know a good comparison?

Answer:
The names say it all really, a toolkit is a set of tools that you can use however you wish. A framework is an empty frame that you can fill in to form your application. The line between them is blurry though a framework contains tools, and a toolkit sometimes forces you to perform actions in a specific sequence.
I wouldn't know of a generic comparison, i guess it depends on the toolkits and frameworks themselves.


Question:
I recently had to rename a table (and a column and FK/PK contraints) in SQL Server 2000 without losing an data. There did not seem to be an obvious DDL T-SQL statements for performing this action, so I used sp_rename to directly fiddle with object names.

Was this the only solution to the problem? (other, than give the table the correct name in the first place - doh!)

Answer:
sp_rename is the correct way to do it.
```
```
EXEC sp_rename 'Old_TableName', 'New_TableName'
```
```


Question:
I need to get the Class of an object at runtime.

For an non-abstract class I could do something like:

public class MyNoneAbstract{
    public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass();

But for an abstract class this does NOT work (always gives me Object)

public abstract class MyAbstract{
    public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass();

This code will be running in JavaME environments.

Answer:
You just need
```
```
MyAbstract.class
```
```
That expression returns the Class object representing MyAbstract.


Question:
Should methods in a Java interface be declared with or without the public access modifier?

Technically it doesn't matter, of course. A class method that implements an interface is always public. But what is a better convention?

Java itself is not consistent in this. See for instance Collection vs. Comparable, or Future vs. ScriptEngine.

Answer:
I always write what I would use if there was no interface and I was writing a direct implementation, i.e., I would use
```
public
```
.


Question:
I have two overloads of a c++ function and I would like to set a breakpoint on one of them:

0:000> bu myexe!displayerror
Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *)
Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT)
Ambiguous symbol error at 'myexe!displayerror'

Heck I would be fine with setting breakpoints on all overloads, but can't seem to figure out how:

0:000> bu myexe!displayerror*
Matched: 00000000`ff3c6100 myexe!displayError (int, HRESULT, wchar_t *)
Matched: 00000000`ff3c60d0 myexe!displayError (int, HRESULT)
Ambiguous symbol error at 'myexe!displayerror*'

Answer:
Try:
```
```
bu 0xff3c6100
```
```
If I remember right, WinDbg allows setting breakpoints by address too.


Question:
Consider the following subversion directory structure

/dir1/file.txt

/dir2/file.txt

I want to move the file.txt in dir1 to replace the same file in dir2 and ensure that the history for the dir1 file is maintained. I don't care about the history of original dir2 file.

Is this possible using subversion commands and not hacking the backend?

Answer:
Firstly you should never consider hacking the backend - it negates the point of using SVN in the first place.
I don't see why you couldn't just do
```
```
svn rm /dir2/file.txt
svn mv /dir1/file.txt /dir2/file.txt
```
```
the history of the file will follow it after the move.


Question:
I'm trying to learn scheme via SICP. Exercise 1.3 reads as follow: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Please comment on how I can improve my solution.

(define (big x y)
    (if (> x y) x y))

(define (p a b c)
    (cond ((> a b) (+ (square a) (square (big b c))))
          (else (+ (square b) (square (big a c))))))

Answer:
Looks ok to me, is there anything specific you want to improve on?
You could do something like:
```
```
(define (max2 . l)
  (lambda ()
    (let ((a (apply max l)))
      (values a (apply max (remv a l))))))

(define (q a b c)
  (call-with-values (max2 a b c)
    (lambda (a b)
      (+ (* a a) (* b b)))))

(define (skip-min . l)
  (lambda ()
    (apply values (remv (apply min l) l))))

(define (p a b c)
  (call-with-values (skip-min a b c)
    (lambda (a b)
      (+ (* a a) (* b b)))))
```
```
And this (proc p) can be easily converted to handle any number of arguments.


Question:
I noticed some code of a colleague today that initialized class variables in the initialization.  However it was causing a warning, he says because of the order they are in.  My question is why is it better to do variable initialization where it currently is and not within the curly brackets?

DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent )
    : QGraphicsScene( screenRect, parent ),
    myParent( parent ),
    slideUndoImageCurrentIndex(-1),
    nextGroupID(0),
    m_undoInProgress(false),
    m_deleteItemOnNextUndo(0)
    line(0),
    path(0)
{
    /* Setup default brush for background */
    scDetail->bgBrush.setStyle(Qt::SolidPattern);
    scDetail->bgBrush.setColor(Qt::white);
    setBackgroundBrush(scDetail->bgBrush);

}

Answer:
It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors.
You can't accidentally assign a value twice in the initialiser list.
The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars).
Reference types and
```
const
```
members must be initialised in the initialiser list, because you can't assign to a reference or to a
```
const
```
member.


Question:
I have a project using GWT and it displays data in a table.

I need a Table for GWT that supports:

sorting by particular column

scrolling the data, while the header is immobile

filtering rows for data searched in the table

The project is being created for internal purpose of the company, so I look for a solution that does not require commercial licensing for such uses.

Answer:
Here is a table supporting sorting and filtering :
http://code.google.com/p/gwt-advanced-table/
Google itself is working on it. Look at this example in the incubator which supports multi-column sorting and fixed header but unfortunately no filtering :
http://code.google.com/p/google-web-toolkit-incubator/wiki/ScrollTable
Other grids and tables are available in the incubator at this address :
http://code.google.com/docreader/#p=google-web-toolkit-incubator&s=google-web-toolkit-incubator&t=Tables
Ext GWT proposes a very nice table, but it is not free (in your case) :
http://extjs.com/products/gxt/


Question:
You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem.  Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation.

So an example Perl problem:

A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file.

The question, for Perl developers: What is your best way to accomplish this?

Answer:
I write a subroutine that reads a directory with
```
readdir
```
, throws out the "." and ".." directories, recurses if it finds a new directory, and examines the files for what I'm looking for (in your case, you'll want to use
```
utime
```
or
```
stat
```
).  By time the recursion is done, every file should have been examined.
I think all the functions you'd need for this script are described briefly here:
http://www.cs.cf.ac.uk/Dave/PERL/node70.html
The semantics of input and output are a fairly trivial exercise which I'll leave to you.


Question: I'm using a local artifactory to proxy the request, but the build and test phases are still a bit slow. It's not the actual compile and tests that are slow, it's the "warmup" of the maven2 framework. Any ideas?

Answer:
I don't know what version of Maven you are using, I assume 2, but I will give what I use for Maven 1.x to speed up and make things build a tiny bit quicker.
These will fork the junit tests into a new process (also helps when you use environment variables in tests etc and gives the tests a little more memory.
```
```
-Dmaven.junit.fork=true
-Dmaven.junit.jvmargs=-Xmx512m
```
```
This forks the compilation which might speed things up for you
```
```
-Dmaven.compile.fork=true
```
```
I hope this can help a little, try it out.
Also refer to
get more speed with your maven2 build
.


Question:
I know there is already a question about this but my issue is more oriented to remote scenarios.

With net start/stop you can specify a /y parameter to bounce users off current sessions but you cannot start/stop remotely.

With sc you can start/stop remotely but if the SQLServer instance is being used it won't let you stop the service (with a "[SC] ControlService FAILED 1051: A stop control has been sent to a service that other running services are dependent on." message)

So my question is: what's the best way of kicking out users stopping the SqlServer service remotely?

Answer:
I think the /y just answers Yes to the "Are you sure?" prompt. I'd think that sc could be used as well, though it may time out waiting for the service to stop if there's a lot of inflight transactions. Does it give you any specifics of why it can't stop?
Here's a couple of other methods to stop a remote SQL instance. Except for SHUTDOWN WITH NOWAIT, I'd recommend any of them.
psexec
will let you run net stop remotely.
There's also the
SQL SHUTDOWN
command - you can issue that WITH NOWAIT to avoid waiting for current transactions to finish and checkpointing, which will make shutdown faster (but subsequent startup slower, and could lead to lost data).
Or you could use either
Configuration Manager
or
Management Studio
to stop a remote instance.
Edit: The error is
pretty self explanatory
. It means you must stop dependent services first. Sql Agent is probably at least one of them. Checking Admin Tools->Services will show you the rest.


Question:
There are truckloads of counters available in perfmon for ASP.NET.  What are the best (I am thinking of choosing 5-10) that will be the best to monitor in our test environment so that we can feed back to developers.

I am thinking of things like request time, request queue length, active sessions etc.

Answer:
For a normal (not performance/stress testing) you would be OK with the following:
Request Bytes Out Total
(very important especially for web (not intranet) applications)
Requests Failed
Requests/Sec
Errors During Execution
Errors Unhandled During Execution
Session SQL Server Connections Total
State Server Sessions Active
For the performance testing you would probably want things like:
% CPU Utilization
(make sure you're checking for very low CPU utilisation as well as it might indicate that something is dead)
Requests Queued
Output Cache Hits


Question:
How can I check if a given string is a valid URL address?

My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web.

Answer:
The post
Getting parts of a URL (Regex)
discusses parsing a URL to identify its various components. If you want to check if a URL is well-formed, it should be sufficient for your needs.
If you need to check if it's actually valid, you'll eventually have to try to access whatever's on the other end.
In general, though, you'd probably be better off using a function that's supplied to you by your framework or another library. Many platforms include functions that parse URLs. For example, there's Python's
urlparse
module, and in .NET you could use the
System.Uri class's constructor
as a means of validating the URL.


Question:
I would like to allow the logged user to edit MediaWiki/Common.css without adding them to the sysop group.

I understand that this will allow user to change it to harful ways but it is a closed wiki so that is not a problem.

Any solution is acceptable even changing php code :)

Answer:
Create a new group, add give it "editinterface" privilege. In LocalSettings.php it's done like this:
```
```
$wgGroupPermissions['mynewgroup']['editinterface'] = true;
```
```
Then add the user to you new group.
Or if you want to give that right to all logged-in users, do it like this:
```
```
$wgGroupPermissions['user']['editinterface'] = true;
// user is the default group for all logged-in users
```
```
For details see
MediaWiki manual
.


Question:
Ant has a nice way to select groups of files, most handily using ** to indicate a directory tree. E.g.

**/CVS/*            # All files immediately under a CVS directory.
mydir/mysubdir/**   # All files recursively under mysubdir

More examples can be seen here:

http://ant.apache.org/manual/dirtasks.html

How would you implement this in python, so that you could do something like:

files = get_files("**/CVS/*")
for file in files:
    print file

=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries

Answer:
```
os.walk
```
is your friend. Look at the example in the Python manual
(
https://docs.python.org/2/library/os.html#os.walk
) and try to build something from that.
To match "
```
**/CVS/*
```
" against a file name you get, you can do something like this:
```
```
def match(pattern, filename):
    if pattern.startswith("**"):
        return fnmatch.fnmatch(file, pattern[1:])
    else:
        return fnmatch.fnmatch(file, pattern)
```
```
In
```
fnmatch.fnmatch
```
, "*" matches anything (including slashes).


Question: What is the best MemCache solution for ASP.NET applications running in a windows server environment? Why?

Answer:
My sentiments exactly -
My Question
From what I've gathered,
memcacheddotnet
is the best free options,
scaleout
if you want to pay


Question:
What are the main/best Maven repositories to use that will include the majority of your open source Java package dependencies.

Also in what order should these be included? Does it matter?

Answer:
This is the current setup in the project we are building:
MavenCentral
ObjectWeb
JBoss Maven2
and some snapshots (see below)
```
```
<repository>
    <id>MavenCentral</id>
    <name>Maven repository</name>
    <url>http://repo1.maven.org/maven2</url>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>
<repository>
    <id>objectweb</id>
    <name>Objectweb repository</name>
    <url>http://maven.objectweb.org/maven2</url>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>
<repository>
    <id>jboss</id>
    <name>JBoss Maven2 repository</name>
    <url>http://repository.jboss.com/maven2/</url>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
    <releases>
        <enabled>true</enabled>
    </releases>
</repository>
<repository>
    <id>glassfish</id>
    <name>Glassfish repository</name>
    <url>http://download.java.net/maven/1</url>
    <layout>legacy</layout>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>
<repository>
    <id>apache.snapshots</id>
    <name>Apache Snapshot Repository</name>
    <url>
        http://people.apache.org/repo/m2-snapshot-repository
    </url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>
<repository>
    <id>ops4j.repository</id>
    <name>OPS4J Repository</name>
    <url>http://repository.ops4j.org/maven2</url>
    <releases>
        <enabled>true</enabled>
    </releases>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>
<repository>
    <id>Codehaus Snapshots</id>
    <url>http://snapshots.repository.codehaus.org/</url>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
    <releases>
        <enabled>false</enabled>
    </releases>
</repository>
```
```


Question:
I need to control the data type when reading XML data in SAS. The XML data are written and accessed using the XML libname engine in SAS.

SAS seems to guess the data type based on the contents of a column: If I write "20081002" to my XML data in a character column, it will be read back in as a numerical variable.

An example:

filename my_xml '/tmp/my.xml'; * Yes, I use SAS on Unix *;
libname my_xml XML;

data my_xml.data_type_test;
  text_char="This is obviously text";
  date_char="20081002";
  num_char="42";
  genuine_num=42;
run;

proc copy inlib=my_xml outlib=WORK;
run;

libname my_xml;
filename my_xml CLEAR;

Only the last column is defined as numerical data type in the XML data, but when I copy it into my WORK library, only the column text_char is character. The other 3 are now numeric.

How can I control the data type when reading XML data in SAS?

Answer:
I think you need to define some xml specific options whith your libname XML statement for export go:
```
```
libname my_xml_out XML XMLMETA=SCHEMADATA;
```
```
To include the data schema. Also, you might want to save the XML schema to a separate file for later import:
```
```
libname my_xml_in XML XMLSCHEMA='external-file'
```
```
after you exported the schema using
```
XMLMETA=SCHEMA
```
of course.
I think
this is the documentation you need
.
Apart from that liberal use of format statements on original dataset creation is recommended.


Question:
Is it possible to unlisten on a socket after you have called listen(fd, backlog)?

Edit: My mistake for not making myself clear. I'd like to be able to temporarily unlisten on the socket. Calling close() will leave the socket in the M2LS state and prevent me from reopening it (or worse, some nefarious program could bind to that socket)

Temporarily unlistening would be a way (maybe not the best way) to signal to an upstream load balancer that this app couldn't accept any more requests for the moment

Answer:
Close it. As I recall;
```
```
close(fd);
```
```


Question:
I would like to draw a diagram in HTML. The positioning structure looks like this:

<div id='hostDiv'>
  <div id='backgroundDiv'>
    ... drawing the background ...
  </div>
  <div id='foregroundDiv' style='position: absolute;'>
    ... drawing the foreground ...
  </div>
</div>

The foreground contains a Table element that is dynamically populated with text, hence the row heights might alter depending on the amount of text going into a cell.
How can I predict the final height of the Table element in the foregroun? I need this information to set the correct height of the background. Is there a way to pre-render the Table from Javascript and read out its height? Or some other trick?

PS. The size of the hostDiv may vary as the browser resizes.

Answer:
There isn't any way to predict the height without actually rendering it in the target browser.
Once you do that, you can use (for example)
jQuery
to get the height of the element:
```
```
var height = $('#myTable').height();
```
```


Question:
Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests?

The full story:
I would like to help my clients do acceptance testing by providing them with a suite of tests that use some smarts to create random (or at least pseudo-random) values for the database. One of the issues with my Selenium IDE tests at the moment is that they have predefined values - which makes some types of testing problematic.

Answer:
First off, the Selenium IDE is rather limited, you should consider switching to Selenium RC, which can be driven by Java or Perl or Ruby or some other languages.
Using just Selenium IDE, you can embed JavaScript expressions to derive command parameters.
You should be able to type a random number into a text field, for example:
```
```
type fieldName javascript{Math.floor(Math.random()*11)}
```
```
Update:
You can define helper functions in a file called "user-extensions.js". See the
Selenium Reference
.


Question:
Assuming I have an open source web server or proxy I can enhance, let's say apache or squid.

Is there a way to determine the time each client spends on a web page?

HTTP is of course stateless, so it's not trivial, but maybe someone has an idea on how to approach this problem?

Answer:
Not without having some javascript constantly hit your server on the client side and then checking when it stops (but of course that assumes the user has javascript enabled). There are also various (ugly) ways to detect windows being closed with javascript, but of course these won't always trigger. eg. browser crash.
I sort of wonder why you want this anyway. What if a person looks at the web page for 3 seconds, gets distracted by another tab/window but leaves your page open for 2 hours? The answer you get is 2 hours, the answer you (probably) want is 3 seconds.


Question:
I have a Nant build file which executes NUnit after compiling the dll's. I am executing the NAnt build file with a  task in CruiseControl. So NAnt is running the tests not CruiseControl.

How do I configure it so that the CruiseControl web dashboard can be used to view the NUnit output ?

This fixed it:

<publishers>
    <merge>
        <files>
                 <file>build\*.test-result.xml</file>
        </files>
    </merge>
    <xmllogger />
 </publishers>

Answer:
You want to use the merge capabilities of CruiseControl to grab your NUnit XML output.  This is the situation my company has going, and it seems to work fairly well.  Here is a config snippet (This goes in the <publishers> element in CCNet.config):
```
```
<merge>
     <files>
         <file><path to XML output>\*.xml</file>
     </files>
 </merge>
```
```
Hope this works for you.


Question:
There seem to many ways to skin this particular cat - but which is the best and easiest to implement.  It would seem that the ASP.net Membership Provider is the one that will save more time, so my questions are:

What are the pros/cons of Membership?

How do you integrate the auto generated user db with your own custom made db? e.g customers/orders/products db.  (We are talking MS Sql here BTW)

Where can I find a good tutorial thats up do date?

Many thanks.

Answer:
Membership is lightweight and easy to set up.  You can also use the various providers to use Active Directory or some other member location.
You shouldn't need to integrate the databases, you can use one to authenticate users and then as long as they are valid, go query another database for the data.  This is a good way to keep information seperate for security reasons.
For a good tutorial, I'd suggest:
http://msdn.microsoft.com/en-us/library/yh26yfzy.aspx
And if you want to create your own membership provider:
http://www.asp.net/learn/videos/video-189.aspx


Question:
I've got two arrays of the same size.  I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other.

Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this.  I don't see any array functions for this purpose, but maybe I missed something?  Is there a simple way to this along these lines?

$mapped_array = mapkeys($array_with_keys, $array_with_values);

Answer:
See
```
array_combine()
```
on PHP.net.


Question:
My Outlook add-in handles NewInspector event of the Inspector object, in order to display a custom form for the mail item.

I can get EntryID of the CurrentItem of the Inspector object which is passed as a parameter of the event. But, the problem is that the EntryID of the current mail item is shorter than it should be, and is unknown. I know every EntryID of every mail item that was created, and I can see that specific mail item has a wrong EntryID.

What is wrong?

Answer:
The idea is to remember every EntryID of the MailItem that was created by an add-in, so that it can be treated differently later. Problem was that EntryID of the item opened by an Inspector was the short one, and not in the list of remembered ids, although it should be.
Few lines of code where I was creating mail item were:
```
```
item.Save();
item.Move(some_folder);
items_list.Add(item.EntryID);
```
```
Folder 'some_folder' is inside of external non-default PST, so mail item gets new EntryID. I changed those lines to:
```
```
item.Save();
item = (Outlook.MailItem)item.Move(some_folder);
items_list.Add(item.EntryID);
```
```
Now, item has a new EntryID, which can be found later.


Question: I'm building a Thunderbird extension and would like to add my own header to all outgoing email (e.g. <myext-version: 1.0> ). Any idea how to do this? I know it's possible since this is done in the OpenPGP Enigmail extension. Thanks!

Answer:
I don't know the answer but just some thoughts...
I think thunderbird extensions are usually just xul and js.  From the enigmail site:
Unlike most Mozilla AddOns, Enigmail
  contains platform dependent parts: it
  depends on the CPU, the compiler,
  libraries of the operating system and
  the email application it shall
  integrate into.
Looking at the Enigmail source code,
this might be the relevant section
(written in c++)
So you might need to either translate what they've done into js(!) or keep looking for a different example.
Here's another link that might be helpful


Question:
We have the usual web.xml for our web application which includes some jsp and jsp tag files.  I want to switch to using pre-compiled jsp's.  I have the pre-compilation happening in the build ok, and it generates the web.xml fragment and now I want to merge the fragment into the main web.xml.

Is there an include type directive for web.xml that will let me include the fragment.

Ideally I will leave things as is for DEV- as its useful to change jsp's on the fly and see the changes immediately but then for UAT/PROD, the jsp's will be pre-compiled and thus work faster.

Answer:
Doh - there is an option on the jasper2 task to auto-merge the fragment into the main web.xml -
addWebXmlMappings
```
```
<jasper2
         validateXml="false"
         uriroot="${web.dir}"
         addWebXmlMappings="true"
         webXmlFragment="${web.dir}/WEB-INF/classes/jasper_generated_web.xml"
         outputDir="${web.dir}/WEB-INF/jsp-src" />
```
```
I wonder how good the merge is...
Annoyingly you need to generate the fragment still, even though its not needed after this task.


Question:
in web.xml i set my welcome file to a jsp within web.xml

<welcome-file>WEB-INF/index.jsp</welcome-file>

inside index.jsp i then forward on to a servlet

<% response.sendRedirect(response.encodeRedirectURL("myServlet/")); %>

however the application tries to find the servlet at the following path

applicationName/WEB-INF/myServlet

the problem is that web-inf should not be in the path. If i move index.jsp out of web-inf then the problem goes but is there another way i can get around this?

Answer:
Doh - there is an option on the jasper2 task to auto-merge the fragment into the main web.xml -
addWebXmlMappings
```
```
<jasper2
         validateXml="false"
         uriroot="${web.dir}"
         addWebXmlMappings="true"
         webXmlFragment="${web.dir}/WEB-INF/classes/jasper_generated_web.xml"
         outputDir="${web.dir}/WEB-INF/jsp-src" />
```
```
I wonder how good the merge is...
Annoyingly you need to generate the fragment still, even though its not needed after this task.


Question:
I use serialize in one ActiveRecord model to serialize an Array of simple Hashes into a text database field. I even use the second parameter to coerce deserialization into Arrays.

class Shop < ActiveRecord::Base
  serialize : recipients, Array
end

It seems to work fine but, after a few requests, the content of recipients turns to HashOfIndifferentAccess hashes instead of arrays. This only happens after a few reloads of the models and I haven't been able to reproduce it in tests or the console, only in production environment.

Answer:
This seems like something you should be able to reproduce locally with enough testing.
Look through your production db and logs and attempt to use the same data in your local tests.
The hashwithindifferentaccess is coming from the controller. Perhaps you are taking data straight from the controller and not massaging it at all.
Create a gist of your page, controller, and model saving code, and update this question.
Depending on how deeply nested your hash, you can convert a HWIA hash to a regular one before saving.
Shouldn't be too hard to debug and resolve.


Question: What's a good method of programatically generating etag for web pages, and is this practice recommended? Some sites recommend turning etags off, others recommend producing them manually, and some recommend leaving the default settings active - what's the best way here?

Answer:
Well ETags make sense when you rely heavily on caching. They are a great indicator for the state of a resource (e.g. a URL).
For example, let's say you use an
ajax
request to pull the latest comments of a user and you want to know if there are any new comments. Changing the ETag to
alert
your application of new content is a less expensive way to check on that.
Because if the ETag is the same, you can keep your cache, but otherwise rebuild it.
ETags also make a lot of sense with RESTful APIs.
As for generating it, looking at the
spec
, I think you can do almost anything you want. A timestamp, a hash, whatever makes sense to you/your application.


Question:
I'm looking for an elegant, high performance solution to the following problem.

There are 256 linked lists.

Each list contains the same types of object that among other things holds a whole number that is used to define a sort order.

All numbers across all lists are unique

Each individual list is sorted in ascending order by these numbers

How would you create a single ascending ordered list from all the objects from the 256 original linked lists? I'd prefer not to brute force it, and have a few other ideas, but this seems like one of those problems that there's a standard, optimal solution for.

Answer:
You could use a priority queue that holds the “topmost” item of each of the 256 linked lists. This “topmost” item is the one that is scheduled to be inserted into the resulting list. This way, you can just take the smallest element from the priority queue, insert it into your resulting queue, and insert its next element into the priority queue:
```
```
# Preprocessing:
result = list.new()
queue = priority_queue.new()

foreach (list in lists):
    queue.push(list.first())

# Main loop:
while (not queue.empty()):
    node = queue.pop()
    result.insert(node)
    if (node.next() != null):
        queue.push(node.next())
```
```