q:
I am using 0.97-pre-SVN-unknown release of Django.

I have a model for which I have not given any primary_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy.

[A]
Look into the command-line options for
```
manage.py
```
; there's a command to dump all of the model data to JSON, and another command to load it back in from JSON. You can export all of your model data, add your new field to the model, then import your data back in. Just make sure that you set the
```
db_column
```
option to
```
'id'
```
so you don't break your existing data.
Edit
: Specifically, you want the commands
```
dumpdata
```
and
```
loaddata
```
.


q:
With SQLAlchemy, is there a way to know beforehand whether a relation would be lazy-loaded?

For example, given a lazy parent->children relation and an instance X of "parent", I'd like to know if "X.children" is already loaded, without triggering the query.

[A]
I think you could look at the child's
```
__dict__
```
attribute dictionary to check if the data is already there or not.

s: huggingface

c: devops

d: intermediate


q:
I need to be able to compare some month names I have in an array.

It would be nice if there were some direct way like:

Month.toInt("January") > Month.toInt("May")

My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?

[A] If you are using c# 3.0 (or above) you can use extenders


q:
I've got 2 remote databases as part of a query

select p.ID,p.ProjectCode_VC,p.Name_VC,v.*
FROM [serverB].Projects.dbo.Projects_T p
LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on
p.ProjectCode_VC = v.PROJ_CODE

The problem is that serverA uses collation Latin1_General_BIN and serverB uses Latin1_General_CP1_CP_AS and the query refuses to run.

Both servers are SQL 2000 servers.  Both databases are set in stone so I cannot change their collations, unfortunately.

Is there anyway you guys know how to get this to work?

Update:  I found an alternative solution.  In the Linked Server Properties, you can specify the linked server's collation there.

[A]
Just add the collation to your select, like:
```
```
select
  p.ID,
  p.ProjectCode_VC,
  p.Name_VC,
  v.*
FROM
  [serverB].Projects.dbo.Projects_T p
  LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on p.ProjectCode_VC
    collate Latin1_General_Bin = v.PROJ_CODE
```
```
or the other way around. So "convert" one of the collations to the other.


q:
I've created a Silverlight project that produces [something].xap file to package a few silverlight UserControls.  I would like to manipulate that .xap file through the use of javascript in the browser to show and hide user controls based upon java script events.

Is it possible to do this?

If so any sample could or links to documentation would be appreciated.

Thanks in advance

Kevin

[A]
Here is a my collections of my links for this subject.
Javascript communication to
Silverlight 2.0
Silverlight
interoperability
Silverlight
and JavaScript Interop Basics


q:
So here I am just about to start a big project using LINQ to SQL and then I read this:

Is LINQ to SQL Truly Dead? by Jonathan Allen for InfoQ.com

Well, I don't want to be supporting LINQ to SQL indefinitely if it's a dead end.  So, how should I get started learning about ADO.NET Entity Framework?

[A]
How Do I...? Videos
How Do I Get Started with the Entity Framework?
How Do I Use the new Entity Data Source?
How Do I Serialize a Graph with the Entity Framework?
How do I use Entity Client?
ADO.NET Entity Designer Video - CTP 2
Webcasts
MSDN Webcast: Framework Masterclass: LINQ to Entities (Level 200)


q:
In C#, how do I set the Identity of a Thread?

For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?

Or is this not possible?

[A]
Yes, using
impersonation
literally
```
```
using (new Impersonation())
{
    // your elevated code
}
```
```
and the class is as follows, for settings I use castle dictionary adaptor if it looks strange.
```
```
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public class Impersonation : IDisposable
{
    private readonly SafeTokenHandle _handle;
    private readonly WindowsImpersonationContext _context;

    //const int Logon32LogonNewCredentials = 9;
    private const int Logon32LogonInteractive = 2;

    public Impersonation()
    {
        var settings = Settings.Instance.Whatever;
        var domain = settings.Domain;
        var username = settings.User;
        var password = settings.Password;
        var ok = LogonUser(username, domain, password, Logon32LogonInteractive, 0, out _handle);
        if (!ok)
        {
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode));
        }
        _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());
    }

    public void Dispose()
    {
        _context.Dispose();
        _handle.Dispose();
    }

    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
    {
        private SafeTokenHandle()
            : base(true)
        { }

        [DllImport("kernel32.dll")]
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [SuppressUnmanagedCodeSecurity]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
        {
            return CloseHandle(handle);
        }
    }
}
```
```


q:
I'm dynamically generating an asp form, and I would like to add the label and input elements inside a list.

For example, I would like to end up with something like:

<ul>
<li><label for="input"/><input id=input"/></li>
</ul>

To do this, I create a Label object and a TextBox object, then assign the AssociatedControlId property of the Label to link these. But I cannot add any of these in a ListItem, nor can I add these in the Controls collection of BulletedList...

Any ideas would be greatly apreciated.

[A]
You could probably do something like this using a Repeater.
```
```
<asp:Repeater ID="rpt" runat="server">
    <HeaderTemplate>

    </HeaderTemplate>
    <ItemTemplate>

            <label for='<%# string.Format("ctrl-{0}", Container.ItemIndex) %>'>label for ctrl #<%# Container.ItemIndex %>
            <input id='<%# string.Format("ctrl-{0}", Container.ItemIndex) %>' type="text" />

    </ItemTemplate>
    <FooterTemplate>

    </FooterTemplate>
</asp:Repeater>
```
```
If you need to add server controls to the list, you'll need to do something with the Repeater's ItemDataBound event.


q:
I have a problem applying the DebuggerDisplay attribute on a generic class:

[DebuggerDisplay("--foo--")]
class Foo
{
}

[DebuggerDisplay("Bar: {t}")]
class Bar<T>
{
    public T t;
}

When inspecting an object of type Bar<Foo> I would expect it to show as Bar: --foo--, but I get Bar: {Foo}

What am I doing wrong?

[A]
The DebuggerDisplay attribute is not recursive.  The {} inside the string essentially say evaluate this expression and display the result inline.  The string for the inner result is calculated as if there was no DebuggerDisplay attribute in play for type or member.  That is why you see {Foo} instead of --foo--.
The reason for this is reliability.  It is far too easy to have mutually recursive DebuggerDisplay attribute tags.  This would cause a stack overflow or infinite loop to occur when evaluating an inner expression.  Not recursively evaluating the DebuggerDisplay attribute prevents this infinite recursion (although it's still quite possible for the user to create it themselves inside a particular expression).
One way you can control the way the inner expression is displayed is by overriding the .ToString() method.  This will be evaluated when computing the display string for an inner expression.


q:
Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, where the methods taught, would have far better solutions now.

What are some boilerplate code situations, especially ones that you see people implement through force of habit, that you find yourself refactoring to utilize the latest versions of Java?

[A]
Generics and no longer needing to create an iterator to go through all elements in a collection. The new version is much better, easier to use, and easier to understand.
EDIT:
Before:
```
```
List l = someList;
Iterator i = l.getIterator();
while (i.hasNext()) {
    MyObject o = (MyObject)i.next();
}
```
```
After
```
```
List<MyObject> l = someList;
for (MyObject o : l) {
    //do something
}
```
```


q: Is there a way for me to serialize an object in .NET without the XML Namespaces automatically serializing also?  It seems that by default .NET believes the XSI and XSD namespaces should be included, but I don't want them there.

[A]
Ahh... nevermind.  It's always the search after the question is posed that yields the answer.  My object that is being serialized is
```
obj
```
and has already been defined.  Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.
In VB like this:
```
```
Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")

Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True

Using ms As New MemoryStream(), _
    sw As XmlWriter = XmlWriter.Create(ms, settings), _
    sr As New StreamReader(ms)
    xs.Serialize(sw, obj, ns)
    ms.Position = 0
    Console.WriteLine(sr.ReadToEnd())
End Using
```
```
in C# like this:
```
```
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
```
```


q:
What is the optimal number of connections that can be open on a SQL Server 2000 DB. I know in the previous company I was working for, on a tru 64 box with Oracle 8i, 8 processor machine we'd figured out that 8*12= 96 connections seemed to be a good number. Is there any such calc for SQL Server 2000. The DB runs on a 2-processor(hyper threaded 4) machine. There are a lot of transactions that run against the DB. The reason I ask is because we have an app that typically tends to leave around 100 connections open even if it is not doing anything and I am having difficulty explaining that that might be a cause for our performance issues. Maybe, SQL Server does not have such a limitation... Can any of you pour forth some wisdom on this? Much appreciate it. Thanks,

I should add it is the Standard Edition.

[A]
This blog post on MSDN indicates there is no limit - at least in the Express editions:
http://blogs.msdn.com/euanga/archive/2006/03/09/545576.aspx
And this indicates that it might be 256, for lite editions -
http://blogs.msdn.com/stevelasker/archive/2006/04/10/SqlEverywhereInfo.aspx
This also shows no limit:
http://channel9.msdn.com/forums/TechOff/169030-The-difference-between-SQL-Server-2005-Express-and-Developer-Edition/?CommentID=299642
addition
- from a comment,
http://msdn.microsoft.com/en-us/library/aa196730(SQL.80).aspx
indicates the max is 32767, while there is no "ideal"


q:
I want to create a license key, which cryptography algorithm would you recommend?

Basically the inputs would be:

company name

  major version number

  date created

  expirey date

  has feature1:

  has feature2:

  has feature3:

e.g.  Acme Inc 5.0 20081102 20081102 0 1 0

Related: Which built-in .NET cryptography algorithm is the most secure?

[A]
If you are doing validation on the customer-side, you want to use asymmetric encryption. That way you do not have to distribute the private key to the customer. I would generate a RSA signature using SHA-256 and a 2048 bit key. If you do that, the cryptographic operations will not be the weak link. A cracker could of course change the code to skip the verification step, but no cryptographic algorithm will help that.
If you are doing validation server-side, I would choose a SHA-256 based HMAC.


q:
I have a system which is using phone numbers as unique identifiers. For this reason, I want to format all phone numbers as they come in using a normalized format. Because I have no control over my source data, I need to parse out these numbers myself and format them before adding them to my DB.

I'm about to write a parser that can read phone numbers in and output a normalized phone format, but before I do I was wondering if anyone knew of any pre-existing libraries I could use to format phone numbers.

If there are no pre-existing libraries out there, what things should I be keeping in mind when creating this feature that may not be obvious?

Although my system is only dealing with US numbers right now, I plan to try to include support for international numbers just in case since there is a chance it will be needed.

Edit I forgot to mention I'm using C#.NET 2.0.

[A]
Just strip out any non-digits, possibly using a RegEx:
```
[^\d]
```
The only exception might be if you want to handle extensions, to distinguish a number without an area code but with a 3 digit extension, or if you need to handle international numbers.


q:
This is what I have written:

if ((lstProperty[i].PropertyIdentifier as string).CompareTo("Name") == 0)

Resharper put me an error (I am new with ReSharper... I am trying it) and it suggests me :

  if (((string) lstProperty[i].PropertyIdentifier).CompareTo("Name") == 0)

Why is the second is NullException safe? For me both will crash if null value appear?

[A]
The 'as' operator will return null if the cast cannot be executed, while a C-style cast will throw an exception if it can't cast.
I suggest breaking this out into multiple statements:
```
```
string propertyIdentifier = lstProperty[u].PropertyIdentifier as string;
if(propertyIdentifier != null && propertyIdentifier.CompareTo("Name") == 0)
{
    ... your if statement ...
}
```
```
Resharper shouldn't complain about this, and you also won't get a NullReferenceException if the PropertyIdentifier is null or not a string.


q:
Consider that I have a transaction:

BEGIN TRANSACTION
DECLARE MONEY @amount
SELECT Amount AS @amount
  FROM Deposits
  WHERE UserId = 123
UPDATE Deposits
  SET Amount = @amount + 100.0
  WHERE UserId = 123
COMMIT

And it gets executed on 2 threads, in the order:

thread 1 - select

thread 2 - select

thread 1 - update

thread 2 - update

Assume that before execution Amount is 0.

What will happen in this case in the different settings of SQL Server (read uncommited, read commited, repeatable read, serializable), what will be amount at the end, will there be a deadlock?

[A]
I believe that you would want to use Repeatable read, which would lock the records, the first select would get the value, then it would update blocking thread two until it was completed.  Thus an end result of 200 in your example
Read uncommitted would result in both records setting the value to 100.
Read committed might have a bit of an intersting result, depending on timing of the two threads....
Here is a nice article I found about
Repeatable Read
as well, that provides a good example


q:
Iv been encountering problems with disk space when deploying my app to a pocket pc emulator.

So what Iv done is set up a shared directory on my pc to simulate a SD card, Iv copied the program there manually and then run it from the emulator, with this approach I still need to do the visual studio deployment as well so that so that the .net compact framework gets copied over.

How do I make visual studio deploy to the shared dir? The 'Output file folder' is grayed out and I can only choose from a list of pre-defined locations.

Sorry maybe I want not clear, when I said "I can only choose from a list of pre-defined locations", I was referring to the the options in the [..] menu. I need some sort of free text entry. I want something like d:\MyShare.

The best I was thinking is to manually edit the solution xml, but that seems a poor approach?

[A]
The "Output File Folder" under Properties->Devices is greyed out, but the [...] button just to the right of it isn't.  Adjust it there.
NOTE: To clarify, You click on the [...] button and you get a dialog that allows you to select a folder from the device ("Location of output on device") and enter an additional subfolder ("Subdirectory").  Now it may seem that you're forced to use a specific folder here, but one of the dropdown options is "Root Folder" which is "\".  You can then add your folder, like "Storage Card" as the Subdirectory and get a deployment folder of "\Storage Card".  Intuitive?  No.  But you can construct any output folder you want.


q: I am trying to debug a web application through IIS that has a virtual directory other than localhost.  It compiles fine but gets the above message anytime that I try to start debugging.  I have compilation debug="true".

[A]
Right click your 'web' project and select 'property pages'.  Then change 'Start Options' to 'Don't open a page. Wait for a request from an external application.' and for server, select 'Use custom server' with Base URL: '
http://localhost/your_virtual_dir/
'
Then with a web browser opened pointing to the IIS location (and virtual dir) you setup, the two should work in tandem with each other.
Hope that helped.


q: Is there any reason why I should pick JSON over XML, or vice-versa if both are available? Tips for optimizing performance when dealing with data feeds are also appreciated!

[A] When it comes to PHP the one reason I choose XML over JSON is because even in PHP 5 there is no officially supported API for traversal. You can encode, and you can decode, and that is it. There is no validation, no efficient way to traverse key/value pairs, and all-in-all, very little support for it. Don't get me wrong, you can just use a foreach looping structure, but it really is cumbersome. JSON was touted as a great data-interchange format because JavaScript has an easy time understanding the lexical structure. So when you go from PHP to JavaScript, it is great, but when you go from JavaScript to PHP, or PHP to PHP, then JSON is not the best choice for data interchange.


q:
I guess this is a multi-part question.

I can import a 3D model into my WPF application but how do I apply an ambient occlusion shader effect to it?
I know with .NET 3.5 SP1 you can do custom effects but that's limited to pixel shaders and doesn't include vertex shaders.

I think i can do this with an XNA application but Im not familiar with XNA so the second question is:
How much different is WPF and XNA? I don't seem to have any notion of XAML in XNA. How much ramp up would moving from WPF to XNA take?

Thanks,
Chris

[A]
To answer your second question:
WPF and XNA are completely different.  They do share the following:
Built upon .net
Use DirectX
Can access hardware acceleration of the video card
XNA does not have any GUI support built in and is really aimed at games (for PC and XBOX-360) whilst WPF is usable in business style applications.  As you've discovered XNA does not have any XAML support, indeed it is mainly an abstract .net wrapper for DirectX.


q:
Is there any way to change the entire width of the horizontal scroll bar on a scrolling div (including the nudge arrows and the handle).

EDIT: I only need an IE7 solution - it's for a scrolling DIV on a touch screen terminal

Thanks

Matt

[A]
Actually, I revise my statement...
in IE7
, you
CAN
do some scaling.
```
```
<div style="zoom:5;font-size:20%;overflow-x:auto;">
  Hello World!       Hello World!       Hello World!       Hello World!       Hello World!       Hello World!       Hello World!
</div>
```
```
zoom tells IE to scale up the contents by 500%, and I've set the font-size to be 1/5 of normal (thus remain the same)... this scales the scrollbars (but it looks a bit ugly at this zoom, since the images are raster based, not vector based.


q:
Use case:

A does something on his box and gots stuck. He asks B (remote) for support.

B logs into the session of A, sees all windows, A was seeing and is able to manipulate the GUI.

If A uses Windows it is very convenient to log into a running session e.g. via VNC. But if A uses Linux, AFAIK, this is not possible. Using VNC requires a "vncserver"-session, which is a separate session. You could get screen captures from remote by querying the X-server, but you cannot press buttons on the screen.

Is there some workaround for this?


q:
How do I search the whole classpath for an annotated class?

I'm doing a library and I want to allow the users to annotate their classes, so when the Web application starts I need to scan the whole classpath for certain annotation.

I'm thinking about something like the new functionality for Java EE 5 Web Services or EJB's. You annotate your class with @WebService or @EJB and the system finds these classes while loading so they are accessible remotely.

[A]
The Classloader API doesn't have an "enumerate" method, because class loading is an "on-demand" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).
So, even if you
could
enumerate all classes, this would be very time- and memory-consuming.
The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory.


q: I have seen bind and eval used interchangeably especially in ASP.NET GridViews. What is the difference?

[A]
Eval is one-way, read only databinding.
Bind is two-way, read/write databinding.
See
here
and
here
.


q:
I'm currently using a UIImageView with an array of images to create a small looping animation sequence with about 20 images in there (at 320x480). Whilst this works okay for 20 - 30 images, any more and the app quits on the iphone. There is nothing else in my test app at the moment so I know it's just down to the animationImages sequence.

Has anyone come across any samples of doing this type of thing through Core Animation to achieve better performance and allow many more images? From what I've read it sounds like its possible to set up a ton of CALayers and put an image in each, and then create the animation by manipulating the layers on and off in sequence. Is this a good way to do it?

Or, alternatively, as I'm basically after the effect of a looping movie, is there a way to use the moviecontroller to achieve the effect without it fading in and out at the start and at the end?

I'd be grateful for any pointers. Many thanks.

[A] This could be a simple memory issue. 20 images (320x480) is about 3 MB of memory, assuming 8bpp (if they're higher color, obviously even more). You might try loading and unloading as needed (though, of course, that'll mean rolling your own animation, rather than using UIImageView).


q:
I am trying to find an algorithm to count from 0 to 2n-1 but their bit pattern reversed. I care about only n LSB of a word. As you may have guessed I failed.

For n=3:

000 -> 0
100 -> 4
010 -> 2
110 -> 6
001 -> 1
101 -> 5
011 -> 3
111 -> 7

You get the idea.

Answers in pseudo-code is great. Code fragments in any language are welcome, answers without bit operations are preferred.

Please don't just post a fragment without even a short explanation or a pointer to a source.

Edit: I forgot to add, I already have a naive implementation which just bit-reverses a count variable. In a sense, this method is not really counting.

[A]
This solution was originally in binary and converted to conventional math as the requester specified.
It would make more sense as binary, at least the multiply by 2 and divide by 2 should be << 1 and >> 1 for speed, the additions and subtractions probably don't matter one way or the other.
If you pass in mask instead of nBits, and use bitshifting instead of multiplying or dividing, and change the tail recursion to a loop, this will probably be the most performant solution you'll find since every other call it will be nothing but a single add, it would only be as slow as Alnitak's solution once every  4, maybe even 8 calls.
```
```
int incrementBizarre(int initial, int nBits)
    // in the 3 bit example, this should create 100
    mask=2^(nBits-1)
    // This should only return true if the first (least significant) bit is not set
    // if initial is 011 and mask is 100
    //                3               4, bit is not set
    if(initial < mask)
        // If it was not, just set it and bail.
        return initial+ mask // 011 (3) + 100 (4) = 111 (7)
    else
        // it was set, are we at the most significant bit yet?
        // mask 100 (4) / 2 = 010 (2), 001/2 = 0 indicating overflow
        if(mask / 2) > 0
            // No, we were't, so unset it (initial-mask) and increment the next bit
            return incrementBizarre(initial - mask, mask/2)
        else
            // Whoops we were at the most significant bit.  Error condition
            throw new OverflowedMyBitsException()
```
```
Wow, that turned out kinda cool.  I didn't figure in the recursion until the last second there.
It feels wrong--like there are some operations that should not work, but they do because of the nature of what you are doing (like it feels like you should get into trouble when you are operating on a bit and some bits to the left are non-zero, but it turns out you can't ever be operating on a bit unless all the bits to the left are zero--which is a very strange condition, but true.
Example of flow to get from 110 to 001 (backwards 3 to backwards 4):
```
```
mask 100 (4), initial 110 (6); initial < mask=false; initial-mask = 010 (2), now try on the next bit
mask 010 (2), initial 010 (2); initial < mask=false; initial-mask = 000 (0), now inc the next bit
mask 001 (1), initial 000 (0); initial < mask=true;  initial + mask = 001--correct answer
```
```


q: How do I run a function on a loop so all the results go straight into a list and is there a way to run a function which acts on all the values in a list?


q:
I'm just getting back into C++ after a couple of years of doing a lot of C#, and recently Objective C.

One thing I've done before is to roll my own iterator adapter for std::map that will deref to just the value part, rather than the key-value pair. This is quite a common and natural thing to do. C# provides this facility with its Keys and Values properties of its Dictionary class. Objective-C's NSDictionary, similarly, has allKeys and allValues.

Since I've been "away", Boost has acquired the Range and ForEach libraries, which I am now using extensively. I wondered if between the two there was some facility to do the same, but I haven't been able to find anything.

I'm thinking of knocking something up using Boost's iterator adapters, but before I go down that route I thought I'd ask here if anyone knows of such a facility in Boost, or somewhere else ready made?

[A]
I don't think there's anything out of the box.  You can use boost::make_transform.
```
```
template<typename T1, typename T2> T2& take_second(const std::pair<T1, T2> &a_pair)
{
  return a_pair.second;
}

void run_map_value()
{
  map<int,string> a_map;
  a_map[0] = "zero";
  a_map[1] = "one";
  a_map[2] = "two";
  copy( boost::make_transform_iterator(a_map.begin(), take_second<int, string>),
    boost::make_transform_iterator(a_map.end(), take_second<int, string>),
    ostream_iterator<string>(cout, "\n")
    );
}
```
```


q:
I would like to include a different file depending on the version of GCC. More precisely I want to write:

#if GCC_VERSION >= 4.2
#  include <unordered_map>
#  define EXT std
#elif GCC_VERSION >= 4
#  include <tr1/unordered_map>
#  define EXT std
#else
#  include <ext/hash_map>
#  define unordered_map __gnu_cxx::hash_map
#  define EXT __gnu_cxx
#endif

I don't care about gcc before 3.2.

I am pretty sure there is a variable defined at preprocessing time for that, I just can't find it again.

[A]
There are a number of macros that should be defined for your needs:
```
```
__GNUC__              // major
__GNUC_MINOR__        // minor
__GNUC_PATCHLEVEL__   // patch
```
```
The version format is major.minor.patch, e.g. 4.0.2
The documentation for these can be found
here
.


q:
What are the API calls to copy a file that is currently locked.  I'm hoping to be able to use .Net, but Win32 calls would be fine as well.

Please feel free to chime in about the same functionality on Unix, or any other OS.

[A]
Almost the same as my answer to
another question
:
If you are on Win32, the official way to do it is to mark it to be moved on reboot, and ask the user to reboot. To mark the file to be moved on reboot, use
```
MoveFileEx
```
with the
```
MOVEFILE_DELAY_UNTIL_REBOOT
```
flag.
It's the same function, only this time you don't pass NULL as the destination.


q:
I have a loop that reads each line in a file using getline():

istream is;
string line;
while (!getline(is, line).eof())
{
    // ...
}

I noticed that calling getline() like this also seems to work:

while (getline(is, line))

What's going on here? getline() returns a stream reference. Is it being converted to a pointer somehow? Is this actually a good practice or should I stick to the first form?

[A]
Updated:
I had mistakenly pointed to the
basic_istream documentation
for the operator bool() method on the basic_istream::sentry class, but as has been pointed out this is not actually what's happening.  I've voted up Charles and Luc's correct answers.  It's actually operator void*() that's getting called.  More on this
in the C++ FAQ
.


q:
http://biochrom.fivesite.co.uk/catalogue4.asp

On the page above there is an image floated to the left. To the right of it is a list, titled "features". The list items have a background image, however, it isn't appearing. List 2 shows how the background image looks.

Does anyone know how I can make the bullets visible?

[A]
Your image has a float:left property. The list items are therefore rendered "behind" the image.
```
```
margin-left:200px;
```
```
on the UL element will solve your problem.
Alternatively, you can apply a float:left on your UL-element. This will make it float right to the image, but will make the following content appear on the same line. You can prevent this by
clearing the UL-element
, or adding element after the UL-element with...
```
```
clear:both
```
```
...applied to it.
More information about this behaviour can be found at
http://www.positioniseverything.net/easyclearing.html
.


q: WPF's view model oriented way of doing things makes it very tempting to just use business objects in the UI. Have you seen any issues with this? Why or why wouldn't you do this?

[A]
Not being a WPF guru, I can't be sure, but the usual reason for separating your M, V and C is so you can test the controller independent of the view, and the other way around.
Nothing stopping you, of course, but it should be a lot more testable (ie, unit tests) if it's separate. The MVP pattern, which is usually the one that MS promotes, is more geared around the presenter (ie, your WPF form) having more control, and thats fine too....


q:
I am working in Visual Studio 2008 on an ASP.NET application, which has been deployed to a test server.  I would like to make a build without debug information to place in production, but the configuration manager only shows "Debug" in the configuration dropdown for my project.

My other Visual Studio projects show "Debug", "Release", "New...", and "Edit...".

Why do I not see a release option, or the new and edit commands?

[A]
The Configuration Manager for the Solution allows you to delete either (or both) of these default build configurations (through the Edit... option you mention above). I would bet that someone deleted the Release configuration.
You can get it back by recreating it, or copy the appropriate lines from a solution you make from scratch real quick. A file diff shows the following:
Default solution file:
```
```
GlobalSection(SolutionConfigurationPlatforms) = preSolution
    Debug|Any CPU = Debug|Any CPU
    Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.ActiveCfg = Release|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
```
```
Solution after I manually deleted the Release configuration:
```
```
GlobalSection(SolutionConfigurationPlatforms) = preSolution
    Debug|Any CPU = Debug|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
```
```


q:
Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code:

session = smtplib.SMTP("smtp-auth.ourhosting.com", 587)
session.login(smtpuser, smtppass)

and it's giving me this error:

exceptions.AttributeError :  SMTP instance has no attribute 'login' :  <traceback object at 006BB1D0>

I'm assuming this is because the login() method was added after python 2.1. so how do I fix this?

I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server)

OR

Do it whatever way is expected by the libsmtp in python 2.1.


q:
I'm still learning Grails and seem to have hit a stumbling block.

Here are the 2 domain classes:

class Photo {
    byte[] file

    static belongsTo = Profile
}

class Profile {
    String fullName
    Set photos

    static hasMany = [photos:Photo]
}

The relevant controller snippet:

class PhotoController {

    def viewImage = {

      def photo = Photo.get( params.id )
      byte[] image = photo.file
      response.outputStream << image

    }
}

Finally the GSP snippet:

<img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" />

Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that
profileInstance.photos.get(1).id is not correct.

[A]
As it is a Set, if you want the first element, you will have to go:
```
```
profileInstance.photos.toArray()[0].id
```
```
or
```
```
profileInstance.photos.iterator().next()
```
```


q:
Say I'm mapping a simple object to a table that contains duplicate records and I want to allow duplicates in my code.  I don't need to update/insert/delete on this table, only display the records.

Is there a way that I can put a fake (generated) ID column in my mapping file to trick NHibernate into thinking the rows are unique?  Creating a composite key won't work because there could be duplicates across all of the columns.

If this isn't possible, what is the best way to get around this issue?

Thanks!

Edit:  Query seemed to be the way to go

[A]
The NHibernate mapping makes the assumption that you're going to want to save changes, hence the requirement for an ID of some kind.
If you're allowed to modify the table, you could add an identity column (SQL Server naming - your database may differ) to autogenerate unique Ids - existing code should be unaffected.
If you're allowed to add to the database, but not to the table, you could try defining a view that includes a RowNumber synthetic (calculated) column, and using that as the data source to load from. Depending on your database vendor (and the products handling of views and indexes) this
may
face some performance issues.
The other alternative, which I've not tried, would be to map your class to a SQL query instead of a table. IIRC, NHibernate supports having named SQL queries in the mapping file, and you can use those as the "data source" instead of a table or view.


q:
I've been adding css support for handheld to my website but haven't been able to find a good tool for testing.

I tried using the webdeveloper plugin for Firefox but it doesn't work for me. Maybe that is because all my css is in the html and not a seperate css file.

Are there any other testing tools available aside from going out and buying a handheld device?

[A]
If you have Visual Studio, there should be device emulators which let you test mobile IE, or they can be found standalone on Microsoft's site.
Here are some for WM 5
.  There is an
OpenWave simulator
available to test that browser.
Blackberry simulators
are available as well, to test the Blackberry browser.  You can (kind of) test iPhone support with Safari, although you can't verify the viewport meta-tag.  There's an
Opera Mini simulator
here.
Also, get your CSS out of your HTML :)


q: Is there any way to reboot the JVM?  As in don't actually exit, but close and reload all classes, and run main from the top?

[A]
AFAIK there is no such way.
Notice that if there were a way to do that, it would highly depend on the current loaded code to properly release all held resources in order to provide a graceful restart (think about files, socket/tcp/http/database connections, threads, etc).
Some applications, like Jboss AS, capture Ctrl+C on the console and provide a graceful shutdown, closing all resources, but this is application-specific code and not a JVM feature.


q:
Is there a substitute in emacs for the vi "gf" command?
meaning try to open the file which is under the cursor right now
if a real file name is in fact there.

Thanks

[A]
You want the
```
find-file-at-point
```
function (which is also aliased to
```
ffap
```
).  It's not bound to a key by default, but you can use
```
```
M-x ffap
```
```
Or, you can put in your
```
.emacs
```
file:
```
```
(ffap-bindings)
```
```
This will replace many of the normal
```
find-file
```
key bindings (like
```
C-x C-f
```
) with
```
ffap
```
-based versions.  See the commentary in
```
ffap.el
```
for details.


q:
How can I change the background color of a Tab Control.  I changed the forms color, but the tabs stay the same.

Thanks.

[A]
Check the Back Style of the Tab Control. If it's Normal. you'll get a gray background (with normal Windows settings). If it's Transparent then it will inherit the background colour of the form.
If you want it to be an entirely different colour, you might have to add a rectangle to the form (make the background non-transparent), maximise it within the tab and then set the colour of the rectangle.
As for the tabs them selves, I don't see a way of setting their colour independently.


q:
On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using gethostbyname or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.

Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of gethostbyinterface("eth0")?

[A]
edit:
I saw you don't like shelling. Then you can look at how ifconfig does its job (it extracts at least some information from /proc).
When you have interface name, you can do this (in your shell):
```
```
ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
```
```
To enumerate interfaces you can use this:
```
```
ifconfig | egrep '^[^ ]' | awk '{print $1}'
```
```
Combined:
```
```
for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
  echo -n "${x}"
  echo -n "    "
  ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
done
```
```


q:
Sometimes while developing in Visual Studio IDE, when you use "Find in Files"  dialog to find something, the search fails and you will see the following message in the "Find Results" window.

No files were found to look in. Find stopped progress

Once this message shows up, all the subsequent searches will result in the same message. Nothing fixes the problem including restarting the computer except pressing Ctrl + ScrLk.

What causes Visual Studio to get into this state and is there a setting to permanently prevent it from happening?

[A]
I don't think there is anything you can do to prevent it.
It seems to occur after I have stopped a build with CTRL+Break...Maybe I am pressing CTRL+Scroll Lock during that time???
I have only had it happen to me 2-3 times, and that was several months apart.
What he is saying is that occasionally when performing a search within Visual Studio you get the mentioned error message. Even though you know there is stuff to find. It is some weird state that Visual Studio gets into. If you press the (CTRL+Scroll Lock) it will 'fix' the issue.


q:
When I changed the rankdir of my graph from LR to TD, my record nodes also changed their layout direction so they no longer look like a 'record'. I tried applying a separate rankdir to the nodes, but this had no effect.

How does one keep the record nodes with the correct layout?

digraph sample {
  graph [rankdir=TD];
  node [shape=record];

  A [label="ShouldBeTop | ShouldBeBottom"];
  B [label="Top | Bottom"];
  A -> B;
}

[A]
Taking into account that rankdir effectively replaces the notion of "top" and "bottom" for the given graph, that's not surprising.
I am afraid that there is no easy remedy for this, save hacking the source (and that would not be easy at all). You can surround your labels in "{}" with some kind of mass search-replace solution to get the requested effect:
```
```
digraph sample { graph [rankdir=TD]; node [shape=record];

A [label="{ShouldBeTop | ShouldBeBottom}"];
B [label="{Top | Bottom}"]; A -> B;
}
```
```


q:
I have a source XML file that is used to create C# files that are then compiled as part of a project.

Currently I have a BeforeBuild target that runs my XML to C# converter.

The problem is that by the time the BeforeBuild step is run the old files appear to have been stored by the build system so the new files are ignored.

How can I get around this? It seems that Transforms would be the way but they are limited in what they can do.

[A]
Well we have something similar-ish here. We gen a .cs off an xml file using a .tt. Both files are part of a specific csproj. Going properties->BuildEvents on the csproj gives this little snippet in the Pre-build event command line:
```
```
del "$(ProjectDir)MyCsFile.cs"
copy /b /y "$(ProjectDir)\MyXmlFile.xml" "$(TargetDir)"
"$(ProjectDir)tt.bat" "$(ProjectDir)MyTemplateFile.tt"
```
```
No idea if that's of any use to you, I hope it might suffice as a last chance workaround.


q: I need some basic CMS functionality with rich text editing. On stack overflow there is a regular textarea edit control, with support for Markdown style syntax formatting. That would be beyond my users, so I want something like a rich edit control that you can type into on the web site. I know it is possible, as loads of sites do it, but I don't know where to start.

[A]
TinyMCE
is probably one of the more popular versions of this sort of thing. You can customize it to fit your needs, in terms of what functionality you want to offer your viewers. a few alternatives (tend to be lighter weight than a full TinyMCE install):
FCKeditor
Xinha


q:
If I've got an array of values that are basically zerofilled string representations of various numbers and another array of integers, will array_intersect() still match elements of different types?

For example, would this work:

$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);

$intersect = array_intersect($arrayOne, $arrayTwo);

// $intersect would then be = "array(4, 5)"

And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run array_intersect() after?

[A]
$ cat > test.php
```
```
<?php
$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);

$intersect = array_intersect($arrayOne, $arrayTwo);

print_r($intersect );

?>
```
```
$ php test.php
Array
(
)
$
So no, it will not.   But if you add
```
```
foreach($arrayOne as $key => $value)
{
   $arrayOne[$key] = intval($value);
}
```
```
you will get
$ php test.php
Array
(
    [1] => 4
    [2] => 5
)


q: Is there an event that fires when a WCF service gets started or shut down?  Hopefully, independent of whether it is self hosted or hosted in IIS?

[A]
Sure, the constructor of your object (especially if you are using a Singleton style). Please pardon the shameless self promotion, but I've written two articles on how to get started with a WCF (Net.Tcp) client/server system... The first is non-IIS (to which the service starts on your own terms), the latter is how to modify the first to be hosted in IIS to which my first sentense would apply:
1)
Client Server Programming with WCF
2)
Duplex WCF Services Hosted in IIS Using Net.Tcp


q:
SQL Server 2005.

I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them.  Naturally, the data has become unreliable and there are orphaned entries in the foreign key field.

Setup:

Two tables, TableUser and TableOrder.
TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'.

How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID?

For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.

[A]
Here's one way:
```
```
select * from TableOrder where UserID not in (select UserID from TableUser);
```
```
There are many different ways to write this sort of query.


q: Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.

[A]
Try using this instead.
```
```
System.Reflection.MethodBase.GetCurrentMethod().Name
```
```
C# doesn't have
```
__LINE__
```
or
```
__FUNCTION__
```
macros like C++ but there are equivalents


q:
It seems that the following piece of HTML is ignored in IE7 but works ok in IE6/FF. It supposes to override all the html links to be opened in the desired frame

<HEAD>
 <title>LeftPane</title>
 <base target="rightFrame">
</HEAD>

The above code is the header of a left frame that holds an Infragistics UltraWebTree (tree menu) which doesn't support the TargetFrame property.

Is there another way to add the target attribute to all the links elements on the desired page.

Any server or client-side code workarounds?

The site is built on ASP.Net 1.1 and Infragistics V 2.0

Update
the web page is aspx an the doctype is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

[A]
The
```
href=""
```
attibute is
mandatory on the base tag
- that's one possible explanation.  You don't say what doctype you're using, but
target is not allowed in strict XHTML
.
Edit: tested it without href and it worked ok... that leaves the doctype, or something else.


q:
If I have a table like this:

CREATE TABLE sizes (
    name ENUM('small', 'medium', 'large')
);

Is MySQL going to store those strings in every row, or internally will it use something smaller like integers to know which enum value to refer to?

I want to use an enum in a table but I'm worried if it's as wasteful as storing a string in every row.

[A]
It converts them to integers on INSERT / UPDATE and back to strings on SELECT so the internal storage is as integers but you don't get exposed to that.
You can retrieve the integer like
```
SELECT mycolumn + 0
```
.
See
ENUMs in MySQL 5


q:
I'm an old hand at embedded programming but new to CE and having a lot of trouble doing reasonably simple things, because I am not familiar with the API and struggling to understand the obscure MSDN docs.

All I want to do is minimize and maximise two separate applications that are running from one of the applications.

E.g. Application A decides that now it is time for it to appear and then minimises application B (App B being a third party application e.g. Notepad, no access to source code etc) and then at a later stage maximising B and minimising itself.

Application A would be written by myself.

I'm sure this must be very simple, but where to find answers.. :)

Thanks in advance.
EOI

[A]
Firstly you will need to locate the window handle (hwnd) using the
FindWindow
API function or some alternate means. Next use the
ShowWindow
API function specifying either
SW_HIDE
or
SW_SHOW
to hide or show the window respectively. Note that Windows CE 5.0 does not technically support the Win32 window states like SW_MINIMIZE, SW_MAXIMIZE, etc.
A simple example would be:
```
```
HWND hWnd = ::FindWindow( _T("Notepad"), NULL);
::ShowWindow(hWnd, SW_HIDE);
```
```


q:
I'm new to .NET, so please be patient with me ;)

On my Windows Form, I have a DataGridView that is bound to a data source. Since my grid is read-only, I have a set of controls (textbox, checkbox, etc.) outside the grid that will be used to edit the data.

I want the controls to be binded to the currently selected row in the grid. Currently, if I set the DataBindings of the controls to the same data source as the grid, only the first record is showned even if I move the record pointer in the grid.

What am I missing?

Environment: Windows Form, C#, Visual Studio 2008.

[A]
You want to check out the custom datagridviewcolumn types that are available with the datagridview.
Add in special columns and then bind a list of business objects to the grid (or a DataSet).
I think you can even ask the grid to autogenerate sensible columns based upon the objects you give it.
I wouldn't recommend trying to stuff normal controls into the datagrid per se, there is a grid column framework based on cells, columns and editingcontrols that deals with this stuff. Have a little searchy on Google based on those kind of words (e.g DataBinding/DataGridViewEditingControl), i'm afraid I don't have my DataGridView resources to hand right now.
Oh wait, sorry I re-read. You'll want to look at the BindingContext object.


q: We have 3 applications using 3 different spring configuration files. But we have one database and one datasource, so one session factory.Hhow can we import the session factory bean into the 3 different spring config files?

[A]
If you are using XML configuration:
Put your database settings in a Spring configuration called "database-config.xml" and import it in the other configuration files.
```
```
<import resource="database-config.xml"/>
```
```
As to how you share it among three applications is more of a Configuration Management issue. You could use ant / maven to check it out of a repository and move it into the correct location.


q:
ok so basically I am asking the question of their name
I want this to be one input rather than Forename and Surname.

Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g.

name = "Thomas Winter"
print name.split()

and what would be output is just "Winter"

[A]
Like this:
```
```
print name.split()[-1]
```
```


q:
I had a painful experience with the "Analysis of Algorithms" classes back in college but have recently found a need for it in the real world.  -- Anyway, I'm looking for a simple-yet-effective crash course.  Any ideas?

Related Sidenote:  It sure would be nice if there were a "Cartoon Guide to Algorithm Analysis", taught by Dilbert.

UPDATE:  A very similar question can be found at: How to get started on ALGORITHMS?

[A]
There are a lot of good books on the subject.  I like
An Introduction to the Analysis of Algorithms
.  Also check out the algorithms course on
MIT OpenCourseWare
(using
CLRS
as the course text).  It's a little bit deep, but having it online allows you to go at your own pace.
A couple of other books that I've started reading recently are
Algorithms in a Nutshell
and the
Algorithm Design Manual
.  They both take a lighter approach than most algorithms books.  Instead of heavy math and formal proofs these books give you realistic problem statements and show you the steps taken to refine an algorithm.  They also show you how to
estimate
and
measure
the complexity of a solution.  I would highly recommend either book.


q:
In a simple winform application, I call a function that endlessy create files on a button click event. I add Application.DoEvents() to the loop.

I press the red X to close the form.

the form closes, but files continue to be created ...

I think its on the buttons thread, but shouldnt it be a background one ? trying changing Thread.CurrentThread.IsBackGround to True on the loop function does not help.

Ideas ?

[A]
The fact that you're using
```
Application.DoEvents
```
is the first sign of a problem: it shows that you're doing too much in the UI thread. It's almost never appropriate in a well-structured program. The UI thread is not meant to have any long-running tasks. (Admittedly if it takes a long time to draw your UI you have little choice - but that suggests you should simplify your UI... and it's not applicable in this case, I suspect.)
Instead, you should be performing the long-running task (creating the files) in a separate thread.
BackgroundWorker
is a perfect fit for this - you can use it to report progress back to the UI, and the UI can call
```
CancelAsync
```
method to request that it stops. You need to check the
```
CancellationPending
```
property from within the worker thread, to see whether cancellation has been requested, and stop appropriately.
EDIT: Just to clarify what I believe is happening - I suspect your form is closing, but the program won't terminate until the event loop has finished. You're keeping the event loop going with your file-creation loop, hence the problem.
Note that there isn't a thread for the button - there's just one for your whole UI. (In certain cases you may need more than one UI thread, but that's rare - and you'd know it if you'd done it.)


q:
I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:

$doc->addChild('myToken');

This generates (what I know as) a self-closing or single tag:

<myToken/>

However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:

<myToken></myToken>

The question is, how do I do this, outside of running the generated XML through a preg_replace?

[A]
From the documentation at
SimpleXMLElement->__construct
and
LibXML Predefined Constants
, I think this should work:
```
```
<?php
$sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG);

// some processing here

$out = $sxe->asXML();
?>
```
```
Try that and see if it works. Otherwise, I'm afraid, it's preg_replace-land.


q:
I am using XmlSerializer to write and read an object to xml in C#.  I currently use the attributes XmlElement and XmlIgnore to manipulate the serialization of the object.

If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine.   How do I indicate (preferably via Attributes) that a certain field is "required"?

Here is a sample method of what I am using currently:

[XmlElement(ElementName="numberOfWidgets")]
public int NumberThatIsRequired {
    set ...;
    get ...;
}

My ideal solution would be to add something like an XmlRequired attribute.

Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?

[A]
I've got an answer for the second part:
"Attributes that control XML serialization"
.
Still investigating the first part...
EDIT: I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which includes a required attribute - and it's exactly the same if the attribute is marked as being optional. If there were a way of requiring properties to be set, I'd expect it to be implemented in that case.
I suspect you've basically got to just validate your tree of objects after deserializing it. Sorry about that...


q:
I have two vb.net class:

Public MustInherit Class Class1
    Private m_sProperty1 As String = ""
    Public Property sProperty1() As String
        Get
            Return m_sProperty1
        End Get
        Set(ByVal value As String)
            m_sProperty1 = value
        End Set
    End Property
End Class

<ComClass("classid","interfaceid","eventid")> _
Public Class Class2
    Inherits Class1

    Private m_sProperty2 As String = ""
    Public Property sProperty2() As String
        Get
            Return m_sProperty2
        End Get
        Set(ByVal value As String)
            m_sProperty2 = value
        End Set
    End Property
End Class

When I reference the compiled DLL through VB6, Class2 only exposes sProperty2.  How can I access the inherited property of the base class (sProperty1) through COM?

[A]
I'll take a guess as I'm not up to speed on .NET
I would imagine your declaration is taking your public methods of Class2 and creating a COM interface out of them.  It will only take methods (and properties) on Class2 and not inherited ones (otherwise you would get all public methods all the way down to your base class).
The solution would probably be to declare Class1 as a COM class also (it may be possible to mark it as private) then specify that the COM interfaceid of Class2 descends from the COM interfaceid of Class1.
Some thing like that shoudl do the trick.


q:
In my Python app, I have an XML document that I'd like to transform using my XSL file.  I'm currently using xml.etree to generate the XML document, but I haven't found anything within Python 2.5 that will allow me to natively transform my XML document.

I've already found one library (libxslt) which can execute the transformation, but I figured Python would have a native library that achieves the desired result.

Any thoughts?

[A] There is no XSLT processor in Python 2.5.


q:
Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):

CREATE PROCEDURE incrementCounter AS

DECLARE @current int
SET @current = (select CounterColumn from MyTable) + 1

UPDATE
    MyTable
SET
    CounterColumn = current
GO

We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count.

Can this stored procedure be executed multiple times, at the same time?

i.e. is this possible:

I call 'incrementCounter' twice.  Call A gets to the point where it sets the 'current' variable (let's say it is 5).  Call B gets to the point where it sets the 'current' variable (which would also be 5).  Call A finishes executing, then Call B finishes.  In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution

[A]
This is for SQL Server.
Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with
BEGIN TRANSACTION
Statement ...
Statement ...
COMMIT TRANSACTION
(It's common to use BEGIN TRAN and END TRAN for short.)
Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious.
Contrary to a popular misconception, this will work in your case with default transaction level settings.


q:
We have a fairly complex web application (.NET 3.5) that need to be launched from a CD-ROM (or DVD, or from an USB key).

I'm thinking of using Cassini and SqlCe for the database (we use LinqToSql for data access, so I think it's the only choice without rewriting the entire data access classes). Is anyone ever done something like that?

Notes :
http://www.microsoft.com/belux/msdn/nl/community/columns/desmet/hostaspnet2.mspx
Kind of does what I want.

[A]
Where are you going to get the web server to serve the ASP.NET pages? You can open stuff like straight HTML, Flash or Silverlight directly in the browser, but unless I am missing something, you need IIS to do the server side ASP.NET.
I don't know your requirements, but you might want to consider a WinForms app or even MFC (if you can't guarantee .NET is installed on the target computers).
This doesn't answer your database question though. SqlCE should work as the required assemblies can be distributed with your application. Another option is SQLite along with Subversion for your data layer. I have no experience with Cassini though.


q:
I want to create a view that consists solely of a UITextView. When the view is first shown, by default, I'd like the keyboard to be visible and ready for text entry. This way, the user does not have to touch the UITextView first in order to begin editing.

Is this possible? I see the class has a notification called UITextViewTextDidBeginEditingNotification but I'm not sure how to send that, or if that is even the right approach.

[A]
to accomplish that just send the becomeFirstResponder message to your UITextField, as follows (assuming you have an outlet called textField, pointing to the field in question):
```
```
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [textField becomeFirstResponder];
}
```
```


q:
I am performing two validations on the client side on the samve event.
I have defined my validations as shown below

btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();"

Pseudo code for

prepareSave():
{
  if (bPendingchanges)
    {
     return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first')
    }
  else
   {return true}
}

Pseudo code for

prepareSearch():
{
  if (bNoSearchText)
    {
      alert('Please specify search criteria before proceeding')
      return false;
   }
  else
   {return true;}
}

When bPendingchanges=false, I never get the second validation running.
Anyone who can quickly spot what I have overlooked here? Please?

[A]
Your second
```
return
```
statement will never be reached. Execution stops after
```
javascript:return prepareSave()
```
.
Looks like you want to return true if both functions return true - therefore, do:
```
```
btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch();
```
```


q:
I want to assign a resource I already have a second name, similar to using the BasedOn property of Styles. Specifically I have a brush that I use for a group of elements called ForegroundColor and I would like to use it in a control template (a ComboBox) calling it MouseOverBackgroundBrush. I would like to do something like this:

<ResourceCopy x:key="MouseOverBackgroundBrush" Value="{StaticResource ForegroundColor}" />

Is there a way to do this or is there a better way to go about this in Xaml?

[A]
This is a feature that doesn't have very good support in XAML. I believe that you'll either need to repeat yourself (and change both locations anytime you need to change the brush)
or
if you don't mind a bit of code behind, you can accomplish the duplication like this:
```
```
Resources["MouseOverBackgroundBrush"] = Resources["ForegroundColor"];
```
```


q:
If I have a button like the one in this image :

http://www.freeimagehosting.net/image.php?4cd775814c.png

how could I make the text display itself vertically ? As in

j
B
u
t
t
o
n
1

I would like to know how to do the same thing for JLabel . I'm sure there has to be a better way than to create as many labels as there are characters in the string . Right ?

EDIT: how can I insert an image into my post ? The button for the image shows the image in the preview section , but when I actually post the data , I only get some text back , like the tags are getting messed up .

[A]
You can use HTML for JButton or JLabel. So
```
```
button = new JButton("J
b
u
t
t
o
n
1");
```
```
should do the trick.


q:
This question is related to my previous one.

Can you explain or provide a link to an explanation of how Excel VBA code password protection actually works in versions prior to 2007? What is the difference in Excel 2007 and previous versions in terms of password protection?

Also does Excel's password protection actually encrypt the code? How does Excel execute the code if it is encrypted?

Lastly, how does password removal software for excel work?

[A]
VBA security is widely considered to be pretty poor.  The VBA code isn't compiled, and the source is available in the excel file. The password protection is pretty easy to circumvent.
As I understand it, Office 2003 and earlier saves the vba code as part of the binary format of the worksheet (or document / presentation).  When you fire up the VBA IDE, it simply looks to see whether the VBA code has been "protected" or not.  This doesn't mean it's encrypted - just unavailable for viewing.  The theory is that this stops your users from meddling with your code, but a hard-core coder would be able to get around the password.
So Excel doesn't need to unencrypt any code - it just needs to stop people from viewing it.
Office 2007
does
encrypt macros (don't ask me how or what algorithm).  This is necessary presumably because XLSM files (or any Office 2007 file) are just zip files with a different extension.  Anyone can get into those files and poke around.
To answer your last question - how does the password removal work on older Office formats, I'm not entirely sure.  Different vendors will possibly approach the problem different ways, but I suspect the most common approach will be a brute-force attack on the passwords until a match is found.
The Excel VBProject object has a Protection property which will return different enumerations depending on the protection status of the macro (
```
vbext_pp_locked
```
if the macro is protected, for example).  If you were to keep trying passwords programmatically until the
```
vbext_pp_locked
```
evaluated to false, you would have found your password.


q:
In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid.

I.e. instead of just

dynamic foo = GetSomeDynamicObject();

have the ability to cast or transform it to constrain it to a known contract, such as

IFoo foo2 = foo.To<IFoo>;

or even just

IFoo foo2 = foo as IFoo;

Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?

[A]
I'm not aware of anything really resembling duck typing, I'm afraid. I've
blogged about the idea
, but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.


q:
I have to simultaneously load data into a table and run queries on it. Because of data nature, I can trade integrity for performance. How can I minimize the overhead of transactions?

Unfortunately, alternatives like MySQL cannot be used (due to non-technical reasons).

[A]
You want transaction isolation read uncommitted. I don't recommend it but that's what you asked for :)
This will allow you to breach transaction isolation and read uncommitted inserted data.
Please read this Ask Tom article:
http://www.oracle.com/technology/oramag/oracle/05-nov/o65asktom.html
.
UPDATE: I was actually mistaking, Oracle doesn't really support read uncommitted isolation level, they just mention it :).


q: What is the best way to tokenize/split a NSString in Objective-C?

[A]
Found answer
here
:
```
```
NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];
```
```


q:
Consider the following file

var1 var2 variable3
1     2    3
11    22   33

I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:

variable_names = char('var1', 'var2', 'variable3');

I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option.

Note that there can be an arbitrary number of variables (columns)

[A]
Just use textscan with different format specifiers.
```
```
fid = fopen(filename,'r');
heading = textscan(fid,'%s %s %s',1);
fgetl(fid); %advance the file pointer one line
data = textscan(fid,'%n %n %n');%read the rest of the data
fclose(fid);
```
```
In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.


q: Is there a way to increase the font-size in the Firefox extension Firebug?

[A]
Right click on the bug icon in the status bar.
Select "Open Firebug in New Window"
Select "View" > "Text Size" > "Increase Text Size"
The changes should stick if you revert back to opening Firebug in the same window.
Update
In new versions you can simply click on the bug icon in the code navigator and choose 'Text size'.


q: If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. SELECT * FROM table WHERE column LIKE %news%), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.

[A]
You can use substring function in a SELECT part. Something like:
```
```
SELECT SUBSTRING(column, 1,20) FROM table WHERE column LIKE %news%
```
```
This will return the first 20 characters from column
column


q: I want to display from cache for a long time and I want a slightly different behavior on page render vs loading the page from cache.  Is there an easy way I can determine this with JavaScript?

[A] One way you could do it is to include the time the page was generated in the page and then use some javascript to compare the local time to the time the page was generated.  If the time is different by a threshold then the page has come from a cache.  The problem with that is if the client machine has its time set incorrectly, although you could get around this by making the client include its current system time in the request to generate the page and then send that value back to the client.


q:
I have a project to recognize the footprint of animals. It is similar to facial recognition.

There is a need to store footprint images in a database and compare them with images captured by camera.

What is the appropriate programming language to do this?

[A]
I think the question is rather how you represent the data and determine likeness/sameness/distance measuring rather than an implementation language.
Lisp is a strong candidate, as is C/C++ - but really you are probably better off with whatever language you/your team knows best.
Again, figure out the data representation first.
Also - find another imaging/matching solution out there.  There are already ones for license plates, fingerprint, etc - and maybe just use that source.  The roblem is mostly solved...


q: I'd like to create a popup dialog box in silverlight  in which i can manipulate controls, enter data, and return a value. I want it to be modal, so that when it is open, the page "Below" is inaccessible. I havent found an easy way to do this yet. Any suggestions?

[A]
I haven't found a perfect solution either. The closest I have seen is this:
Using Popup to create a Dialog class
If it is ok to be non-modal, you can try this tip using HtmlPage.PopupWindow().
How to Popup a Browser Window


q:
I'll preface this by saying I'm a C# programmer who inherited horrible code with no documentation.  I have an unmanaged C++ library wrapped with managed code that worked fine in VS2003 with .Net 1.1 Framework.  I'm trying to get it upgraded to at least .Net 2.0.

I have the unmanaged C++ library that was compiled with "MSVC 8.x" (thus equivalent to VS 2005, I assume).  I've been trying to migrate everything to VS2008 and still have some issues with this library at runtime.

My question is this: should this library work with VS2008?  Or should I be developing in VS2005 if the library was compiled with VC8.x?

Any thoughts would be greatly appreciated.  Thanks!

[A]
It should work, I expect that you are having issues with your marshalling. It is probably stuff that was declared incorrectly for PInvoking that managed to work in .NET 1.1 but not in later versions.
You don't say what sort of problems you are having at run time, nor do you state how you access your library. For example, do you compile your library along with your project? If so, can you turn on unmanaged debugging in your C# project and step into the code you are having trouble with? How are you calling the unmanaged code? Is it through PInvoke, or do you have managed C++ wrappers?
In my experience, the best solution for calling out to a legacy unmanaged library is to add a managed wrapper library for your legacy library written in managed C++. This way you present a managed interface for your library for all .NET languages to consume and you don't have to worry about getting your PInvoke signatures correct.
Your project should look something like this.
C# Application -> Manage C++ Wrapper DLL -> Legacy DLL


q:
I'm not a designer, so I'm looking for some free WPF themes.

Any suggestions?

[A]
The only one that I have found (for sale) is
reuxables
. A little pricey, if you ask me, but you do get 9 themes/61 variations.
UPDATE 1:
A WPF Contrib project ... which does have 1
theme
that they never released.
UPDATE 2:
Rudi Grobler (above) just created CodePlex
community
for this ... starting with converted themes he mentions above. See his blog
post
for more info. Way to go Rudi!
UPDATE 3:
As another answer below has mentioned, since this question and my answer were written, the WPF Toolkit has incorporated some free
themes
, in particular, the themes from the Silverlight Toolkit. Rudi's
project
goes a little further and adds several more ... but depending on your situation, the WPF Toolkit might be all you need (and you might be installing it already).


q:
You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal?

If so, how?

[A]
Why do you not want to prefix string literals with an L?  It's quite simple - strings without an L are ANSI strings (
```
const char*
```
), strings with an L are wide-character strings (
```
const wchar_t*
```
).  There is the
```
TEXT()
```
macro, which makes a string literal into an ANSI or a wide-character string depending on of the current project is set to use Uncode:
```
```
#ifdef UNICODE
#define TEXT(s) L ## s
#else
#define TEXT(s) s
#endif
```
```
There's also the
```
_T()
```
macro, which is equivalent to
```
TEXT()
```
.


q:
I would like to set up some WMV Video Streaming, using Windows 2003's Streaming Media Server and Silverlight.

Now, unfortunately Silverlight only supports HTTP, which means that people can just download the videos. While that in itself is not a problem, I wonder what options there are to prevent them being playable outside of the network.

Of course, DRM comes into mind. Is there an easy way to get it and set it up? I do not want to have some complicated User-Scheme, it essentially boils down to "If you can reach the server (which is only in the internal network), you get a license, otherwise not".

Any experience with WMV DRM or Content Protection in that area?
What would I need on top of Windows 2003 Server and Silverlight 2?

[A] DRM is a negative sum game.  You lose money and time in implementing it that you could have spent on something useful to your users, and your content becomes less valuable to your users.  It is also impossible to implement effectively.  I'm not going to address any specific DRM scheme, but the core of the argument is that in order to show content to the user, the user's computer must be able to decrypt it.  Therefore, the decryption code, and the decryption keys, must be present on the user's computer.  Encryption can only protect data from interception and tampering between two secure endpoints.  If one of the endpoints is compromised (and you are assuming this in your distrust of the user), then cryptographic techniques are useless.


q:
I have a short preliminary interview with Microsoft in less than 2 hours.
I've been told that they might ask questions in Java and/or C++.
Where can I find a quick overview of both languages?
I don't need to full tutorial, just something that goes over the language-specific features and a refresher of the semantics.
I also only have 1.5 hours to study so...
Any ideas?

Thx!

[A] An hour and a half is a bit fast to learn a language. You can try Wikipedia, but you may want to avoid discussion of either language if you don't know them. Instead focus on the languages you do know. Learning a new language is not difficult, but you shouldn't try to rush it and then sound like you know more than you do. They'll figure that one out pretty quickly, and it will be worse if you don't admit your lack of knowledge. We had someone who tried that with my company, and he lasted less than a week.


q:
I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run.
So far I have:

SELECT startTime, endTime,
cast(datediff(hh,starttime,endtime) as varchar)
+':'
+cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME
FROM applog
WHERE runID = 33871
ORDER BY startTime DESC

When I execute this I get expected values and also some unexpected.
For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54.
How do I get a quere in MS SQL SMS to return the value 3:06 for this case?

Thanks.

Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.

[A]
Here's
a way to do it:
```
```
-- Find Hours, Minutes and Seconds in between two datetime
DECLARE @First datetime
DECLARE @Second datetime
SET @First = '04/02/2008 05:23:22'
SET @Second = getdate()

SELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,
DATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,
DATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds
```
```


q:
I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link.

<ul id="targetedArea">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<div id="clickedItems">
  <a></a>
  <a></a>
  <a></a>
  <a></a>
</div>

I can target them individually, but I know there must be a faster way by passing which <a> element I clicked on.

$("#clickedItem a:eq(2)").click(function() {
  $("#targetedArea:eq(2)").addClass('active');
  return false;
});

Cheers,

Steve

[A]
how about something like this:
```
```
$('#clickedItems a').click(function() {
// figure out what position this element is in
   var n = $('#clickedItems a').index($(this) );
// update the targetedArea
   $('#targetedArea li:eq('+n+')').html('updated!');
   return false;
});
```
```
assuming a 1:1 relationship between your
```
<a>
```
and
```
<li>
```
elements it will update the appropriate
```
<li>
```


q:
How can i draw a dotted line in .NET/WinForms/GDI+?

Pen p = new Pen (Color.Black)

gives me only solid line pen.

I am trying to have a dotted (or dashed) lines; can't seem to be able to google it up successfully.

Will much appreciate any help on this one.

[A]
```
```
p.DashStyle = DashStyle.Dash;
```
```
I believe.


q:
I want to select records that are 1 month old or newer.

The query is: SELECT * FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)

Using Propel in Symfony, I do:

$c = new Criteria

  $c->add(FoobarPeer::CREATED_AT, "DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::GREATER_THAN);

What Propel generates is: SELECT * FROM foobar WHERE created_at > 'DATE_SUB(curdate(), INTERVAL 1 MONTH)' - in other words, it puts the MySQL function in single quotes, which makes it a (meaningless) string and I get no records.

What I've done for now is:

$c->add(FoobarPeer::CREATED_AT, "created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::CUSTOM);

But I don't want to use custom workarounds unless I have to. Any hints besides using Criteria::CUSTOM?

[A]
I think there is no option more than using Criteria::CUSTOM or doing a custom SQL query like this:
```
```
$con = Propel::getConnection(DATABASE_NAME);

$sql = "SELECT foobar.* FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)";
$stmt = $con->prepare($sql);
$stmt->execute();

$books = FoobarPeer::populateObjects($stmt);
```
```
That's because Propel tries to be DBMS-agnostic, to help migration by doing a simple configuration value change, so it doesn't have any DBMS specific functions built in.


q:
I know that php has md5(), sha1(), and the hash() functions, but I want to create a hash using the MySQL PASSWORD() function.  So far, the only way I can think of is to just query the server, but I want a function (preferably in php or Perl) that will do the same thing without querying MySQL at all.

For example:

MySQL hash -> 464bb2cb3cf18b66

MySQL5 hash -> *01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229

Thanks!

[A]
Why do you want to use mysql password() function?
Even the Mysql documentation advises against this:
http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html#function_password
The PASSWORD() function is used by the authentication system in MySQL Server; you should not use it in your own applications
You can use md5() for example, wich is present in almost every programming language, php and perl included.


q:
A little example

TTest<T> = class
private
  f : T;
public
  function ToString : string;
end;

If  is an object then this should work

TTest<T>.ToString;
begin
  Result := f.ToString;
end;

But what happens when  is say an integer? This would be ok in .net. of course.

I know it won't work, but how do I code this to work with objects AND simple types?

[A]
The last example will not work. You need to add a constraint in order to use methods. In this case TObject will be enough:
```
```
TTest<T: TObject>.ToString;
begin
  Result := T.ToString;
end;
```
```
You can use simple types with unrestrained generics, but you are very limited in the use. Because the only valid operations are assignment and comparison (equal and not equal).
In Delphi simple types are no classes, so they don't have methods.
But you can do the following:
```
```
type
  TToString<T> = reference to function(const AValue: T): string;
  TGenContainer<T> = class
  private
    FValue: T;
    FToString : TToString<T>;
  public
    constructor Create(const AToString: TToString<T>);

    function ToString: string;

    property Value: T read FValue write FValue;
  end;

constructor TGenContainer<T>.Create(const AToString: TToString<T>);
begin
  FToString := AToString;
end;

function TGenContainer<T>.ToString: string;
begin
  Result := FToString(FValue);
end;

procedure TForm2.Button1Click(Sender: TObject);
var
  gen : TGenContainer<Integer>;
begin
  gen := TGenContainer<Integer>.Create(
    function(const AValue: Integer): string
    begin
      Result := IntToStr(AValue);
    end);
  try
    gen.Value := 17;
    Memo1.Lines.Add(gen.ToString);
  finally
    gen.Free;
  end;
end;
```
```
This works fine.


q:
I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web.  As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename.

Is there a simple way to do this without re-writing the function myself?  I searched around for a simple library, but couldn't find anything.  Surely this is a common problem.

[A]
A simpler approach is to replace everything which is not a character or a number with an underscore.
EDIT: Here's a naive implementation in C:
```
```
#include <cctype>

char *safe_url(const char *str) {
    char *safe = strdup(str);
    for (int i = 0; i < strlen(str); i++) {
        if (isalpha(str[i]))
            safe[i] = str[i];
        else
            safe[i] = '_';
    }
}
```
```


q: Is anyone using the OSGi Bundle Repository and what for?

[A]
I am using it!
When you develop an osgi bundle and the target platform doesn't include the libraries (jar/bundle) your bundle relies on, it needs to added to the target platform. you could either repackage your jar to make it an osgi bundle or just download the bundle from the OBR.
Eclipse also provides an OBR call
Orbit
, and springsource one is called
Enterprise Bundle Repository
.


q:
For reference, this would be for Visual Studio 2008 with a fair amount of WinForms working with the VS Designer.

Given the same price bracket, would there be certain specs you look for in a development rig vs what one would get for a gaming machine?

Edit: The reason I ask is on my laptop that I can run low-mid end games decently on, there's still a fair amount of time redrawing when switching between apps sometimes.(I keep about 20 tabs open average on  a browser and have like 10-15 apps open at a time), and working with the VS designer on things like a TableLayoutPanel takes up to 10-15 seconds for changes and so forth. I'd like a really smooth experience.

[A]
Any new video card you could buy today would be more than adequate for non-3D software development. In fact whatever integrated video came with your system is fine. The only exception would be for multiple monitor support, in that case you would need to get an extra $50 video card since most (all?) motherboards only have a single monitor output.
Edit: in response to the edit, the lag you're describing sounds like your machine is out of RAM and is swapping to disk, rather than you being video card limited. You'll want at least 2-3GB of ram in your system if you're running vs2008 plus 20 other applications. That's about the max. you can install if you're running a 32-bit operating system. If you want more than that you'll need to go to a 64-bit OS and you'll need to make sure all your hardware has 64-bit drivers. Also very few laptops out there support more than 4GB of RAM.


q: I'm in need of a macro that will enter data into a webpage search field and than copy the results to excel.

[A]
It's just a simple "File Open". No need for a macro.
Excel can open URLs directly. If the URL contains any tables, those will be formatted appropriately.
Try this:
Run Excel
File | Open
Type
```
http://finance.yahoo.com/q?s=MSFT
```
as the file name
Ignore the warning


q:
I've got a canvas that's 800x600 inside a window that's 300x300. When I press a certain key, I want it the canvas to move in that direction.

I've done this inside the window's code behind:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    Key keyPressed = e.Key;

    if (keyPressed == Key.W)
    {
        gcY += 5;
    }
    if (keyPressed == Key.S)
    {
        gcY -= 5;
    }
    if (keyPressed == Key.A)
    {
        gcX += 5;
    }
    if (keyPressed == Key.D)
    {
        gcX -= 5;
    }

    gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY);
}

Well, it works, but the movement is jerky. And if I hold on to a key, W for instance, then it pauses for a split second, before moving.

Is there anyway to make the movement smoother and to get rid of the pause when you hold down a key?

Thanks.

[A]
Yes, you could incorporate the time into your calculation. Currently you add/substract 5 whenever the event fires, and that's not really predictable.
To smoothe the movement make sure you don't fire more often than X times per second by using a DateTime.
like:
```
```
private static DateTime nextUpdate

if (nextUpdate <= DateTime.Now)
{
//Move
nextUpdate = DateTime.Now.AddMilliseconds(100);
}
```
```
I don't have VS right now, so I'm not perfectly sure for the syntax, but you get the idea.


q:
I need to take production data with real customer info (names, address, phone numbers, etc) and move it into a dev environment, but I'd like to remove any semblance of real customer info.

Some of the answers to this question can help me generating NEW test data, but then how do I replace those columns in my production data, but keep the other relevant columns?

Let's say I had a table with 10000 fake names. Should I do a cross-join with a SQL update? Or do something like

UPDATE table
SET lastname = (SELECT TOP 1 name FROM samplenames ORDER By NEWID())

[A]
Anonymizing data can be tricky and if not done correctly can lead you to trouble, like what happened to
AOL when they released search data a while back
. I would attempt to create test data from scratch at all costs before I tried to convert existing customer data. Things may lead you to be able to figure out who the data belonged to using things such as behavioral analysis and other data points that you might not consider sensitive. I would rather be safe than sorry.


q:
Why does this test program result in a java.lang.IllegalMonitorStateException?

public class test {
    static Integer foo = new Integer(1);
    public static void main(String[] args) {
        synchronized(foo) {
            foo++;
            foo.notifyAll();
        }
        System.err.println("Success");
    }
}

Result:

Exception in thread "main" java.lang.IllegalMonitorStateException
        at java.lang.Object.notifyAll(Native Method)
        at test.main(test.java:6)

[A]
You have noted correctly that
```
notifyAll
```
must be called from a synchronized block.
However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked
```
notifyAll
```
on. In fact, the new, incremented
```
foo
```
instance is still confined to the stack, and no other threads could possibly be blocked on a
```
wait
```
call.
You could implement your own, mutable counter on which synchronization is performed. Depending on your application, you might also find that
AtomicInteger
meets your needs.


q:
I occasionally work on an old project that uses classic asp as a front end and an access database as a backend.

I'd like to create a new column in one of the tables that contains logic to calculate its value from the other columns in the row.

I know how to do this in a more modern DBMS, but I don't think that access supports it. Keep in mind I'm not using the access frontend, just the Jet DB engine via ODBC.

Any pointers?

[A]
Can you just make a calculated column?
```
```
SELECT Table1.Col_1, Table1.Col_2, [Col_1]*[Col_2] AS Col_3
FROM Table1;
```
```


q:
I am using the code below to display all the files from a directory in a drop down menu. Does anyone know how to make this alphabetical? I presume it has something to do with the sort function, I just can't figure out how!

<?php
$dirname = "images/";
$images = scandir($dirname);
$dh = opendir($dirname);

while ($file = readdir($dh)) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
closedir($dh);
?>

[A]
Why are you reading all the filenames using scandir() and then looping through them with the readdir() method? You could just do this:
```
```
<?php

$dirname = "images/";
$images = scandir($dirname);

// This is how you sort an array, see http://php.net/sort
sort($images);

// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; }
    }
}

?>
```
```
Also you might want to use
natsort()
, which works the same way as
sort()
but sorts in "natural order". (Instead of sorting as
```
1,10,2,20
```
it will sort as
```
1,2,10,20
```
.)


q:
I have a list of stores, departments within the stores, and sales for each department, like so (created using max(sales) in a subquery, but that's not terribly important here I don't think):

toronto    baskets 500
vancouver  baskets 350
halifax    baskets 100
toronto    noodles 275
vancouver  noodles 390
halifax    noodles 120
halifax    fish    200

I would like to ask for the highest-selling department at each store. The results should look like this:

toronto    baskets 500
vancouver  noodles 275
halifax    fish    200

Whenever I use GROUP BY, it includes all the listings from my subquery. Is there a nice clean way to do this without a temporary table?

[A]
This works in Oracle, other implementations may have different syntax for analytic functions (or lack them entirely):
```
```
select store
     , max(department) keep(dense_rank last order by sales)
     , max(sales)
  from (
        ...query that generates your results...
       )
 group by store
```
```


q:
I know you cannot use a alias column in the where clause for T-SQL; however, has Microsoft provided some kind of workaround for this?

Related Questions:

Unknown Column In Where Clause

Can you use an alias in the WHERE clause in mysql?

“Invalid column name” error on SQL statement from OpenQuery results

[A]
One workaround would be to use a derived table.
For example:
```
```
select *
from
   (
   select a + b as aliased_column
   from table
   ) dt
where dt.aliased_column = something.
```
```
I hope this helps.


q:
I currently have two text boxes which accept any number. I have a text block that takes the two numbers entered and calculates the average.

I was wondering if there was a way I could bind this text block to both text boxes and utilize a custom converter to calculate the average? I currently am catching the text changed events on both text boxes and calculating the average that way, but I am under the assumption data binding would be more efficient and easier.

[A]
You're looking for
```
MultiBinding
```
.
Your
```
XAML
```
will look something like this:
```
```
<TextBlock>
  <TextBlock.Text>
    <MultiBinding Converter="{StaticResource myConverter}">
      <Binding Path="myFirst.Value" />
      <Binding Path="mySecond.Value" />
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>
```
```
With reasonable replacements for
```
myConverter
```
,
```
myFirst.Value
```
, and
```
mySecond.Value
```
.


q: I'd like to set up a large linear programming model to solve an interesting problem.  I would be most comfortable in Java.  What tools/libraries are available?

[A]
I used
lp_solve
with success. It looks like there is a native Java API, but I've only used the text file interface. It supports the semi-standard MPS and LP file formats, which I found more convenient for trying out different solvers (such as
glpsol
).


q:
When hosting a WCF service on IIS you have an option of manually configuring the endpoint or declaratively by means of WebServiceHostFactory. It doesn't seem to be that difficult to manually create the endpoint so I figured I would ask.

What are the benefits of using WebServiceHostFactory?

Are there any performance implications to dynamically creating the endpoints?

[A]
Can you clarify : are you asking specifically about
Web
ServiceHostFactory (emph: "Web")? Or just the  difference between IIS hosting it vs starting your own server through code?
WebServiceHostFactory is new in .NET 3.5, and supports some of the newer AJAX/JSON stuff.
Actually, within IIS (using .svc), you are already using a ServiceHostFactory - simply the default one shipped with WCF. You can write your own factory if you want, and I've done this in the past to create a factory that
only
listens on https (I had an issues on a farm hosting multiple sites, where it couldn't identify the correct site for http, but https was fine - so I completely disabled http via the factory).
Performance shouldn't be any different as long as you don't go mad and listen on 200 end-points...
Generally, manually creating the server is used when you are hosting the server in (for example) a windows service. IIS is fine for some things, but app-pools get recycled, so aren't ideal for a server that needs to retain long-lived state. IIS has the advantage of being much easier to configure, especially with security (SSL etc) and compression.


q:
I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:

warning: HEAP[test.exe]:
warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1

How can I track down where this is happening at? Viewing the memory doesn't give me any clues.

Thanks!

[A]
So you're busting your heap. Here's a nice
GDB tutorial
to keep in mind.
My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way.
Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).


q: How do I query the iPhone's current IP address?

[A]
You can try to use similar to this service:
Whatismyip
and capture the string :)
Credit to Erica Sadun's iPhone Developer's Cookbok, 2nd ed, page 555.