q:
Please share how you do version control for Lotus Notes/Domino development.

I want to put in our SVN repository all the scripts, views, custom forms, script libraries, etc.

Semi-automated methods are accepted as well (i.e. if I find a way to get all the event scripts for a form in one file, and to be able to place it back in Notes Designer as a whole file).

[A]
The short answer is that you aren't going to be able to do this reliably in an automated or semi automated way.  If DXL had full fidelity and full round-trip capability then you would be able to store DXL exports of the design elements in SVN, but there are places where DXL isn't good enough.
The only real version control you are gong to get is via propitiatory third part vendors like
TeamStudio's CIAO
product.
Update:
Some people have reported success in exporting elements in an encoded binary format that retains full fidelity on import.  This makes round tripping for the purpose of version control possible.


q: I am making a post from a .NET console app to a .NET web service.  I know that the timeout on the server side is 20 min, but if my client takes more than 100 seconds to post my data to that service then I get a timeout exception.  How would I tell my client to wait the available 20 min to timeout?

[A]
on the client side, your webservice object has a timeout value. It should be pretty easy to set by going:
```
```
myServiceInstance.Timeout = 1200000
```
```
for 20 minutes

s: huggingface

c: devops

d: intermediate


q:
Let's say I have an html form.  Each input/select/textarea will have a corresponding <label> with the for attribute set to the id of it's companion. In this case, I know that each input will only have a single label.

Given an input element in javascript — via an onkeyup event, for example — what's the best way to find it's associated label?

[A]
Earlier...
```
```
var labels = document.getElementsByTagName("LABEL"),
    lookup = {},
    i, label;

for (i = 0; i < labels.length; i++) {
    label = labels[i];
    if (document.getElementById(label.htmlFor)) {
        lookup[label.htmlFor] = label;
    }
}
```
```
Later...
```
```
var myLabel = lookup[myInput.id];
```
```
Snarky comment: Yes, you can also do it with JQuery. :-)


q:
Is there a way to determine if the loop is iterating for the last time. My code looks something like this:

int[] array = {1, 2, 3...};
StringBuilder builder = new StringBuilder();

for(int i : array)
{
    builder.append("" + i);
    if(!lastiteration)
        builder.append(",");
}

Now the thing is I don't want to append the comma in the last iteration. Now is there a way to determine if it is the last iteration or am I stuck with the for loop or using an external counter to keep track.

[A]
It might be easier to always append. And then, when you're done with your loop, just remove the final character. Tons less conditionals that way too.
You can use
```
StringBuilder
```
's
```
deleteCharAt(int index)
```
with index being
```
length() - 1
```


q:
Up till now all my programming experience has been desktop development (mostly C/C++ with OpenGL/DirectX) but I'm interested in trying my hand at some web dev.

The two directions I'm considering are Ruby on Rails and ASP.net.

Which is most widely used?

Which would be a more marketable skill to have?

Thanks!

[A]
Learning Ruby will help you learn a different way of thinking about programming. It will help you become a better programmer, even if you determine that it's not a language for you. The same applies to several other languages (including Python). There are fewer job opportunities for Ruby developers.
ASP.Net is a fairly pedestrian way to develop fairly pedestrian webapps that don't really challenge how you think as a programmer. Job and consulting opportunities are more common.
From this point, it's your call. I chose Ruby six years ago.


q: I have a data acquisition program written in C++ (Visual Studio 6.0).  Some clients would like to control the software from their own custom software or LabView.  I would like to come up with a simple API with a dll I can distribute to them and would like some tips on how to get started.  This is going to be VERY basic, maybe 4 or 5 commands.  My DAQ program will still be running in its own window on the same machine, I would just like to set it up to be controlled from another program.

[A]
You are on the right track with a DLL.  The real trick, it sounds like, will be deciding what sort of inter-process communication (IPC) you want to use.  Options are: sockets, pipes, shared memory, synchronization objects (events, etc.), files, registry, etc.
Once you decide that, then implement a listener within your executable to wait for incoming IPC messages from whatever software is using your DLL.
As far as the API is concerned, you can keep it simple just like you were wanting.  Have the DLL expose your 4 or 5 functions (make sure you only use native data types, like char* and long, to avoid module boundary issues), and then those will use your IPC mechanism to communicate with your executing app.


q:
I need to be able to store a date (year/month/day) with no time component. It's an abstract concept of a date, such as a birthday - I need to represent a date in the year and not a particular instant in time.

I am using Java to parse the date from some input text, and need to store in a MySQL database. No matter what timezone the database, application, or any client is in, they should all see the same year/month/day.

My application will run on a machine with a different system timezone from the database server, and I don't have control over either. Does anyone have an elegant solution for ensuring I store the date correctly?

I can think of these solutions, neither of which seems very nice:

Query my MySQL connection for its timezone and parse the input date in that timezone

Process the date entirely as a string yyyy-MM-dd

[A]
You could zero out all time/timezone stuff:
```
```
public static Date truncateDate(Date date)
    {
        GregorianCalendar cal = getGregorianCalendar();
        cal.set(Calendar.ZONE_OFFSET, 0); // UTC
        cal.set(Calendar.DST_OFFSET, 0); // We don't want DST to get in the way.

        cal.setTime(date);
        cal.set(Calendar.MILLISECOND, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.AM_PM, Calendar.AM);

        return cal.getTime();
    }
```
```


q: I have googled quite a bit and I cannot find the answer. So how many characters can be stored in a Windows Installer property value. If you give an answer can you provide the source of the answer?

[A]
The MSDN documentation isn't very clear on this, but it does provide some hints.  For example, this article mentions that property values may be written to the registry, which means that registry value limitations apply:
http://msdn.microsoft.com/en-us/library/aa372432%28VS.85%29.aspx
Here is an article detailing registry value limitations:
http://support.microsoft.com/kb/256986
So at a maximum, I'd use the registry value limitations as a guide (and still try to stay well below that).


q:
When i do

wnd = CreateWindow("EDIT", 0,
    WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE |
    ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN,
    x, y, w, h,
    parentWnd,
    NULL, NULL, NULL);

everything is fine, however if i remove the WS_VSCROLL and WS_HSCROLL then do the below, i do not get them thus have incorrect window. Why?
Not only do i get an incorrect window it is unusable if both WS_VSCROLL and WS_HSCROLL are missing

style = WS_CHILD | WS_VISIBLE | WS_VSCROLL | WS_HSCROLL | ES_MULTILINE |
    ES_AUTOVSCROLL | ES_AUTOHSCROLL | ES_WANTRETURN;
SetWindowLong(wnd, GWL_STYLE, style);

[A]
Some control styles cannot be changed after window creation. The ES_AUTOHSCROLL style (which essentially controls word wrapping) is one of them; this is stated (somewhat indirectly) by the MSDN section on
Edit Control Styles
. You can set the bits using SetWindowLong(), but the control will either ignore them or behave erratically.
The only way to do this cleanly is to recreate the edit control using the required styles. This is actually what Notepad does when you toggle the "Word Wrap" setting.


q:
Is it possible to use the __unused attribute macro on Objective-C object method parameters? I've tried placing it in various positions around the parameter declaration but it either causes a compilation error or seems to be ignored (i.e., the compiler still generates unused parameter warnings when compiling with -Wall -Wextra).

Has anyone been able to do use this? Is it just unsupported with Objective-C? For reference, I'm currently using Apple's build of GCC 4.0.1.

[A]
I can compile the following just fine:
```
```
- (NSString *) test:(__unused NSString *)test {
    return nil;
}
```
```
Edit: Actually, that may not be strictly an arch thing:
```
```
Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror
Phoenix-VI:CouchPusher louis$ cc -c Pusher.m -Wall -Werror  -Wunused-parameter
cc1obj: warnings being treated as errors
Pusher.m:40: warning: unused parameter ‘test’
Phoenix-VI:CouchPusher louis$
```
```
So -Wall does not include not include -Wunused-parameter....


q:
Another angle:
how do I browse all the XUL for a given chrome path, e.g.

http://kb.mozillazine.org/Dev_:_Firefox_Chrome_URLs has a listing but seems to be out of date.

[A]
Mozilla
```
chrome://
```
URLs
refer to actual files located in a .jar file in some fairly well-defined places.
The main browser (chrome://browser/content/...) itself:
```
```
{where you installed Firefox}/chrome/browser.jar
```
```
Firefox add-ons:
```
```
{your profile directory}/extensions/{extension id}/chrome/content/...
```
```
where
```
{your profile directory}
```
, on Windows XP at least, is
```
```
c:\Documents and Settings\{your username}\Application Data\Mozilla\Firefox\Profiles\{your profile name, usually ends in .default}
```
```


q:
I have an input String say Please go to http://stackoverflow.com. The url part of the String is detected and an anchor <a href=""></a> is automatically added by many browser/IDE/applications. So it becomes Please go to <a href='http://stackoverflow.com'>http://stackoverflow.com</a>.

I need to do the same using Java.

[A]
You could do something like this (adjust the regex to suit your needs):
```
```
String originalString = "Please go to http://www.stackoverflow.com";
String newString = originalString.replaceAll("http://.+?(com|net|org)/{0,1}", "$0");
```
```


q: Is there a way in FreeBSD to (being root) run a command as unprivileged user, like nobody? Kind of like reverse of sudo. Oh and considering that 'nobody' has /usr/sbin/nologin as shell - so su is not an option.

[A]
sudo will allow you to run a command as another user.
```
```
sudo -u nobody <command>
```
```
will run  as nobody, even if their login shell is not available.


q:
In Vim I can :set wrapscan so that when I do an incremental search, the cursor jumps to the first match whether the first match is above or below the cursor.

In Emacs, if I start a search via C-s, the search fails saying Failing I-search if the first match is above the cursor.  If I hit C-s again it then wraps the search, saying Wrapped I-search.  How do I wrap and jump the cursor by default as in Vim, without having to C-s a second time?

[A]
The easiest way to do this is to use the following defadvice:
```
```
(defadvice isearch-repeat (after isearch-no-fail activate)
  (unless isearch-success
    (ad-disable-advice 'isearch-repeat 'after 'isearch-no-fail)
    (ad-activate 'isearch-repeat)
    (isearch-repeat (if isearch-forward 'forward))
    (ad-enable-advice 'isearch-repeat 'after 'isearch-no-fail)
    (ad-activate 'isearch-repeat)))
```
```
When Isearch fails, it immediately tries again with wrapping. Note that it is important to temporarily disable this defadvice to prevent an infinite loop when there are no matches.


q:
We've got a WinForms app written in C# that has a very custom GUI.  The user is not allowed to run any other applications and the user cannot go into the OS (WinXP Pro) at all.  We're planning on allowing the user to connect to available wireless networks. We're going to have to create a configuration screen that displays available networks (by SSID) and allows the user to connect.  While connected we want to display signal strength.

Are there any existing components that provide this capability?  I haven't found anything but this.

I can set the TCP/IP settings using WMI, but it's the wireless stuff that I need a direction on.

Many thanks!

Matt

[A]
Managed Wifi API
should work.
This might not be ideal - you have XP, which is good, but you would have to deploy a hotfix.  I'd go for it, because all the wifi code I've dealt with (for the Compact Framework) is hideous.  This code is as simple as could be.
Their sample code doesn't include reading the signal strength, though, and I'm not sure if the Native wifi API provides that.  I have written C# code that gets the wireless signal strength, but it did this by PInvoking into a manufacturer-specific DLL available only on their devices.  It may be that you'll have to do something similar to get the wireless strength from your PC's wireless card (and that may be why that functionality is not available in an all-purpose API).


q:
I need to know how to return a default row if no rows exist in a table. What would be the best way to do this? I'm only returning a single column from this particular table to get its value.

Edit: This would be SQL Server.

[A]
Do you want to return a full row?  Does the default row need to have default values or can it be an empty row?  Do you want the default row to have the same column structure as the table in question?
Depending on your requirements, you might do something like this:
1)  run the query and put results in a temp table (or table variable)
2)  check to see if the temp table has results
3)  if not, return an empty row by performing a select statement similar to this (in SQL Server):
```
```
select '' as columnA, '' as columnB, '' as columnC from #tempTable
```
```
Where columnA, columnB and columnC are your actual column names.


q: I understand that BigDecimal is recommended best practice for representing monetary values in Java. What do you use? Is there a better library that you prefer to use instead?

[A]
```
BigDecimal
```
all the way. I've heard of some folks creating their own
```
Cash
```
or
```
Money
```
classes which encapsulate a cash value with the currency, but under the skin it's still a
```
BigDecimal
```
, probably with
```
BigDecimal.ROUND_HALF_EVEN
```
rounding.
Edit:
As Don mentions in
his answer
, there are open sourced projects like
timeandmoney
, and whilst I applaud them for trying to prevent developers from having to reinvent the wheel, I just don't have enough confidence in a pre-alpha library to use it in a production environment. Besides, if you dig around under the hood, you'll see
they use
```
BigDecimal
```
too
.


q:
Here is a nice underhand lob pitch to you guys.

So basically I've got my content table with unique primary key IDs and I've got my tag table with unique primary key IDs.

I've got a table that has an identity column as a primary key but the two other columes are the contentID and tagID.  What do I need to do to the table to make sure that I only have the same contentID and tagID combo only once.

[A]
You put a Unique constraint on contentID, tagID.
For SQL Server
```
```
ALTER TABLE ContentTag ADD CONSTRAINT
    IX_ContentID_TagID_Unique UNIQUE NONCLUSTERED ( contentID,  tagID )
GO
```
```


q: i'm looking for a way to programatically convert word documents in docx format to doc format without using ole automation.  i already have a windows service that does this but it means installing office on a server and it is a little unreliable and not supported.  i am aware of the aspose.words product, and i will try it out, but has anyone any recommendations for how to do this as simply, reliably, and cheaply as possible?

[A]
One option without using OLE automation would be to wrap the converter dlls coming with compatibility pack in order to convert from docx to doc without automating Office.
This requires only that the Compatibility Pack of Office is installed on the machine.
The Office converter dlls convert from the document format that they support to RTF and/or from RTF to their document format using the interface ForeignToRtf/RtfToForeign. You can chain converters as you wish to convert from one format to another, e.g. to do a conversion DOCX -> RTF -> DOC.
You can get the
SDK from Microsoft
, which includes several samples on how to use existing converters. If I remember correctly there is already a command line wrapper sample included. Everything is C/C++ stuff.
You can find out which of the converter dlls are responsible for OpenXML conversion by looking at the following registry key:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Shared Tools\Text Converters\Import\Word12
```
```
Let me know if you need further details on this.


q:
Some of the platforms that I develop on, don't have profiling tools.  I am looking for suggestions/techniques that you have personally used to help you identify hotspots, without the use of a profiler.

The target language is C++.

I am interested in what you have personally used.

[A]
In essence, if a profiling tool is not available, you emulate what a profiler would have done.  You insert counters into functions you think are interesting and count how many times, and potentially with what size/sort of arguments they're called.
If you have access to any timers on your platform, you may start/stop these at the beginning/end of said functions to get execution time information as well, if this is unclear from the code.  This is going to give you the biggest bang for your buck in complex code, as there will usually be too many functions to instrument them all.  Instead, you can obtain the time spent in certain sections of code by dedicating a timer to each one.
These two techniques in tandem can form an iterative approach, where you find the broad section of code that consumes the majority of your cycles using timers, then instrument individual functions at a finer granularity to hone in on the problem.


q:
I have a file (called "number.txt") which I want to read to an array in Java. How exactly do I go ahead and do this? It is a straight-forward "1-dimensional" file, containing 100 numbers.

The problem is that I get an exception every time. Apparently it can't find it (I am sure its spelled correctly). When looking through code examples, it doesn't specify the file's entire file path, only the name of the file itself. How would I go about doing that if its necessary?

Also, when reading the file, will the array automatically contain all the lines of the file, or will I have to make a loop which which copies every line to corresponding subscript i?

I've heard of BufferedReader class, what it's purpose, and how does it corelate to reading input?

[A]
Here is some example code to help you get started:
```
```
package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}
```
```
And an example unit test:
```
```
package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}
```
```
Hope this helps.


q: What's the best way to run scheduled tasks in a Rails environment? Script/runner? Rake? I would like to run the task every few minutes.

[A]
Assuming your tasks don't take too long to complete, just create a new controller with an action for each task. Implement the logic of the task as controller code, Then set up a cronjob at the OS level that uses wget to invoke the URL of this controller and action at the appropriate time intervals. The advantages of this method are you:
Have full access to all your Rails objects just as in a normal controller.
Can develop and test just as you do normal actions.
Can also invoke your tasks adhoc from a simple web page.
Don't consume any more memory by firing up additional ruby/rails processes.


q:
I've tried the following, but I was unsuccessful:

ALTER TABLE person ALTER COLUMN dob POSITION 37;

[A]
"
Alter column position
" in the PostgreSQL Wiki says:
PostgreSQL currently defines column
  order based on the
```
attnum
```
column of
  the
```
pg_attribute
```
table. The only way
  to change column order is either by
  recreating the table, or by adding
  columns and rotating data until you
  reach the desired layout.
That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either.  Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.
One other idea occurs to me:  you can define a
```
VIEW
```
that specifies the order of columns how you like it, without changing the physical position of the column in the base table.


q:
So, let's say I want to write a class that operates on different kinds of numbers, but I don't a priori know what kind of numbers (i.e. ints, doubles, etc.) I will be operating on.

I would like to use generics to create a general class for this scenario.  Something like:

 Adder<Double> adder = new Adder<Double>();
 adder.add(10.0d, 10.0d);   // = 20.0d

But, I cannot instantiate the generic type I pass in to my Adder class!  So -- what to do?

[A]
Uh oh---generics are not C++ templates. Because of type erasure, the
```
Double
```
in your example won't even show through to the runtime system.
In your particular case, if you just want to be able to add various types together, may I suggest method overloading? e.g.,
```
double add(double, double)
```
,
```
float add(float, fload)
```
,
```
BigDecimal add(BigDecimal, BigDecimal)
```
, etc.


q: In Python I could've converted it to Unicode and do '(?u)^[\w ]+$' regex search, but PHP doesn't seem to understand international \w, or does it?

[A]
Although I haven't tested myself, looking at
http://us3.php.net/manual/en/reference.pcre.pattern.syntax.php
suggests the following: '/^[\p{L} ]+$/u' would work - the \p{L} will match any unicode letter.  Additionally, you can apparently write this without the curly brackets - '/^[\pL ]+$/u'.


q:
One of my columns is called from. I can't change the name because I didn't make it.
Am I allowed to do something like SELECT from FROM TableName or is there a special syntax to avoid the SQL Server being confused?

[A]
Wrap the column name in brackets like so,
```
from
```
becomes [from].
```
```
select [from] from table;
```
```
It is also possible to use the following (useful when querying multiple tables):
```
```
select table.[from] from table;
```
```


q:
I have been using git for several months in a project developed only by myself. I have a local repository and push it regularly to github for backup purposes.

I want to add another developer to this project, however I will have the responsibility of integrating the whole project.

What is the recommended workflow?

Do we need a private and a public repository for each developer?

If the github repository is the main one, does the other developer have to clone this repository or the repository in my computer?

Should he have the right to push in my repository or should I pull from his repository?

[A]
Git is geared towards
pulling
, rather than pushing. Ideally, the other developer would clone from your
public
repo on Github; then, when he was done with his changes, you'd either pull from a repo that he makes available to you, or you'd integrate his changes with patches that he emails to you. Either way, you'd pull the changes into the
private
repo
on your computer
, fix any mistakes that result from the merge, and then push his changes to your public repo (the one on Github).
Of course, there's nothing wrong with giving him commit access to your Github repo, either.


q:
Eclipse issues warnings when a serialVersionUID is missing.

The serializable class Foo does not declare a static final
  serialVersionUID field of type long

What is serialVersionUID and why is it important?  Please show an example where missing serialVersionUID will cause a problem.

[A]
The docs for
```
java.io.Serializable
```
are probably about as good an explanation as you'll get:
The serialization runtime associates with each serializable class a version number, called a
```
serialVersionUID
```
, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different
```
serialVersionUID
```
than that of the corresponding sender's class, then deserialization will result in an
```
InvalidClassException
```
. A serializable class can declare its own
```
serialVersionUID
```
explicitly by declaring a field named
```
serialVersionUID
```
that must be static, final, and of type
```
long
```
:
```
```
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
```
```
If a serializable class does not explicitly declare a
```
serialVersionUID
```
, then the serialization runtime will calculate a default
```
serialVersionUID
```
value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is
strongly recommended
that all serializable classes explicitly declare
```
serialVersionUID
```
values, since the default
```
serialVersionUID
```
computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected
```
InvalidClassExceptions
```
during deserialization. Therefore, to guarantee a consistent
```
serialVersionUID
```
value across different java compiler implementations, a serializable class must declare an explicit
```
serialVersionUID
```
value. It is also strongly advised that explicit
```
serialVersionUID
```
declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class —
```
serialVersionUID
```
fields are not useful as inherited members.


q:
I want to reverse engineer (import into diagram form) the database definition dump of a database I have, then since no foreign keys are defined in this particular database, I want to be able to manually create the table to table key mappings (using crow feet notation if possible).

I've taken a look at MySQL Workbench, and it gets me 85% of the way there.
The nice little relationship lines won't show up though, and the auto arrange is horrible. A quick search of google turns up several other options, so I can evaluate these on my own, but:

Can I get some feedback from you guys for which are your favorite tools to use for this scenario? Why do you like that(your) particular tool?

My intended purpose is to take a legacy database, and train jr. engineers on the organization of the DB. Visual aids are nifty. My fallback option is to recreate an ER diagram by hand. Not fun for 250+ tables.

[A]
I've had some success using two commercial (but relatively cheap!) tools- but I still haven't found any really solid open source ones after months of looking.
MyEclipseIDE
is a subscription product, I think it's around $60 a year. It's a set of bundled plugins for Eclipse, one of them is an ERD analyzer that works OK. If you're programming in Java (or another eclipse-supported language), it may be worth it.
SQLMaestro for MySQL
: This one is a bit more expensive, with a $99 noncommercial / $179 single seat license. The ERD it generates is much better, and it provides other tools that make it easier to administer and maintain a more complex schema.
My understanding is that MySQL Workbench is still under active development, but they've been banging on it for a long time without really wrapping it up. Maybe now that Sun owns them, they'll get it together.


q:
Using Java, how can I test that a URL is contactable, and returns a valid response?

http://stackoverflow.com/about

[A]
The solution as a unit test:
```
```
public void testURL() throws Exception {
    String strUrl = "http://stackoverflow.com/about";

    try {
        URL url = new URL(strUrl);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.connect();

        assertEquals(HttpURLConnection.HTTP_OK, urlConn.getResponseCode());
    } catch (IOException e) {
        System.err.println("Error creating HTTP connection");
        e.printStackTrace();
        throw e;
    }
}
```
```


q:
I want to create an Ant buildfile, that includes some files as a sort of plugin.

So if I want to activate a feature in a project - say pmd-checking - I copy a pmd.xml in a directory and the build.xml get on the start the idea, that pmd.xml exists and imports it, so that new targets can be available to the build.

But the 'import' task can only be used as a top-level task, so I have no idea how to relize this functionality. Is this possible with Ant and if so, how can I do it?

EDIT: I would prefer a solution, that allows new targets to show up in the listing presented by ant -p.

[A]
You can use the
ant
task and even parameterize the target name. Here's an example:
```
```
<ant antfile="plugins/pmd.xml" target="${pmd-target}"/>
```
```
If you want more flexibility, I recommend checking
gant
or
gradle
.


q:
Does anyone know how to use the Raw Input facility on Windows from a WX Python application?

What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too.

[A]
Have you tried using ctypes?
```
```
>>> import ctypes
>>> ctypes.windll.user32.RegisterRawInputDevices
<_FuncPtr object at 0x01FCFDC8>
```
```
It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython.


q:
On my current project, I came across our master DB script. Taking a closer look at it, I noticed that all of our original primary keys have a data type of numeric(38,0)
We are currently running SQL Server 2005 as our primary DB platform.

For a little context, we support both Oracle and SQL Server as our back-end. In Oracle, our primary keys have a data type of number(38,0).

Does anybody know of possible side-effects and performance impact of such implementation? I have always advocated and implemented int or bigint as primary keys and would love to know if numeric(38,0) is a better alternative.

[A]
Barring the storage considerations and some initial confusion from future DBAs, I don't see any reason why NUMERIC(38,0) would be a bad idea. You're allowing for up to 9.99 x 10^38 records in your table, which you will certainly never reach. My quick digging into this didn't turn up any glaring reason not to use it. I suspect that your only potential issue will be the storage space consumed by that, but seeing as how storage space is so cheap, that shouldn't be an issue.
I've seen this a fair number of times in Oracle databases since it's a pretty big default value that you don't need to think about when you're creating a table, similar to using INT or BIGINT by default in SQL Server.


q:
Everyone managing open-source-software runs into the problem, that with the time the process of releasing a new version gets more and more work. You have to tag the release in your version-control, create the distributions (that should be easy with automated builds), upload them to your website and/or open-source-hoster. You have to announce the new release with nearly the same message on chosen web-forums, the news-system on sourceforge, mailinglists and your blog or website. And you have to update the entry of your software on freshmeat. Possible more tasks have to be done for the release.

Do you developed techniques to automate some of these tasks? Does software exist that supports you with this?


q:
As the title suggest...
How can I apply a scrum process to anything that doesn't work on new code and can be estimated to some degree?

How can I apply a scrum process to maintenance and emergency fixes (which can take from 5 minutes to 2 weeks to fix) type of environment when I still would like to plan to do things?

Basically, how do I overcome unplanned tasks and tasks that are very difficult to estimate with the scrum process? or am I simply applying the wrong process for this enviroment?

[A]
Treat all fixes and improvements as individual stories and estimate accordingly. My personal view is that things that take less then 10-15 minutes to fix should just be done straight away. For those that take longer, they become part of the current 'fix & improvement' iteration cycle. As with estimating regular requirements, you take a best guess as a team. As more information comes to light, and the estimates are off adjust the iteration and upcoming sprints.
It's hard to apply a iteration cycle to fixes and improvements as more often then not, they prevent the system from working as they should and the 'business' puts pressure for them to go live asap. At this point it may work out better moving to a really short iteration cycle, like one or two weeks.


q:
Is it possible to insert a row, but only if one of the values already in the table does not exist?

I'm creating a Tell A Friend with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't want any more than 1 person getting the referral points once the new customer signs up and purchases something. Therefore I want only one email ever once in the table.

I'm using PHP 4 and MySql 4.1.

[A]
I'm not sure if I got it, but what about a
```
```
try {
  mysql_query($sql);
}
catch(Exception $e) {

}
```
```
combined with an unique field index in MySQL?
if it throws an exception then you know that you got a duplicated field.
Sorry if that don't answer your question..


q:
Given an HTML link like

<a href="urltxt" class="someclass" close="true">texttxt</a>

how can I isolate the url and the text?

Updates

I'm using Beautiful Soup, and am unable to figure out how to do that.

I did

soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))

links = soup.findAll('a')

for link in links:
    print "link content:", link.content," and attr:",link.attrs

i get

*link content: None  and attr: [(u'href', u'_redirectGeneric.asp?genericURL=/root    /support.asp')]*  ...
...

Why am i missing the content?

edit: elaborated on 'stuck' as advised :)

[A]
Use
Beautiful Soup
.  Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.
EDIT:
I think you want:
```
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
```
```
By the way, it's a bad idea to try opening the URL there, as if it goes wrong it could get ugly.
EDIT 2:
This should show you all the links in a page:
```
```
import urlparse, urllib
from BeautifulSoup import BeautifulSoup

url = "http://www.example.com/index.html"
source = urllib.urlopen(url).read()

soup = BeautifulSoup(source)

for item in soup.fetchall('a'):
    try:
        link =  urlparse.urlparse(item['href'].lower())
    except:
        # Not a valid link
        pass
    else:
        print link
```
```


q: Does anyone know if NHibernate supports returning output parameters from stored procedures? I've had a search in the documentation but can't really find anything that confirms either way.

[A]
I can't officially
confirm
for you, but as far as I know, not directly. Stored procedure use in NHibernate is very specific to doing standard CRUD.
If you want to grab output paramaters (that are't the standard row count output parameter for INSERT, UPDATE, and DELETE), you could fall back to a different (or the standard) database access tools that give you direct access to SQL and the result set. (Assuming you can get by with bypassing NHibernate's cache. You'll want to make sure you flush NHibernate before you run the query too, etc.)


q: Does anybody have a snippet of Java that can return the newest file in a directory (or knowledge of a library that simplifies this sort of thing)?

[A]
Something like:
```
```
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;

public class Newest {
    public static void main(String[] args) {
        File dir = new File("C:\\your\\dir");
        File [] files  = dir.listFiles();
        Arrays.sort(files, new Comparator(){
            public int compare(Object o1, Object o2) {
                return compare( (File)o1, (File)o2);
            }
            private int compare( File f1, File f2){
                long result = f2.lastModified() - f1.lastModified();
                if( result > 0 ){
                    return 1;
                } else if( result < 0 ){
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        System.out.println( Arrays.asList(files ));
    }
}
```
```


q: The equals() method of the URL class in the Java class library makes a DNS request to get the IP for the hostname, to check the two IP's for equality. This happens even for URLs that are created from the same String. Is there a way to avoid this internet access?

[A]
Don't use URL.equals. As the documentation says,
Note: The defined behavior for
```
equals
```
is known to be inconsistent with virtual hosting in HTTP.


q: The renewal wizard doesn't seem to ask for a renewal period.

[A] I think the Cerficate Supplier sets the renewal period.  So it depends on the type of Cert you buy (or the setup of your certification service).


q:
I'd love to use WPF for a consumer app. However, some real world tests are not very encouraging. On several high-end computers I've tested, the .NET 3.5 installation has taken 15-20 mins to complete. I've seen reports online mentioning 50 mins.

When Vista marketshare is at 70%, this subject will be moot. Until then, reality is that the majority of consumers are on XP and will need a .NET 3.5 install. Adding 15-20 mins (at best) to the install of a consumer app is simply unacceptable.

1) What the frack is the .NET installer taking so long for?

2) Is there any way to optimize the .NET install?

Oh, and I know about the .NET Client Profile. Doesn't improve the situation much.

[A]
Its big.
Using the MS supplied web install is the best cause it only installs what it needs (but thats still big)
Only option is to only detect its not there and warn the user and ask them to install it.  Only the first 3.5 app is affected.  All others will be speedy.
Apparently, all supported OSs will be rolled out to this over time using Windows Update and Services Packs and the like.


q:
There seem to be a decent number of mod_rewrite threads floating around lately with a bit of confusion over how certain aspects of it work. As a result I've compiled a few notes on common functionality, and perhaps a few annoying nuances.

What other features / common issues have you run across using mod_rewrite?

[A]
Where to place mod_rewrite rules
```
mod_rewrite
```
rules may be placed within the
```
httpd.conf
```
file, or within the
```
.htaccess
```
file. if you have access to
```
httpd.conf
```
, placing rules here will offer a performance benefit (as the rules are processed once, as opposed to each time the
```
.htaccess
```
file is called).
Logging mod_rewrite requests
Logging may be enabled from within the
```
httpd.conf
```
file (including
```
<Virtual Host>
```
):
```
```
# logs can't be enabled from .htaccess
# loglevel > 2 is really spammy!
RewriteLog /path/to/rewrite.log
RewriteLogLevel 2
```
```
Common use cases
To funnel all requests to a single point:
```
```
RewriteEngine on
# ignore existing files
RewriteCond %{REQUEST_FILENAME} !-f
# ignore existing directories
RewriteCond %{REQUEST_FILENAME} !-d
# map requests to index.php and append as a query string
RewriteRule ^(.*)$ index.php?query=$1
```
```
Since Apache 2.2.16 you can also use
```
FallbackResource
```
.
Handling 301/302 redirects:
```
```
RewriteEngine on
# 302 Temporary Redirect (302 is the default, but can be specified for clarity)
RewriteRule ^oldpage\.html$ /newpage.html [R=302]
# 301 Permanent Redirect
RewriteRule ^oldpage2\.html$ /newpage.html [R=301]
```
```
Note
: external redirects are implicitly 302 redirects:
```
```
# this rule:
RewriteRule ^somepage\.html$ http://google.com
# is equivalent to:
RewriteRule ^somepage\.html$ http://google.com [R]
# and:
RewriteRule ^somepage\.html$ http://google.com [R=302]
```
```
Forcing SSL
```
```
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://example.com/$1 [R,L]
```
```
Common flags:
```
[R]
```
or
```
[redirect]
```
- force a redirect (defaults to a 302 temporary redirect)
```
[R=301]
```
or
```
[redirect=301]
```
- force a 301 permanent redirect
```
[L]
```
or
```
[last]
```
- stop rewriting process (see note below in common pitfalls)
```
[NC]
```
or
```
[nocase]
```
- specify that matching should be case insensitive
Using the long-form of flags is often more readable and will help others who come to read your code later.
You can separate multiple flags with a comma:
```
```
RewriteRule ^olddir(.*)$ /newdir$1 [L,NC]
```
```
Common pitfalls
Mixing
```
mod_alias
```
style redirects with
```
mod_rewrite
```
```
```
# Bad
Redirect 302 /somepage.html http://example.com/otherpage.html
RewriteEngine on
RewriteRule ^(.*)$ index.php?query=$1

# Good (use mod_rewrite for both)
RewriteEngine on
# 302 redirect and stop processing
RewriteRule ^somepage.html$ /otherpage.html [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# handle other redirects
RewriteRule ^(.*)$ index.php?query=$1
```
```
Note
: you can mix
```
mod_alias
```
with
```
mod_rewrite
```
, but it involves more work than just handling basic redirects as above.
Context affects syntax
Within
```
.htaccess
```
files, a leading slash is not used in the RewriteRule pattern:
```
```
# given: GET /directory/file.html

# .htaccess
# result: /newdirectory/file.html
RewriteRule ^directory(.*)$ /newdirectory$1

# .htaccess
# result: no match!
RewriteRule ^/directory(.*)$ /newdirectory$1

# httpd.conf
# result: /newdirectory/file.html
RewriteRule ^/directory(.*)$ /newdirectory$1

# Putting a "?" after the slash will allow it to work in both contexts:
RewriteRule ^/?directory(.*)$ /newdirectory$1
```
```
[L] is not last! (sometimes)
The
```
[L]
```
flag stops processing any further rewrite rules
for that pass through the rule set
. However, if the URL was modified in that pass and you're in the
```
.htaccess
```
context or the
```
<Directory>
```
section, then your modified request is going to be passed back through the URL parsing engine again. And on the next pass, it may match a different rule this time. If you don't understand this, it often looks like your
```
[L]
```
flag had no effect.
```
```
# processing does not stop here
RewriteRule ^dirA$ /dirB [L]
# /dirC will be the final result
RewriteRule ^dirB$ /dirC
```
```
Our rewrite log shows that the rules are run twice and the URL is updated twice:
```
```
rewrite 'dirA' -> '/dirB'
internal redirect with /dirB [INTERNAL REDIRECT]
rewrite 'dirB' -> '/dirC'
```
```
The best way around this is to use the
```
[END]
```
flag (
see Apache docs
) instead of the
```
[L]
```
flag, if you truly want to stop all further processing of rules (and subsequent passes). However, the
```
[END]
```
flag is only available for
Apache v2.3.9+
, so if you have v2.2 or lower, you're stuck with just the
```
[L]
```
flag.
For earlier versions, you must rely on
```
RewriteCond
```
statements to prevent matching of rules on subsequent passes of the URL parsing engine.
```
```
# Only process the following RewriteRule if on the first pass
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ...
```
```
Or you must ensure that your RewriteRule's are in a context (i.e.
```
httpd.conf
```
) that will not cause your request to be re-parsed.


q:
I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA_OPTS environment variable, but I'm testing that with jconsole to see if it works and it... doesn't.

As per the comment below, CATALINA_OPTS doesn't work either. So far, the only way I can get it to work is via the Tomcat configuration GUI, and that's not an acceptable solution for my problem.

[A]
Use the
```
CATALINA_OPTS
```
environment variable.


q:
We have YouTube videos on a site and want to detect if it is likely that they will not be able to view them due to (mostly likely) company policy or otherwise.

We have two sites:

1) Flex / Flash
2) HTML

I think with Flex I can attempt to download http://youtube.com/crossdomain.xml and if it is valid XML assume the site is available

But with HTML I don't know how to do it. I can't even think of a 'nice hack'.

[A]
This should work.  Basically, it loads a youtube.com javascript file, then checks if a function in that file exists.
```
```
<html>

<head>
    <script src="http://www.youtube.com/js/account.js"></script>
    <script>
        function has_you_tube()
        {
            if(typeof addVideosToQuicklist == 'function')
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    </script>

</head>
<body>
    <script>alert( "has_youtube: " + has_you_tube() ); </script>
</body>

</html>
```
```


q: Is there a way to get the count of rows in all tables in a MySQL database without running a SELECT count() on each table?

[A]
You can probably put something together with
Tables table
.  I've never done it, but it looks like it has a column for
TABLE_ROWS
and one for
TABLE NAME
.
To get rows per table, you can use a query like this:
```
```
SELECT table_name, table_rows
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = '**YOUR SCHEMA**';
```
```


q: If I have a key set of 1000, what is a suitable size for my Hash table, and how is that determined?

[A]
There's some discussion of these factors in the documentation for
```
Hashtable
```


q: How would I go about creating a Google map that allows the user to zoom beyond the default zoom levels for the map?  Would I have to create a new map type that has a greater maximum zoom?  Are there any tutorials out there that show how to do this?

[A]
I'm not familiar enough with the Decimal class to help you out, but your problem is due to the fact that decimal fractions can often not be accurate represented in binary, so what you're seeing is the closest possible approximation; there's no way to avoid this problem without using a special class (like Decimal, probably).
```
EDIT:
```
What about the decimal class isn't working properly for you? As long as I start with a string, rather than a float, powers seem to work fine.
```
```
>>> import decimal
>>> print(decimal.Decimal("1.2") ** 2)
1.44
```
```
The
module documentation
explains the need for and usage of
```
decimal.Decimal
```
pretty clearly, you should check it out if you haven't yet.


q:
My question is a lot like this one. However I'm on MySQL and I'm looking for the "lowest tech" solution that I can find.

The situation is that I have 2 databases that should have the same data in them but they are updated primarily when they are not able to contact each other. I suspect that there is some sort of clustering or master/slave thing that would be able to sync them just fine. However in my cases that is major overkill as this is just a scratch DB for my own use.

What is a good way to do this?

My current approach is to have a Federated table on one of them and, every so often, stuff the data over the wire to the other with an insert/select. It get a bit convoluted trying to deal with primary keys and what not. (insert ignore seems to not work correctly)

p.s. I can easily build a query that selects the rows to transfer.

[A]
MySQL's inbuilt replication is very easy to set up and works well even when the DBs are disconnected most of the time. I'd say configuring this would be much simpler than any custom solution out there.
See
http://www.howtoforge.com/mysql_database_replication
for instructions, you should be up and running in 10-15 mins and you won't have to think about it again.
The only downside I can see is that it is asynchronous - ie. you must have one designated master that gets all the changes.


q:
I've installed Subversion on Ubuntu following the guide Installation of Subversion on Ubuntu, with Apache, SSL, and BasicAuth..

It works, and I was able commit and create different repositories, but somehow, from time to time (sometimes minutes), when trying to do a commit, I'm forced to reset or recreate my user and password with the following command.

htpasswd2 -c -m /etc/apache2/dav_svn.passwd $AUTH_USER

Because SVN does not recognize my user/password anymore.

I'm using TortoiseSVN as SVN Client. I would like to know why this is happening. Maybe it's a configuration issue, or maybe TortoiseSVN is sending invalid credentials, causing a locked account. Since I'm far from being an SVN expert/administrator. Are there some pointers in order to attack the problem.

[A]
I'm using TortoiseSVN as well, but on Windows users' passwords are managed by
Active Directory
on the network domain. So usernames are in the format
```
<domain>\<user>
```
. And from time to time (weeks), I need to reset the password; it seems like the password is changed. I just do not know why.


q:
I am not a fan of using SQL*PLUS as an interface to Oracle.  I usually use yasql, but it hasn't been updated since 2005 and can do with some improvements.  A quick Google search shows yasql and SQLPal.  I am using linux, so SQLPal is not an option.

Are there any alternatives out there, or am I stuck with an interface that I do not like or one that is no longer maintained?

[A]
TOAD is pretty expensive, but you can download a 90-day trial from the Quest site to see if it's got the feature set you want (don't be fooled by the "freeware" title - it's only free for 90 days, and then it expires, which definitely makes it shareware):
http://www.toadworld.com/Freeware/ToadforOracleFreeware/tabid/558/Default.aspx
Another options is a tool I've seen on CodeProject:
http://www.codeproject.com/KB/database/OQuery.aspx
It's in .NET, so you'd have to see if it compiled on Mono, but it might be worth a shot. I haven't used either tool (Toad or this one), since I'm a SQL Server guy, but I've heard good things about Toad.


q:
I want to assert that a method is called exactly one time. I'm using RhinoMocks 3.5.

Here's what I thought would work:

[Test]
public void just_once()
{
    var key = "id_of_something";

    var source = MockRepository.GenerateStub<ISomeDataSource>();
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Once();

    var client = new Client(soure);

    // the first call I expect the client to use the source
    client.GetMeMyThing(key);

    // the second call the result should be cached
    // and source is not used
    client.GetMeMyThing(key);
}

I want this test to fail if the second invocation of GetMeMyThing() calls source.GetSomethingThatTakesALotOfResources().

[A]
Here is what I just did (as recommended by
Ray Houston
). I would still appreciate a more elegant solution...
```
```
[Test]
public void just_once()
{
    var key = "id_of_something";

    var source = MockRepository.GenerateStub<ISomeDataSource>();

    // set a positive expectation
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Once();

    var client = new Client(soure);

    client.GetMeMyThing(key);

    // set a negative expectation
    source.Expect(x => x.GetSomethingThatTakesALotOfResources(key))
        .Return(new Something())
        .Repeat.Never();

    client.GetMeMyThing(key);
}
```
```


q:
typedef struct {
        nat id;
        char *data;
        } element_struct;

typedef element_struct * element;

void push(element e, queue s) {
        nat lt = s->length;
        if (lt == max_length - 1) {
                printf("Error in push: Queue is full.\n");
                return;
        }
        else {
                s->contents[lt] = e;
                s->length = lt + 1;
        }
}
int main () {
         push(something_of_type_element, s);
}

How would i go about formatting "something_of_type_element"?

Thanks

Notes:
nat is the same as int

[A]
How about:
```
```
element elem = malloc(sizeof(element_struct));
if (elem == NULL) {
    /* Handle error. */
}

elem->id = something;
elem->data = something_else;

push(elem, s);
```
```
Note that there's lots of memory management missing here...


q:
Our Windows Forms application by default saves data files in a user's 'My Documents' folder (on XP) or 'Documents' folder (on Vista). We look up this location by calling:

Environment.GetFolderPath( Environment.SpecialFolder.Personal )

We know for sure this works great for users whose personal folder is on a local disk. What we're not sure about is domain users who have Folder Redirection in effect for their profile/personal data folders.

My question is: Does the above call properly resolve regardless of whether Folder Redirection is active?

I don't have the environment to test this out, and I haven't been able to find any definite confirmation one way or the other.

[A]
I would expect that it does.  The documentation for both
```
Environment.GetFolderPath
```
and the underlying
```
SHGetSpecialFolderPath
```
don't give any indication that it would not resolve correctly nor can I find anything that you would use its place.


q: How can I test Controller.ViewData.ModelState? I would prefer to do it without any mock framework.

[A]
You don't have to use a Mock if you're using the Repository Pattern for your data, of course.
Some examples:
http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx
```
```
// Test for required "FirstName".
   controller.ViewData.ModelState.Clear();

   newCustomer = new Customer
   {
       FirstName = "",
       LastName = "Smith",
       Zip = "34275",
   };

   controller.Create(newCustomer);

   // Make sure that our validation found the error!
   Assert.IsTrue(controller.ViewData.ModelState.Count == 1,
                 "FirstName must be required.");
```
```


q:
I have developed a simple mechanism for my mvc website to pull in html via jquery which then populates a specified div.  All is well and it looks cool.

My problem is that i'm now creating html markup inside of my controller (Which is very easy to do in VB.net btw) I'd rather not mix up the sepparation of concerns.

Is it possible to use a custom 'MVC View User Control' to suit this need?  Can I create an instance of a control, pass in the model data and render to html?  It would then be a simple matter of rendering and passing back to the calling browser.

[A]
In rails this is called rendering a partial view, and you do it with
```
render :partial => 'yourfilename'
```
. I believe ASP.NET MVC has a similar
```
RenderPartial
```
method, but I can't find the official docs for MVC to confirm or deny such a thing.


q:
How do I remove all attributes which are undefined or null in a JavaScript object?

(Question is similar to this one for Arrays)

[A]
You are probably looking for the
```
delete
```
keyword.
```
```
var obj = { };
obj.theProperty = 1;
delete obj.theProperty;
```
```


q: So I'm using python to do some parsing of web pages and I want to split the full web address into two parts. Say I have the address http://www.stackoverflow.com/questions/ask. I would need the protocol and domain (e.g. http://www.stackoverflow.com) and the path (e.g. /questions/ask). I figured this might be solved by some regex, however I'm not so handy with that. Any suggestions?

[A]
```
```
import re
url = "http://stackoverflow.com/questions/ask"
protocol, domain = re.match(r"(http://[^/]*)(.*)", url).groups()
```
```


q:
example:

I want to see if array[5] holds a value or is empty.

[A]
There is no such thing as an "empty" element in a Java array. If the array's length is at least six, then element 5 exists and it has a value. If you have not assigned anything else to that location, then it will have the value zero, just like an object's uninitialized field would have.
If it is an array of
```
Object
```
descendants, then you can check whether the element is equal to
```
null
```
.


q: I just started getting into BizTalk at work and would love to keep using everything I've learned about DDD, TDD, etc. Is this even possible or am I always going to have to use the Visio like editors when creating things like pipelines and orchestrations?

[A]
You can certainly apply a lot of the concepts of TDD and DDD to BizTalk development.
You can design and develop around the concept of domain objects (although in BizTalk and integration development I often find interface objects or contract first design to be a more useful way of thinking - what messages get passed around at my interfaces). And you can also follow the 'Build the simplest possible thing that will work' and 'only build things that make tests pass' philosophies of TDD.
However, your question sounds like you are asking more about the code-centric sides of these design and development approaches.
Am I right that you would like to be able to follow the test driven development approach of first writing a unti test that exercises a requirement and fails, then writing a method that fulfils the requirement and causes the test to pass - all within a traditional programing language like C#?
For that, unfortunately, the answer is no. The majority of BizTalk artifacts (pipelines, maps, orchestrations...) can only really be built using the Visual Studio BizTalk plugins. There are ways of viewing the underlying c# code, but one would never want to try and directly develop this code.
There are two tools
BizUnit
and
BizUnit Extensions
that give some ability to control the execution of BizTalk applications and test them but this really only gets you to the point of performing more controled and more test driven integration tests.
The shapes that you drag onto the Orchestration design surface will largely just do their thing as one opaque unit of execution. And Orchestrations, pipelines, maps etc... all these things are largely intended to be executed (and tested) within an entire BizTalk solution.
Good design practices (taking pointers from approaches like TDD) will lead to breaking BizTalk solutions into smaller, more modular and testable chunks, and are there are ways of testing things like pipelines in isolation.
But the detailed specifics of TDD and DDD in code sadly don't translate.
For some related discussion that may be useful see this question:
Mocking WebService consumed by a Biztalk Request-Response port


q:
Previously it was .net 2.0 which is the big change in .net developement. many developers are working mostly on this. Presently microsoft has introduced .net 3.0 and yet its next version .net 4.0. So the next version is going to be major change in .net development.

I have listed some features of this...

Workflow foundation
WPF
WCF
Windows cardspace
Agile methodalogy implementation.
Silverlight features enhancement.

In the new generation framework what are the features that you like and why it attracts you.

[A]
If you're asking which new features will the upcoming .NET 4.0 Framework present, I've heard a lot about Parallel Computing, specifically about a Task Parallel Library built in the core of the Framework, also
PLinq
or Parallel Linq, focusing on LINQ-to-Objects and LINQ-to-XML .
Check te
Microsoft PDC Website
and you'll find more interesting info.


q:
I'm writing an app for Blackberry that was originally implemented in standard J2ME.  The network connection was done using Connector.open("socket://...:80/...") instead of http://

Now, I've implemented the connection using both methods, and it seems like some times, the socket method is more responsive, and some times it doesn't work at all.  Is there a significant difference between the two?  Mostly what I'm trying to achieve is responsiveness from the connection to get a smooth progress bar.

[A]
Since both operate over a network I don't think you can guarantee a smooth progress bar. You might have more chance of that if you remind the person to stay in one place so you have a chance of a consistent connection ;)
There is less overhead with a socket connection than an HTTP one. In fact, HTTP connections run over the socket connection. You can take advantage of the reduced overhead of the socket connection to appear more responsive, but you will likely have more work to do than you would with HTTP. The API is more low-level so coding is more complex.


q:
is it possible to throw a custom error message to a ThrowActivity, in windows workflow foundation?

eg. Imagine i want to throw this exception, in my WF :-

CutomException("This is my custom error message", myNumber, myObect);

cheers :)

[A]
Maybe I do not understand your question well, but you can set the specific exception with the
```
Fault
```
property of
```
ThrowActivity
```
in any place before the activity execution, e.g.:
```
```
throwActivity1.Fault = new CustomException("This is my custom error message", myNumber, myObect);
```
```


q:
If I am evaluating two variables and not two method calls does it matter weather I use "&&" or "&"

//some logic that sets bool values

boolean X = true;
boolean Y = true;

if (X & Y){
   // perform some operation
}

if (X && Y){
   // perform some operation
}

Further a book I am using for C# 3.0 / .NET 3.5 only makes reference to the && operator, is the & operator going away?

[A]
Always use && if you are performing a true/false logic test. A single & performs a bit-wise 'and'.  It make work like a logic test in some cases but it is not guaranteed to work for all logic cases.  The most common use of a single & is when applying a bit-mask.
Examples (&&):
```
```
true && true == true
```
```
Example (&):
```
```
00101001 & 00100001 = 00100001
```
```


q:
I am making a small game number game in Java (Nim) in OS X and was thinking about trying to make the GUI interface of the game using something other than Swing. I looked at SWT, but I read somewhere that SWT has some problems with OS X. I also looked at GTK+ bindings for Java, but I am not sure if that's a good choice either. Do you guys have any suggestions for a good Java GUI Framework that would look good and be compatible with OS X ?

Thanks

[A]
It depends, with eclipse 3.4, SWT 3.4 is quite supported with
MacOs
.
Now, SWT is OS specific, and you may not have the same flexibility than Swing, so you need to have good reason for looking for an alternative to Swing, especially when you consider there are good
LAFs (look and feel)
for java.


q:
What is the best way to password protect quicktime streaming videos using php/.htaccess. They are being streamed using rtsp, but I can use other formats if necessary.

I know how to do authentication with php, but I'm not sure how to setup authentication so that will protect the streaming files urls so that a user can't just copy the url and share it.

Or am I overthinking this and I can just use a normal authentication scheme and place the files in a protected directory?

[A]
First off, it is very easy to spoof a referer. This information is stored in the user's browser, so a user can simply telnet into your server and provide his own referer which matches your domain.
A couple things you could try:
First, more secure, but still spoofable. mod_rewrite provides the ability to check cookies. What you could do is set a cookie when the user visits your website that contains some obscure data. Then, you could modify your RerwriteCond to something like this:
```
```
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_COOKIE} obscurename=obscurevalue [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
RewriteRule \.(asx¦ASX)$ http://www.yourdomain.com/images/leech.gif [R,L]
```
```
Another, better technique would involve working with PHP and mime-types. I'm not sure to what extent this would support streaming content, but I assume it'll work. What you can do is have all your video links point to a .php file (the query string will determine which video has been selected). Then, when a user tries to visit this link, you do something like so:
```
```
<?php
    // You could also check some sort of session variable
    // that is set when the user visits another part of your
    // site
    if(!isLoggedIn()){
       header("Location: errorPage.htm");
       exit;
    }else{
       // Get the name of the file specified
       $file = get_file_name($_GET['fileID']);

       // Specify the proper mime-type for the data you're sending
       // (this may have to change, depending on your situation)
       header("Content-type: video/vnd.rn-realvideo");

       // Read the file and output it to the browser
       readfile($file);
    }
?>
```
```
From what I read, most servers know which mime-types are streaming mime-types, so the browser should be able to figure out how to handle the streaming file properly.


q:
Given two 3D vectors A and B, I need to derive a rotation matrix which rotates from A to B.

This is what I came up with:

Derive cosine from acos(A . B)

Derive sine from asin(|A x B| / (|A| * |B|))

Use A x B as axis of rotation

Use matrix given near the bottom of this page (axis angle)

This works fine except for rotations of 0° (which I ignore) and 180° (which I treat as a special case). Is there a more graceful way to do this using the Direct3D library? I am looking for a Direct3D specific answer.

Edit: Removed acos and asin (see Hugh Allen's post)

[A]
No, you're pretty much doing it the best way possible.  I don't think there is a built-in DirectX function that does what you want.  For step 4, you can use
```
D3DXMatrixRotationAxis()
```
.  Just be careful about the edge cases, such as when |A| or |B| is zero, or when the angle is 0° or 180°.


q:
What's the best way (if any) to make an image appear "grayed out" with CSS (i.e., without loading a separate, grayed out version of the image)?

My context is that I have rows in a table that all have buttons in the right most cell and some rows need to look lighter than others. So I can make the font lighter easily of course but I'd also like to make the images lighter without having to manage two versions of each image.

[A]
Does it have to be gray? You could just set the opacity of the image lower (to dull it). Alternatively, you could create a
```
<div>
```
overlay and set that to be gray (change the alpha to get the effect).
html:
```
```

```
```
css:
```
```
#myImage {
    opacity: 0.4;
    filter: alpha(opacity=40); /* msie */
}

/* or */

#wrapper {
    opacity: 0.4;
    filter: alpha(opacity=40); /* msie */
    background-color: #000;
}
```
```


q: How can I make cookies in my Flash application using ActionScript 2.0?

[A]
You would need to use JavaScript to work with cookies. You can do so from ActionScript using the
ExternalInterface API
.


q:
I have a suspicion that I'm using the finally block incorrectly, and that I don't understand the fundamentals of its purpose...

 function myFunc() {
      try {
           if (true) {
                throw "An error";
           }
      } catch (e) {
           alert (e);
           return false;
      } finally {
           return true;
      }
 }

This function will run the catch block, alert "An error", but then return true. Why doesn't it return false?

[A]
The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement. The finally block executes whether or not an exception is thrown. If an exception is thrown, the statements in the finally block execute even if no catch block handles the exception.
more
The
```
finally
```
block will always run, try returning
```
true
```
after your
```
try
```
block
```
```
function myFunc() {
     try {
         if (true) {
               throw "An error";
          }
          return true;
     } catch (e) {
          alert (e);
          return false;
     } finally {
          //do cleanup, etc here
     }
 }
```
```


q:
Our team is experienced in web development (tomcat/Oracle) but not with AJAX on our existing projects.  This is new technology for us, so I want to introduce this carefully and correctly.

What should I look at in terms of frameworks or best practice or common pitfalls?

[A]
read this:
progressive enhancement
and use a library such as
jQuery
,
mootools
, or
YUI
it'll save you many headaches with cross-browser implementation.
this
will show you why you want to use a library.


q:
I would like to make my application somewhat REST compliant.  I am using Rails on the backend and GWT on the frontend.  I would like to do updates and deletes.  I realize I can do something like mydomain.com/:id/delete (GET) and accomplish the same thing.  However, as I stated previously, I would like to have a REST compliant backend.  Thus, I want to do mydomain.com/:id (DELETE) and have it implicitly call my delete method.

Now, it's my understanding that if a browser (my browser is GWT RequestBuilder) doesn't support DELETE/GET, Rails somehow accomplishes this task with a POST and some other url parameter.  So, how can I accomplish this with a GWT RequestBuilder?

[A]
Rails does this with hidden attributes. The easiest way to figure this out would be to create a new rails application, generate a scaffold and have a look at the HTML in a browser.
Try this:
```
```
rails jp
cd jp
./script/generate scaffold RequestBuilder name:string
rake db:migrate
./script/server
```
```
Then navigate to
http://localhost:3000/request_builders
, click on New and have a look at the HTML. You'll see something like:
```
```
<form action="/request_builders" class="new_request_builder"
  id="new_request_builder" method="post">

    <input name="authenticity_token" type="hidden" value="e76..." />

```
```
This is a creation, method is POST. Enter a name, save then Edit:
```
```
<form action="/request_builders/1" class="edit_request_builder"
  id="edit_request_builder_1" method="post">

    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="e76..." />

```
```
Of course the form is sent with POST, but Rails hads a hidden field to simulate a PUT request. Same for deletion, but the scaffold will do it with a bit of Javascript:
```
```
var m = document.createElement('input');
m.setAttribute('type', 'hidden');
m.setAttribute('name', '_method');
m.setAttribute('value', 'delete');
```
```
To have this work with another front-end, you'll have to both:
Use the same style URL such as /request_builders/1 (RESTful URLs)
Include the hidden fields (Rails trick)


q:
I want to build two-dimentional array of strings where length of one dimention is 2. Similar to this

string[,] array = new string[,]
{
    {"a", "b"},
    {"c", "d"},
    {"e", "f"},
    {"g", "h"}
}

Doing

List<string[]> list = new List<string[]>();

list.Add(new string[2] {"a", "b"});
list.Add(new string[2] {"c", "d"});
list.Add(new string[2] {"e", "f"});
list.Add(new string[2] {"g", "h"});

list.ToArray();

gives me

string[][]

but not

string[,]

array.

Just curious, is there some trick to build dynamically

string[,]

array somehow?

[A]
This isn't possible with a
```
List<string[]>
```
, as the type
```
string[,]
```
is different from
```
string[]
```
.


q:
Is it possible to build a .dmg file (for distributing apps) from a non-Mac platform?
And if yes, how?

[A]
If you're distributing Mac apps, then surely you have a Mac to write and test them. Why not simply use that same Mac to create the disk image?
[Edit] Alternatively, if you're distributing a portable app, for example a Java .jar file, why bother with a disk image? Macs understand .zip and .tar.gz archives just fine.
I guess what I'm getting at is, I don't understand how one might need a DMG disk image, but not have a Mac with which to create it.


q:
I have a page P1 loading from site S1 which contains an iframe. That iframe loads a page P2 from another site S2. At some point P2 would like to close the browser window, which contains P1 loaded from S1. Of course, since P2 is loaded from another site, it can't just do parent.close().

I have full control over P1 and P2, so I can add JavaScript code to both P1 and P2 as needed.
Suggestions on how to resolve this?

[A]
It's impossible, I am afraid. JavaScript from an iframe that is loaded to a different site then the one it is being rendered on is strictly prohibited due to security issues.
However, if the iframe is pointed to the same site you can get to it like:
```
```
<iframe name = "frame1" src = "http://yoursite">
</iframe>

<script type = "text/javascript">
    alert(window.frames["frame1"].document);
</script>
```
```


q:
Inspired by this question and answer, how do I create a generic permutations algorithm in F#?  Google doesn't give any useful answers to this.

EDIT: I provide my best answer below, but I suspect that Tomas's is better (certainly shorter!)

[A]
My latest best answer
```
```
//mini-extension to List for removing 1 element from a list
module List =
    let remove n lst = List.filter (fun x -> x <> n) lst

//Node type declared outside permutations function allows us to define a pruning filter
type Node<'a> =
    | Branch of ('a * Node<'a> seq)
    | Leaf of 'a

let permutations treefilter lst =
    //Builds a tree representing all possible permutations
    let rec nodeBuilder lst x = //x is the next element to use
        match lst with  //lst is all the remaining elements to be permuted
        | [x] -> seq { yield Leaf(x) }  //only x left in list -> we are at a leaf
        | h ->   //anything else left -> we are at a branch, recurse
            let ilst = List.remove x lst   //get new list without i, use this to build subnodes of branch
            seq { yield Branch(x, Seq.map_concat (nodeBuilder ilst) ilst) }

    //converts a tree to a list for each leafpath
    let rec pathBuilder pth n = // pth is the accumulated path, n is the current node
        match n with
        | Leaf(i) -> seq { yield List.rev (i :: pth) } //path list is constructed from root to leaf, so have to reverse it
        | Branch(i, nodes) -> Seq.map_concat (pathBuilder (i :: pth)) nodes

    let nodes =
        lst                                     //using input list
        |> Seq.map_concat (nodeBuilder lst)     //build permutations tree
        |> Seq.choose treefilter                //prune tree if necessary
        |> Seq.map_concat (pathBuilder [])      //convert to seq of path lists

    nodes
```
```
The permutations function works by constructing an n-ary tree representing all possible permutations of the list of 'things' passed in, then traversing the tree to construct a list of lists. Using 'Seq' dramatically improves performance as it makes everything lazy.
The second parameter of the permutations function allows the caller to define a filter for 'pruning' the tree before generating the paths (see my example below, where I don't want any leading zeros).
Some example usage: Node<'a> is generic, so we can do permutations of 'anything':
```
```
let myfilter n = Some(n)  //i.e., don't filter
permutations myfilter ['A';'B';'C';'D']

//in this case, I want to 'prune' leading zeros from my list before generating paths
let noLeadingZero n =
    match n with
    | Branch(0, _) -> None
    | n -> Some(n)

//Curry myself an int-list permutations function with no leading zeros
let noLZperm = permutations noLeadingZero
noLZperm [0..9]
```
```
(Special thanks to
Tomas Petricek
, any comments welcome)


q:
In relation to another question, how do you account for paths that may change? For example, if a program is calling a file in the same directory as the program, you can simply use the path ".\foo.py" in *nix. However, apparently Windows likes to have the path hard-coded, e.g. "C:\Python_project\foo.py".

What happens if the path changes? For example, the file may not be on the C: drive but on a thumb drive or external drive that can change the drive letter. The file may still be in the same directory as the program but it won't match the drive letter in the code.

I want the program to be cross-platform, but I expect I may have to use os.name or something to determine which path code block to use.

[A]
If your file is always in the same directory as your program then:
```
```
def _isInProductionMode():
    """ returns True when running the exe,
        False when running from a script, ie development mode.
    """
    return (hasattr(sys, "frozen") or # new py2exe
           hasattr(sys, "importers") # old py2exe
           or imp.is_frozen("__main__")) #tools/freeze

def _getAppDir():
    """ returns the directory name of the script or the directory
        name of the exe
    """
    if _isInProductionMode():
        return os.path.dirname(sys.executable)
    return os.path.dirname(__file__)
```
```
should work. Also, I've used py2exe for my own application, and haven't tested it with other exe conversion apps.


q: I am developing an iOS application, and trying to zip the file I have created in the application, is there any built in function able to do this?

[A]
As Alex pointed out, I responded to
this question
by pointing out the
NSData category
contributed by users of the Cocoadev wiki.  That category includes methods for dealing with zipped and gzipped data in an NSData instance (that could be read from a Zip file or written to one).  This should be all you need to implement the file zipping you describe, as long as you can feed your file data into an NSData instance.
For an example of this category in action, please see the source code for my iPhone application,
Molecules
.  I only use the method to extract data from a gzipped file (in SLSMolecule+PDB.m), but you should be able to get the basic concepts from that.


q:
I've looked at the ReaderWriterLock in .NET 2.0 and the ReaderWriterLockSlim in .NET 3.5, and the slim version doesn't use kernel objects for the locking. For my context, which can potentially generate a large (but not huge) amount of objects, this sounds better.

But the code I write needs to be used in both .NET 2.0 and 3.5 during a transition period, so the 3.5 version, while looking good for my purposes, can't be used.

Does anyone have, or know of, a similar class that I can plug into .NET 2.0 and get some of the same benefits with?

[A]
As far as I know there isn't one from Microsoft (otherwise
```
ReaderWriterLockSlim
```
would be somewhat pointless) and if you find one from a third party other than one you trust to have
excellent
minds who have spent a long time thinking about, implementing and testing it, I wouldn't trust it. I certainly wouldn't trust a random CodeProject implementation, for example.
Do you have any concrete measures to suggest that using
```
ReaderWriterLockSlim
```
would be
so
much better that it's worth looking hard for alternatives for .NET 2.0? It's certainly a "nice to have" but I suspect the cases where it's
massively
significant are relatively rare. Unless you already know that locking is a bottleneck for you, I would stick with what you've got and just be ready to upgrade when you can.
You might want to try just using normal monitors rather than
```
ReaderWriterLock
```
though - in many cases the overhead of RWL outweighs the benefit.
Of course, it's all on a case-by-case basis - your app may be one which really would be made much, much faster by
```
ReaderWriterLockSlim
```
...


q:
Can PL/SQL procedure in Oracle know it's own name?

Let me explain:

CREATE OR REPLACE procedure some_procedure is
    v_procedure_name varchar2(32);
begin
    v_procedure_name := %%something%%;
end;

After %%something%% executes, variable v_procedure_name should contain 'SOME_PROCEDURE'. It is also OK if it contains object_id of that procedure, so I can look up name in all_objects.

[A]
Try:
```
```
v_procedure_name := $$PLSQL_UNIT;
```
```
There's also $$PLSQL_LINE if you want to know which line number you are on.


q:
Does Ruby have any tools along the lines of pylint for analyzing source code for errors and simple coding standards?

It would be nice if it could be integrated with cruisecontrolrb for continuous integration.

Or does everyone write such good tests that they don't need source code checkers!

[A]
One recently-updated interesting-looking tool is
Ruby Object Oriented Design Inferometer
- roodi for short. It's at v1.3.0, so I'm guessing it's fairly mature.
I haven't tried it myself, because my code is of course already beyond reproach (hah).
As for test coverage (oh dear, I haven't tried this one either) there's
rcov
Also (look, I am definitely going to try some of these today. One at least) you might care to take a look at
flog and flay
for another style checker and a refactoring candidate finder.


q:
I have several init.d scripts that I'm using to start some daemons. Most of these scripts I've found on the internet and they all use start-stop-daemon. My understanding is that "start-stop-daemon" is a command that is specific to Linux or BSD distros and is not available on Solaris.

What is the best way to translate my init.d scripts from Linux to Solaris? Is there a command equivalent to start-stop-daemon that I can use, roughly?

Since I'm not much of a Solaris user, I'm willing to admit upfront that I don't even know if my question is inherently invalid or not.

[A]
start-stop-daemon is a Linux thing, and not used that much on Solaris. I guess you can port the command though, if you want to reuse your init scripts.
Otherwise it depends on what version of Solaris you are using. Starting with Solaris 10 and also OpenSolaris they use a new startup script framework "Solaris Service Management Facility", which you configure with the commands
```
svcs
```
,
```
svccfg
```
and
```
svcadm
```
.
See
http://www.oracle.com/technetwork/server-storage/solaris/overview/servicemgmthowto-jsp-135655.html
for more information.
For older Solaris releases most init scripts are written in pure shell without any helper commands like start-stop-daemon.


q:
I need a member of my class to be a Control, and for it to implement an interface we define.

If I declare it like this...

public class MyClass
{
    public Control MyMember;
}

... then I don't get the interface methods, but if I declare it like this...

public class MyClass
{
    public IMyInterface MyMember;
}

...then I don't get the Control methods.  Is there a way to specify that MyMember must be initialised to a type that inherits from both?  I can't find one on MSDN.  Something like...

public class MyClass
{
    public Control : IMyInterface MyMember;
}

... or  ...

public class MyClass
{
    public Control MyMember : IMyInterface;
}

... except that neither of those work.  Can I specify interfaces when I declare a member, and if so, how?

[A]
Use the power of inheritance on the interface
```
```
public interface IMyInterface : Control
{
  ..
}
```
```
Now you say you want a control with some special methods.
EDIT:
TcKs is of course right.. you can't inherit an interface from a concrete class.
One way of solving this problem could be to extend the interface with a property or method that returns a control.
Sample:
```
```
public interface IMyInterface
{
  Control Control { get; }

  [..rest of the definition..]
}
```
```
and implement it like that:
```
```
class MyControl : Control, IMyInterface
{
  public Control Control { get { return this; } }

  [..rest of the implementation..]
}
```
```


q:
I'm writing a ruby program that executes some external command-line utilities. How could I mock the filesystem from my rspec tests so that I could easily setup some file hierarchy and verify it after testing. It would also be best to be implemented in ram so that tests would run quickly.

I realize that I may not find a portable solution as my external utilities are native programs interacting directly with operating system file services. Linux is my primary platform and solution for that would suffice.

[A]
Maybe this won't answer your question directly, but in such cases I tend to create a temporary directory during test setup and remove it on teardown. Of course you also have to ensure the application writes to this temporary directory. I always have a configuration option defining destination directory that I can overwrite during testing.
When it comes to assertions I use plain
```
File.exist?
```
or
```
File.directory?
```
, but of course you can create your own wrappers around it. If you need some initial state you can build a directory that can be used as a fixture and will be copied to the temporary direcory during test setup.


q:
I am trying to use Ganymede CDT to index our large codebase. It is painfully slow, can take a whole night to index the C++ files. Same project takes only 5 seconds to index with exuberant ctags 5.7.

Is there some way to find what the root of the problem is and to speed it up?
Maybe turn on logging in CDT, or some obscure option somewhere that I missed?

[A]
Do you know if this is a regression from 5.0.0? In that case you should definitely open a bugreport.
Is all of your code in the same project? That may have an impact.


q:
I am trying to create a Key Listener in java however when I try

KeyListener listener = new KeyListener();

Netbeans is telling me that KeyListener is abstract;cannot be instantiated. I know that I am missing some other piece of this key listener, but since this is my first time using a key listener i am unsure of what else i need. Why is it telling me this?

Thanks,

Tomek

[A]
```
KeyListener
```
is an interface - it has to be implemented by something. So you could do:
```
```
KeyListener listener = new SomeKeyListenerImplementation();
```
```
but you can't instantiate it directly. You
could
use an anonymous inner class:
```
```
KeyListener listener = new KeyListener()
{
    public void keyPressed(KeyEvent e) { /* ... */ }

    public void keyReleased(KeyEvent e) { /* ... */ }

    public void keyTyped(KeyEvent e) { /* ... */ }
};
```
```
It depends on what you want to do, basically.


q:
In the application there is a dialog where only numeric string entries are valid. Therefore I would like to set the numeric keyboard layout.

Does anyone know how to simulate key press on the keyboard or any other method to change the keyboard layout?

Thanks!

[A]
You can use the InputModeEditor:
```
```
InputModeEditor.SetInputMode(textBox1,InputMode.Numeric);
```
```


q: Is there any open source Object Database available? I would like to have a look at the source code and see how stuffs are implemented.

[A]
http://www.zope.org/Wikis/ZODB
is the first coming to mind, but here's a list of both commercial and open source object databases:
http://www.odbms.org/vendors.html


q: What is meant by using an explicit memory fence?

[A]
In my experience it refers to a
memory barrier
, which is an instruction (explicit or implicit) to synchronize memory access between multiple threads.
The problem occurs in the combination of modern agressive compilers (they have amazing freedom to reorder instructions, but usually know nothing of your threads) and modern multicore CPUs.
A good introduction to the problem is the "
The 'Double-Checked Locking is Broken' Declaration
". For many, it was the wake-up call that there be dragons.
Implicit full memory barriers are usually included in platform thread synchronization routines, which cover the core of it. However, for lock-free programming and implementing custom, lightweight synchronization patterns, you often need just the barrier, or even a one-way barrier only.


q:
When I add an assembly reference to a project in Visual Studio 8 the Aliases property, of that reference, is set to "global".  What is this property good for and why is it set to global?

MSDN tells me that this is a list of aliases for the assembly but not why I might want to use this property or why most are aliased as "global".

MSDN reference

[A]
Search for "
extern alias
"; it is a very rarely used feature that is only needed to disambiguate between two dlls that contribute the same types (for example, two different versions of the same assembly, or two assemblies that have a class which shares a fully-qualified-name).
"global" is the default. For example, if you have a class called
```
Foo.System
```
, you can unambiguously refer to the main
```
System
```
namespace via
```
global::System
```
.


q:
StackOverflow user jolson had a very nice piece of code that exemplifies how one can register menthods without using strings, but expression trees here.

Is it possible to have something similar for properties instead of methods? To pass a property (not the name of the property) and inside the method to obtain the property name?

Something like this:

    RegisterMethod(p => p.Name)

    void RegisterMethod(Expression??? propertyExpression) where T : Property ???
    {
        string propName = propertyExpression.Name;
    }

Thanks.

[A]
You can write something along this:
```
```
static void RegisterMethod<TSelf, TProp> (Expression<Func<TSelf, TProp>> expression)
{
    var member_expression = expression.Body as MemberExpression;
    if (member_expression == null)
        return;

    var member = member_expression.Member;
    if (member.MemberType != MemberTypes.Property)
        return;

    var property = member as PropertyInfo;
    var name = property.Name;

    // ...
}
```
```


q: I want to do the inverse of sort(1) : randomize every line of stdin to stdout in Perl.

[A]
This perl snippet does the trick :
```
```
#! /usr/bin/perl
# randomize cat

# fisher_yates_shuffle code copied from Perl Cookbook
# (By Tom Christiansen & Nathan Torkington; ISBN 1-56592-243-3)

use strict;

my @lines = <>;
fisher_yates_shuffle( \@lines );    # permutes @array in place
foreach my $line (@lines) {
    print $line;
}

# fisher_yates_shuffle( \@array ) : generate a random permutation
# of @array in place
sub fisher_yates_shuffle {
    my $array = shift;
    my $i;
    for ($i = @$array; --$i; ) {
        my $j = int rand ($i+1);
        next if $i == $j;
        @$array[$i,$j] = @$array[$j,$i];
    }
}

__END__
```
```


q:
Is there a way to find all web pages that implement a specific master page in Visual Studio?

I'm looking for a shortcut like shift F12 that will find all usages of a master page. When I do it on the master page class name it only takes me to the design view instead of showing all pages that use it.

I do have Resharper if there is something in there that will help.

I know that I can use the Find dialog but that is not as nice.

[A]
That would be
very
hard to do. You can set master pages in the aspx-files, web.config or in the Page_PreInit event, which make it impossible to know exactly which master page is going to be used.
What MasterPage to you think is used here?
```
```
protected void Page_PreInit(object o)
{
  this.Master = GetMasterFromDataBase(HttpContext.Current.User.Username);
}
```
```
As you can see, there is no way to be sure which master page is really used.


q: What options do I have to read the roles of the current user from my JSP pages? I'm aware of the visibleOnUserRole="myRole" attribute on Tomahawk components, but I need roles for a bit more complicated things than simple visibility.

[A]
The
ExternalContext
exposes user and role information.
```
```
public class RolesAccess implements Serializable {

    public String getUserPrincipalName() {
        FacesContext context = FacesContext.getCurrentInstance();
        Principal principal = context.getExternalContext().getUserPrincipal();
        if(principal == null) {
            return null;
        }
        return principal.getName();
    }

    public String getUser() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getExternalContext().getRemoteUser();
    }

    public boolean isManager() {
        FacesContext context = FacesContext.getCurrentInstance();
        return context.getExternalContext().isUserInRole("manager");
    }

}
```
```
If you're using JSF in servlets, this information maps to the values exposed by the
HttpServletRequest
.
You can use managed beans to expose values to the view via the
Expression Language
.
```
```
<f:view>
    <h:outputLabel value="#{rolesBean.userPrincipalName}" />
    <h:outputLabel value="#{rolesBean.user}" />
    <h:outputLabel value="#{rolesBean.manager}" />
</f:view>
```
```


q:
I have a few text boxes and buttons on my form.

Lets say txtBox1 is next to btnSubmit1,
txtBox2 is next to btnSubmit2,
txtBox3 is next to btnSubmit3.

How can I set the focus on btnSubmit3 when the user starts to type something in txtBox3.
Meaning..... if a user type in a text box the program will know what button to fire when the user press the enter key.

[A]
If you use a panel, you should be able to set a defaultbutton. I´m not sure if it´s an win forms application or a web forms application, but this is how you should do it with web forms:
```
```
<asp:Panel id="panel1" runat="server" DefaultButton="Button1">
   <asp:TextBox id="textbox1" runat="server" />
   <asp:Button id="Button1" runat="server" Text="Button 1" />
</asp:Panel>

<asp:Panel id="panel2" runat="server" DefaultButton="Button2">
   <asp:TextBox id="textbox2" runat="server" />
   <asp:Button id="Button2" runat="server" Text="Button 2" />
</asp:Panel>

<asp:Panel id="panel3" runat="server" DefaultButton="Button3">
   <asp:TextBox id="textbox3" runat="server" />
   <asp:Button id="Button3" runat="server" Text="Button 3" />
</asp:Panel>
```
```


q: Is anybody using JSON.NET with nHibernate?  I notice that I am getting errors when I try to load a class with child collections.

[A]
Are you getting a circular dependancy-error? How do you ignore objects from serialization?
Since lazy loading generates a proxy-objects, any attributes your class-members have will be lost. I ran into the same issue with Newtonsoft JSON-serializer, since the proxy-object didn't have the [JsonIgnore] attributes anymore.


q:
I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:

System.out.println("test");
addKeyListener(new KeyListener() {
    public void keyPressed(KeyEvent e) { System.out.println( "tester"); }

    public void keyReleased(KeyEvent e) { System.out.println("2test2"); }

    public void keyTyped(KeyEvent e) { System.out.println("3test3"); }
});

When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.

I was thinking that it could be because the focus is not on the JFrame

and so they KeyListener doesn't receive any events.  But, I'm pretty sure it is.

Is there something that I am missing?

[A]
Hmm.. what class is your constructor for? Probably some class extending JFrame? The window focus should be at the window, of course but I don't think that's the problem.
I expanded your code, tried to run it and it worked - the key presses resulted as print output. (run with Ubuntu through Eclipse):
```
```
public class MyFrame extends JFrame {
    public MyFrame() {
        System.out.println("test");
        addKeyListener(new KeyListener() {
            public void keyPressed(KeyEvent e) {
                System.out.println("tester");
            }

            public void keyReleased(KeyEvent e) {
                System.out.println("2test2");
            }

            public void keyTyped(KeyEvent e) {
                System.out.println("3test3");
            }
        });
    }

    public static void main(String[] args) {
        MyFrame f = new MyFrame();
        f.pack();
        f.setVisible(true);
    }
}
```
```


q:
Total newbie question but this is driving me mad!
I'm trying this:

myInt = [myFloat integerValue];

but I get an error saying essentially integerValue doesn't work on floats.

How do I do it?

[A]
what's wrong with:
```
```
int myInt = myFloat;
```
```
bear in mind this'll use the default rounding rule, which is towards zero (i.e. -3.9f becomes -3)


q:
Here's the deal - I want a way to figure out specifically which methods were touched or changed within the last milestone/iteration so that the methods' Javadoc is checked for correct content, especially for the public API methods.

Any ideas on how to do this, perhaps with an SVN hook?


q:
I have an invokeworkflow activity inside a replicator activity. The workflow that I'm trying to invoke requires 2 parameters to be passed to it, an integer and a string parameters, and these should be passed to the workflow by the replicator activity. Any ideas on how this could be done?

Thanks.

[A]
You can declare two properties in the target workflow like this:
```
```
public static readonly DependencyProperty MyIntProperty =
        DependencyProperty.Register("MyInt", typeof(int), typeof(Workflow3));
    public static readonly DependencyProperty MyStringProperty =
        DependencyProperty.Register("MyString", typeof(string), typeof(Workflow3));

    public int MyInt
    {
        get { return (int)GetValue(MyIntProperty); }
        set { SetValue(MyIntProperty, value); }
    }

    public string MyString
    {
        get { return (string)GetValue(MyStringProperty); }
        set { SetValue(MyStringProperty, value); }
    }
```
```
After that, if you check the Properties tab of the
```
InvokeWorkflowActivity
```
you will see the two properties in the
```
Parameters
```
category.
You can either provide constant values or you can bind them to any property of the hosting workflow.


q: I have A $param that I am passing into a template. I wish to use the value of this parameter as class name for a div. The class is not taking the value of the parameter but taking the parameter name (in the html page it is $param). Is there any way I can use the value of a parameter as a class name?

[A]
The following should work:
```
```
<div>
<xsl:attribute name="class">
<xsl:value-of select="$param"/>
</xsl:attribute>
</div>
```
```