Question:
Right now a project I'm working on has reached a level of complexity that requires more than a few steps (actually its become arcane!) to produce a complete/usable product. And unfortunately we didn't start out with a Continuos Integration mindset, so as you can imagine its kind of painful at times, and at others I can easily waste half a day trying to get a clean/tested build.

Anyways as any HUGE project it consists of many components in many different languages (not only enterprise style Java or C# for example), as well as many graphical, and textual resources. Now the problem is that when I look for Continuos Integration, I always find best practices and techniques that assume one is starting a new project, from the ground up.  However this isn't a new project, so I was wondering what are some good resources to proactively start migrating from Arcane Integration towards Continuos Integration :)

Thanks in advance!

Answer:
I would guess that migrating isn't really an option--Half-ass solutions will only make it worse.
My approach would be to take one creative engineer who understands the build process, sit him down and say "Fix this".  Give him a week or two.
The end goal would be a process that runs beginning to end with a single make command.
I also recommend an automated "Setup" procedure where you simply do a checkout and run a batch file from a network share to install and build all your tools.  The amount of time this will save overall is staggering if you bring in new programmers.  Most projects take one to three days to get set up on a new computer--and it's always the "new" programmer who doesn't know what's going on doing the installs on his own system...


Question:
Okay, I guess this is entirely subjective and whatnot, but I was thinking about entropy sources for random number generators. It goes that most generators are seeded with the current time, correct? Well, I was curious as to what other sources could be used to generate perfectly valid, random (The loose definition) numbers.

Would using multiple sources (Such as time + current HDD seek time [We're being fantastical here]) together create a "more random" number than a single source? What are the logical limits of the amount of sources? How much is really enough? Is the time chosen simply because it is convenient?

Excuse me if this sort of thing is not allowed, but I'm curious as to the theory behind the sources.

Answer:
Don't worry about a "good" seed for a random number generator.  The statistical properties of the sequence do not depend on how the generator is seeded.  There are other things, however. to worry about.  See
Pitfalls in Random Number Generation
.
As for hardware random number generators, these physical sources have to be measured, and the measurement process has systematic errors. You might find "pseudo" random numbers to have higher quality than "real" random numbers.


Question: I've looked into and considered many JavaScript unit tests and testing tools, but have been unable to find a suitable option to remain fully TDD compliant. So, is there a JavaScript unit test tool that is fully TDD compliant?

Answer:
Take a look at
the Dojo Object Harness (DOH) unit test framework
which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at
Unit testing Web 2.0 applications using the Dojo Objective Harness
.
If you want to automate the UI testing (a sore point of many developers) — check out
doh.robot
(temporary down. update: other link
http://dojotoolkit.org/reference-guide/util/dohrobot.html
)
and
dijit.robotx
(temporary down)
. The latter is designed for an acceptance testing.
Update:
Referenced articles explain how to use them, how to emulate a user interacting with your UI using mouse and/or keyboard, and how to record a testing session, so you can "play" it later automatically.


Question:
For a deleted file what's the command to use to view the content of a old revision

E:\Downloads\eeli\eel\eel>svn cat eel-scalable-font.h -r 2
svn: warning: 'eel-scalable-font.h' is not under version control

Answer:
I think what your looking for is:
```
```
svn cat eel-scalable-font.h@2
```
```


Question:
Joomla has a built-in function on its login screen "I've forgotten my user name", so that you can type in your email address and the username is sent to you via email.

I was thinking of changing it so that the username was displayed on screen immediately, without any form of authentication. This would greatly reduce the friction for our users who are returning after a long while, but it would allow anyone to type in any email address and see the associated username (definitely not the other way around though).

Does this create any security risks? Is it a good idea at all?

Answer:
I would say it is a
slight
security risk for your less savvy users.  For a user with a weak password, particularly if it is related to their username or e-mail address, exposing their user name leaves them open to having their account hijacked.  Other than that, I can't think of a reason it would be a problem.  If the user has good passwords, it shouldn't matter at all.
I guess there is a slight anonymity concern.  On a forum for example, I wouldn't want someone who "knows" me to find out my username without me telling them.  In this case they could take my e-mail and get it.  But whether that is an issue depends on your site and your user base.


Question:
I have a label function like :

private function formatDate (item:Object, column:DataGridColumn):String
{
    var df:DateFormatter = new DateFormatter();
    df.formatString = "MM/DD/YY";

    if (column.dataField == "startDate") {
        return df.format(item.startDate);
    }

    return "ERR";
}

Which I use in a datacolumn by using labelFunction.

This works just fine if my data field is called 'startDate'. I want to make this function generic so I can use it everywhere.

How can I do this. i think i need to use some kind of 'reflection' - or perhaps another approach altogether?

Answer:
You can define another function, let's call it
```
partial
```
that binds some extra arguments to your function:
```
```
function partial( func : Function, ...boundArgs ) : Function {
  return function( ...dynamicArgs ) : * {
    return func.apply(null, boundArgs.concat(dynamicArgs))
  }
}
```
```
Then you change your function like this:
```
```
private function formatDate( dataField : String, item : Object, column : DataGridColumn ) : String {
  var df : DateFormatter = new DateFormatter();

  df.formatString = "MM/DD/YY";

  if ( column.dataField == dataField ) {
    return df.format(item[dataField]);
  }

  return "ERR";
}
```
```
Notice that I have added a new argument called
```
dataField
```
first in the argument list, and replaced all references to "startDate" with that argument.
And use it like this:
```
```
var startDateLabelFunction : Function = partial(formatDate, "startDate");
var endDateLabelFunction   : Function = partial(formatDate, "endDate");
```
```
The
```
partial
```
function returns a new function that calls the original function with the parameters from the call to partial concatenated with the parameters to the new function... you with me? Another way of putting it is that it can return a new function where N of the arguments are pre-bound to specific values.
Let's go through it step by step:
```
partial(formatDate, "startDate")
```
returns a function that looks like this:
```
```
function( ...dynamicArgs ) : * {
  return func.apply(null, boundArgs.concat(dynamicArgs));
}
```
```
but the
```
func
```
and
```
boundArgs
```
are what you passed as arguments to
```
partial
```
, so you could say that it looks like this:
```
```
function( ...dynamicArgs ) : * {
  return formatDate.apply(null, ["startDate"].concat(dynamicArgs));
}
```
```
which, when it is called, will be more or less the same as this
```
```
function( item : Object, column : DataGridColumn ) : * {
  return formatDate("startDate", item, column);
}
```
```
Tada!


Question:
I love grids - especially the cool third party ones like Devex, C1 etc..

Our programmer doesn't think end users can handle them - so he always designs his forms with read-only grids (with read-only classes).  Choosing to edit an item in the grid opens up a detail form that allows editing.

This app is going to be used by general business folk - not geeks.  But they are all very good Excel users - which I think is kinda 'grid' like. Should I trust my lead developer, or go with my gut which says that users like fast editing - which the grid does much better than the detail forms?  I do want to have a consistent feel to the application, so prefer not to mix it up too much.

Answer:
Users can totally handle grids. It's more intuitive than an edit button and a detail form.
However, is this application a multiple user application? Could the underlying data be changed by more than one user at a time?
If so, then you have some concurrency design decisions to make, and sometimes, that can be easier to solve when users can only edit one row at a time.
It smells a little fishy though, and I suspect your programmer is making convenient excuses because it's easier for him to design read-only grids in a master / detail pattern.
Stick with your gut instinct. :)


Question:
I am using several NSButtonCell objects in an NSTableView. They are simple square buttons with custom images on them.

These buttons draw properly when they are not highlighted: all that is visible is the image, and the rest of the button rectangle is transparent. However, when I click on them, the entire button rectangle is highlighted, inverting the background in the parts that were transparent.

I would prefer to see the image drawn inverted, and the transparent parts remain transparent. How can this be done?

Answer:
Try setting your cell's
```
highlightsBy
```
property to
```
NSContentsCellMask
```
. I think you'll have to do this in code (probably in
```
awakeFromNib
```
); I don't see a way to do it in IB alone.


Question: Is there ever a good reason to not declare a virtual destructor for a class?  When should you specifically avoid writing one?

Answer:
There is no need to use a virtual destructor when any of the below is true:
No intention to derive classes from it
No instantiation on the heap
No intention to store with access via a pointer to a superclass
No specific reason to avoid it unless you are really so pressed for memory.


Question:
To calculate a top position for an element of variable height, I was thinking of doing the following:

Move the element 1000px off the top of the viewport

Set the element to display: block

Get the height of the element

Set the element to display: none

Continue on as if everything is normal and good

Any pitfalls in this approach? Is there a more elegant solution?

Answer:
I'd look at
prototype's implementation
of
```
getDimensions
```
.
It sets the position to absolute, visibility to hidden, and display to block briefly. I've written one which handles getting the height of something which is contained within a
```
display:none
```
element, but it's a bit shonky in some edge cases.


Question:
We were using stringstream to prepare select queries in C++. But we were strongly advised to use QUERY PARAMETERS to submit db2 sql queries to avoid using of stringstream. Can anyone share what exactly meant by query parameter in C++? Also, share some practical sample code snippets.

Appreciate the help in advance.

Edit: It is stringstream and not strstream.

Thanks,
Mathew Liju

Answer:
I suspect this refers to parameterized queries in general, rather than constructing the query in a string, they supply sql variables (or parameters) and then pass those variables separately.  These are much better for handling SQL Injection Attacks.  To illustrate with an example:
```
```
"SELECT * FROM Customers WHERE CustomerId = " + _customerId;
```
```
Is bad, while this:
```
```
"SELECT * FROM Customers where CustomerId = @CustomerId"
```
```
is good.  The catch is that you have to add the parameters to the query object (I don't know how this is done in C++.
References to other questions:
https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Stored Procedures vs Parameterized Queries
Wild Wild Web:
http://www.justsoftwaresolutions.co.uk/database/database-tip-use-parameterized-queries.html


Question:
I recently started diving into low level OS programming. I am (very slowly) currently working through two older books, XINU and Build Your Own 32 Bit OS, as well as some resources suggested by the fine SO folks in my previous question, How to get started in operating system development.

It could just be that I haven't encountered it in any of those resources yet, but its probably because most of these resources were written before ubiquitous multicore systems, but what I'm wondering is how interrupts work in a multicore/multiprocessor system.

For instance, say the DMA wants to signal that a file read operation is complete.  Which processor/core acknowledges that an interrupt was signaled?  Is it the processor/core that initiated the file read? Is it whichever processor/core that gets to it first?

Answer: In the old days the interrupt went to all processors.  In modern times some kinds of hardware can be programmed by an OS to send an interrupt to one particular processor.  Of course if you could choose a processor dynamically instead of statically, you wouldn't want to send the interrupt to whichever processor initiated the I/O, you'd want to send it to whichever processor is least burdened at the present time and can most efficiently start the next I/O operation, and/or whichever processor is least burdened at the present time and can most efficiently execute the thread that was waiting for the results.


Question:
I'm writing a function for an installer DLL to verify the Authenticode signature of EXE files already installed on the system.

The function needs to:

A) verify that the signature is valid.

  B) verify that the signer is our organization.

Because this is in an installer, and because this needs to run on older Win2k installations, I don't want to rely on CAPICOM.dll, as it may not be on the target system.

The WinVerifyTrust API works great to solve (A).

I need to find a way to compare a known certificate (or properties therein) to the one that signed the EXE in question.

Answer:
If the signature is valid, its certificate chain will contain your certificate.
CertGetCertificateChain
will get that chain.


Question:
Is it possible to re-assign the Win+L hotkey to another executable/shortcut?

Use-case - I would like to switch off the monitor of my laptop as soon as it is locked. I know of a executable which can lock and turn off the monitor but I do not want to change the way the system is locked (by running the program explicitly or by some other shortcut). It would be best if Win+L can be assigned to this executable.

Answer:
Looks like you can't.
You can disable all built-in Windows
  hotkeys
except Win+L
and Win+U by
  making the following change to the
  registry (this should work on all OSes
  but a reboot is probably required):
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
  NoWinKeys REG_DWORD 0x00000001 (1)
(
http://www.autohotkey.com/docs/misc/Override.htm
)
But you could try using Tweak UI. Under the Explorer tree view item, uncheck "Enabled Windows+X" hotkeys.
Hoekey
also might work, haven't tried it.
Source
.


Question:
How can I determine if a Win32 thread has terminated?

The documentation for GetExitCodeThread warns to not to use it for this reason since the error code STILL_ACTIVE can be returned for other reasons.

Thanks for the help! :)

Answer:
The documentation you link to warns against using
```
STILL_ACTIVE
```
as a return code, since it can't be distinguished from the return value used to indicate an active thread.
So don't use it as a return value and you won't have this problem.


Question: say I want to find the latest added rows (UPDATE by any user, not necessarily the one which is executing UPDATE)  in XX table.

Answer:
Please refer to SQL Docs & look for OUTPUT clause (that you can use with UPDATE/INSERT to get the affected records).
http://msdn.microsoft.com/en-us/library/ms177564.aspx


Question:
I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:

>>> foo = 'baz "\"'
>>> foo
'baz ""'

So instead of baz "\" like I want I'm getting baz "". If I then try to escape the backslash, it doesn't help either:

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'

Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?

Answer:
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
```
```
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
```
```
Incidentally, there's another string form which might be a bit clearer:
```
```
>>> print(r'baz "\"')
baz "\"
```
```


Question:
I realize that this could probably be done easier in any number of other scripting languages but started to do it quick in cmd and now Im curious.

Looking to start a process at an offset to the time that another process started.  Lets say 5 minutes to keep it simple.  Is there a way to add to the %TIME% variable?

For instance:

start /b foo.exe
at %TIME% + 5 minutes bar.exe

Thanks for any assistance

Answer:
I just typed
```
set/?
```
and discovered cmd is much better than old bat... :-)
```
```
set h=%TIME:~0,2%
set m=%TIME:~3,2%
set/a m2="m+5"
set t2=%h%:%m2%
set t2
```
```
Obviously, you can get 62 minutes, etc., I let you do the extra math... :-D


Question: How would I implement "close all other tabs" function for a tab control using Context menu strip?

Answer:
I made a small app with just one tabcontrol in the main window and a context menu connected to that tabcontrol.
The following is the handler for the context menu item:
```
```
private void closeAllOtherToolStripMenuItem_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < this.tabControl1.TabCount; i++)
            if (i != tabControl1.SelectedIndex)
                tabControl1.TabPages.RemoveAt(i--);
    }
```
```


Question: My program works already, I have Perl (GUI Window) where I can input data, data passed to the webpage (using to Tomcat server, JSP) and then saved it to oracle database. What I want is to make search parameter (webapp) that retrieve/extract data from the Oracle database using Perl CGI. Is it possible? Or any suggestions to solve my program? Thanks!:-)

Answer:
Any specific reason for the mix in technologies? Why not use a servlet/JSP?
If you must use Perl, then you need to choose what web-server will run your Perl script.
Normally, this would be Apache using
mod_perl
.
But if you only intend to use this for a few admin scripts, then you can run Perl from tomcat as outlined
here
.
Once you have managed to get a simple perl script running, then I would look into using
DBI/DBD::Oracle
to access your database?
Hope this helps...


Question:
I want to show a table of fixed width at the center of browser window. Now I use

<table width="200" align="center">

But Visual Studio 2008 gives warning on this line:

Attribute 'align' is considered outdated. A newer construct is recommended.

What CSS style should I apply to the table to obtain the same layout?

Answer:
```
```
style="text-align:center;"
```
```
(i think)
or you could just ignore it, it still works


Question: Is there a way to define the timezone for an application in ASP.NET such that all times read from/compared to current server time are implicitly converted, or do I need to put in conversion statements as each and every DateTime.Now call?

Answer:
Internally use
DateTime.UtcNow
. For .NET 3.5, check out
TimeZoneInfo.ConvertTime
.


Question:
How to delete a file which is in use/open by some process in runtime.
I am using vb.net for my project and a image is shown in picturebox,
and that should be deleted, without closing that file.

Answer:
If the file is opened by another process in exclusive mode, you can't -- Windows won't let you.  In that case, the best you can do is to either wait for the other process to close the file and then delete it, or have it be deleted at the next reboot by using
```
MoveFileEx()
```
with the flag
```
MOVEFILE_DELAY_UNTIL_REBOOT
```
and a destination location of
```
NULL
```
.
If the file is opened non-exclusively by another process, you can just call
```
DeleteFile()
```
normally (assuming you have permission to do so).  The file will remain while the other process has it open, but it will be deleted as soon as the other process closes it.
(And yes, I realize those links are for the Win32 C API; the same functions should be available under VB .NET)


Question:
I need to use a byte array as a profile property in a website. Normally I would declare the type as system.string or system.int32 but I have no idea what the type if for a byte array.

EDIT: I need to use this as profile property that is declared in the web.config like below:

<profile defaultProvider="ProfileProvider" enabled="true">
    <properties>
            <add name="Username" allowAnonymous="false" type="System.String" />
            <add name="LoginToken" allowAnonymous="false" type=" System.Byte()" />
        </properties>
</profile>

Answer:
If the file is opened by another process in exclusive mode, you can't -- Windows won't let you.  In that case, the best you can do is to either wait for the other process to close the file and then delete it, or have it be deleted at the next reboot by using
```
MoveFileEx()
```
with the flag
```
MOVEFILE_DELAY_UNTIL_REBOOT
```
and a destination location of
```
NULL
```
.
If the file is opened non-exclusively by another process, you can just call
```
DeleteFile()
```
normally (assuming you have permission to do so).  The file will remain while the other process has it open, but it will be deleted as soon as the other process closes it.
(And yes, I realize those links are for the Win32 C API; the same functions should be available under VB .NET)


Question: how do I get information about a photo like the author, the license using PHP?

Answer:
This information is all available through the
Flickr API
, if you poke around their docs you may find what you're looking for.


Question:
Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.

For example:

typedef std::bitset<16> WordSet;

Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in g++.

Answer:
In the case of
```
std::bitset
```
, you can just use the
```
size()
```
member function:
```
```
size_t sz = oh_my_word.size();  // sz is now 16
```
```
In the general case, you can define a member function which returns the size in a similar manner:
```
```
template <int N>
class Foo
{
public:
  int size() const { return N; }
};
```
```


Question:
I am executing a diff command in perl.

my @lines = `/usr/local/bin/diff -udr \"$expected_file\" \"$gen_file\"`;

if ($? != 0)
{
    print ERRFILE "Diff between $expected_file and $gen_file failed\n";
    return $diff_err;
}

Here the diff might have failed because of some reason. For example: the stderr showed that /usr/local/bin/diff: test.txt: No such file or directory. I want to read this message in the program. How I can find the stderr message of the diff command (or grep or any command I execute)?

Appreciate the help in advance.

Thanks,
Mathew Liju

Answer:
This is answered in
perlfaq8: How can I capture STDERR from an external command?
If I want to read STDOUT and STDERR of a process, I use IPC::Open3, which comes with Perl. That way, I don't have to merge those streams and later figure out what part of the output came from what.
I would try to avoid temporary files whenever possible (so no
```
2>file.txt
```
). That's just too much work and code when I can read STDERR directly.


Question: I am using Xcode to develop a GUI application. I have a model class and a controller class. I have a NSTextView data member in my controller class. How do I access this variable from the model class?

Answer:
First of all, a model class shall not talk to a view class. A TextView is part of the view.
alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/cocoa_mvc.gif
The controller talks to view classes and view classes provide feedback to the controller. The model classes get updated by the controller and provide feedback to it. The model classes never talk to a view class, they don't even know about the existence of any view classes. So I think you have a basic design problem here. You probably implemented MVC as in this model:
alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/traditional_mvc.gif
However this is not the way it is done in Mac OS X, this is not the way Apple does it and this is not the way how the whole Cocoa object structure has been designed! So the answer to your question is: You don't, because you should not.
Aside from the fact, that you have a design flaw, you access it like you access all data members in Objective-C. If it is public, you can access it directly:
```
```
MyController * c = [[MyController alloc] init];
// c has a member name textView, let's access it
[c->textView ...];
```
```
You should already know, that this is actually very bad programming style. You should not access data members of another object directly. You should actually not even make them public. If you declare them private, the code above will fail (the compiler enforces that you don't do this). The other way is to implement a getter and access it via the getter:
```
```
// This goes into the controller

- (NSTextView) textView
{
    return textView;
}

// This is called in the modell

[[c textView] ...];
```
```
However, this is also bad design. The model might do whatever it wants with this object and your controller won't see it! Why doesn't you model just tell the controller what it wants to happen?
```
```
// In the controller

- (void) notifyContentHasChanged:(NSString *)name
{
    // update the text view here ...
}

// In the modell

[c notifyContentHasChanged:...];
```
```
And voila, you have MVC the way Apple wants it to be. The model only notifies the controller of what's going on and the controller updates the view accordingly.


Question:
I have a question regarding an update function I created...

CREATE OR REPLACE FUNCTION rm_category_update(icompany bpchar, iraw_mat_cat_code bpchar, iraw_mat_cat_desc bpchar)

RETURNS character AS

$BODY$

DECLARE
   loc_result    CHAR(50);

BEGIN

UPDATE rm_category

 SET
    raw_mat_cat_code    = iraw_mat_cat_code,
    raw_mat_cat_desc    = iraw_mat_cat_desc

WHERE company = icompany;

loc_result = 'success';

RETURN loc_result ;

END;

$BODY$

LANGUAGE 'plpgsql' VOLATILE;

ALTER FUNCTION rm_category_update(icompany bpchar, iraw_mat_cat_code bpchar, iraw_mat_cat_desc bpchar) OWNER TO postgres;

Okay, so if I input a record that doesn't exist, for example 9, it returns success even though I know it has updated nothing!

Does SQL not throw errors if it is updating a non-existent row??

Thanks

Answer:
First of all, a model class shall not talk to a view class. A TextView is part of the view.
alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/cocoa_mvc.gif
The controller talks to view classes and view classes provide feedback to the controller. The model classes get updated by the controller and provide feedback to it. The model classes never talk to a view class, they don't even know about the existence of any view classes. So I think you have a basic design problem here. You probably implemented MVC as in this model:
alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/traditional_mvc.gif
However this is not the way it is done in Mac OS X, this is not the way Apple does it and this is not the way how the whole Cocoa object structure has been designed! So the answer to your question is: You don't, because you should not.
Aside from the fact, that you have a design flaw, you access it like you access all data members in Objective-C. If it is public, you can access it directly:
```
```
MyController * c = [[MyController alloc] init];
// c has a member name textView, let's access it
[c->textView ...];
```
```
You should already know, that this is actually very bad programming style. You should not access data members of another object directly. You should actually not even make them public. If you declare them private, the code above will fail (the compiler enforces that you don't do this). The other way is to implement a getter and access it via the getter:
```
```
// This goes into the controller

- (NSTextView) textView
{
    return textView;
}

// This is called in the modell

[[c textView] ...];
```
```
However, this is also bad design. The model might do whatever it wants with this object and your controller won't see it! Why doesn't you model just tell the controller what it wants to happen?
```
```
// In the controller

- (void) notifyContentHasChanged:(NSString *)name
{
    // update the text view here ...
}

// In the modell

[c notifyContentHasChanged:...];
```
```
And voila, you have MVC the way Apple wants it to be. The model only notifies the controller of what's going on and the controller updates the view accordingly.


Question: I am running a site about PHP Frameworks, but I can't find a exact definition for it, and I am always thinking a question, how to make out a good PHP framework? Features? Manual? Efficiency? Or something?

Answer:
A PHP Framework in my eyes is a collection of classes which help you develop a web application.
In my company we use the Zend Framework. I have to say that getting started with this Framework is pretty hard, but if you get how to use the API and the Reference Guide you have a great Framework. Also its interessting because they have Zend people sitting on the project so they can use those internal tricks and get some performance boosts others can't get.
What also differs ZF from others is the ability to create MVC programms with no big hassles.


Question:
Ours is an upcoming company, so we cannot buy two three third party controls and find out by ourselves which the best one is.(One of the better solutions)
We have a budget to buy just one.
So we would like to know which is third party control is the best to use in ASP.NET based on your experiences.

And also I definitely saw a question asked already here.

https://stackoverflow.com/questions/215993/best-3rd-party-aspnet-grid-control

Still asking this because

Wanna know not just about grid, i wanna know about the whole set.

Didn't see many answers for that.

So please provide us some advice on how to proceed.
Our requirements are

Bug Free working

Speed

Good documentation

Excellent Support Team

Also is there a third party ListView?

Regards,

Naveen

Answer:
For all those requirements, there's only two companies to choose from:
Telerik
and
DevExpress
.  Both have fantastic support and incredible ASP.NET products.  They release often, and are known to be constantly adding new controls.  I had to decide between the two about a year ago, and went with DevExpress because of the productivity tools included.
The difference I see between these two companies and larger competitors like Infragistics is they are dedicated to making the best quality and best performing products possible.


Question:
A C-program is placing what it considers to be 64-bit unsigned integers into a column in a Postgres database that is typed as int8.
To Postgres, int8 is always 'signed int8' (no such thing to it as 'unsigned int8').
So the Ruby program I have shows numbers retrieved from Postgres in the upper half of that space as negative.

What is the correct way, in Ruby, to take that -ve integer and convert it to the 64-bit unsigned integer that the C-programmer intended?

Answer:
For all those requirements, there's only two companies to choose from:
Telerik
and
DevExpress
.  Both have fantastic support and incredible ASP.NET products.  They release often, and are known to be constantly adding new controls.  I had to decide between the two about a year ago, and went with DevExpress because of the productivity tools included.
The difference I see between these two companies and larger competitors like Infragistics is they are dedicated to making the best quality and best performing products possible.


Question:
I am developing a Java desktop application and would like to have an external configuration.xml.

I am developing the application using Netbeans and tried to add the configuration.xml file in the dist directory so that it resides in the application work folder. But when Netbeans executes its clean operation it deletes the dist directory,

Where should I put this configuration.xml file so that it will not be deleted and will exist in the application start-up directory.

Answer:
You can add this to your build.xml :
```
```
<target name="-post-jar">
   <copy todir="${dist.jar.dir}">
       <fileset dir="resources" includes="**"/>
   </copy>
</target>
```
```
You can now put your configuration.xml file in the folder 'resources' (that you need to create) in your project and all files in it will be copied to the dist folder during the build process.


Question:
I have example of code below.

<script type="text/javascript" src="assets/scripts/somescript.php">.
</script>

So, will my browser still cache this just by not setting this scripts headers meta tag cache to must-revalidate?

Answer:
If you send a
```
Content-type: text/javascript; charset="your_charset"
```
the browser will recognize your PHP script as a valid Javascript resource and will handle it like any other Javascript. You can control browser caching behavior by issuing the correct headers in your PHP script using
```
header()
```
.


Question: I want to increase the I/O priority of a process. Answers for both .NET and Windows Vista would be nice. processexplorer is ok as well.

Answer:
The relevant information seems to be a bit scattered compared to the usual MS documentation. There is this white paper that discusses
I/O Prioritization in windows
. This doc seems to have beta flags all over it but I guess it's probably mostly pretty accurate.
Two important things to note:
You can only reduce the priority of IO requests below normal.
The driver can ignore any such request and treat it as normal anyway.
The useful APIs for client applications are
SetFileInformationByHandle
:
```
```
FILE_IO_PRIORITY_HINT_INFO priorityHint;
priorityHint.PriorityHint = IoPriorityHintLow;
result = SetFileInformationByHandle( hFile,
                                     FileIoPriorityHintInfo,
                                     &priorityHint,
                                     sizeof(PriorityHint));
```
```
SetPriorityClass
:
```
```
// reduce CPU, page and IO priority for the whole process
result = SetPriorityClass( GetCurrentProcess(),
                           PROCESS_MODE_BACKGROUND_BEGIN);
// do stuff
result = SetPriorityClass( GetCurrentProcess(),
                           PROCESS_MODE_BACKGROUND_END);
```
```
SetThreadPriority
which is similar:
```
```
// reduce CPU, page and IO priority for the current thread
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
// do stuff
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
```
```
SetFileBandwithReservation
:
```
```
// reserve bandwidth of 200 bytes/sec
result = SetFileBandwidthReservation( hFile,
                                  1000,
                                  200,
                                  FALSE,
                                  &transferSize,
                                  &outstandingRequests );
```
```
For .Net do the usual stuff with P/Invoke.


Question:
I'm using RSACryptoServiceProvider in .NET 2 and it seems that the Private part of a Public/Private key pair always contains the Public part as well.

I need to encrypt some info using my Public key, and allow the other party to ONLY DECRYPT what I encrypted. I don't want them to be able to know how I encrypted my message. Is that possible using RSACryptoServiceProvider in .NET?

Answer:
The private key always includes the public key.
What you might really want is Signing. Using the same .NET classes, you can sign data with your private key and verify the signature on the other party's side with the public key (which obviously doesn't contain the private key).
```
```
public static string Sign(string data, string privateAndPublicKey)
    {
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        RSACryptoServiceProvider provider = CreateProviderFromKey(privateAndPublicKey);
        byte[] signatureBytes = provider.SignData(dataBytes, "SHA1");
        return Convert.ToBase64String(signatureBytes);
    }

    public static bool Verify(string data, string signature, string publicKey)
    {
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        byte[] signatureBytes = Convert.FromBase64String(signature);
        RSACryptoServiceProvider provider = CreateProviderFromKey(publicKey);
        return provider.VerifyData(dataBytes, "SHA1", signatureBytes);
    }

    private static RSACryptoServiceProvider CreateProviderFromKey(string key)
    {
        RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
        provider.FromXmlString(key);
        return provider;
    }
```
```


Question:
If I have a template function, for example like this:

template<typename T>
void func(const std::vector<T>& v)

Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:

template<typename T>
void func(const std::vector<T*>& v)

Thanks

Answer:
Indeed, templates can do that, with partial template specialization:
```
```
template<typename T>
struct is_pointer { static const bool value = false; };

template<typename T>
struct is_pointer<T*> { static const bool value = true; };

template<typename T>
void func(const std::vector<T>& v) {
    std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
}
```
```
If in the function you do things only valid to pointers, you better use the method of a separate function though, since the compiler type-checks the function as a whole.
You should, however, use boost for this, it includes that too:
http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html


Question:
I use the Autocomplete extender feature to get the list of suggestions from my database. There is no scroll bar for this control, so I have added a scroll bar in a panel (MS .net 2.0) which i attach to my autocomplete extender.Now the issue is with the srcoll bar.
like this

<asp:Panel ID="autocompleteDropDownPanel" runat="server"  ScrollBars="Auto"  Height="100px" HorizontalAlign="Left" />

and add it to autocompete extender  like this

:CompletionListElementID="autocompleteDropDownPanel"

When I call my page, I get the list of suggestions and the scroll bar appears. When I click on scroll bar or try to drag, everything just disappears.

Am i doing something wrong? Is there any other way to add a scroll bar to my autocomplete extender control

Any hints would be very helpful.

Answer:
This does not directly answer your question - but I would ask if you're sure that the autocomplete extender is the best control to be using in this scenario.
From a usability perspective the great thing about autocomplete is that I can type a 3-4 characters, see a few available inputs and easily select them using the keyboard using a few down-cursor keypresses.
If you are displaying more items in the autocomplete list than can be easily viewed on screen then I'm not sure that the fix is to add a scrollbar.
In our scenario we had a list of 2800 names that were available in the autocomplete. We limited the number shown to 20, but set the
```
MinimumPrefixLength
```
to 1. This meant that when the user typed one character they would see an autocomplete list that effectively just lets them know that the textbox they're typing in has this ability. The list of results in the list only becomes really useful once the user has entered 3-4 characters though.


Question:
I am probably doing something wrong -- but cant figure why.
I have a DateTime field in my DB keeping a UTC time

My server is in the US, and the browser is in Europe.

The PageLoad Code is as follow:

DateTime t = DateTime.SpecifyKind((DateTime)rdr["startTime"], DateTimeKind.Utc);
label1.Text = t.ToLocalTime().ToString();

The time displayed I get is US localtime and not Europe. What should I do to display the browser's localtime?

Thanks!

Answer:
One technique is to detect the client timezone offset (in minutes) using JavaScript on the client browser:
```
```
alert((new Date()).getTimezoneOffset());
```
```
This can then be sent back to the server and stored in the session, or a cookie, and used to offset the UTC dates displayed to them. Alternatively, another technique is to have user profiles where they can specify their timezone.


Question:
OK, deploying ASP.NET MVC seems to be painful. I want to deploy my ASP.NET MVC application on Windows XP (IIS 5.1), but can't seem to find how to do it. When I type the application name into the web browser address bar I get a "website not available" message.

There are workarounds for IIS 6.0, but what about IIS 5.1?

Answer:
The
same
process (using Ionic rewriter) which works for 6.0 works for us on 5.x. What do you see in the Windows App Event log? And the IIS server log? Have you tried a rewriter?


Question:
My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments.
eg.

/// <summary>Summary here</summary>
/// <example>Here is an example  <code>example code here</code> </example>
public void SomeFunction()

We then use Sandcastle and build the help files we need (chm and an online website).

It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.

Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?

Answer:
Simple solution:
Make a small application in which you include all the sample code headers and then call their respective entry points
```
```
#include "samples/sampleA.h"

void main()
{
  SomeFunction();
}
```
```
then after you make a build run these little apps you need to be sure they ran ok.
But can you verify that the code ran ok without having someone have a slumber party with the NightlyBuild server?
Better Solution:
Log the output and have someone look at it in the morning.
Even Better Solution:
Log the output and grep it or something so no one has to look at it unless its broken.
Best Solution:
Find a suitable test framework, hopefully something with all the bells and whistles you can get so it can email people if its broken or something like that. In our case we avoid the bells and whistles instead we connected a
USB Police Siren
that goes off when something breaks It's quite exciting!


Question:
I am using Oracle form 10
I want to know how can I access the parameters of URL in oracle form

Ex:
whenever I run the form it opens in a browser and the URL for the same is

http://112.10.0.10:7778/forms/frmservlet?config=pkamble

I just want to know how can I access the value of 'config' parameter inside oracle form code.

when we run oracle form using 10g then

I will appreciate the help !!

Answer:
I don't know if you can read config parameter, but to read another parameter from URL your URL have to be like:
```
```
http://112.10.0.10:7778/forms/frmservlet?config=pkamble&otherparams=name=value
```
```
In your .fmb you will have to add 'name' parameter in the parameters block and then you could do something like:
```
```
if :PARAMETER.name = 'value' then
 message('ok');
end if;
```
```
And for more than one parameter use:
```
```
http://112.10.0.10:7778/forms/frmservlet?otherparams=name1=value1+name2=value2+name3=value3
```
```


Question: How do I declare a session variable in PL/SQL - one that will persist for the duration of the session only, without me having to store it in the database itself?

Answer:
You create a package level variable.  This is a minimal example:
```
```
CREATE OR REPLACE PACKAGE my_package
AS
    FUNCTION get_a RETURN NUMBER;
END my_package;
/

CREATE OR REPLACE PACKAGE BODY my_package
AS
    a  NUMBER(20);

    FUNCTION get_a
    RETURN NUMBER
    IS
    BEGIN
      RETURN a;
    END get_a;
END my_package;
/
```
```
If you do this you should read up on (and handle correctly)
```
ORA-04068
```
errors.  Each database session will have it's own value for a.  You can try this with:
```
```
SELECT my_package.get_a FROM DUAL;
```
```


Question:
In most programming languages, dictionaries are preferred over hashtables.
What are the reasons behind that?

Answer:
Because
```
Dictionary
```
is a generic class (
```
Dictionary<TKey, TValue>
```
), so that accessing its content is type-safe (i.e. you do not need to cast from
```
Object
```
, as you do with a
```
Hashtable
```
).
Compare
```
```
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
```
```
to
```
```
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
```
```
However,
```
Dictionary
```
is implemented as hash table internally, so technically it works the same way.


Question:
In a PHP application I am writing, I would like to have users enter in text a mix of HTML and text with pointed-brackets, but when I display this text, I want to let the HTML tags be rendered by the non-HTML tags be shown literary, e.g. a user should be able to enter:

<b> 5 > 3 = true</b>

when displayed, the user should see:

5 > 3 = true

What is the best way to parse this, i.e. find all the non-HTML brackets, convert them to &gt; and &lt;?

Answer:
I'd recommend having the users enter BBcode style markup which you then replace with the html tags:
```
```
[b]This is bold[/b]
[i]this is italic with a > 'greater than' sign there[/i]
```
```
This gives you more control over how you parse user's input into html, though I admit it looks like an unnecessary burden.


Question:
Coming from a java background, one of the things I am used to is telling the JVM what the maximum heap size should be.  If the running program tries to swallow more than is allowed, and the garbage collector cannot free any more resources, then OutOfMemoryError is thrown and it all goes bang.  So setting the maximum heap size is important in Java.

Does this apply in .net?  Can you set the heap size limits?  Does the CLR just keep growing its heap until it reaches the machine's physical limits?  Or is it not an issue in .net for some subtle reason that my Java blinkers stop me from seeing?

Answer:
No, it doesn't apply in .NET. The heap does indeed keep growing until it can't grow any more. (Obviously this is "after attempting to recover memory through GC, grow the heap".) Basically there isn't nearly as much tuning available in the .NET GC as in Java. You can choose the server GC or the client one, and I think there's an option for turning on/off the concurrent GC (I'll find links in a minute) but that's basically it.
EDIT: It seems there's a little more to it, although not a huge amount.
Rick Minerich's blog entry on GC settings
and
the subsequent one
seem to know rather more than I do about the matter. They're probably a good starting point for any further investigation - but they're mostly flags rather than the sort of memory limits available in JVMs.
EDIT: Pop's answer raises a good point - I've been assuming a "normal" CLR hosting model (i.e. not under your control). If you want to go to the effort of hosting it yourself, you're likely to get a lot more control - at the cost of the extra work of hosting it. I can't say I've ever looked into that side of things.


Question:
I am working with Rails fixtures for testing my rails application.  It is all good except one of my database columns is supposed to hold YAML content.  But, I am sure how to put the YAML markup I want to load into my database inside the YAML file.  Here is an example:

mvnforum:
    name: mvnforum
    abstraction_type: SVN
    url: src: test username: admin #is this possible?
    sourcepath: mvnforum/src/
    webroot:
    codesecure_project: mvnforum

If it is impossible to have YAML inside a YAML file what would be the best why to load this into a database for testing?

Answer:
If you want to put YAML code inside a YAML document, you need to treat it like a string:
```
```
url: "src: test username: admin"
```
```
If you need a multiline string, you can do
```
```
mvnforum:
   name: mvnforum
   abstraction_type: SVN
   url: "
src: test\n
username: admin\n
"
   sourcepath: mvnforum/src/
   webroot:
   codesecure_project: mvnforum
```
```


Question:
This might of been asked elsewhere (seems like a useful topic) but searches turned up nothing.

One feature I love in Eclipse when programming Java is that I don't have to worry about putting in the import statements and any missed functions from interfaces that I am implementing them - if I do miss them a simple click from a list implements them for me.

Now I am working in VisualStudio2008 with C# I am really missing that functionality. I was wondering if the functionality is in there, but buried or can be purchased through a 3rd party?

Thanks.

Answer: you have to pay for this feature. Look at Resharper 4.0 from JetBrains. It is a perfect solution for me.


Question: Since the speed of the top Javascript engines seems to be on par, the next criteria is footprint.  What are the code and data footprints of the leading javascript engines?

Answer:
squirrelfish should have the smallest footprint ( i remember i read somewhere that it uses a really simple translation table from JS code to native code), but if you want something very small you should look at earlier js engines (that dont use native code tables) as they interpret code as they go, and dont compile the whole thing according to the current machine.
I dont see the point of comparing js engines though as they are basically single-threaded(well new engines are multithreaded but this is from the new "highly-optimized" engines) and they are only loaded once, and then interpret megabytes of JS code... The speed is more important than size..even for mobile devices, because i dont expect a JS engine to use more than 1-2Mb of memory(even that is waaay too much in my opinion..) but the sum of JS scripts in a JS based page can easily pass that.


Question:
I have a method to return a group of objects as a generic list which I then bind to a Repeater. I want to implement paging on the repeater using the PagedDataSource class but I'm not sure that this is possible as it doesn't seem to work.

Will I have to change the return type of my method or is it possible to bind the PagedDataSource to the generic list?

Answer:
I've just modified some of my code to use a generic list and seems to have worked fine, hope this helps:
Note that this entire method can be called with or without a page number to automatically set the page, it also builds a paging control inside of a panel calling PagingPanel.
The line that sets the DataSource on the PagedDataSource instance (dataSource) did take an array of NewsItems (searchResults), I've updated it to consume a List that's created using the NewItem array.
```
```
void PopulateNewsItems (int? pageNo)
{
    var model = ModelFactory.GetNewsModel ();
    var searchResults = model.GetNewsItems ();

    var dataSource = new PagedDataSource ();

    // CHANGED THE ARRAY OF NEWSITEMS INTO A GENERIC LIST OF NEWSITEMS.
    dataSource.DataSource = new List<NewsItem> (searchResults);
    dataSource.AllowPaging = true;

    var pageSizeFromConfig = ConfigurationManager.AppSettings["NewsItemsPageCount"];
    var pageSize = 10;

    int.TryParse (pageSizeFromConfig, out pageSize);

    dataSource.PageSize = pageSize;
    dataSource.CurrentPageIndex = pageNo ?? 0;

    PagingPanel.Controls.Clear ();
    for (var i = 0; i < dataSource.PageCount; i++)
    {
        var linkButton = new LinkButton ();
        linkButton.CommandArgument = i.ToString ();
        linkButton.CommandName = "PageNo";
        linkButton.Command += NavigationCommand;
        linkButton.ID = string.Format ("PageNo{0}LinkButton", i);
        if (pageNo == i || (pageNo == null && i == 0))
        {
            linkButton.Enabled = false;
            linkButton.CssClass = "SelectedPageLink";
        }

        linkButton.Text = (i + 1).ToString ();

        PagingPanel.Controls.Add (linkButton);
        if (i < (dataSource.PageCount - 1))
            PagingPanel.Controls.Add (new LiteralControl ("|"));
    }

    NewsRepeater.DataSource = dataSource;
    NewsRepeater.DataBind ();
}

void NavigationCommand (object sender, CommandEventArgs e)
{
    PopulateNewsItems (int.Parse ((string)e.CommandArgument));
}
```
```


Question:
...or am I stuck rolling my own "XML chopping" functions. I'd like to create a small tasktray app so I can quickly re-point a Virual Directory to one of several of folders on my harddisk.

Bit of background:

I have 3 different svn branches of our code base on my dev machine.

Current Production Branch    ( C:\Projects\....\branches\Prod\ )
Next Release Canidate Branch ( C:\Projects\....\branches\RCX\ )
Trunk                        ( C:\Projects\....\trunk\ )

Our app integrates with a 3rd party CMS which I've installed at

http://localhost/cms/

In order to work our app has to live at the same root directory. so:

http://localhost/app/

Depending on the branch I'm working on, I'm re-pointing the /app/ directory to one of the 3 paths listed above by going into IIS Manager. Just thought it'd be handy to have a quick-app to do it for me.

Answer:
I haven't used this my self, so I'm not 100% sure it will solve your problem. But take a look at System.DirectoryServices in .NET. It can access IIS.
MSDN help for DirectoryServices


Question:
I want to create a compiled JavaScript file for my website.  For development I would prefer to keep the JavaScript in separate files and just as part of my automated scripts  concatenate the files into one and run the compressor over it.

My problem is that if I use the old DOS copy command it also puts in the EOF markers which the compressor complains about:

copy /A *.js compiled.js /Y

What are other people doing?

Answer:
To copy without EOF use binary mode:
```
```
copy /B *.js compiled.js /Y
```
```
If the resulting file still has EOFs, that might have come from one of original files,
it can be fixed by this variant:
```
```
copy /A *.js compiled.js /B /Y
```
```
/A removes trailing EOFs from original files if any and /B prevents appending EOF to the resulting file. If an EOF is not at the end, the source file will be truncated at it. The order of switches is important. If you write
```
```
copy /A *.js /B compiled.js /Y
```
```
- EOFs in source files won't be removed but still resulting EOF won't be appended.
Try it yourself, thats where I get it. DOS commands are weird.


Question:
I have a relatively powerful dev workstation - 8 cores and 3 Gig of Ram. However, Visual Studio 2008 does not seem to take full advantage, especially during large builds.
Are there any tweaks to be performed on XP VM settings etc to increase performance? I remember back in the bad old days that out of the box windows does not take best advantage of machines with lots of memory, is this still the case?

PS assume I can make no hardware changes

Answer:
The biggest issue I usually have when working in large projects aren't cpu or memory, but the hard drive. Get several HD's on different channels (or use SCSI for best performance) and put the output files, intermediate files, temp folder on 3 different HD's. That should make a big difference.
I know you said no hardware changes, but since you didn't write what type of HD setup you had, I just wanted to mention this.
VS will not be able to use all your 8 cpu's efficiently unless you have a really fast HD setup.


Question:
A lot of files will be stored in the DB and I need file hashes to unique identify that the file was not changed.
(In general, will be used as the Windows Personal Firewall part)

Answer:
This is, of course, not possible in general. Many people still use hashing for this purpose, and
MD5
is a popular algorithm, that gives you a 128-bit "signature" for the file with a high probability of changing when the contents of the file changes.
In the general case, you need to look at every bit of the file to include it in the hash, and performance will probably be I/O-limited. It's a sequential sweep over all data in the file, updating the state of whatever hash algorithm you use for each new byte. On a modern CPU, the latter will be quicker than the former.
This rather old analysis
shows around ~45 MB/s on a Pentium 90 MHz CPU.


Question:
I'm trying to load javascript code with a user web control into a page via a the Page.LoadControl method during an asyncron post back of an update panel.

I've tried the specially for that scenario designed methods of the scriptmanager, but the javascript just doens't get returned to the user.

To explain my scenario a bit better:

Master Page has the script manager and one page loads the user control via Page.LoadControl-method during an async post back. The custom control injects in the pre-render event handler the javascript. Is that a matter of timing to inject the js or is it just not possible to do so?

Answer:
Have your tried
```
```
Page.ClientScript.RegisterStartUpScript(GetType(Page), "key", <your script here>, addSctiptTags:=true)
```
```
We do this in our User Controls and it works for us
HTH


Question:
Here is new C# future in version 4.0 known as dynamic. Show me the way i can use it in my code and how this future can help me?

Related questions:

Does the new ‘dynamic’ C# 4.0 keyword deprecate the ‘var’ keyword ?

What do you think of the new C# 4.0 ‘dynamic’ keyword?

Answer:
One of the usages is interop between static and dynamic languages.
Say you want to invoke a JavaScript function fron silverlight:
```
```
HtmlPage.Window.Invoke("HelloWorldFunction");
```
```
If the window was dynamic (and properly implemented) you would be able to use it like this:
```
```
HtmlPage.Window.HelloWorldFunction();
```
```


Question:
I have a ListBox control that I want to change into having a toggle selection. i.e. Click once on an item selects it, click again it deselects it. Also, clicking another item in the list should do the default action of deselecting the previous item and selecting the new one.

What's the best way of achieving this?

Answer:
I would keep the standard ListBox as that way you will keep the default behaviour you want, then for deselecting an item could you just handle it in the mouse down event? i.e. use something like this:
```
```
Point newPoint = e.GetPosition(backgroundImage);

HitTestResult result = VisualTreeHelper.HitTest(this, newPoint);

if (result.VisualHit is ListBoxItem)
```
```
I'm not sure if this is the best way, the only other way I would go about doing this is to derive my own ListBox from the standard windows control and add in a dependency property to allow me to handle the deselection in the style. If you want to take this approach I shouldn't remove the default behaviour you want to keep either, I used this approach to create a ListBox that would display an image next to the text.
If you need any pointers on where to start, then just give me a shout.


Question:
We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with?
(It is a web-app)

Answer:
In .NET, C# 3.0 and VB9 provide excellent support for working with XML using LINQ to XML:
LINQ to XML Overview


Question:
I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.

I mean that I have an offline paper based form. I need to convert it into a software that people can use on their computers to fill and submit information. Since the form (it is a tax return) requires considerable time in filling, it is not convenient to have it online only. I would much rather have a simple exe which gathers information, applies validation rules and then uploads a structured data file (like an XML file) containing the filled info.

Answer:
What do you mean, exactly? When you build a project containing a form, it will already build an executable if the project type is "Windows Forms Application".
If you've got one project with several forms and you need one executable per form, you should split your project out - one project per form. (You
could
make the code display a different form based on executable name - or have several entry points and build the same code with different
```
/main
```
flags, but that would be pretty nasty.)


Question:
Does anyone know how to unit test SiteMapNode? We’re building some custom navigation controls, which renders unordered html lists from Site Maps with custom attributes.

I’m trying to follow a test first approach but am finding that SiteMapNode has internal dependencies on HttpContext. To traverse the site map file it insists on using a virtual path to find the site map file.

I have build a site map, which I’d like to test against but I don’t want to create my unit testing environment in web project(!)

Any suggestions? Mocking?  Overriding the relevant members?

Answer:
A rather dull question, so no surprise it didn't get a response! For anyone else who may stumble across this problem, here's my preferred solution:
I've found the best way to handle this is to load the physical site map into an xml document. I then have a NavigationNodeFactory, which validates and builds my own composite NavigationNode tree from the xml document.
My NavigationNode class is as opinionated as I like and circumnavigates the issues I found with SiteMap and SiteMapProvider, namely poor testability for implementers.


Question:
I am working on a big C++ project. It is building using single Ant script which makes possible to compile the same source targeting more than one platform and compiler.

But, I have to work only for Windows platform and Visual Studio 2005 C++ compiler. It would be really nice if I could write code and compile in Visual Studio, instead of using Notepad++ and Ant scripts, as I do now.

I tried to install Nant and Nant addin for Visual Studio 2005, and to use existing Ant script, but it seems that Ant script cannot be used as a Nant script.

Is there any way to convert Ant script to Nant? Is any other approach to the problem at all, or I must create Visual Studio solution and projects manually?

I would try to avoid such solution because I have a bunch of tests that I don't know how to use in that case.

Answer:
To my knowledge, there is no
automatic
way of converting Ant script to NAnt. However, since NAnt is based off of the Ant the conversion process would not be too far from the original, as long as the tasks are the "core" ones. Possibly an XSLT translation could be made on the Ant scripts to convert to NAnt as both are XML. If one were to go down this path the conversion should be done
dynamically
based of the original Ant scripts, so that only one set of scripts would have to be maintained.
If you would like to write and compile your C++ code inside of Visual Studio it's tough to beat the functionality that is built in with the IDE. However, this requires creating project files though. Otherwise, it seems that one would risk fighting an uphill battle with the tool.
One option for the tests would be to call out through a
custom build step
to run them.


Question:
I've got this date time string:

post["date"] = "2007-07-18 10:03:19"

I'd like to extract just "2007-07-18" as a date. I've seen some reference to strptime but I'm not sure how to use it.  How can I extract the date from this string?

Answer:
In your case, just use split:
```
```
>>> d1="2007-07-18 10:03:19"
>>> d1.split()[0]
'2007-07-18'
>>>
```
```
(The 1st part after splitting with whitespace)
If you insist on using
```
strptime
```
, the format is
```
"%Y-%m-%d %H:%M:%S"
```
:
```
```
>>> import time
>>> time.strptime(d1,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2007, tm_mon=7, tm_mday=18, tm_hour=10, tm_min=3, tm_sec=19, tm_wday=2, tm_yday=199, tm_isdst=-1)
>>> time.strftime("%Y-%m-%d", _)
'2007-07-18'
>>>
```
```


Question:
I'm using the MultiPoint SDK to create a collaborative educational application for children in less affluent countries, where there is not one computer for each student in the classroom.

Because we need to support up to 40 mice connected to one computer, we need an automated way to test our software. The SDK will support as many mice that it can find on the system and detects when mice are added and removed. Each mouse appears as a 'virtual' mouse pointer within a WPF window. Each child has independent control of 'their' pointer on the screen.

We would like to create a test harness that tricks Windows into thinking that it has more than one mouse. The harness would need to create these fake devices (40+) and use them to send mouse messages like move, button down, etc

Any help would be greatly appreciated.

Answer:
Faking mice to the extent that you'd need for MultiPoint is going to require a device driver. This is not an easy task, but is by no means impossible.
The best approach would probably be a
HID minidriver
that you can install using the
Setup API
. The driver would then accept
```
DeviceIoControl
```
s which would cause it to simulate mouse input reports.


Question:
PHP has a var_dump() function which outputs the internal contents of an object, showing an object's type and content.

For example:

class Person {
  private $firstName;
  private $lastName;

  public function __construct($firstName, $lastName) {
    $this->firstName = $firstName;
    $this->lastName = $lastName;
  }
}

$person = new Person('Jon', 'Smith');
var_dump($person);

will output:

object(Person)#1 (2) {
  ["firstName:private"]=>
  string(3) "Jon"
  ["lastName:private"]=>
  string(5) "Smith"
}

What is the equivalent in Java that will do the same?

Answer:
It is not quite as baked-in in Java, so you don't get this for free.
It is done with convention rather than language constructs.  In all data transfer classes (and maybe even
in all classes you write...
), you should implement a sensible
```
toString
```
method.  So here you need to override
```
toString()
```
in your
```
Person
```
class and return the desired state.
There are
utilities available
that help with writing a good toString method, or most IDEs have an automatic
```
toString()
```
writing shortcut.


Question:
I have this SQL query:

SELECT * FROM IMAGES WHERE
IMAGENAME in ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6')
ORDER BY CASE IMAGENAME
  WHEN 'IMG1' THEN 1
  WHEN 'IMG2' THEN 2
  WHEN 'IMG3' THEN 3
  WHEN 'IMG4' THEN 4
  WHEN 'IMG5' THEN 5
  WHEN 'IMG6' THEN 6
  ELSE 7
END

I cannot guarantee that the list of IMAGENAMEs will be in alphabetical order, hence the case statement, but I would prefer to sort in the DB rather than in code because I trust their sorting code better than mine :)

SQL server analyses that 78% of the execution time is spent sorting - can I reduce this?

It needs to be fairly vanilla SQL as we target SQL Server and Oracle.

Any tuning advice would be fantastic.

Answer:
Could you strip the
```
IMG
```
(or non-numeric) part of the
```
IMAGENAME
```
to a new column when writing to the database, then sort on the new numeric-only column?
For example:
```
```
SELECT * FROM IMAGES WHERE
IMAGENAME in ('IMG1', 'IMG2', 'IMG3', 'IMG4', 'IMG5', 'IMG6')
ORDER BY IMAGENO
END
```
```
where
```
IMAGENO
```
would contain
```
1, 2, 3, 4, 5, 6
```
for each row in your example, respectively.


Question:
There's a web services I want to call in my application, I can use it with importing the WSDL or by just use "HTTP GET" with the URL and parameters, so I prefer the later because it's simple thing.

I know I can use indy idhttp.get, to do the job, but this is very simple thing and I don't want to add complex indy code to my application.

UPDATE: sorry if I was not clear, I meant by "not to add complex indy code", that I don't want add indy components for just this simple task, and prefer more lighter way for that.

Answer:
Calling a RESTful web service using Indy is pretty straight forward.
Add IdHTTP to your uses clause.  Remember that IdHTTP needs the "HTTP://" prefix on your URLs.
```
```
function GetURLAsString(const aURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create;
  try
    Result := lHTTP.Get(aURL);
  finally
    lHTTP.Free;
  end;
end;
```
```


Question:
I want to be able to create a file, distribute it to an end-user, but prevent them from making modifications to the file.

Now, obviously, I can't actually stop anybody from modifying the file - so my approach is to detect and reject the file if it's modified.

My intention is to generate a salted hash of the file contents and append it to the file. On reading, the hash is verified before reading the rest of the file. The downside of this is that I have to distribute the fixed "salt" in the executable which reads the file. Obviously I can obfuscate it to some extent, but that still feels like a weak link.

Are there any better approaches to solving this kind of problem?

Answer:
Not if you want a 100% solution. Just look at the movie and music industry. They have tried and failed for many years now :)
I think your solution is good enough. To make it harder to modify the file you could encrypt it, but then they can't read it, so it will only work if that is an ok limitation.


Question:
I am having a postgres production database in production (which contains a lot of Data). now I need to modify the model of the tg-app to add couple of new tables to the database.

How do i do this? I am using sqlAlchemy.

Answer:
If you are just adding tables, and not modifying any of the tables which have the existing data in it, you can simply add the new sqlAlchemy table definitions to model.py, and run:
```
```
tg-admin sql create
```
```
This will not overwrite any of your existing tables.
For schema migration, you might take a look at
http://code.google.com/p/sqlalchemy-migrate/
although I haven't used it yet myself.
Always take a backup of the production database before migration activity.


Question: How to create a WCF application without using the svcutil.exe tool?

Answer:
What version of Visual Studio are you using?
VS2008 incorporates the functionality of the svcutil tool.  To generate the proxy, click on the Solution Explorer and select 'Add Service Reference', you can then enter the URL of the server, give the namespace a name and off you go.
You may want to expand your question to provide some more details of what you are wanting to achieve.


Question:
I'm trying to load spring beans using XmlWebApplicationContext setConfigLocations method.  However, I keep getting a

BeanIsAbstractException

I know that the bean is abstract, I have it configured this way, so Spring should know not to try to instantiate it.

I'm using Spring2.0.8.jar with jetspeed2.1.

Spring bean:

<bean id="ThreadPool" abstract="true" class="com.sample.ThreadPoolFactoryBean"/>

Code:

ctx = appContext;
    appContext.refresh();
    BeanFactory factory = appContext.getBeanFactory();
    String[] beansName = appContext.getBeanFactory()
            .getBeanDefinitionNames();

...

map.put(beansName[mnCnt], factory.getBean(beansName[mnCnt]));

Anyone have any ideas?

Answer:
The following code will try, and fail to create an instance of your abstract class:
```
```
map.put(beansName[mnCnt], factory.getBean(beansName[mnCnt]));
```
```
Just so there is no confusion, 'abstract' beans are
not the same
as abstract classes.They are primarily a convenient mechanism for reducing duplicate property settings.
A child bean definition will inherit constructor argument values,
      property values and method overrides from the parent, with the option
      to add new values. If init method, destroy method, factory bean and/or
      factory method are specified, they will override the corresponding
      parent settings.
A contrived example:
```
```
class Fruit {
    private String colour;
    private String name;
    // setters...
}

class Car {
    private String colour;
    private String manufacturer;
    // setters...
}
```
```
And:
```
```
<!-- specifying a class for an abstract bean is optional -->
<bean id="sharedPropsBean" abstract="true">
    <property name="colour" value="red" />
</bean>

<bean id="myFruit" parent="sharedPropsBean" class="Fruit">
    <property name="name" value="apple" />
</bean>

<bean id="myCar" parent="sharedPropsBean" class="Car">
    <property name="manufacturer" value="Ferrari" />
</bean>
```
```


Question:
I need to perform a HTTP GET from PHP.

More specifically, from within /index.php I need to get the content of /trac/ and /svn/, find the "ul" element and then render then inline on the index.php.

/trac and /svn are relative URLs and not filesystem folders.
http://myserver/trac and http://myserver/svn

Answer:
Have a look at
file_get_contents
- it can be used to open urls under some conditions as can some of the other
filesystem functions
:
A URL can be used as a filename with
  this function if the fopen wrappers
  have been enabled. See fopen() for
  more details on how to specify the
  filename and List of Supported
  Protocols/Wrappers for a list of
  supported URL protocols.


Question:
Can anyone explain to me what this means?

"Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call.  This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention."

Answer:
Possibility #1 is your object got Aliased wrong. That means the compiler mistakenly casted an object incorrectly, most commonly as an optimization.
Possibility #2 your using a reference to an object that isn't valid.
Possibility #3 something totally unrelated broke your stack, likely a buffer overflow.
Without code sample It's hard to predict beyond these possibilities, but they cover 90% of what might be happening.


Question:
How do you set a break points in server tags in .aspx pages. e.g.

<%   dim breakhere =new object() %>

The web application is running in debug mode with the <compilation debug="true" ... in the web.config. But the page says:

The break point will not currently be
  hit. No symbols have been loaded for
  this document.

Is there anything else i need to set?

Answer:
I havent tried this myself but in ASP (VBScript) you can inject a STOP statement and that will trigger the IDE to break on that line
Example
```
```
<%
STOP
Dim o as Object = new Object()
%>
```
```
HTH


Question:
Edit: This behaviour is reproducible with query globals on.

I have the following:

  $_SESSION['query_key'] = $_GET['query_key'];
  print($query_key);

Vs.

  $_SESSION['query_key'] = clone $_GET['query_key'];
  print($query_key);

The former prints out the value of $query_key, while the latter prints nothing.
What sort of weird side effect is this of clone?

Answer:
You must be doing something very weird with your code.
clone
is for use on objects.  Unless you're stuffing objects into $_GET then that code will result in a fatal error (or a warning in older PHP versions).
@Michael Haren - clone actually does a shallow copy of an object, that is, it copies all the properties, but if a property is a reference to another object it will copy the reference, not clone the other object.


Question:
In the grails-framework some objects are using log. This is normally injected by grails. It works on execution of grails test-app. But the same test (an integration-test) fails on execution of grails test-app -integration.

What goes wrong here and can I force the injection of the log-object somehow?

Answer:
What version of grails are you using?  It's working fine for both situations for me on 1.0.4 (the latest).
I create a new blank app and created a service class with an integration test:
FooService.groovy:
```
```
class FooService {
    def logSomething(message) {
        log.error(message)
        return true
    }
}
```
```
FooServiceTests.groovy:
```
```
class FooServiceTests extends GroovyTestCase {
    def fooService
    void testSomething() {
    assert fooService.logSomething("it works")
    }
}
```
```
When running just test-app, I get the log message:
```
```
% grails test-app

Welcome to Grails 1.0.4 - http://grails.org/
....
-------------------------------------------------------
Running 1 Integration Test...
Running test FooServiceTests...
                        testSomething...[4174] service.FooService it works
SUCCESS
Integration Tests Completed in 440ms
-------------------------------------------------------
...
```
```
When running only integration tests, it also works:
```
```
% grails test-app -integration

Welcome to Grails 1.0.4 - http://grails.org/
....
-------------------------------------------------------
Running 1 Integration Test...
Running test FooServiceTests...
                    testSomething...[4444] service.FooService it works
SUCCESS
Integration Tests Completed in 481ms
-------------------------------------------------------
....
```
```
Are you munging around with the logger class (or overriding any metaclass stuff on the logger, in any previous integration classes or unit tests and not then re-initializing the metaClass?


Question:
I have a web app that is heavily loaded in javascript and css. First time users log in it takes some time to load once it is downloading js etc. Then the caching will make everything faster.

I want my users to be aware of this loading time. How can I add some code to "show" some loading information while js and css are downloaded?

Answer:
Sweet mother of mercy, Ricardo, how much Javascript and CSS are involved with this application?
You could, I guess, do something where you load the JS and CSS using an AJAX request and do nothing with them.  This will load your JS and CSS files into the cache.  You could do all of this on a "Loading" page, and redirect to the real page once you've loaded the files.  But IMO you really shouldn't have to do this.  Use
Fiddler
to really see what's going on behind the scenes -- make sure people are really having to wait for their JS/CSS files to come down before doing this optimization.


Question:
I would like to do the equivalent of the following:

#define print_max(TYPE) \
#  ifdef TYPE##_MAX \
     printf("%lld\n", TYPE##_MAX); \
#  endif

print_max(INT);

Now the #ifdef or any nested preprocessor directive is
not allowed as far as I can see in a function macro.
Any ideas?

Update: So it seems like this is not possible. Even a hack to check at runtime seems unachievable. So I think I'll go with something like:

#ifndef BLAH_MAX
#  define BLAH_MAX 0
#endif
# etc... for each type I'm interested in

#define print_max(TYPE) \
    if (TYPE##_MAX) \
       printf("%lld\n", TYPE##_MAX);

print_max(INT);
print_max(BLAH);

Answer:
I don't think it's a case of the ## operator not being allowed in an #ifdef. I tried this:
```
```
#define _print_max(TYPE) \
#ifdef TYPE \
printf("%lld\n", _TYPE); \
#endif

#define print_max(TYPE) _print_max(MAX##_TYPE)

void main()
{
    print_max(INT)
}
```
```
and it still didn't work (it didn't like #ifdef TYPE). The problem is that #ifdef will only accept #defined symbols, not #define arguments. Those are two different things.


Question:
My scenario is:

I have a WPF Window with 3 data-bound text boxes

SettingsUI : Window

<Grid Name="SettingsUIGrid1">
    <TextBox Text="{Binding val1}" ....
    <TextBox Text="{Binding val2}" ....
    <TextBox Text="{Binding val3}" ....
</Grid>

In the constructor I do this:

SettingsUIGrid1.DataContext = coll[0]; // collection first value

When the Cancel button is clicked, I close my window:

private void btnCancel_Click(object sender, RoutedEventArgs e) {
Close();
}

When I click the Show button, is shows values from the DB in text boxes, if user changes a text box value, and reloads the window the new value is displayed not the old one.  Can someone suggest what to do to reload the values again and clear the in memory object?

Answer:
I would suggest putting some code into your cancel button click event to check whether any of the data has been changed from what was initially loaded as I am assuming that if they don't click cancel the other button would be save/ok meaning that the data would be committed to the database.
What is coll?
if it is a DataTable then you could use this:
```
```
private static bool DataRowReallyChanged(DataRow row)
    {
        if (row == null)
        {
            return false;
        }

        if (!row.HasVersion(DataRowVersion.Current) || (row.RowState == DataRowState.Unchanged))
        {
            return false;
        }

        foreach (DataColumn c in row.Table.Columns)
        {
            if (row[c, DataRowVersion.Current].ToString() != row[c, DataRowVersion.Original].ToString())
            {
                return true;
            }
        }

        return false;
    }
```
```
then simply add a call into the cancel button event like:
```
```
if (DataRowReallyChanged((DataRow)SettingsUIGrid1.DataContext))
{
     ((DataRow)SettingsUIGrid1.DataContext).RejectChanges();
}
```
```
I hope this helps. If you are not using a DataTable then let me know what you are using and ill see if i can help further.


Question:
I have a form with a DIV, 3 INPUTS, each INPUT sits within a LABEL element. I would like to change the background image of the DIV element when focusing on each INPUT.

I can't move back up the DOM to fix this with CSS, so could someone suggest a few lines of jQuery please?

Thanks

Answer:
```
```
$('input').focus(function(){
    $(this).parent().parent().addClass('highlight');
}).blur(function(){
     $(this).parent().parent().removeClass('highlight');
});
```
```


Question:
How can I return to the start of a line and overwrite what has already been output on the console? The following does not appear to work:

System.out.print(mystuff+'\r');

Answer:
If you just want to write a new line to the console, you should use the println() method:
```
```
System.out.println(mystuff);
```
```
However, this will not delete what is already on the line. Actually, since System.out is a PrintStream, which is a type of OutputStream, that is basically hard to do, although you may find terminal-specific ways to do it.
You might have better luck using a Java implementation of a curses library, such as
JavaCurses
.


Question: I would like to know if there is any easy way to print multiple emails(about 200) so that they continue on as opposed to printing one per page. I have tried with thunderbird and evolution and this does not seem possible. Would concatenating the individual mail files work or are there other unix utilities that could do this? WOuld sed or awk be suited for this?

Answer:
Why don't you put all the data from the mails in one text file and print that one.
This could be done by something like:
```
```
cat *.eml > file.txt
```
```
Or print it directly with
```
```
cat *.eml | lpr
```
```


Question:
I need to purchase SQL Server 2008 Standard edition, because it's features fit what I need. On the features page, it says it can handle 32,767 user connections, but how does that connect with CALs?

What are CALs and how can they affect a project?

Answer:
A CAL is a client access license.
SQL Server 2008 has 3 licensing models (explained
here
):
Processor Licensing Model
Server Plus Device CALs Licensing Model
Server Plus User CALs Licensing Model
You try and select the cheapest model that meets your requirements.
From this
page
:
Q: What is the difference between device client access licenses (CALs) and user CALs?
A. A device CAL allows any number of users to gain access to licensed server software from a particular device. A user CAL lets a particular user gain access to licensed server software from any number of devices. In other words, a user CAL covers a particular user's access to the server software from work computers and laptops, as well as from home computers, handheld computers, Internet kiosks, and other devices. A device CAL covers access by multiple users to server software from a single, shared device.


Question:
I am trying to accomplish the following in MySQL (see pseudo code)

SELECT DISTINCT gid
FROM `gd`
WHERE COUNT(*) > 10
ORDER BY lastupdated DESC

Is there a way to do this without using a (SELECT...) in the WHERE clause because that would seem like a waste of resources.

Answer:
```
```
SELECT COUNT(*)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC;
```
```
EDIT (if you just want the gids):
```
```
SELECT MIN(gid)
FROM `gd`
GROUP BY gid
HAVING COUNT(gid) > 10
ORDER BY lastupdated DESC
```
```


Question:
There has been a lot of sentiment to include a nameof operator in C#. As an example of how this operator would work, nameof(Customer.Name) would return the string "Name".

I have a domain object. And I have to bind it. And I need names of properties as strings then. And I want them to be type-safe.

I remember coming across a workaround in .NET 3.5 which provided the functionality of nameof and involved lambda expressions. However, I have not been able to locate this workaround. Can anyone provide that workaround to me?

I am also interested in a way to implement the functionality of nameof in .NET 2.0 if that is possible.

Answer:
The workaround is to use an expression tree, and to take that expression tree apart to find the relevant
```
MemberInfo
```
. There's slightly more detail and comment in
this note
(although not the code to pull out the member - that's in another SO question somewhere, I believe).
Unfortunately as expression trees don't exist in .NET 2.0, there's really no equivalent.
One solution to avoid typos is to have a set of accessors which fetch the relevant
```
PropertyInfo
```
for a particular property, and unit test them. That would be the only place which had the string in it. This would avoid duplication and make refactoring easier, but it's a bit draconian.


Question: I'm wondering if there's some kind of criteria that can be used to determine where a script or file should go.

Answer:
If you don't mind the possibility that anyone might be able to see the contents then put it inside the web path. Otherwise keep it outside.
Inside:
anything publicly available - images, javascript, css, static content. You'll be putting less strain on the server and will automatically be taking advantage of whatever caching and compression services it has.
Outside:
Anything private. Script files, with password and other sensitive details, might be vulnerable if a server failure results in them being served as text instead of being parsed.


Question:
Currently, I am splitting all my tests by package (projects). So if I have 12 projects, I will create 1 more project for Unit Test with 12 classes that will test all my package.

Do you do the same way or do you have 1 testing class by class? How do you organize all your test?

Answer:
We have it organized like this (C++):
```
```
package/Class.cpp
package/Class.hpp
package/test/ClassUnitTest.cpp
package/test/ClassIntegrationTest.cpp
test/unit-test/main.cpp
test/integration-test/main.cpp
test/data
test/tmp
```
```
Where
unit-test
and
integration-test
are just the test runners,
test/data
holds data files that are used by the integration tests and
test/tmp
holds temporary files created by the same tests and is cleared for each test suite.


Question:
Am I right to think that there is no way to set the selected value in the C# class SelectList after it is created?
Isn't that a bit silly?

Answer:
You mean client-side, in the browser?
```
```
var select = document.getElementById('mySelect');
select.options[newIndex].selected = true;
```
```


Question:
I need to check whether the user executing the script has administrative privileges on the machine.

I have specified the user executing the script because the script could have been executed with a user other than the logged on using something similar to "Runas".

@Javier: Both solutions work in a PC with an English version of Windows installed but not if the installed is in different language. This is because the Administrators group doesn't exist, the name is different for instance in Spanish. I need the solution to work in all configurations.

Answer:
You can use script if you want to see if the logged on user is an administrator
```
```
Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strUser = objNetwork.UserName

isAdministrator = false

Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")
For Each objUser in objGroup.Members
    If objUser.Name = strUser Then
        isAdministrator = true
    End If
Next

If isAdministrator Then
    Wscript.Echo strUser & " is a local administrator."
Else
    Wscript.Echo strUser & " is not a local administrator."
End If
```
```
I am not sure how to handle it when the script is run with "Runas" I am afraid.


Question:
There seem to be so many color wheel, color picker, and color matcher web apps out there, where you give one color and the they'll find a couple of other colors that will create a harmonic layout when being used in combination. However most of them focus on background colors only and any text printed on each background color (if text is printed at all in the preview) is either black or white.

My problem is different. I know the background color I want to use for a text area. What I need help with is choosing a couple of colors (the more, the merrier) I can use as font colors on this background. Most important is that the color will make sure the font is readable (contrast not being too low, also maybe not being too high to avoid that eyes are stressed) and of course that the combination of foreground and background just looks good.

Anyone being aware of such an application? I'd prefer a web application to anything I have to download. Thanks.

Answer: This is an interesting question, but I don't think this is actually possible.  Whether or not two colors "fit" as background and foreground colors is dependent upon display technology and physiological characteristics of human vision, but most importantly on upon personal tastes shaped by experience.  A quick run through MySpace shows pretty clearly that not all human beings perceive colors in the same way.  I don't think this is a problem that can be solved algorithmically, although there may be a huge database somewhere of acceptable matching colors.


Question:
I have the following table in MySQL (version 5):

id     int(10)       UNSIGNED             No    auto_increment
year   varchar(4)    latin1_swedish_ci    No
title  varchar(250)  latin1_swedish_ci    Yes   NULL
body   text          latin1_swedish_ci    Yes   NULL

And I want the db to auto add the current year on insert, I've tried the following SQL statement:

ALTER TABLE `tips` CHANGE `year` `year` VARCHAR(4) NOT NULL DEFAULT year(now())

But it gives the following error:

1067 - Invalid default value for 'year'

What can I do to get this functionality? Thanks in advance!

Answer:
The following should work:
```
```
ALTER TABLE tips MODIFY COLUMN year YEAR(4) NOT NULL DEFAULT CURRENT_TIMESTAMP
```
```
Please see
Year Data Type
for further information.
So, I tested this once I got access and it doesn't work. As another poster pointed out CURRENT_TIMESTAMP only works on the
TIMESTAMP
data type.
Is there a specific problem with storing a complete time stamp and then only using the year in your code? If not, then I would recommend storing this value as a timestamp.
Your other option would be to create a
trigger
:
```
```
CREATE TRIGGER example_trigger AFTER INSERT ON tips
FOR EACH ROW BEGIN
UPDATE tips SET year = YEAR(NOW()) WHERE tip_id = NEW.tip_id
END;
```
```
Otherwise, assign this value to the INSERT statement from within your code.
The best solution in your case will depend entirely on the circumstances surrounding your particular application.


Question:
I have an abstract base class called Shape from which both Circle and Rectangle are derived, but when I execute the following code in VS 2005 I get the error Debug assertion failed. At the same time I have not overloaded == operator in any class

Expression:Vector iterator not dereferencable, what is the reason for this.

  vector<Shape*> s1;
  s1.push_back(new Circle(point(1,2),3));
  s1.push_back(new Circle(point(4,3),5));
  s1.push_back(new Rectangle(point(1,1),4,5));

  vector<Shape*> s2(s1);
  reverse(s1.begin(),s1.end());

  (*find(s1.begin(),s1.end(),new Circle(point(1,2),3)))->move(point(10,20));

Answer:
Simple :
find fails since your newly created Circle can't be found in the vector with comparing Shape *
a failed find returns the end iterator which is not deferencable as caught by a Debug assertion
For it to work like you want, you do need to compare Shape, not Shape*
As pointed out in other answers,
boost::ptr_vector
is an easy way to achieve this.


Question: I heard that Visual Studio came with an Image Library, but I can't find it anywhere. Does anyone know where it is?

Answer:
In VS 2008 they're under:
PROGRAMFILES\Microsoft Visual Studio 9.0\Common7\VS2008ImageLibrary\1033


Question:
I am looking for an alternative to my old "Font Navigator" that I... borrowed... from the CorelDraw Suite :-)

Googling for it, took me to hundreds of pages with old software, so I hope to find a quick idea from here (waiting for FontExplorer X from Linotype).

Which Font Explorer for Windows do you currently use?
My "requisites" are:

browse and preview installed/uninstalled fonts

install/uninstall fonts

free :-)

Thanks in advance

Answer:
This
thread
references the main font explorers like
Bitstream Font Navigator
,
Typograf
(both already mentioned) and
OT1 Font Manager
... but they are not free.
The only one which
might
be free would be
Font Explorer X
, which has a
beta version for PC
, but that version is quite "dangerous"
“It IS very glitchy. Not totally useless but you have to get over the fact that it totally messes up any directory of fonts. So make a seperate folder for the fonts you want to import into the program as it will delete those fonts from the original folder. Also make a backup copy of your windows fonts folder just in case it decides to remove the fonts from there too.”


Question: I am working on an ASP.NET MVC application where I need to export data to an excel spreadsheet.  Previously, in webforms apps, I used some code I found to render a GridView as an excel-compatible file.  This was quite handy. I was wondering what the quickest/most effective method would be to do this in MVC. Thanks.

Answer:
One simple option would be to create a view to render an XML-version of an Excel File. You could either use the new Office 2007 version, or the older 2003 version. We chose the 2003 version so that more people could use it, but that's up to you, of course.
XML 2003 ref on MSDN
XML 2007 ref on MSDN


Question:
I'm writing an MFC App to automatically configure Postgresql with ODBC for use by another app. The idea being that the user runs the app and it automatically creates the database and the tables within it. My problem is that when I set up the File DSN it seems to require the name of the database it will access. This appears in the DSN file as ..

DATABASE=mydb

However I haven't created mydb yet so can't connect to Postgresql ! I have tried editing the DSN file so this line reads ..

DATABASE=

and removing it totally but then I get an error and can't connect.

Is it possible for a DSN file to allow access to any database ? If so how do I do this ?

Thanks

Ian

Answer:
One simple option would be to create a view to render an XML-version of an Excel File. You could either use the new Office 2007 version, or the older 2003 version. We chose the 2003 version so that more people could use it, but that's up to you, of course.
XML 2003 ref on MSDN
XML 2007 ref on MSDN


Question:
Inspired by the question What’s the simplest way to call Http GET url using Delphi?
I really would like to see a sample of how to use POST. Preferably to receive XML from the call.

Added: What about including an image or other file in the post data?

Answer:
Using Indy.  Put your parameters in a StringList (name=value) and simply call Post with the URL and StringList.
```
```
function PostExample: string;
var
  lHTTP: TIdHTTP;
  lParamList: TStringList;
begin
  lParamList := TStringList.Create;
  lParamList.Add('id=1');

  lHTTP := TIdHTTP.Create;
  try
    Result := lHTTP.Post('http://blahblahblah...', lParamList);
  finally
    lHTTP.Free;
    lParamList.Free;
  end;
end;
```
```


Question:
I try to write to a large file, but it seems like it does not work for files larger than 2GB.
I have tried with boost::iostreams::file_sink. Is this just a limit with the boost stream? Is there some other way I can write a large file on Win64 and win32?

Answer:
This depends on:
The file system which you're using. Old file systems like FAT allow only files up to 2GB. Use NTFS.
Your library must be compiled to allow large files (64bit seek offsets). If they use 32bit ints to seek in file (check the arguments and results of the calls "seek" and "tell"), you can only ever access 2GB (2^31bits, the 32th is the sign +/-)
This might also help:
http://www.boost.org/doc/libs/1_37_0/libs/iostreams/doc/faq.html#offsets