q: What would be a good local database for a Silverlight application?  The database's main purpose is for local data caching and synchronization services. I do not believe that SQL anywhere or SQLite will work since they use unmanaged code which will not run under the silverlight sandbox

[A]
@Aaron Fischer,
I'm very interested in this question too. I'm looking DB for XBAP (WPF in browser) apps. Here is my question
"What embedded database with Isolated Storage support can you recommend?"
SQLite & MSSQL CE (aka SQL anywhere) wouldn't work.
VistaDB is implemented in .NET and can work under constraints (it has support for Isolated Storage) but I'm looking for alternatives.
Another option is Sybase iAnywhere - but I'm not sure how to deploy it on end-user machine.
I'm going to try DB4objects for Silverlight. If it would work, I'll update the post.


q: The background should be transparent, but the text should not.

[A]
By making an "Enso style" application you mean the Enso launcher?
Here is a screenshot of it:
alt text http://enscreenshots.softonic.com/s2en/68000/68880/3_ensolauncher03.jpg
I would suggest at looking at the open-source C#
Cropper
application.  He does a similar looking GUI with transparent background.  You can open up his project and see how he implements it.
alt text http://img352.imageshack.us/img352/726/cropperuijt3.png

s: huggingface

c: devops

d: intermediate


q:
Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means.

I suppose everybody made once a mistake with parenthesis, resulting  in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __call__ can be used for.

Could you give me some explanations, including examples with the magic method ?

[A]
A Callable is an object that has the
```
__call__
```
method.  This means you can fake callable functions or do neat things like
Partial Function Application
where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as
Currying
in functional programming circles).
Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string.  This can produce errors where the interpreter attempts to execute a non-callable application.  You can see this happening in a python interpreter by doing something like the transcript below.
```
```
[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 15:55:44)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'()    # <== Here we attempt to call a string.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>>
```
```


q: I'm looking for an .xsd schema file to drop into my Visual Studio directory to provide intellisense for the xml configuration file for the Castle Windsor IoC container. I've looked in the downloaded code for Windsor, as well as googled several different ways. I see many people asking the same question, but no answers. Anyone know if there is such a document?

[A]
Perhaps this is what you are looking for:
http://jimblogdog.blogspot.com/2008/05/castlewindsor-schema-enables-visual.html
Here is the link to download the castle windsor schema:
http://www.projectdistributor.net/Releases/Release.aspx?releaseId=427
Good Luck!


q:
The question of whether P=NP is perhaps the most famous in all of Computer Science. What does it mean? And why is it so interesting?

Oh, and for extra credit, please post a proof of the statement's truth or falsehood. :)

[A]
A short summary from my humble knowledge:
There are some easy computational problems (like finding the shortest path between two points in a graph), which can be calculated pretty fast ( O(n^k), where n is the size of the input and k is a constant (in the case of graphs, it's the number of vertexes or edges)).
Other problems, like finding a path that crosses every vertex in a graph or getting the RSA private key from the public key is harder (O(e^n)).
But CS speak tells that the problem is that we cannot 'convert' a non-deterministic Turing-machine to a deterministic one, we can, however, transform non-deterministic finite automatons (like the regex parser) into deterministic ones (well, you can, but the run-time of the machine will take long). That is, we have to try every possible path (usually smart CS professors can exclude a few ones).
It's interesting because nobody even has any idea of the solution. Some say it's true, some say it's false, but there is no consensus. Another interesting thing is that a solution would be harmful for public/private key encryptions (like RSA). You could break them as easily as generating an RSA key is now.
And it's a pretty inspiring problem.


q: I have an Interbase DB. How can I convert it to SQL Server?

[A]
If you want to spend some money, this will do it:
http://www.spectralcore.com/fullconvert/tutorials/convert-interbase-firebird-to-mssql-sql-server.php


q: Needs to be secure and able to handle thousands of users.

[A]
Check out ADAM and AzMan.
ADAM is Active Directory Application Mode.  There is a how-to guide at:
http://msdn.microsoft.com/en-us/library/ms998331.aspx
AzMan is Authorization Manager.  There is a how-to guide at:
http://msdn.microsoft.com/en-us/library/ms998336.aspx


q: From my own "key logger like" process I figured out that another process Locale is wrong (i.e. by sniffing few keys, I figured out that the foreground process Locale should be something while it is set to another). What's the best way to do this?

[A]
I'd use
setLocale
from within that process to change it, and notify the process about this with some form of IPC like:
signals
sockets
pipes
from the process who knows


q:
Is there a cheap way to get the dimensions of an image (jpg, png, ...)? Preferably, I would like to achieve this using only the standard class library (because of hosting restrictions). I know that it should be relatively easy to read the image header and parse it myself, but it seems that something like this should be already there. Also, I’ve verified that the following piece of code reads the entire image (which I don’t want):

using System;
using System.Drawing;

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            Image img = new Bitmap("test.png");
            System.Console.WriteLine(img.Width + " x " + img.Height);
        }
    }
}

[A]
Have you tried using the WPF Imaging classes?
```
System.Windows.Media.Imaging.BitmapDecoder
```
, etc.?
I believe some effort was into making sure those codecs only read a subset of the file in order to determine header information. It's worth a check.


q:
I have a Rails project which I neglected to build tests for (for shame!) and the code base has gotten pretty large. A friend of mine said that RSpec was a pain to use unless you use it from the beginning. Is this true? What would make him say that?

So, considering the available tests suites and the fact that the code base is already there, what would be my best course of action for getting this thing testable? Is it really that much different than doing it from the beginning?

[A]
Maybe start with the models? They should be testable in isolation, which ought to make them the lowest-hanging fruit.
Then pick a model and start writing tests that say what it does. As you go along, think about other ways to test the code - are there edge cases that maybe you're not sure about? Write the tests and see how the model behaves. As you develop the tests, you may see areas in the code that aren't as clean and de-duplicated (DRY) as they might be. Now you have tests, you can refactor the code, since you know that you're not affecting behaviour. Try not to start improving design until you have tests in place - that way lies madness.
Once you have the models pinned down, move up.
That's one way. Alternatives might be starting with views or controllers, but you may find it easier to start with end-to-end transaction tests andwork your way into smaller and smaller pieces as you go along.


q:
Should simple JavaBeans that have only simple getters and setters be unit tested??

What about Beans with some logic in getters and setters?

[A]
If it's not worth testing, it's not worth writing.
That doesn't always mean you should write tests.  Sometimes it means you should delete code.  Do you need these beans?  Do they actually do anything important?  If you need them, you should write tests.  If not, delete the code and live a happier life knowing you have less to maintain.


q:
Is it OK if the same OpenSSL context is used by several different accepting sockets?

In particular I'm using the same boost::asio::ssl::context with 2 different listening sockets.

[A]
Yep, SSL_CTX--which I believe is the underlying data structure--is just a global data structure used by your program. From ssl(3):
SSL_CTX (SSL Context)
That's the global context structure which is created by a server or client once per program life-time and which holds mainly default values for the SSL structures which are later created for the connections.


q:
I have some problems with Miktex installed on Windows Vista Business SP1/32 bit. I use miktex 2.7, ghostscript, and texniccenter 1 beta 7.50. When I compile a document with the following profiles: Latex=>DVI, Latex=>PDF everything works fine; the system crashes when I compile with profiles Latex=>PS and Latex=>PS=>PDF. The error is reported into a window that states: "Dvi-to-Postscript converter has stopped working". What can I do? I need Latex=>PS=>PDF to include my images into the final PDF.

Thanks in advance,
Yet another LaTeX user

[A]
If everything you need is images, you could still compile directly to PDF. You only need to have an image in PNG or JPG format, and use the following code:
```
```
%in the document preamble
\usepackage{graphicx}

%in the document, in the place where you want to put your image
\includegraphics{image_filename_without_extension}
```
```
When the image is a PNG or JPG file (there are some more, I don't remember which ones ATM), you can compile the file with pdfLaTeX, but not with the normal LaTeX (i.e. you can produce a PDF, but not DVI or PS).
Of course normally, if everything works fine, it's nice to have one copy of the image in EPS, and another in, say, PNG -- this way you can compile easily both to PDF, and to PS.
Hope that helps.


q:
I have a simple unordered list that I want to show and hide on click using the jQuery slideUp and slideDown effect.  Everything seems to work fine, however in IE6 the list will slide up, flicker for a split second, and then disappear.

Does anyone know of a fix for this?

Thanks!

[A]
```
```
$(document).ready(function() {
    // Fix background image caching problem
    if (jQuery.browser.msie) {
        try {
            document.execCommand("BackgroundImageCache", false, true);
        } catch(err) {}
    }
};
```
```
Apparently
.


q: What’s the difference between Response.Write() and Response.Output.Write()?

[A]
Nothing really.
But.
```
Response.Write
```
takes the stream in the
```
Response.Output
```
property. You could set another Output stream, and in that way instead of writing back to the client, maybe write to a file or something crazy. So thats there relation.


q: I want to have my PHP application labeled with the revision number which it uses, but I don't want to use CruiseControl or update a file and upload it every time. How should I do it?

[A]
Assuming your webroot is a checked-out copy of the subversion tree, you could parse the /.svn/entries file and hook out the revision number (4th line here)...
In PHP:
```
```
$svn = File('.svn/entries');
$svnrev = $svn[3];
unset($svn);
```
```


q:
How can I detect, using php, if the machine has oracle (oci8 and/or pdo_oci) installed?

I'm working on a PHP project where some developers, such as myself, have it installed, but there's little need for the themers to have it.  How can I write a quick function to use in the code so that my themers are able to work on the look of the site without having it crash on them?

[A]
I dont know if I fully understand your question but a simple way would be to do this:
```
```
<?php
  $connection = oci_connect('username', 'password', 'table');
  if (!$connection) {
    // no OCI connection.
  }
?>
```
```


q: Why is it wrong to use std::auto_ptr<> with standard containers?

[A]
The
copy semantics
of
```
auto_ptr
```
are not compatible with the containers.
Specifically, copying one
```
auto_ptr
```
to another does not create two equal objects since one has lost its ownership of the pointer.
More specifically, copying an
```
auto_ptr
```
causes one of the copies to let go of the pointer. Which of these remains in the container is not defined. Therefore, you can randomly lose access to pointers if you store
```
auto_ptrs
```
in the containers.


q:
When adding new properties to classes, I find myself typing the same things over and over in xcode:

add TYPE *NAME; (in .h interface)

add @property (nonatomic, retain) TYPE *NAME; (in .h)

add @synthesize NAME; (in .m)

add [NAME release]; (in .m dealloc)

(I'm in a non-garbage collected environment.)

How can I do this automatically?

[A]
That sounds about right.  IIRC, the Objective-C 2.0 doc says you might be able to leave out step #1, but otherwise I don't know of any shortcuts.
You could probably write a user script to do so within Xcode.  See
http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html
.


q:
Is there any way to create the query parameters for doing a GET request in JavaScript?

Just like in Python you have urllib.urlencode(), which takes in a dictionary (or list of two tuples) and creates a string like 'var1=value1&var2=value2'.

[A]
If you are using
Prototype
there is
Form.serialize
If you are using
jQuery
there is
Ajax/serialize
I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.


q: What are some popular spam prevention methods besides CAPTCHA?

[A]
Javascript evaluation techniques like this
Invisible Captcha
system require the browser to evaluate Javascript before the page submission will be accepted. It falls back nicely when the user doesn't have Javascript enabled by just displaying a conventional CAPTCHA test.


q: How do I name a result group in a Regex? (.Net)

[A]
```
```
(?<NameOfGroup>[a-z]*)
```
```
Use the ? syntax like in the sample above.


q: Basically I’ve heard that certain conditions will cause .NET to blow past the finally block.  Does anyone know what those conditions are?

[A]
Unless the CLR blows up and goes down with an ExecutingEngineException (I've seen a few in the .net 1.1 days with just the right amount of COM Interop :) .. I think finally should
always
execute.


q:
How would it be possible to capture the audio programmatically? I am implementing an application that streams in real time the desktop on the network. The video part is finished. I need to implement the audio part. I need a way to get PCM data from the sound card to feed to my encoder (implemented using Windows Media Format).

I think the answer is related to the openMixer(), waveInOpen() functions in Win32 API, but I am not sure exactly what should I do.

How to open the necessary channel and how to read PCM data from it?

Thanks in advance.

[A]
I don't think there is a direct way to do this using the OS - it's a feature that may (or may not) be present on the sound card.  Some sound cards have a loopback interface - Creative calls it "What U Hear".  You simply select this as the input rather than the microphone, and record from it using the normal waveInOpen() that you already know about.
If the sound card doesn't have this feature then I think you're out of luck other than by doing something crazy like making your own driver.  Or you could convince your users to run a cable from the speaker output to the line input :)


q:
Some of the controls I've created seem to default to the old Windows 95 theme, how do I prevent this? Here's an example of a button that does not retain the Operating System's native appearance (I'm using Vista as my development environment):

HWND button = CreateWindowEx(NULL, L"BUTTON", L"OK", WS_VISIBLE | WS_CHILD | BS_PUSHBUTTON,
                                  170, 340, 80, 25, hwnd, NULL, GetModuleHandle(NULL), NULL);

I'm using native C++ with the Windows API, no managed code.

[A]
I believe it has got nothing to do with your code, but you need to set up a proper
manifest
file to get the themed controls.
Some info here:
@msdn.com
and here:
@blogs.msdn.com
You can see a difference between application with and without manifest here:
heaventools.com


q:
I'm currently convering my ASP.NET v2 application to serialize/deserialize it's objects because I want to shift from inproc session state to stateserver. This is because my host, webhost4life, has a nasty tendency to recycle the worker process frequently thus causing session timeouts. Anyway... the question...

I'm trying to not serialize things I don't need to, i.e. variables that are re-initialised each page, don't need to be serialised. Here's one of them:

 Private RollbackQueue As New Queue(Of DataServer.Rollback)

On deserialisation, will RollbackQueue be a) nothing or b) an empty queue? My guess is that when .NET deserialises, it creates the parent object as normal and then fills in the fields one by one. Therefore, the NEW bit will fire.

But that is a guess.

Thanks, Rob.

[A]
It will be nothing. The CLR serialization logic will create the object uninitialized by way of
FormatterServices.GetSafeUnitializedObject
without running any construction logic. If you need to ensure the field has a value I would recommend moving such initialization into an
```
Initialize()
```
method that is called both from your constructor and from a method marked with the
OnDeserialized
attribute.


q: Is there a way to lock a row in the SQL 2005-2008 database without starting a transaction, so other processes cannot update the row until it is unlocked?

[A]
Everything you execute in the server happens in a transaction, either implicit or explicit.
You can not simply lock a row with no transaction (make the row read only). You can make the database read only, but not just one row.
Explain your purpose and it might be a better solution. Isolation levels and lock hints and
row versioning
.


q: Does anyone have any advice for a consistent way to unit test a multithreaded application?  I have done one application where our mock "worker threads" had a thread.sleep with a time that was specified by a public member variable.  We would use this so we could set how long a particular thread would take to complete its work, then we could do our assertions.  Any ideas of a better way to do this?  Any good mock frameworks for .Net that can handle this?

[A]
TypeMock
(commercial) has a unit testing framework that automatically tries to find deadlocks in multithreaded applications and I think can be set up to run threads with predictable context switching.
I saw a demo this week at a show -- apparently it's in Alpha (called Racer)
http://www.typemock.com/Typemock_software_development_tools.html


q:
Every morning, after logging into your machine, you do a variety of routine stuffs.
The list can include stuffs like opening/checking your email clients, rss readers, launching visual studio, running some business apps, typing some replies, getting latest version from Source Control, compiling, connecting to a different domain etc. To a big extend, we can automate using scripting solutions like AutoIt, nightly jobs etc.

I would love to hear from you geeks out there for the list of stuffs you found doing repeatedly and how you solved it by automating it. Any cool tips?

[A]
I use Linux. I have a bunch of scripts that do anything I want. Typically I write a script whenever a "block" of work can be reused in the future. For example, simple refactorings, deployments, etc...
Over time I started to combine these blocks, hence getting ever more efficient.
Regarding the "load stuff at startup", under Linux that comes out of the box (you can "save your current session" when you log out or turn off the computer).
On windows, my suggestion is to use programs that can be automated via command line.


q:
Is it absolutely critical that I always close Syslog when I'm done using it? Is there a huge negative impact from not doing so?

If it turns out that I definitely need to, what's a good way to do it? I'm opening Syslog in my class constructor and I don't see a way to do class destructors in Ruby, and currently have something resembling this:

class Foo
  def initialize
    @@log = Syslog.open("foo")
  end
end

I don't immediately see the place where the Syslog.close call should be, but what do you recommend?

[A]
The open method accepts a block.  Do something like this:
```
```
class Foo
  def do_something
    Syslog.open do
      # work with the syslog here
    end
  end
end
```
```


q:
I am encountering very infrequent yet annoying SQL deadlocks on a .NET 2.0 webapp running on top of MS SQL Server 2005. In the past, we have been dealing with the SQL deadlocks in the very empirical way - basically tweaking the queries until it work.

Yet, I found this approach very unsatisfactory: time consuming and unreliable. I would highly prefer to follow deterministic query patterns that would ensure by design that no SQL deadlock will be encountered - ever.

For example, in C# multithreaded programming, a simple design rule such as the locks must be taken following their lexicographical order ensures that no deadlock will ever happen.

Are there any SQL coding patterns guaranteed to be deadlock-proof?

[A]
As you said, always access tables in the same order is a very good way to avoid deadlocks. Furthermore, shorten your transactions as much as possible.
Another cool trick is to combine 2 sql statements in one whenever you can. Single statements are always transactional. For example use "UPDATE ... SELECT" or "INSERT ... SELECT", use "@@ERROR" and "@@ROWCOUNT" instead of "SELECT COUNT" or "IF (EXISTS ...)"
Lastly, make sure that your calling code can handle deadlocks by reposting the query a configurable amount of times. Sometimes it just happens, it's normal behaviour and your application must be able to deal with it.


q:
The GoDiagram object model has a GoDocument.

GoViews have a reference to a GoDocument.

If the user does any modification on the diagramming surface, a GoDocument.Changed event is raised with the relevant information in the event arguments.

I would like to be notified when some user-actions happen, so that I can confer with my Controller (disallow/cancel it if need be) and then issue view-update orders from there that actually modify the Northwoods GoDiagram third party component.

The Changed event is a notification that something just happened (past tense) - Doing all of the above in the event handler results in a .... (wait for it)... StackOverflowException. (GoDocument.Changed handler > Updates GoDocument > Firing new Changed events.. )

So question, how do I get a BeforeEditing or BeforeResizing kind of notification model in GoDiagrams? Has anyone who's been there lived to tell a tale?

[A]
The event arguments (GoChangedEventArgs) for the change event has a property IsBeforeChanging which indicates whether the change event was raised from the "RaiseChanging" method (true), or the RaiseChanged (false).  That should tell you whether the change has occurred yet, but I know of no way to cancel it.
The best I can suggest is instead of checking if the change is allowed and performing it, check if the change is
not
allowed, and if it isn't call the "Undo" method on the arguments in the change event.  So essentially:
```
```
OnChanged(GoChangedEventArgs e)
{
  if(NotAllowed)
  {
    e.Undo();
  }
}
```
```


q:
What is the web interface tool that Debian or Ubuntu use for publicizing their custom repositories on the web?

Like packages.debian.org

Is such tool open sourced, so that it could be re-used for a custom repository?

[A]
You really only need something to parse the Packages file, no?
Example Packages file
. I've never attempted to do this before, but I cant imagine it being a horrendous task.
Edit: Well it would technically be spidering the repo to process a series of Packages files, but that wouldn't make it too much tougher.
Edit 2: Unless you specify the Packages files manually. Then it would be simple again.


q:
For example:

root.Nodes.Add(new TNode() { Foo1 = bar1, Foo2 = bar2, Foo3 = bar3 });

or:

root.Nodes.Add(new TNode() { Foo1 = bar1,
                             Foo2 = bar2,
                             Foo3 = bar3 });

[A]
I've done it both ways.. IMO it depends on the complexity of the initialization.
If it is simple 2 or 3 properties I will initialize on one line generally, but if i'm setting up an object with values for insertion into a database or something that has alot of properties i'll break it out like your second example.
```
```
Income income = new Income
{
    Initials = something,
    CheckNumber = something,
    CheckDate = something,
    BranchNumber = something
};
```
```
or
```
```
return new Report.ReportData { ReportName = something, Formulas = something};
```
```


q:
What tools do you use to develop Oracle stored procedures, in a team :

To automatically "lock" the current procedure you are working with, so nobody else in the team can make changes to it until you are finished.

To automatically send the changes you make in the stored procedure, in an Oracle database, to a Subversion, CVS, ... repository

Thanks!

[A]
Oracle's new SQL Developer has version control built-in.
Here is a link to the product.
http://www.oracle.com/technology/products/database/sql_developer/files/what_is_sqldev.html
http://www.oracle.com/technology/products/database/sql_developer/images/what_version.png http://www.oracle.com/technology/products/database/sql_developer/images/what_version.png


q:
The one-liner should:

solve a real-world problem

not be extensively cryptic (should be easy to understand and reproduce)

be worth the time it takes to write it (should not be too clever)

I'm looking for practical tips and tricks (complementary examples for perldoc perlrun).

[A]
The problem
: A media player does not automatically load subtitles due to their names differ from corresponding video files.
Solution
: Rename all *.srt (files with subtitles) to match the *.avi (files with video).
```
```
perl -e'while(<*.avi>) { s/avi$/srt/; rename <*.srt>, $_ }'
```
```
CAVEAT: Sorting order of original video and subtitle filenames should be the same.
Here, a more verbose version of the above one-liner:
```
```
my @avi = glob('*.avi');
my @srt = glob('*.srt');

for my $i (0..$#avi)
{
  my $video_filename = $avi[$i];
  $video_filename =~ s/avi$/srt/;   # 'movie1.avi' -> 'movie1.srt'

  my $subtitle_filename = $srt[$i]; # 'film1.srt'
  rename($subtitle_filename, $video_filename); # 'film1.srt' -> 'movie1.srt'
}
```
```


q: If you are creating a 1d array in Python, is there any benefit to using the NumPy package?

[A]
It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the
array
module will do just fine.
If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that.
NumPy
(and
SciPy
) give you a wide variety of operations between arrays and special functions that are useful not only for scientific work but for things like advanced image manipulation or in general anything where you need to perform efficient calculations with large amounts of data.
Numpy is also much more flexible, e.g. it supports arrays of any type of Python objects, and is also able to interact "natively" with your own objects if they conform to the
array interface
.


q:
I have a simple list I am using for a horizontal menu:

<ul>
    <h1>Menu</h1>
    <li>
      <a href="/" class="selected">Home</a>
    </li>
    <li>
      <a href="/Home">Forum</a>
    </li>
</ul>

When I add a background color to the selected class, only the text gets the color, I want it to stretch the entire distance of the section.

Hope this makes sense.

[A]
The a element is an inline element, meaning it only applies to the text it encloses. If you want the background color to stretch across horizontally, apply the selected class to a block level element. Applying the class to the li element should work fine.
Alternatively, you could add this to the selected class' CSS:
```
```
display: block;
```
```
Which will make the a element display like a block element.


q:
I want to create a hidden field and create a link in one helper and then output both to my erb.

<%= my_cool_helper "something", form %>

Should out put the results of

link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"

What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.

[A]
So far the best I have come up with is:
```
```
def my_cool_helper(name, form)
  out = capture { link_to name, a_path }
  out << capture { form.hidden_field name.tableize, value => 'something' }
end
```
```
Is there a better way?


q:
I made a panel and set it to fill the screen, now I can see the windows under it but I want it to be click through, meaning they could click a file or see a tool tip of another object through the transparency.

RE: This may be too obvious, but have you tried sending the panel to the back by right clicking and choosing "Send to Back"?

I mean like the desktop or firefox, not something within my project.

[A]
Creating a top level form that is transparent is very easy. Just make it fill the screen, or required area, and define it to have a TransparenyKey color and BackColor of the same value.
Getting it to ignore the mouse is simple enough, you just need to override the WndProc and tell the WM_HITTEST that all mouse positions are to be treated as transparent. Thus causing the mouse to interact with whatever happens to be underneath the window. Something like this...
```
```
protected override void WndProc(ref Message m)
    {
        if (m.Msg == (int)WM_NCHITTEST)
            m.Result = (IntPtr)HTTRANSPARENT;
        else
            base.WndProc(ref m);
    }
```
```


q:
I want to put a Canvas with an image in my window, and then I want to pack widgets on top of it, so the Canvas acts as a background.

Is it possible to have two states for the pack manager: one for one set of widgets and another for another set?

[A]
The answer to your specific question is no. You can't have two states or otherwise use pack two different ways in the same parent.
However, what I think you want to accomplish is simple. Use the built-in features of the canvas to create an image item that is part of the canvas, then pack things into the canvas as if it were a frame.
You can accomplish a similar thing by creating a label widget with an image, then pack your other widgets into the label.
One advantage to using a canvas is you can easily tile an image to fill the whole canvas with a repeating background image so as the window grows the image will continue to fill the window (of course you can just use a sufficiently large original image...)


q:
I don't expect a straightforward silver bullet answer to this, but what are the best practices for ensuring good performance for SharePoint 2007 sites?

We've a few sites for our intranet, and it generally is thought to run slow. There's plenty of memory and processor power in the servers, but the pages just don't 'snap' like you'd expect from a web site running on powerful servers.

We've done what we can to tweak setup, but is there anything we could be missing?

[A]
Just a few ideas...
Is displaying your pages as slow when doing it from the Server or from a Client? If slower from client, do check your network.
Are your pages very "heavy"? (means, many elements, web parts and so on?) Than maybe it's normal.
Have you noticed they load slowlier since you've add one specific web part? Maybe there's some issues with that specific web part (for example, it's accessing to a document library that has many -thousands of- documents). If that's the case, try to deactivate that specific web part and see if the performance works better.


q:
I set a passphrase when creating a new SSH key on my laptop. But, as I realise now, this is quite painful when you are trying to commit (Git and SVN) to a remote location over SSH many times in an hour.

One way I can think of is, delete my SSH keys and create new. Is there a way to remove the passphrase, while still keeping the same keys?

[A]
Short answer:
```
```
$ ssh-keygen -p
```
```
This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).
If you would like to do it all on one line without prompts do:
```
```
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
```
```
Important:
Beware that when executing commands they will typically be logged in your
```
~/.bash_history
```
file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.
Notice though that you can still use
```
-f keyfile
```
without having to specify
```
-P
```
nor
```
-N
```
, and that the keyfile defaults to
```
~/.ssh/id_rsa
```
, so in many cases, it's not even needed.
You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.


q:
I'm getting a JS error on displaying a page: Nothing concrete is specified but the line where it seems to be thrown. When looking into the source code of the page, I see the error is thrown inside the following script, but I can't understand why! It's only about loading images!

    <SCRIPT language=JavaScript>
<!--
function newImage(arg) {
    var rslt = new Image();
    rslt.src = arg;
    return rslt;
}
function changeImages(a, b) {
    a.src = b;
}
newImage("\/_layouts\/images\/icon1.gif");
newImage("\/_layouts\/images\/icon2.gif");
// -->
</SCRIPT>

The error I am getting is when clicking on a drop down context menu on a page, for this line:

newImage("\/_layouts\/images\/icon1.gif");

The object doesn't accept this property or method
  Code: 0

I really don't see what could happen... Any tips on what may be happening here?

[A]
Write proper xml with the " around attributes.
```
```
<script type="text/javascript">
function newImage(arg) {
    var rslt = new Image();
    rslt.src = arg;
    return rslt;
}
function changeImages(a, b) {
    a.src =     b;
}
newImage("/_layouts/images/icon1.gif");
newImage("/_layouts/images/icon2.gif");
</script>
```
```


q: I'm specifically looking for one that lets me display a map of US states with each one as it's own "object" in the sense that I can control the color, on click, and on mouseover of each one individually.  GTK is my personal preference, but at this point I'd settle for just about anything.  The application itself will be written in Python, FWIW.

[A]
You can use
QGraphicsView
in PyQt. Each state is a new
```
QGraphicsItem
```
, which is either a bitmap or a path object. You just need to provide the outlines (or bitmaps) and the positions of the states.
If you have SVGs of the states, you can use them, too.
There is no generally accepted canvas class for GTK+.


q:
Given an array of n Objects, let's say it is an array of strings, and it has the following values:

foo[0] = "a";
foo[1] = "cc";
foo[2] = "a";
foo[3] = "dd";

What do I have to do to delete/remove all the strings/objects equal to "a" in the array?

[A]
Make a
```
List
```
out of the array with
```
Arrays.asList()
```
, and call
```
remove()
```
on all the appropriate elements. Then call
```
toArray()
```
on the 'List' to make back into an array again.
Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.


q: Are there any libraries (3rd party or built-in) in PHP to calculate text diffs?

[A]
it depends exactly what you mean and what you want to do but there is
PEAR Text_Diff
- Engine for performing and rendering text diffs


q:
How would a go about making a program where the user enters a string, and the program generates a list of words beginning with that string?

Ex:

User: "abd"

Program:abdicate, abdomen, abduct...

Thanks!

Edit:  I'm using python, but I assume that this is a fairly language-independent problem.

[A]
```
```
var words = from word in dictionary
            where word.key.StartsWith("bla-bla-bla");
            select word;
```
```


q: I recently discovered the genshi.builder module. It reminds me of Divmod Nevow's Stan module. How would one use genshi.builder.tag to build an HTML document with a particular doctype? Or is this even a good thing to do? If not, what is the right way?

[A]
Genshi.builder is for "programmatically generating markup streams"[1]. I believe the purpose of it is as a backend for the templating language. You're probably looking for the templating language for generating a whole page.
You can, however do the following:
```
```
>>> import genshi.output
>>> genshi.output.DocType('html')
('html', '-//W3C//DTD HTML 4.01//EN', 'http://www.w3.org/TR/html4/strict.dtd')
```
```
See other Doctypes here:
http://genshi.edgewall.org/wiki/ApiDocs/genshi.output#genshi.output:DocType
```
```
[1] genshi.builder.__doc__
```
```


q:
I want to select the topmost element in a document that has a given namespace (prefix).

More specifically: I have XML documents that either start with /html/body (in the XHTML namespace) or with one of several elements in a particular namespace. I effectively want to strip out /html/body and just return the body contents OR the entire root namespaced element.

[A]
The XPath expression that I want is:
```
```
/html:html/html:body/node()|/foo:*
```
```
Where the "html" prefix is mapped to the XHTML namespace, and the "foo" prefix is mapped to my target namespace.


q:
I am using jProfiler to find memory leaks in a Java swing application. I have identified instances of a JFrame which keeps growing in count.

This frame is opened, and then closed.

Using jProfiler, and viewing the Paths to GC Root there is only one reference, 'JNI Global reference'.

What does this mean? Why is it hanging on to each instance of the frame?

[A]
Wikipedia has a good overview of
Java Native Interface
, essentially it allows communication between Java and native operating system libraries writen in other languages.
JNI global references are prone to memory leaks, as they are not automatically garbage collected, and the programmer must explicitly free them.  If you are not writing any JNI code yourself, it is possible that the library you are using has a memory leak.
edit
here
is a bit more info on local vs. global references, and why global references are used (and how they should be freed)


q:
I thought I heard that py2exe was able to do this, but I never figured it out.  Has anyone successfully done this?  Can I see your setup.py file, and what command line options you used?

Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.

[A]
No, it's doesn't give you a single executable in the sense that you only have one file afterwards - but you have a directory which contains everything you need for running your program, including an exe file.
I just wrote
this setup.py
today. You only need to invoke
```
python setup.py py2exe
```
.


q:
What is the easiest way, preferably using recursion, to find the shortest root-to-leaf path in a BST (Binary Search Tree).  Java prefered, pseudocode okay.

Thanks!

[A]
General description:
Use a
Breadth-first search (BFS)
as opposed to a
Depth-first search (DFS)
.  Find the first node with no children.
Using a DFS you might get lucky on some input trees (but there is no way to know you got lucky so you still need to search the whole tree), but using the BFS method is much faster and you can find a solution without touching all nodes.
To find the root to leaf path, you could follow the first found childless node all the way back up to the root using the parent reference.  If you have no parent reference stored in each node, you can keep track of the parent nodes as you recurse down.  If you have your list in reverse order you could push it all on a stack and then pop it off.
Pseudo-code:
The problem is very simple; here is pseudo code to find the smallest length:
Put the root node on the queue.
Repeat while the queue is not empty, and no result was found:
Pull a node from the beginning of the queue and check if it has no children.  If it has no children you
are done you found the shortest path.
Otherwise push all the children (left, right) onto the queue.
Finding all shortest paths:
To find all shortest paths you can store the depth of the node along with node inside the queue.  Then you would continue the algorithm for all nodes in the queue with the same depth.
Alternative:
If instead you decided to use a DFS, you would have to search the entire tree to find the shortest path.  But this could be optimized by keeping a value for the shortest so far, and only checking the depth of future nodes up until you find a new shortest, or until you reach the shortest so far.  The BFS is a much better solution though.


q:
(ClientCookie is a module for (automatic) cookie-handling: http://wwwsearch.sourceforge.net/ClientCookie)

# I encode the data I'll be sending:
data = urllib.urlencode({'username': 'mandark', 'password': 'deedee'})

# And I send it and read the page:
page = ClientCookie.urlopen('http://www.forum.com/ucp.php?mode=login', data)
output = page.read()

The script doesn't log in, but rather seems to get redirected back to the same login page asking it for a username and password. What am I doing wrong?

Any help would be greatly appreciated! Thanks!

[A]
Have you tried fetching the login page first?
I would suggest using
Tamper Data
to have a peek at exactly what's being sent when you request the login page and then log in normally using a web browser from a fresh start, with no initial cookies in place, so that your script can replicate it exactly.
That's the approach I used when writing the following, extracted from a script which needs to login to an Invision Power Board forum, using cookielib and urllib2 - you may find it useful as a reference.
```
```
import cookielib
import logging
import sys
import urllib
import urllib2

cookies = cookielib.LWPCookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies))
urllib2.install_opener(opener)
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.0; en-GB; rv:1.8.1.12) Gecko/20080201 Firefox/2.0.0.12',
    'Accept': 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5',
    'Accept-Language': 'en-gb,en;q=0.5',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
}

# Fetch the login page to set initial cookies
urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=00', None, headers))

# Login so we can access the Off Topic forum
login_headers = headers.copy()
login_headers.update({
    'Referer': 'http://www.rllmukforum.com/index.php?act=Login&CODE=00',
    'Content-Type': 'application/x-www-form-urlencoded',
})
html = urllib2.urlopen(urllib2.Request('http://www.rllmukforum.com/index.php?act=Login&CODE=01',
                                       urllib.urlencode({
                                           'referer': 'http://www.rllmukforum.com/index.php?',
                                           'UserName': RLLMUK_USERNAME,
                                           'PassWord': RLLMUK_PASSWORD,
                                       }),
                                       login_headers)).read()
if 'The following errors were found' in html:
    logging.error('RLLMUK login failed')
    logging.info(html)
    sys.exit(1)
```
```


q: Our subversion repository has been moved to a new host, and we have old applications that connect to that host.  We CANNOT add an alias for the new server with the old name, how can we re-connect our checked out clients to the new repository?

[A]
Look up the
svn switch
command. In particular, the
```
--relocate
```
option is what you want.


q:
I'm building a PHP site, but for now the only PHP I'm using is a half-dozen or so includes on certain pages. (I will probably use some database queries eventually.)

Are simple include() statements a concern for speed or scaling, as opposed to static HTML? What kinds of things tend to cause a site to bog down?

[A]
Certainly include() is slower than static pages. However, with modern systems you're not likely to see this as a bottleneck for a long time - if ever. The benefits of using includes to keep common parts of your site up to date outweigh the tiny performance hit, in my opinion (having different navigation on one page because you forgot to update it leads to a bad user experience, and thus bad feelings about your site/company/whatever).
Using caching will really not help either - caching code is going to be slower than just an include(). The only time caching will benefit you is if you're doing computationally-intensive calculations (very rare, on web pages), or grabbing data from a database.


q:
Is there a way to view the key/value pairs of a NSDictionary variable through the Xcode debugger?  Here's the extent of information when it is fully expanded in the variable window:

Variable  Value      Summary
jsonDict  0x45c540   4 key/value pairs
 NSObject {...}
  isa     0xa06e0720

I was expecting it to show me each element of the dictionary (similar to an array variable).

[A]
In the gdb window you can use
```
po
```
to inspect the object.
given:
```
```
NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"foo" forKey:@"bar"];
[dict setObject:@"fiz" forKey:@"buz"];
```
```
setting a breakpoint after the objects are added you can inspect what is in the dictionary
```
```
(gdb) po dict
{
  bar = foo;
  buz = fiz;
}
```
```
Of course these are
```
NSString
```
objects that print nicely. YMMV with other complex objects.


q: Does anyone know of an MD5/SHA1/etc routine that is easily used with GLib (i.e. you can give it a GIOChannel, etc)?

[A]
You normally have to do library glue stuff yourself...
```
```
void get_channel_md5( GIOChannel* channel, unsigned char output[16] )
{
    md5_context ctx;

    gint64 fileSize = <get file size somehow?>;
    gint64 filePos = 0ll;

    gsize bufferSize = g_io_channel_get_buffer_size( channel );
    void* buffer = malloc( bufferSize );

    md5_starts( &ctx );

    // hash buffer at a time:
    while ( filePos < fileSize )
    {
        gint64 size = fileSize - filePos;
        if ( size > bufferSize )
            size = bufferSize;

        g_io_channel_read( channel, buffer );
        md5_update( &ctx, buffer, (int)size );

        filePos += bufferSize;
    }

    free( buffer );

    md5_finish( &ctx, output );
}
```
```


q:
How do I access parameters passed into an Oracle Form via a URL.
Eg  given the url:

http://example.com/forms90/f90servlet?config=cust&form='a_form'&p1=something&p2=else

This will launch the 'a_form' form, using the 'cust' configuration, but I can't work how (or even if it's possible) to access p1 (with value of 'something') p2 (with value of 'else')

Does anyone know how I can do this? (Or even if it is/isn't possible?

Thanks

[A]
Within Forms you can refer to the parameters p1 an p2 as follows:
:PARAMETER.p1
:PARAMETER.p2
e.g.
```
```
if :PARAMETER.p1 = 'something' then
   do_something;
end if;
```
```


q:
I am creating a standalone asp.net page that needs to be embedded into a sharepoint site using the Page Viewer Web Part.  The asp.net page is published to the same server on a different port, giving me the URL to embed.

The requirement is that after a user is authenticated using Sharepoint authentication, they navigate to a page containing the asp.net web part for more options.

What I need to do from this asp.net page is query Sharepoint for the currently authenticated username, then display this on the page from the asp.net code.

This all works fine when I debug the application from VS, but when published and displayed though Sharepoint, I always get NULL as the user.

Any suggestions on the best way to get this to work would be much appreciated.

[A]
When it works in debug, is that being used in SharePoint?
Your page and the Sharepoint site might as well be on different servers as far as authentication is concerned -- in order to get the information over you might need to pass it via the QueryString from the webpart if you can -- or you might need to make your own webpart to do this (just put an IFRAME in the part with the src set to your page with the QueryString passing the username).
It does seem that this would be a security issue if you use the name for anything though -- if you are just displaying it, then it's probably fine.
If you actually need to be authenticated, you might need to add authentication into the web.config of the site hosting your standalone page.
edit: I think you'd have better luck putting your page on the same port and server as SharePoint.


q: Sometimes my c++ program crashes in debug mode, and what I got is a message box saying that an assertion failed in some of the internal memory management routines (accessing unallocated memory etc.). But I don't know where that was called from, because I didn't get any stack trace. How do I get a stack trace or at least see where it fails in my code (instead of library/ built-in routines)?

[A]
If you have a crash,  you can get information about where the crash happened whether you have a debug or a release build.  And you can see the call stack even if you are on a computer that does not have the source code.
To do this you need to use the PDB file that was built with your EXE.  Put the PDB file inside the same directory as the EXE that crashed. Note: Even if you have the same source code, building twice and using the first EXE and the second PDB won't work.  You need to use the exact PDB that was built with your EXE.
Then attach a debugger to the process that crashed.  Example: windbg or VS.
Then simply checkout your call stack, while also having your threads window open.  You will have to select the thread that crashed and check on the callstack for that thread.  Each thread has a different call stack.
If you already have your VS debugger attached, it will automatically go to the source code that is causing the crash for you.
If the crash is happening inside a library you are using that you don't have the PDB for.   There is nothing you can do.


q:
According to the documentation the return value from a slot doesn't mean anything.

Yet in the generated moc code I see that if a slot returns a value this value is used for something. Any idea what does it do?

Here's an example of what I'm talking about. this is taken from code generated by moc. 'message' is a slot that doesn't return anything and 'selectPart' is declared as returning int.

case 7: message((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])));
    if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; }  break;

[A]
Looking through the Qt source it seems that when a slot is called from QMetaObject::invokeMethod the return type can be specified and the return value obtained. (Have a look at invokeMethod in the Qt help)
I could not find many examples of this actually being used in the Qt source. One I found was
```
```
bool QAbstractItemDelegate::helpEvent
```
```
which is a slot with a return type and is called from
```
```
QAbstractItemView::viewportEvent
```
```
using invokeMethod.
I think that the return value for a slot is only available when the function is called directly (when it is a normal C++ function) or when using invokeMethod. I think this is really meant for internal Qt functions rather than for normal use in programs using Qt.
Edit:
For the sample case:
```
```
case 8: { int _r = selectPart((*reinterpret_cast< AppObject*(*)>(_a[1])), *reinterpret_cast< int(*)>(_a[2])));
if (_a[0]) *reinterpret_cast< int*>(_a[0]) = _r; }  break;
```
```
the vector _a is a list of arguments that is passed to qt_metacall. This is passed by QMetaObject::invokeMethod. So the return value in the moc generated code is saved and passed back to the caller. So for normal signal-slot interactions the return value is not used for anything at all. However, the mechanism exists so that return values from slots can be accessed if the slot is called via invokeMethod.


q:
I'm using C++ and accessing a UNC path across the network.  This path is slightly greater than MAX_PATH. So I cannot obtain a file handle.

But if I run the program on the computer in question, the path is not greater than MAX_PATH.  So I can get a file handle.  If I rename the file to have less characters (minus length of computer name) I can access the file.

Can this file be accessed across the network even know the computer name in the UNC path puts it over the MAX_PATH limit?

[A] You might be able to get a handle to the file if you try opening the file after converting the file name to a short (8.3) file name.  Failing that can you map the dir the file is in as a drive and access the file that way?


q: What's the difference between file and open in Python?  When should I use which one?  (Say I'm in 2.5)

[A]
You should always use
```
open()
```
.
As the
documentation
states:
When opening a file, it's preferable
  to use open() instead of invoking this
  constructor directly. file is more
  suited to type testing (for example,
  writing "isinstance(f, file)").
Also,
```
file()
```
has been removed
since Python 3.0.


q:
I want to implement Generics in my Page Class like :

Public Class MyClass(Of TheClass)
Inherits System.Web.UI.Page

But for this to work, I need to be able to instantiate the Class (with the correct Generic Class Type) and load the page, instead of a regular Response.Redirect. Is there a way to do this ?

[A]
I'm not sure to fully understand what you want to do.
If you want something like a generic Page, you can use a generic BasePage and put your generic methods into that BasePage:
```
```
Partial Public Class MyPage
    Inherits MyGenericBasePage(Of MyType)

End Class

Public Class MyGenericBasePage(Of T As New)
    Inherits System.Web.UI.Page

    Public Function MyGenericMethod() As T
        Return New T()
    End Function

End Class

Public Class MyType

End Class
```
```


q:
SELECT GETDATE()

Returns: 2008-09-22 15:24:13.790

I want that date part without the time part: 2008-09-22 00:00:00.000

How can I get that?

[A]
Try this:
```
```
SELECT CONVERT(VARCHAR(10),GETDATE(),111)
```
```
The above statement converts your current format to
```
YYYY/MM/DD
```
, please refer to
this link
to choose your preferable format.


q: How does selenium work? Can you explain the internal working of it.

[A] First there's a layer of javascript code that is used to automate the browser and simulate events, run and verify tests. Next, you run a proxy server - which you point your browser to - that injects this javascript code. Then, you can talk to this proxy server through another port using a set of commands which causes the proxy server to inject javascript code to be run on(or remote controlling) the running browser. Using this framework you can write automated test scripts in a style very much like writing macros for the browser.


q:
It appears the Python signal module doesn't have anything similar to the sighold and sigrelse functions found in C, using signal.h. Are there Python equivalents of any sort?

Many thanks!

[A]
How sure are you that calling a member function via a pointer is slower than just calling it directly? Can you measure the difference?
In general, you should not rely on your intuition when making performance evaluations. Sit down with your compiler and a timing function, and actually
measure
the different choices. You may be surprised!
More info: There is an excellent article
Member Function Pointers and the Fastest Possible C++ Delegates
which goes into very deep detail about the implementation of member function pointers.


q:
I'm working on a something related to roughset right now. The project uses alot of sets operation and manipulation. I've been using string operations as a stop gap measure for set operation. It has worked fine until we need to process some ungodly amount of data ( 500,000 records with about 40+ columns each ) through the algorithm.

I know that there is no set data structure in .net 2.0(2.0 was the latest when I started the project) I want to know if there is any library that offer fast set operation in .net c# or if 3.5 has added native set data structure.

Thanks .

[A] You can use Linq to Objects in C# 3.0.


q:
Is it always possible to ping localhost and it resolves to 127.0.0.1?

I know Windows Vista, XP, Ubuntu and Debian do it but does everyone do it?

[A]
Any correct implementation of TCP/IP will reserve the address 127.0.0.1 to refer to the local machine. However, the mapping of the name "localhost" to that address is generally dependent on the system
```
hosts
```
file. If you were to remove the localhost entry from
```
hosts
```
, then the localhost name may no longer resolve properly at all.


q: Do you think that project iteration length is related to project team size? If so, how? What other key factors do you use to recognize correct iteration length for different projects?

[A]
Iteration length is primarily related to the teams ability to communicate and complete a working version of the software.  More team members equals more communication channels (
Brooks's Law
) which will likely increase your iteration time.
I think that 2 week iterations, whether you deliver to the client or not, are a good goal, as it allows for very good health checks.
Ultimately, the iteration length will depend on the features you wish to implement in the next iteration, and in the early phases your iterations may jump around from 1 week to 1 month as you become comfortable with the team and the technology stack.


q: How do you impose a character limit on a text input in HTML?

[A]
there's a maxlength attribute
```
```
<input type="text" name="textboxname" maxlength="100" />
```
```


q:
I have a marker interface defined as

public interface IExtender<T>
{
}

I have a class that implements IExtender

public class UserExtender : IExtender<User>

At runtime I recieve the UserExtender type as a parameter to my evaluating method

public Type Evaluate(Type type) // type == typeof(UserExtender)

How do I make my Evaluate method return

typeof(User)

based on the runtime evaluation. I am sure reflection is involved but I can't seem to crack it.

(I was unsure how to word this question. I hope it is clear enough.)


q: Is there anyway to declare an object of a class before the class is created in C++?  I ask because I am trying to use two classes, the first needs to have an instance of the second class within it, but the second class also contains an instance of the first class.  I realize that you may think I might get into an infinite loop, but I actually need to create and instance of the second class before the first class.

[A]
You can't declare an instance of an undefined class but you can declare a
pointer
to one:
```
```
class A;  // Declare that we have a class A without defining it yet.

class B
{
public:
    A *itemA;
};

class A
{
public:
    B *itemB;
};
```
```


q:
CSS width value = display width of inside?

or

CSS width value = display width of inside + CSS margin-left + CSS margin-right?

[A]
You have to make yourself familiar with the
CSS Box Model
. It explains where padding, margin and border as well as width work.
However do note that different browsers implement this differently: most notably,
Internet Explorer has a box model bug
(this is infamously present in IE6 -- I am not aware if this has been fixed in IE7 or IE8) that caused the infamous "quirks mode" CSS hack.
Briefly stated, Internet Explorer set their box model to include padding in computing the width, as opposed the official standard wherein width should only constitute the content.


q: Is there any way to interpret Reverse Polish Notation into "normal" mathematical notation when using either C++ or C#? I work for an engineering firm, so they use RPN occasionally and we need a way to convert it. Any suggestions?

[A]
C# doesn't have built-in support for parsing Reverse Polish Notation (RPN).You'll need to write your own parser, or find one online.
There are dozens of tutorials for converting postfix form (RPN) to infix (Algebraic Equation). Take a look at
this
, maybe you'll find it useful and you can try to ‘reverse engineer’ it to convert postfix expressions to infix form, keeping in mind that there can be multiple infix notations for a given postfix one. There are very few useful examples that actually discuss converting postfix to infix. Here’s a 2-part entry that I found very useful. It also has some pseudo code:
PostFix to Infix: converting RPN to algebraic expressions
Postfix to infix, part 2: adding the parentheses


q: I want to connect to a USB Webcam in .NET, specifically using C#. Being new to .NET I don't know what kind of support there is in the standard libraries for doing so. I found one example on the web that copies bitmaps through the clipboard, but that seems very hacky (and probably slow). Is there a better way?

[A]
You will need to use
Windows Image Acquisition (WIA)
to integrate a webcam with your application.  There are plenty examples of this readily available. Here is a
C# Webcam User Control
with source.
Here are some more articles and blog posts from people looking to solve the same problem you are:
MSDN Coding4Fun: Look at me! Windows Image Acquisition
CodeProject: WIA Scripting and .NET
CodeProject: WebCam Fast Image Capture Service using WIA
clausn.dk: Webcam control from C# and WIA


q: I'm working on an iphone application (not web app) and I'd like to build a form asking a user to indicate a price range. Instead of using two text fields, I would prefer to use a double slider to set the minimum and the maximum price.  I know that it is possible de use a simple slider (sound control for exemple) but i've never seen a double one. Can anyone help ?

[A]
This is not possible without creating a custom control. You'll need to inherit from UIControl or UIView and provide a custom drawRect method. You'll also need to respond to touch and drag events to update the state of the control. I have not done this myself, but I would be prepared for a fairly significant amount of work to get everything to respond and display as expected.
I'm curious as to why you need to have both values specified on a single slider? Why not use two sliders either side-by-side or stacked? It would not require any more input steps than a double slider, and would conform more to standard UI guidelines.


q:
Java supplies standard User Interface guidelines for applications built using Java Swing. The basic guidelines are good, but I really feel the look and feel is really boring and outdated.

Is anyone aware of a publicly available Java User Interface Guide that has better look & feel guidelines than the Sun provided guidelines?

[A]
You have many LNF (Look And Feel)
displayed here
but they have not exactly a 'Java User Guide' Provided.
However
MigLayout
does follow closely the main User Interface standards that exist out there (including some obcure points of
button order
):
For instance the OK and Cancel buttons have different order on Windows and Mac OS X.
While other layout managers use factories and button builders for this, it is inherently supported by MigLayout by just tagging the buttons.
One just tags the OK button with "ok" and the Cancel button with "cancel" and they will end up in the correct order for the platform the application is running on, if they are put in the same grid cell.
Example on Mac:
(source:
miglayout.com
)


q:
I've got a WordPress powered blog that I'm trying to get setup on our IIS6 server and everything works besides the permalink structure which I'm having a big headache with.

After googling around/wordpress codex I learned that it's because IIS6 doesn't have the equivalent of Apache's mod_rewrite which is required for this feature to work. So that's where I'm at now. I can't seem to find a functional solution to get the pretty permalinks to work without the "index.php/," anyone have any recommendations?

What I can't do:

Upgrade to IIS7

Switch to Apache

Quit my job

Those suggestions have been offered to me, which sadly, I can't do any of those. Just an, FYI.

Much thanks for anyone who can lead me in the right direction.

[A]
I researched this topic briefly and it seems you need an additional piece which is called
URL Rewrite (Go Live)
.
Here is an article
that walks you through how to create a rewrite rule using this. They also require IIS7, which I am not sure if it's really important. But it might be another thing you have to take care of.
Just in case the above URL fails later, here is an example rewrite rule for Wordpress:
```
```
<rewrite>
    <rules>
        <rule name="Main Rule" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
                <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="index.php" />
        </rule>
    </rules>
</rewrite>
```
```


q:
We implemented a server application available on Windows only. Now we like to port it to Linux, HP-UX and AIX, too. This application provides internal statistics through performance counters into the Windows Performance Monitor.

To be more precise: The application is a data base, and we like to provide information like number of connected users or number of requests executed to the administrator. So these are "new" information, proprietary to our application. But we like to make them available in the same environment where the operating system delivers information like the CPU, etc. The goal is to make them easily readable for the administrator.

What is the appropriate and commonly used performance monitor under Linux, HP-UX and AIX?


q: Is there a way to be sure we hold a useable reference to an object i.e. being sure it has not been already freed leaving that non nil reference dangling.

[A] Unfortunately there is no way to 100% guarantee that a pointer to anything is still valid, except by meticolously writing the correct code.


q: How do we decide on the best implementation of hashCode() method for a collection (assuming that equals method has been overridden correctly) ?

[A]
For a simple class it is often easiest to implement hashCode() based on the class fields which are checked by the equals() implementation.
```
```
public class Zam {
    private String foo;
    private String bar;
    private String somethingElse;

    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }

        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }

        Zam otherObj = (Zam)obj;

        if ((getFoo() == null && otherObj.getFoo() == null) || (getFoo() != null && getFoo().equals(otherObj.getFoo()))) {
            if ((getBar() == null && otherObj. getBar() == null) || (getBar() != null && getBar().equals(otherObj. getBar()))) {
                return true;
            }
        }

        return false;
    }

    public int hashCode() {
        return (getFoo() + getBar()).hashCode();
    }

    public String getFoo() {
        return foo;
    }

    public String getBar() {
        return bar;
    }
}
```
```
The most important thing is to keep hashCode() and equals() consistent: if equals() returns true for two objects, then hashCode() should return the same value. If equals() returns false, then hashCode() should return different values.


q:
A client using our system has requested that we store the SSNs/SINs of the end users in our database. Currently, we store minimal information about users (name, email address, and optionally, country), so I'm not overly concerned about a security breach - however, I have a suspicion there could be legal issues about storing SSNs and not taking "appropriate" measures to secure them (coming from Australia, this is my first encounter with them). Is this a valid concern?

I also read on the Wikipedia page about SINs (Canada's equivalent to SSNs) that it should ONLY be used when absolutely necessary and definitely shouldn't be used as a general identifier, or similar.

So, are there any potential legal issues about this sort of thing? Do you have any recommendations?

[A]
Way too many organizations in the USA use SSNs as unique identifiers for people, despite the well-documented problems with them. Unless your application actually has something to do with government benefits, there's no good reason for you to store SSns.
Given that so many organizations (mis)use them to identify people for things like credit checks, you really need to be careful with them. With nothing more than someone's name, address, and SSN, it's pretty easy to get credit under their name, and
steal their identity
.
The legal issues are along the lines of getting sued into oblivion for any leak of personal information that contains SSNs.


q:
Is there a function in Python to split a string without ignoring the spaces in the resulting list?

E.g:

s="This is the string I want to split".split()

gives me

>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']

I want something like

['This',' ','is',' ', 'the',' ','string', ' ', .....]

[A]
The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.
Perhaps this may help:
```
```
s = "String to split"
mylist = []
for item in s.split():
    mylist.append(item)
    mylist.append(' ')
mylist = mylist[:-1]
```
```
Messy, but it'll do the trick for you...


q: Is there any open-source, PHP based, role-based access control system that can be used for CodeIgniter?

[A]
phpgacl
http://phpgacl.sourceforge.net/
is a generic acl based access control framework
while I don't know about any CI specific implementation, i know that you only need the main class file to make phpgacl work. So i belive that integration with CI won't be any problem. (I've work passingly with CI)


q:
We are trying to duplicate one of our informix database on a test server, but without Informix expertise in house we can only guess what we need to do.  I am learning this stuff on the fly myself and nowhere near the expertise level needed to operate Informix efficiently or even inefficiently.  Anyhow...
We managed to copy the .dat and .idx files from the live server somewhere.  Installed Linux and the latest Informix Dynamic Server on it and have it up and running.

Now what should we do with the .dat and idx files from the live server?  Do we copy it somewhere and it will recognize it automatically?

Or is there an equivalent way like you can do attach DB from MS SQLServer to register the database files in the new database?

At my rope end...

[A]
I don't have any Informix-specific advice but for situations like this you can usually find the answer by looking up how to move a database (a common admin task, and usually well described in the manual) and just skipping the steps that would remove the old database.
Also, be careful of problems caused by different system architectures; some DBs fail spectacularly if you move them from a big-endian system (such as Solaris) to a little-endian system (such as x86 Linux)  Again, the manual section on moving a DB would cover any extra steps that are needed.


q:
When a process in jBPM forks into concurrent paths, each of these paths gets their own copy of the process variables, so that they run isolated from each other.

But what happens when the paths join again ?
Obviously there could be conflicting updates.
Does the context revert back to the state before the fork?
Can I choose to copy individual variables from the separate tracks?

[A]
I think that you have to configure the Task Controllers of your tasks. In some cases it is enough to set the
```
access
```
attribute in a way that does not result in conflicts (e.g.
```
read
```
access to the first path and
```
read,write
```
access to the second path). If this is not the case then you can implement your own
```
TaskControllerHandler
```
and implement the method
```
void submitTaskVariables(TaskInstance taskInstance, ContextInstance contextInstance, Token token)
```
with your custom logic. Please see:
Task Controllers
.


q:
Is there a function in python to split a word into a list of single letters? e.g:

s = "Word to Split"

to get

wordlist = ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']


q: How do I add  a "last" class on the last <li> within a Views-generated list?

[A]
You could use the
last-child
pseudo-class on the li element to achieve this
```
```

IE

Firefox

Safari

```
```
There is also a first-child pseudo class available.
I am not sure the last-child element works in IE though.


q:
Is there a way to combine a previous translation when extracting the csv file from an application?
Or any other tool that could do this job for me?

I can’t really see how could i use locbaml if i had to translate everything from scratch every time i add a new control in my application.


q:
I'm trying to implement a pop-up menu based on a click-and-hold, positioned so that a (really) slow click will still trigger the default action, and with the delay set so that a text-selection gesture won't usually trigger the menu.

What I can't seem to do is cancel the text-selection in a way that doesn't prevent text-selection in the first place: returning false from the event handler (or calling $(this).preventDefault()) prevents the user from selecting at all, and the obvious $().trigger('mouseup') doesn't doesn't do anything with the selection at all.

This is in the general context of a page, not particular to a textarea or other text field.

e.stopPropogation() doesn't cancel text-selection.

I'm not looking to prevent text selections, but rather to veto them after some short period of time, if certain conditions are met.

[A]
Try this:
```
```
var input = document.getElementById('myInputField');
if (input) {
    input.onmousedown = function(e) {

        if (!e) e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();

    }
}
```
```
And if not, have a read of:
http://www.quirksmode.org/js/introevents.html


q:
I have an application that is installed and updated via ClickOnce.  The application downloads files via FTP, and therefore needs to be added as an exception to the windows firewall.  Because of the way that ClickOnce works, the path to the EXE changes with every update, so the exception needs to change also.  What would be the best way to have the changes made to the firewall so that it's invisible to the end user?

(The application is written in C#)

[A]
Not sure if this is the best way, but running
netsh
should work:
netsh firewall add allowedprogram C:\MyApp\MyApp.exe MyApp ENABLE
I think this requires Administrator Permissions though,for obvious reasons :)
Edit: I just don't know enough about ClickOnce to know whether or not you can run external programs through it.


q:
Currently i am developing sites using DNN framework. Currently my development and staging environment is same. Client is vewing same site which I am using for development.

I have started using tortoise svn (subversion) for maintaining versions and backup. I am using file based svn repository for it.

The issue is svn creates .svn folder (hidden) in every folder. This folder and files inside it shows in portal system while file selection and at many different locations like FCKEditor File Browser, Icon selection for module / page, skins selection.

I would like to hide this folder for entire application and it should not show up anywhere.

[A]
Do you have to have the same environment for development and staging? I would really recommend against it. Even if you have them on the same server, I think you should have them at least in separate virtual directories.
Assuming you have then done that, it is simple to keep the '.' directories hidden, you simply
```
export
```
your svn repository from dev to staging. Staging will no longer be a working copy so the '.' directories will not be present. This also allows to test potentially breaking changes without affecting the client and it keeps the staging environment more stable.


q: How do I get timestamp from e.g. 22-09-2008?

[A]
Using
mktime
:
```
```
list($day, $month, $year) = explode('-', '22-09-2008');
echo mktime(0, 0, 0, $month, $day, $year);
```
```


q: Is there a runtime performance penalty when using interfaces (abstract base classes) in C++?

[A] There is a small penalty per virtual function call compared to a regular call. You are unlikely to observe a difference unless you are doing hundreds of thousands of calls per second, and the price is often worth paying for added code clarity anyway.


q:
Name of the option tells something but what Visual Studio/compiler really do and what are the real consequences?

Edit: If you search google you can find this address, but that is not really I am looking for. I wonder the real things happening. For example why do the loops get less time, etc.

[A]
The short answer is: use -Ox and let the compiler do its job.
The long answer: the effect of different kind of optimizations is impossible to predict accurately. Sometimes optimizing for fast code will actually yield smaller code than when optimizing for size. If you really want to get the last 0.01% of performance (speedwise or sizewise), you have to benchmark different combination of options.
Also, recent versions of Visual Studio have options for more advanced optimizations such as link-time optimization and profile-guided optimization.


q:
I'm building a project from the command line using WinCE platform builder, and I need RTTI to be enabled, so that my project works correctly. I tried setting the option RTTI="YES" in the sources and in the makefile of each dir, and I also tried to add it at the end of  CDEFINES, but when I try to build the project, I get the D9025 warnings, which says that my "/GR was overriden by /GR-" ( enable RTTI was overriden by don't enable RTTI ).
My question is, how can I find out where that option is set, so that I can modify it?

The thing is that we only copy the sources to some dirs, we specify them in a file named "sources", and then we proceed with the build by issuing the following command: build

What I would like to know is, where is build taking it's options from? What is the name of the file?

[A]
Command-Line Warning D9025
If two options specify contradictory or incompatible directives, the directive specified or implied in the option farthest to the right on the command line is used.
If you get this warning when compiling from the development environment, and are not sure where the conflicting options are coming from, consider the following:
An option can be specified either in code or in the project's project settings. If you look at the compiler's Command Line Property Pages and if you see the conflicting options in the All Options field then the options are set in the project's property pages, otherwise, the options are set in source code.
If the options are set in project's property pages, look on the compiler's Preprocessor property page (with the project node selected in the Solution Explorer). If you do not see the option set there, check the Preprocessor property page settings for each source code file (in Solution Explorer) to make sure it's not added there.
If the options are set in code it could be set either in code or in the windows headers. You might try creating a preprocessed file (/P) and search it for the symbol.
reference:
http://msdn.microsoft.com/en-us/library/8k3f51f1(vs.80).aspx


q: I'm trying to ftp a folder using the command line ftp client, but so far I've only been able to use 'get' to get individual files.

[A]
If you can use
```
scp
```
instead of
```
ftp
```
, the
```
-r
```
option will do this for you. I would check to see whether you can use a more modern file transfer mechanism than FTP.


q:
I want to create a c# application with multiple windows that are all transparent with some text on.

The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?

[A]
Just making the window transparent is very straight forward:
```
```
this.BackColor = Color.Fuchsia;
this.TransparencyKey = Color.Fuchsia;
```
```
You can do something like this to make it so you can still interact with the desktop or anything else under your window:
```
```
public const int WM_NCHITTEST = 0x84;
public const int HTTRANSPARENT = -1;

protected override void WndProc(ref Message message)
{
    if ( message.Msg == (int)WM_NCHITTEST )
    {
        message.Result = (IntPtr)HTTRANSPARENT;
    }
    else
    {
        base.WndProc( ref message );
    }
}
```
```


q:
In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.

How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?

[A]
```
```
SELECT testColumn FROM testTable
    WHERE testColumn COLLATE Latin1_General_CS_AS = 'example'

SELECT testColumn FROM testTable
    WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE'

SELECT testColumn FROM testTable
    WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe'
```
```
Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course)


q: When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call?  I am assuming this is pretty easy, I just don't know how.

[A]
After you commit your object into the db the object receives a value in its ID field.
So:
```
```
myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;
```
```


q: I would like to display some memory statistics (working set, GCs etc.) on a web page using the .NET/Process performance counters. Unfortunately, if there are multiple application pools on that server, they are differentiated using an index (#1, #2 etc.) but I don't know how to match a process ID (which I have) to that #xx index. Is there a programmatic way (from an ASP.NET web page)?

[A]
The first hit on Google:
Multiple CLR performance counters appear that have names that resemble "W3wp#1"
When multiple ASP.NET worker processes
  are running, Common Language Runtime
  (CLR) performance counters will have
  names that resemble "W3wp#1" or
  "W3sp#2"and so on. This was remedied
  in .NET Framework 2.0 to include a
  counter named Process ID in the .NET
  CLR Memory performance object. This
  counter displays the process ID for an
  instance. You can use this counter to
  determine the CLR performance counter
  that is associated with a process.
Also
KB 281884
:
By default, Performance Monitor
  (Perfmon.msc) displays multiple
  processes that have the same name by
  enumerating the processes in the
  following way:
Process#1 Process#2 Process#3
Performance Monitor can also display
  these processes by appending the
  process ID (PID) to the name in the
  following way:
Process_PID


q:
Does anybody know a Europe-based provider for OpenID?
I am not using one of the well-known bigger services (Yahoo,..).

[A]
I have developed one myself,
LoginBuzz
. It is primarily Danish and I have first translated many parts of it the last week, but it should be fully functional.
It supports simple registration, attribute exchange and PAPE. I have also implemented CardSpace support and text messaging (only available in Denmark at the moment) for a more secure authentication process. In a near future it should get support for client certificates as well.
My main goal is keeping it simple and fast. What you really want is to go back to the site that requested the authentication, not to spend time on the provider´s site.
I am very interested in feedback for making it a better service.


q: Is there an easy way (in .Net) to test if a Font is installed on the current machine?

[A]
How do you get a list of all the installed fonts?
```
```
var fontsCollection = new InstalledFontCollection();
foreach (var fontFamily in fontsCollection.Families)
{
    if (fontFamily.Name == fontName) {...} \\ check if font is installed
}
```
```
See
InstalledFontCollection class
for details.
MSDN:
Enumerating Installed Fonts


q:
What is the best way of dynamically writing LINQ queries and Lambda expressions?

I am thinking of applications where the end user can design business logic rules, which then must be executed.

I am sorry if this is a newbie question, but it would be great to get best practices out of experience.

[A]
I can see two ways you can dynamically generate lambda's. You could try Reflection.Emit to generate IL (the .Net bytecode) directly and call them as a lambda or you can use the System.CodeDom and Microsoft.CSharp.CSharpCodeProvider to generate the code from higher level constructs. What you want to do depends on how you want the user to input this stuff. If you want the user to write C# then you can just use the built in compliler.
Generating Linq dynamically should be easier. You should be able to generate LINQ queries as expression trees in runtime and then pass them into an IQueryable to execute. I'd suggest you look into the documentation on IQueryable to learn more about this. Another way would be to pre-define a couple of linq queries and then allow the user to chain them together. This should be workable because any Linq query returns an IEnumerable that can be consumed by the next Linq query.


q:
Can you please clarify the folowing query? I am not sure if the way I am trying to code is correct. Kindly advise me if I am moving in the right/wrong direction.

I am trying to develop an automation framework using QuickTest Professional, a testing tool.

There is an Excel sheet from which the data is being taken for execution based on the ID's stored in an array from another Excel sheet (The same ID is available in both Excel sheets).

I'm trying to handle the exeptional cases through a function call. This function will capture the screenshot of the page error occured and then exit the entire loop.

I need a scenario where execution continues for the next ID stored in the array, and this needs to be handled from the function call.

[A]
Well, it sounds like you already have the answer.. You just need to handle the expection that occurs when reading in the data within the main loop and make it stop there..
Now, I have not done VBScript for a LONG time so, to pseudo it:
```
```
While Not EndOfExcelSheet
    ReadDataFromExcel();
    If errOccurred Then TakeScreenPrint();
    'NOTE: We have caught the error and requested the screen print
    'is taken, but we have NOT bubbled the exception up!
End While
```
```


q:
Is there any way to generate project docs during automated builds?

I'd like to have a single set of source files (HTML?) with the user manual, and from them generate:

PDF document

CHM help

HTML version of the help

The content would be basically the same in all three formats.

Currently I'm using msbuild and CCNET, but I could change that if needed.

[A]
Yes!
Use
SandCastle
to build CHM/HTM documentation of the APIs.
Use
DocBook
+
FOP
and other tools to produce other kinds of documentation in PDF, RTF, HTML etc...
They can be easily integrated with CruiseControl.NET through
NAnt
.


q:
At work we use WiX for building installation packages. We want that installation of product X would result in uninstall of the previous version of that product on that machine.

I've read on several places on the Internet about a major upgrade but couldn't get it to work.
Can anyone please specify the exact steps that I need to take to add uninstall previous version feature to WiX?

[A]
Finally I found a solution - I'm posting it here for other people who might have the same problem (all 5 of you):
Change the product ID to *
Under product add The following:
```
```
<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="YOUR_GUID">
   <UpgradeVersion
      Minimum="1.0.0.0" Maximum="99.0.0.0"
      Property="PREVIOUSVERSIONSINSTALLED"
      IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>
```
```
Under InstallExecuteSequence add:
```
```
<RemoveExistingProducts Before="InstallInitialize" />
```
```
From now on whenever I install the product it removed previous installed versions.
Note:
replace upgrade Id with your own GUID


q:
I have a Windows executable (whoami) which is crashing every so often.  It's called from another process to get details about the current user and domain.  I'd like to know what parameters are passed when it fails.

Does anyone know of an appropriate way to wrap the process and write it's command line arguments to log while still calling the process?

Say the command is used like this:
'whoami.exe /all'

I'd like a script to exist instead of the whoami.exe (with the same filename) which will write this invocation to log and then pass on the call to the actual process.

[A]
You didn't note which programming language. It is not doable from a .bat file if that's what you wanted, but you can do it in any programming language. Example in C:
```
```
int main(int argc, void **argv)
{
    // dump contents of argv to some log file
    int i=0;
    for (i=0; i<argc; i++)
        printf("Argument #%d: %s\n", argv[i]);
    // run the 'real' program, giving it the rest of argv vector (1+)
    // for example spawn, exec or system() functions can do it
    return 0; // or you can do a blocking call, and pick the return value from the program
}
```
```


q:
I'm using httpc:request to post some data to a remote service. I have the post working but the data in the body() of the post comes through as is, without any URL-encoding which causes the post to fail when parsed by the remote service.

Is there a function in Erlang that is similar to CGI.escape in Ruby for this purpose?

[A]
AFAIK there's no URL encoder in the standard libraries. Think I 'borrowed' the following code from YAWS or maybe one of the other Erlang web servers:
```
```
% Utility function to convert a 'form' of name-value pairs into a URL encoded
% content string.

urlencode(Form) ->
    RevPairs = lists:foldl(fun({K,V},Acc) -> [[quote_plus(K),$=,quote_plus(V)] | Acc] end, [],Form),
    lists:flatten(revjoin(RevPairs,$&,[])).

quote_plus(Atom) when is_atom(Atom) ->
    quote_plus(atom_to_list(Atom));

quote_plus(Int) when is_integer(Int) ->
    quote_plus(integer_to_list(Int));

quote_plus(String) ->
    quote_plus(String, []).

quote_plus([], Acc) ->
    lists:reverse(Acc);

quote_plus([C | Rest], Acc) when ?QS_SAFE(C) ->
    quote_plus(Rest, [C | Acc]);

quote_plus([$\s | Rest], Acc) ->
    quote_plus(Rest, [$+ | Acc]);

quote_plus([C | Rest], Acc) ->
    <<Hi:4, Lo:4>> = <<C>>,
    quote_plus(Rest, [hexdigit(Lo), hexdigit(Hi), ?PERCENT | Acc]).

revjoin([], _Separator, Acc) ->
    Acc;

revjoin([S | Rest],Separator,[]) ->
    revjoin(Rest,Separator,[S]);

revjoin([S | Rest],Separator,Acc) ->
    revjoin(Rest,Separator,[S,Separator | Acc]).

hexdigit(C) when C < 10 -> $0 + C;
hexdigit(C) when C < 16 -> $A + (C - 10).
```
```


q: I just want my apache to register some of my predefined environment so that i can retrieve it using getenv function in php. How can i do this? I tried adding /etc/profile.d/foo.sh with export FOO=/bar/baz using root and restarted apache.

[A]
Environment variables are inherited by processes in Unix. The files in /etc/profile.d are only executed (in the current shell, not in a subshell) when you log in. Just changing the value there and then restarting a process will not update the environment.
Possible Fixes:
log out/log in, then start apache
source the file:
```
# . /etc/profile.d/foo.sh
```
, then restart apache
source the file in the apache init script
You also need to make sure that
```
/etc/profile.d/
```
is sourced when Apache is started by
```
init
```
rather than yourself.
The best fix might also depend on the distribution you are using, because they use different schemes for configuration.


q:
What is the difference between the following class methods?

Is it that one is static and the other is not?

class Test(object):
  def method_one(self):
    print "Called method_one"

  def method_two():
    print "Called method_two"

a_test = Test()
a_test.method_one()
a_test.method_two()

[A]
When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable
```
self
```
actually means nothing, it's just a coding convention. You could call it
```
gargaloo
```
if you wanted. That said, the call to
```
method_two
```
would raise a
```
TypeError
```
, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.
To actually make it work, you could append this to your class definition:
```
```
method_two = staticmethod(method_two)
```
```
or you could use the
```
@staticmethod
```
function decorator
.


q:
With the introduction of .NET 3.5 and the IQueryable<T> interface, new patterns will emerge. While I have seen a number of implementations of the Specification pattern, I have not seen many other patterns using this technology. Rob Conery's Storefront application is another concrete example using IQueryable<T> which may lead to some new patterns.

What patterns have emerged from the useful IQueryable<T> interface?

[A]
It has certainly made the repository pattern much simpler to implement as well. You can essentially create a generic repository:
```
```
public class LinqToSqlRepository : IRepository
{
   private readonly DataContext _context;

   public LinqToSqlRepository(DataContext context)
   {
       _context = context;
   }

   public IQueryable<T> Find<T>()
   {
       return _dataContext.GetTable<T>(); // linq 2 sql
   }

   /** snip: Insert, Update etc.. **/
}
```
```
and then use it with linq:
```
```
var query = from customers in _repository.Find<Customer>()
            select customers;
```
```


q:
I use pstack to analyze core dump files in Solaris

How else can I analyze the core dump from solaris?

What commands can be used to do this?

What other information will be available from the dump?

[A]
GDB can be used.
It can give the call that was attempted prior to the dump.
http://sourceware.org/gdb/
http://en.wikipedia.org/wiki/GDB
Having the source is great and if you can reproduce the errors even better as you can use this to debug it.
Worked great for me in the past.


q: The second question is: When do I use what of these two?

[A] Managed C++ means that memory allocation, management, garbage collection is handled by the virtual machine. Whereas in "regular" C++ you would have to allocate and deallocate memory.


q:
I am getting the following error whenever I click on a postbacking control

HttpException (0x80004005): Validation
of viewstate  MAC failed. If this
application is hosted by a Web  Farm
or cluster, ensure that  configuration
specifies the same validationKey and
validation  algorithm. AutoGenerate
cannot be used in a cluster.

I am not using a Web Farm or cluster server. I have even tried setting the page property EnableViewStateMac to false but it changes the error message stating

The state information is invalid for
this page and might be corrupted.

What could possibly be wrong?

[A]
There is an article about this here:
http://blogs.msdn.com/tom/archive/2008/03/14/validation-of-viewstate-mac-failed-error.aspx
.
The basic problem is that Your page hasn't completed loading before You perform the postback.
A few different solutions are in the article listed above:
1. Set enableEventValidation to false and viewStateEncryptionMode to Never
2. Mark the form as disabled and then enable it in script once the load is complete.
3. override the Render Event of the page to place the hidden fields for Encrypted Viewstate and Event validation on the top of the form.
But the main problem is that the page load slow, which should be fixed (if possible ASAP). It can also be good to apply solution 2 above as well as there will always be trigger happy users that will click faster that the page loads no matter how fast it loads :-).
/Andreas


q:
I want to emulate the delete confirmation page behavior before saving
certain models in the admin.  In my case if I change one object,
certain others should be deleted as they depend upon the object's now
out-of-date state.

I understand where to implement the actual cascaded updates (inside
the parent model's save method), but I don't see a quick way to ask
the user for confirmation (and then rollback if they decide not to
save). I suppose I could implement some weird confirmation logic
directly inside the save method (sort of a two phase save) but that
seems...ugly.

Any thoughts, even general pointers into the django codebase?

Thanks!

[A]
I'm by no means a Django expert, so this answer might misguide you.
Start looking somewhere around
```
django.contrib.admin.options.ModelAdmin
```
, especially
```
render_change_form
```
and
```
response_change
```
. I guess you would need to subclass ModelAdmin for your model and provide required behavior around those methods.