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

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

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


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

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

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

s: huggingface

c: devops

d: intermediate


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

Original CSS:

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

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

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

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

Thanks.

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


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

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

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

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

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


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

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


q:
I have a table that looks like that:

The rows are sorted by CLNDR_DATE DESC.

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

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

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

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

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


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

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

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

pick a random point'o' along the line,

     pick 'p' that is relatively prime to x

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

To do this for a triangle, I would

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

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

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

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

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


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

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

www.scaleoutsoftware.com

ncache

memcacheddotnet

MS Velocity

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


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

[A]
There's config file:
```
```
<Netbeans>/etc/netbeans.conf

 netbeans_default_userdir=<dir>
```
```


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

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

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

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

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


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

Anyways I want to write:

myIter = mySet.erase(myIter);

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

mySet.erase(myIter++);

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

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


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

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

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

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

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

Thanks

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


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

What is the RAII idiom?

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

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

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

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

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

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


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

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

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

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

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

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


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

How do I use continuous integration with an Eclipse project?

Is there a command line way to do it?

Is there a build server that already supports it natively?

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


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

The methods that I have identified thus far are:

save()

update()

saveOrUpdate()

saveOrUpdateCopy()

merge()

persist()

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


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

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

Exceptions

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

Operators

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

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

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


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

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


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

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

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

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

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

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

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


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

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

What type of coding patterns cause memory leaks in ruby?

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


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

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


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

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

Is 3.5 fully backwards compatible
with 2.0?

Is Entlib 4.0 fully backwards compatible
with 2.0?

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

:)

//W

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


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

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

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


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

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

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

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


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

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

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

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

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

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

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


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

Lee23

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


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

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

And then read the parameters in my controller as follows:

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

How do you achieve this in the Zend Framework?

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

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

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


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

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

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

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


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

Example:

def func(x)
    x += 1
end

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

Btw. I know I could just use:

a = func(a)

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


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

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


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

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


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

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

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

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


q:
Imagine the following Ruby Module:

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

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

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

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

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

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


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

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


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

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

[A]
sp_rename is the correct way to do it.
```
```
EXEC sp_rename 'Old_TableName', 'New_TableName'
```
```


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

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

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

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

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

This code will be running in JavaME environments.

[A]
You just need
```
```
MyAbstract.class
```
```
That expression returns the Class object representing MyAbstract.


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

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

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

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


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

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

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

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

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


q:
Consider the following subversion directory structure

/dir1/file.txt

/dir2/file.txt

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

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

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


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

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

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

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

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

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

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


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

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

}

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


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

I need a Table for GWT that supports:

sorting by particular column

scrolling the data, while the header is immobile

filtering rows for data searched in the table

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

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


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

So an example Perl problem:

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

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

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


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

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


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

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

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

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

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


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

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

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


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

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

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


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

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

Any solution is acceptable even changing php code :)

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


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

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

More examples can be seen here:

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

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

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

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

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


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

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


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

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

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


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

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

An example:

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

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

proc copy inlib=my_xml outlib=WORK;
run;

libname my_xml;
filename my_xml CLEAR;

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

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

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


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

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

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

[A]
Close it. As I recall;
```
```
close(fd);
```
```


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

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

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

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

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


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

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

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


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

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

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

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


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

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

This fixed it:

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

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


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

What are the pros/cons of Membership?

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

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

Many thanks.

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


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

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

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

[A]
See
```
array_combine()
```
on PHP.net.


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

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

What is wrong?

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


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

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


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

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

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

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


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

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

inside index.jsp i then forward on to a servlet

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

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

applicationName/WEB-INF/myServlet

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


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

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

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

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


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

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


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

There are 256 linked lists.

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

All numbers across all lists are unique

Each individual list is sorted in ascending order by these numbers

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

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

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

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


q:
Perforce allows people to check in unchanged files. Why any version control system would allow this is beyond me, but that's a topic for another question.  I want to create a trigger that will deny the submission of unchanged files.  However, I have no experience with Perforce triggers.  From what I've read, I'm guessing this would be a "Change-content" trigger since the files being submitted would have to be diffed against the respective head revisions they are about to replace.  I would need to iterate over the incoming files and make sure they had all indeed changed.  The problem is, I have no idea how to go about it.

Can anyone with Perforce trigger experience offer an example or at least point me in the right direction?

[A]
If you look at the Triggers table in Perforce, you will see that triggers are nothing but scripts that get invoked when some kind of event happens. In your case, the change-content event is triggered.
You have several options to write scripts that interact with Perforce. The
Perforce downloads page
has libraries and modules for many widely use languages. Any of this will help you and greatly simplify what you need to do. Also, check the
Perforce Documentation page
and download the administrator's guide. It will explain how to create the trigger, etc.
Basically, you need to write a script that will get the information from the change list that is being submitted and for each file in it run a "diff" command against the server. If you find a file that has not change, you need to invalidate the submission.
The Perforce module on you favorite language and the administrators guide will give you all the answers you need.


q:
Our company is sending out a lot of emails per day and planning to send even more in future. (thousands) Also there are mass mailouts as well in the ten thousands every now and then.

Anybody has experience with hotmail, yahoo (web.de, gmx.net) and similar webmail companies blocking your emails because "too many from the same source in a period of time" have been sent to them?

What can be done about it? Spreading email mailouts over a whole day/night? At what rate?

(we are talking about legal emailing just to make sure...)

[A]
If you want to do this you're getting into some of the same techniques spammers use. Spreading email mailouts over a day or night could be a way to do it. I don't think anyone  knows the 'right' rate to do this because varies per mail-provider and they probably adjust this over time. You could try spreading the emails sent to a single provider. If you've got a lot of mail for hotmail.com for example then don't send it all at the same time.
Maybe it would be a good idea to look at pull media instead of push media for your application. You could put the content of the mass mailings up on a website and notify interested readers with an rss feed for example. This has a lower risk of irritating potential customer. And your company has a lower risk of being sued for spamming.
You're right, rss is not really accessible for all users. But as you'll probably need to create a webpage-alternative to the mailings anyway for people who can't read html-mail. You might as well provide an rss feed to those pages as an alternative for the users who do want to use it. This might reduce the volumes for the mailings enough to make your job a bit easier.


q:
I have been trying to determine a best case solution for registering a COM server using WiX to create a Windows Installer package and am struggling.

In this post Deployment Engineering Archive: HOWTO: Use Regsvr32.exe with WIX, there is an open request for the "Setup police" to crack down on using regsvr32 through an exe custom action.  I know the evils of using regsvr32 as it registers to the system rather than the user, but I also recall that OleSelfRegister can have issues from a microsoft support bulletin (sorry, can't find the link) - and I believe they recommended using regsvr32.

Any advice?

[A]
Read "Do not use the SelfReg and TypeLib tables" at:
https://msdn.microsoft.com/en-us/library/bb204770#no_selfreg
For WiX, take a look at the
Component
element in the schema reference at:
http://wixtoolset.org/documentation/manual/v3/xsd/wix/component.html
Take notice of certain child elements such as
AppId
,
Class
,
ProgId
,
Registry
and so on.  The proper technique is to use
```
COM extraction
```
to reflect the registration information and emit it declaratively into your installer so MSI can take care of it for you without going out of process to some code (like
```
DllRegisterServer()
```
) that could fail and also not provides MSI insight into the footprint of the component from a repair and advertisement perspective.


q:
When used like this:

import static com.showboy.Myclass;

public class Anotherclass{}

what's the difference between import static com.showboy.Myclass and import com.showboy.Myclass?

[A]
See
Documentation
The static import declaration is
  analogous to the normal import
  declaration. Where the normal import
  declaration imports classes from
  packages, allowing them to be used
  without package qualification, the
  static import declaration imports
  static members from classes, allowing
  them to be used without class
  qualification.
So when should you use static import?
  Very sparingly! Only use it when you'd
  otherwise be tempted to declare local
  copies of constants, or to abuse
  inheritance (the Constant Interface
  Antipattern). In other words, use it
  when you require frequent access to
  static members from one or two
  classes. If you overuse the static
  import feature, it can make your
  program unreadable and unmaintainable,
  polluting its namespace with all the
  static members you import. Readers of
  your code (including you, a few months
  after you wrote it) will not know
  which class a static member comes
  from. Importing all of the static
  members from a class can be
  particularly harmful to readability;
  if you need only one or two members,
  import them individually. Used
  appropriately, static import can make
  your program more readable, by
  removing the boilerplate of repetition
  of class names.


q:
I am looking for a Dataflow / Concurrent Programming API for Java.

I know there's DataRush, but it's not free. What I'm interested in specifically is multicore data processing, and not distributed, which rules out MapReduce or Hadoop.

Any thoughts?

Thanks,
Rollo

[A]
Does the built in Java
concurrent
package meet your needs?  It's a very nice package, built in ThreadPools, CopyOnWriteCollections, Executors, Future.  We use it to process large volumns of data in thread pools.


q: What level of CPU usage should be considered high for SQL Server? ie 80% 90% 100%?

[A] It really depends on your machine.  The best thing is to monitor the server using perfmon and see when things start to run slowly.  It is normal for SQL to use a lot of CPU under load.


q: What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".

[A]
I thought this would work, based on
this source
.
```
```
SELECT
  'Currently, '
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of '
  || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX)
  || ' connections are used.' AS USAGE_MESSAGE
FROM
  V$LICENSE VL
```
```
However, Justin Cave is right.  This query gives better results:
```
```
SELECT
  'Currently, '
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of '
  || VP.VALUE
  || ' connections are used.' AS USAGE_MESSAGE
FROM
  V$PARAMETER VP
WHERE VP.NAME = 'sessions'
```
```


q:
I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want.  The div that houses the facebox content is created outside of the  tag so even though I am loading up some web controls none of them are firing back to the server.

Has anyone dealt with this that can give me some pointers?

[A]
poking around the facebox.js I came across this line in the function init(settings)...
```
```
$('body').append($.facebox.settings.faceboxHtml)
```
```
I changed that to ...
```
```
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
```
```
and it loads up in the form tag, not sure yet if there are any side effects


q:
How can I check if an application is running from a batch (well cmd) file?

I need to not launch another instance if a program is already running. (I can't change the app to make it single instance only.)

Also the application could be running as any user.

[A]
You should check the parent process name, see
The Code Project
article about a
.NET based solution**
.
A non-programmatic way to check:
Launch Cmd.exe
Launch an application (for instance,
```
c:\windows\notepad.exe
```
)
Check properties of the Notepad.exe process in
Process Explorer
Check for parent process (This shows cmd.exe)
The same can be checked by getting the parent process name.


q:
I have a basic ActiveRecord model in which i have two fields that i would like to validate. The requirement is that at least one of the fields must have a value. Both can have values, but at least one needs a value.

How do i express this with

validates_presence_of

statements? For example:

validates_presence_of :main_file
validates_presence_of :alt_file

i don't want an error to be generated if only one of them is empty, only if both are empty.

[A]
```
```
validates_presence_of :main_file, :if => Proc.new { |p| p.alt_file.blank? }
validates_presence_of :alt_file, :if => Proc.new { |p| p.main_file.blank? }
```
```


q: How can I convert a Char[] (of any length) to a List  ?

[A]
First you need to understand that chars aren't bytes in .NET. To convert between chars (a textual type) and bytes (a binary type) you need to use an encoding (see System.Text.Encoding).
Encoding will let you convert between string/char[] and byte[]. Once you've got a byte array, there are various ways of converting that into a List<byte> - although you may not even need to, as byte[] implements IList<byte>.
See
my article on Unicode
for more about the text conversion side of things (and links to more articles).


q:
I've been using Remote Desktop Connection to get into a workstation. But in this environment, I cannot use the power options in Start Menu. I need an alternative way to shutdown or restart.

How do I control my computer's power state through the command line?

[A]
The most common ways to use the
```
shutdown
```
command are:
```
shutdown -s
```
— Shuts down.
```
shutdown -r
```
— Restarts.
```
shutdown -l
```
— Logs off.
```
shutdown -h
```
— Hibernates.
Note:
There is a common pitfall wherein users think
```
-h
```
means "help" (which it does for every other command-line program... except
```
shutdown.exe
```
, where it means "hibernate"). They then run
```
shutdown -h
```
and accidentally turn off their computers. Watch out for that.
```
shutdown -i
```
— "Interactive mode". Instead of performing an action, it displays a GUI dialog.
```
shutdown -a
```
— Aborts a previous shutdown command.
The commands above can be combined with these additional options:
```
-f
```
— Forces programs to exit. Prevents the shutdown process from getting stuck.
```
-t <seconds>
```
— Sets the time until shutdown. Use
```
-t 0
```
to shutdown immediately.
```
-c <message>
```
— Adds a shutdown message. The message will end up in the Event Log.
```
-y
```
— Forces a "yes" answer to all shutdown queries.
Note:
This option is not documented in any official documentation. It was discovered by
these StackOverflow users
.
I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order.
The
```
-f
```
option
from
JosephStyons
Using
```
rundll32
```
from
VonC
The Run box
from
Dean
Remote shutdown
from
Kip


q: What role is Spring taking in Struts + Spring + Hibernate?

[A]
Spring provides many different "modules" and different programmers will use different parts of Spring.
However, commonly in this sort of stack, you will see Spring being used as a provider of
An inversion of control container for dependency injection
An abstraction to Hibernate called "HibernateTemplate"
Framework classes for simplifying Aspect Oriented Programming
Transaction support, often "declaratively" via the IoC container and AOP.


q:
I use FB1.5.3 and need to eventually add some FK to the database.
It happens that if I try to do it while anyone else is connected to the DB I get an exception.

Is there a way to add an FK while the system is running?

[A]
I believe this is a limitation on firebird 1.5 and earlier.
Try google for (firebird foreign key "object is in use").
hth


q:
I was browsing Scott Hanselman's Developer Interview question list, and ran across this question:

What is wrong with
  DateTime.Parse(myString)?

While I know there are inherent risks in parsing a string of unknow format or origin, are there other reasons? Is it to use DateTime.ParseExact instead? Should it be myString.ToString() first?

[A]
In addition the locale problem,
```
DateTime.Parse()
```
could also throw an exception which you would then have to catch.  Use
```
DateTime.TryParse()
```
or
```
DateTime.TryParseExact()
```
instead.


q:
Hi why doesn't this work in SQL Server 2005?

select HALID, count(HALID) as CH from Outages.FaultsInOutages

where CH > 3

group by HALID

I get invalid column name 'CH'

i think having was the right way to go but still receive the error:
Invalid column name 'CH'.

When running:

select HALID, count(HALID) as CH from Outages.FaultsInOutages
group by HALID having CH > 3

[A]
Try
```
```
select HALID, count(HALID) from Outages.FaultsInOutages
group by HALID having count(HALID) > 3
```
```
Your query has two errors:
Using where an aggregate when grouping by, solved by using having
Using an alias for an aggregate in the condition, not supported, solved by using the aggregate again


q: Can someone explain what are the benefits of using the @import syntax comparing to just including css using the standard link method?

[A] It allows you to keep your logic CSS file spread over multiple physical files. Helps in team development, for example. Also useful when you have a lot of CSS files that you want to separate by functional areas (one for grids, one for lists, etc), let have accessible in the same logical file.


q:
I have 3 tables

Links

Link ID

Link Name

GroupID (FK into Groups)

SubGroupID (FK into Subgroups)

Groups

GroupID

GroupName

SubGroup

SubGroupID

SubGroupName

GroupID (FK into Groups)

Every link needs to have a GroupID but teh SubGroupID is optional.  How do i write a SQL query to show:

Links.LinkName, Groups.GroupName, SubGroup.SubGroupName

For the records with no subgroup just put a blank entry in that field.  If i have 250 link rows, i should get back 250 reecords from this query.

Is there a way to do this in one query or do i need to do multiple queries?

[A]
```
```
SELECT
  links.linkname
  , groups.groupname
  , subgroup.groupname
FROM
  links
  JOIN groups ON links.groupid = groups.groupid
  LEFT OUTER JOIN subgroups ON links.subgroupid = subgroup.subgroupid
```
```
(re-added to address OP's question)
incidentally, why not keep groups and subgroups in the same table, and use a self-referential join?
Akantro:
You'd have something like this:
    create table groups(
    groupid integer primary key,
    parentgroupid integer foreign key references groups (groupid),
    groupname varchar(50))
your query would then be
```
```
SELECT
  links.linkname
  , groups.groupname
  , SUBGROUPS.groupname
FROM
  links
  JOIN groups ON links.groupid = groups.groupid
  LEFT OUTER JOIN groups SUBGROUPS ON links.subgroupid = subgroup.groupid
```
```
there's no functional difference to keeping the tables like this, but the benefit is you only have to go to one place to edit the groups/subgroups


q:
Consider:

int testfunc1 (const int a)
{
  return a;
}

int testfunc2 (int const a)
{
  return a;
}

Are these two functions the same in every aspect or is there a difference?

I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.

[A]
Yes, they are same for just
```
int
```
and different for
```
int*
```


q:
I just upgraded a VS 2005 project to VS 2008 and was examining the changes.  I noticed one of the .Designer.cs files had changed significantly.  The majority of the changes were simply replacements of System with global::System. For example,

protected override System.Data.DataTable CreateInstance()

became

protected override global::System.Data.DataTable CreateInstance()

What's going on here?

[A]
The :: operator is called a Namespace Alias Qualifier.
```
```
global::System.Data.DataTable
```
```
is the same as:
```
```
System.Data.DataTable
```
```
Visual Studio 2008 added it to the designer generated code to avoid ambigious reference issues that occasionally happened when people created classes named System...For example:
```
```
class TestApp
{
    // Define a new class called 'System' to cause problems.
    public class System { }

    // Define a constant called 'Console' to cause more problems.
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // Error  Accesses TestApp.Console
        //Console.WriteLine(number);
    }
}
```
```
However:
```
```
global::System.Console.Writeline("This works");
```
```
For further reading:
http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx


q:
How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work.

For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete.

Then I went into the routes.rb file and entered map.resources :employees, which gives you access to the URL helper functions.

In whatever I want to call the Ajax operation from, I should just have a line like:

<%= link_to_remote "Delete", employee_path(@employee), :method => :delete %>

When I click on the link, it is still is sending a POST operation, so it does nothing.

What am I missing or doing wrong?

[A]
Try
```
```
:url => employee_url(@employee)
```
```
IIRC, *_path is a named route generated by the :resource directive which includes the method, thus overwriting your :method => :delete


q:
I need a way to update the month value on a dateTime field in my db. I'm being past an int value for the month and need to use that for the update.
Is it possible to do this in the sql statement or would I be best doing it in c# in the webservice?

[A]
Shift down and then up again:
```
```
UPDATE table
SET datecol = DATEADD(m, @newmonth, DATEADD(m, -MONTH(datecol), datecol))
WHERE id = @id
```
```
or, more simply:
```
```
UPDATE table
SET datecol = DATEADD(m, @newmonth - MONTH(datecol), datecol)
WHERE id = @id
```
```


q:
I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?

I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.

[A]
Short answer: you can't.
Long answer: you can't, partly because the database may be lazily evaluating the query, only returning rows as you ask for them.
EDIT: Using a scrollable ResultSet you can :)
Indeed, I asked this very question in the Java databases newsgroup a long time ago (back in 2001!) and had some
helpful responses
.


q:
I am currently working on an asp.net application in Visual Studio 2005. I would like to upgrade to 2008 to take advantage of some of the new features, but my remote team won't be able to upgrade to it for a while.

Is it possible for only a few people on my team to upgrade to Visual Studio 2008, while the rest of the team continues to use 2005?

At this point, I don't plan on using any of the 3.0+ foundation stuff yet, so that isn't a concern.

[A]
Yes, the project files between 2005 and 2008 are compatible.  The solutions are not, but those are easy to remake or copy.  There is one gotcha with the project files, if you're using Web Applications projects.  The two versions reference different MSBuild target files.  Steven Harman has
a blog with a fix to add to the project file
.
So long as you aren't using anything new from the 3.5 compiler, you should be good.  Note that even if you are targeting the 2.0 Framework, the compiler will still accept 3.5 syntax (var, object initializers, etc.) so you'll still need to be aware of those.


q:
When creating a new file with vim, I would like to automatically add some skeleton code.

For example, when creating a new xml file, I would like to add the first line:

  <?xml version="1.0"?>

Or when creating an html file, I would like to add:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title></title>
  </head>
  <body>
  </body>
</html>

[A]
Here are two examples using python scripting.
Add something like this in your .vimrc or another file sourced by your .vimrc:
```
```
augroup Xml
  au BufNewFile *.xml :python import vim
  au BufNewFile *.xml :python vim.current.buffer[0:0] = ['<?xml version="1.0"?>']
  au BufNewFile *.xml :python del vim
augroup END

fu s:InsertHtmlSkeleton()
  python import vim
  python vim.current.buffer[0:0] = ['<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', "", "", "  <title></title>", "", "", "", "", ""]
  python del vim
endfu

augroup Html
  au BufNewFile *.html call <SID>InsertHtmlSkeleton()
augroup END
```
```


q:
Using C#

How do you remove a specific node from an XMLDocument using XPATH?

[A]
Here you go.   ChildNodeName, could be just the node name or an XPath query.
```
```
XmlDocument doc = new XmlDocument();

// Load you XML Document

XmlNode childNode = doc.SelectSingleNode(childNodeName);

// Remove from the document
doc.RemoveChild(childNode);
```
```
There is a different way using Linq, but I guessed you were using .NET 2.0


q:
What is the difference between these two pieces of code

type
  IInterface1 = interface
    procedure Proc1;
  end;

  IInterface2 = interface
    procedure Proc2;
  end;

  TMyClass = class(TInterfacedObject, IInterface1, IInterface2)
  protected
    procedure Proc1;
    procedure Proc2;
  end;

And the following :

type
  IInterface1 = interface
    procedure Proc1;
  end;

  IInterface2 = interface(Interface1)
    procedure Proc2;
  end;

  TMyClass = class(TInterfacedObject,  IInterface2)
  protected
    procedure Proc1;
    procedure Proc2;
  end;

If they are one and the same, are there any advantages, or readability issues with either.

I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.

[A]
Assuming you meant
```
```
...
IInterface2 = interface(Interface1)
...
```
```
I interpret it the same as you,
the second form requires a class implementing Interface2 to implement Interface1 as well
, while the first form does not.


q:
We don't exactly comply with the XML-RPC spec, but the concepts are nearly identical.  A client comes in over HTTP/HTTPS with an XML payload.  We respond with an XML payload answering the request.  This is primarily machine to machine, so no human to type a username/password.  Our construct runs within apache tomcat.  We would like to authenticate the request and since not every service is available to every client, we need to authorize the request as well.  We have both subscription and per use charging models so it is necessary to log everything.

What would you recommend for both server and client?

[A]
HTTP BASIC/DIGEST works fine for most machine to machine tasks, and it handled by the server so your API is unaffected.
It doesn't work as well for interactive uses because it's difficult to "log out" the user without closing the browser.
Otherwise you'll most likely need to alter your APIs to include authentication information and have your methods authenticate that within your code.
Or you could use the classic "login", set a cookie, keep a session technique.
But, frankly, for machine to machine work, HTTP BASIC is the easiest.
edit, regarding comments.
HTTP BASIC is simply a protocol used to present the artifacts necessary for authentication, and it works well for machine to machine web services.
HOW IT IS IMPLEMENTED is dependent on you and your application. Using Java, you can use container authentication and that will provide authentication as well as role mapping. The user -> role mapping is handled in either a data file or database. The URLs protected, and what roles are valid for each URL, is managed by web.xml.
If you continue to add different roles to different URLs, then, yes, you'll need to redeploy that application.
However, if you're just adding new users, then you simply update your file or database. And if you're adding new logic, and this new URLs, then you have to redeploy anyway. If you have a ROLE structure with a fine enough granularity, you won't have to be messing with the web.xml until you actually add new methods. For example you could, at the extreme, create a role per method, and assign them individually to users. Most don't need to go that far.
If you don't want to use container authentication, then write a Servlet Filter to implement your vision of mapping user and roles to URLs. You can still use the HTTP BASIC protocol for your clients, even if you implement your own facility.
If you're looking for an overall generic Java security framework, I defer to google -- there are several, I've not used any of them. I've had good luck with container authentication and writing our own.


q:
When using tooltips to show a detailed description of a TreeNode, the tooltip is drawn on top of the node, as if it was completing the node's text. Also, if the text is long, the tooltip is positioned in a way that the text exceeds the screen.

But what I need is the tooltip to show right below the mouse pointer and not on top of the TreeNode.

Any idea how to do this?

Show, don't tell:

How it is:

How I want:

[A]
You need to define a ToolTip and write an MouseOverEventHandler for the TreeView. In the MouseOverEventHandler calculate the node above which mouse is positioned, then show the description ToolTip. Also make sure you are not setting the tooltip description more than once, otherwise the behavior is quite ugly.
A better way is to show the description in the StatusStrip - bottom left of the Form.
Update:
OK since you have clarified your question. You can use
```
ToolTip.Show
```
method where you can specify coordinates:
```
```
public void Show(
    string text,
    IWin32Window window,
    int x,
    int y,
    int duration
)
```
```
Obviously, you'll have to add offset to x and y.


q:
Given the email address: "Jim" <jim@example.com>

If I try to pass this to MailAddress I get the exception:

The specified string is not in the form required for an e-mail address.

How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?

EDIT:  I'm looking for C# code to parse it.

EDIT2:  I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string.

[A]
Try:
```
```
"Jimbo <jim@example.com>"
```
```


q:
Using the default TWebBrowser makes things easy to embed a web browser. Unfortunately the one that comes in by default is IE<n>.

I'm wondering how does one integrate a Gecko or WebKit one.

Are there VCL examples somewhere?

If not, how would one go about doing it?

Where's the best place to find the core for Gecko and/or WebKit in an embeddable format?

[A]
TWebBrowser
is
IE. It is not a plugable construction for browsers. You can have other browsers integrated in your application. See
http://www.adamlock.com/mozilla/
http://delphi.mozdev.org/articles/taming_the_lizard_with_delphi.html
http://ftp.newbielabs.com/Delphi%20Gecko%20SDK/
Time has moved on
This answer is from '08 and since then time has moved on. The links don't work anymore and there are probably better alternatives now.


q:
I have a table column that needs to be limited to a certain width - say 100 pixels.  At times the text in that column is wider than this and contains no spaces. For example:

a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy

I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters.  The problem is that I don't have data about the rendered size of the text.

For example, assuming the browser was Firefox 3 and the font was 12px Arial.  What would be the width of the letter "a", the width of the letter "b", etc.?

Do you have data showing the pixel width of each character?  Or a program to generate it?

I think a clever one-time javascript script could do the trick.  But I don't want to spend time re-inventing the wheel if someone else has already done this.  I am surely not the first person to come up against this problem.

[A]
Very very hard to do server-side. You can never know what fonts users have installed, and there are many things that affect the display of text.
Try this instead:
```
```
table-layout: fixed;
```
```
That'll make sure the table is never larger than the size you specified.


q: What do you think the next evolution of languages will look like?

[A]
You might assume C and C++ are being "phased out" and that Java/.Net/Python/whatever is an "advance" or the "next stop".
They are all used heavily (see the number C or C++ of tags on this site). The difference is that neither one is the lingua-franca of the programming world anymore. It used to be that the majority of apps were desktop or DOS apps on systems with very limited resources, furthermore all the major desktop APIs were written in C or C++. So everyone learned these.
Now its more complex. Languages are becomming more application specific. C/C++ for when performance is important. Scripting languages for when your main performance hit is db reads/writes. Java and .Net for generic, non-performance-critical desktop apps.
Its the same thing with computer or electrical engineering. In the past these were huge fields at the highest level of abstraction available. Now we have all sorts of higher levels of abstraction. Still, we need people to do this lower-level kind of engineering. They are still in demand. In the same manner, C will continue to be used in many environments, as will C++. You'd be crazy, for instance, to think that you could write a device driver in Java, you'd also be mildly crazy (but perhaps less so) to write a full fledged GUI app in C if you had the choice and ability to do it in Java or .Net.
Each tool has its purpose. I expect C, C++, and Java to evolve and continue to be used for new and legacy development.


q:
On a project I'm working on, we use subversion, with tortoiseSVN as a client, under windows XP.

As we enter in production and continue development in parallel, many branches are created.

Often, we have to backport modifications made on the branch to the trunk, or to older branches. Backporting is a very delicate task, as many errors can be introduced into the code.

What are your favorite tools to make backporting easier and more secure ? If possible, add only one tool per answer, and vote for your favorite ones.


q:
I am using a multi-dimensional dynamic array in delphi and am trying to figure this out:

I have 2 seperate values for the first index and second index that are totally seperate of each other.

As new values come I want to grow the array if that new value is outside of either bound.

For new values x, y

I check:

if Length(List) < (x + 1) then
   SetLength(List, x + 1);
if Length(List[0]) < (y + 1) then
   SetLength(List, Length(List), y + 1);

Is this the correct way to do this or is there a better way to grow the array as needed?

[A]
It looks fine to me - if you change the last line to
```
```
SetLength(List, Length(List), y + 1);
```
```