q: Can a WinForms app compiled for "Any CPU" be configured to run as "x86" on a 64-bit server without recompiling the app? Specifically, I'm looking for an app.config setting or Control Panel applet to accomplish this end. All the customer's clients are x86, but the server is x64, and we like to install the WinForms app on the server for administrators to configure and monitor the system. We would much rather not recompile just for the server.

[A]
From
http://www.request-response.com/blog/PermaLink,guid,34966ef8-3142-46b2-84e0-372b5c36ddcc.aspx
You can, however,  control and
  override this default behaviour even
  after your code has been compiled.
  There's a handy tool called
  corflags.exe present in the SDK that
  allows you to force 'anycpu' compiled
  code to use 32-bit process in 64-bit
  world.
The usage of this utility is found here
http://msdn.microsoft.com/en-us/library/ms164699(VS.80).aspx


q:
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix).

Google shows many hits for explanations on how to do this.

Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.

I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.

My specific use case is a command-line python program that needs to send emails.  I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).

I do not need it to work on windows or mac, just linux.

[A]
Use Python's
```
readline
```
bindings.  For example,
```
```
import readline

def completer(text, state):
    options = [i for i in commands if i.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

readline.parse_and_bind("tab: complete")
readline.set_completer(completer)
```
```
The official
module docs
aren't much more detailed, see the
readline docs
for more info.

s: huggingface

c: devops

d: intermediate


q:
I'm looking at maybe moving from an older AMD64 to a new Intel dual-core which is 32 bit. Installation isn't a problem but can I transfer all the installed apps? I haven't been
able to find anything so far on Google except where the migration is to a similar platform and file-system. I won't change the filesystem but the platform will be different. Is there something on the lines of the "World" file in Gentoo?

[A]
For everything you've used apt-get to install, if you want to create a record of what's installed run the following:
```
```
dpkg -l|awk '/^ii\s*(.*)\s*/ {print $2}'|packages.txt
```
```
This will create a text file with all the packages you have installed.  Then after you do the install, create and run a script with the following:
```
```
#!/bin/sh
for p in $(cat packages.txt); do apt-get install $p; done
```
```
Notes:
1) Since you're moving from 64 bit to 32 bit, some of the packages might not be compatible.  I would grep packages.txt for '64' before running the script above and find alternatives if they are needed.
2) Anything you've installed from source, you'll have to make a note of and install from source again.
Good luck!


q:
First of all, I'd like to say that this site is great!

My question is, what are the reasons for the following 2 error messages?

1) In VB.NET (I know this is a C# forum but my next question is from C# experience), property evaluation failed (I do this when putting a watch on an exception variable).

2) In C#, method or class (Can't remember which) does not have a constructor. I think I got this with HttpContext or HttpApplication, which is a class if I remember correctly? Pretty sure it is as it has its own properties and methods.

Thanks

[A]
1) Could be any number of reasons. Some properties just don't work nicely in a debugger. (Imagine watching DateTime.Now for changes!)
2) You're trying to create an instance of a class which doesn't have an appropriate accessible constructor. Usually either the class only has static members, or there's a static member you're meant to use to get an instance. (Having said that, both the classes you've mentioned have public constructors.)
More precise error messages and situation descriptions would be helpful.


q: Is there a tool that creates a diff of a file structure, perhaps based on an MD5 manifest. My goal is to send a package across the wire that contains new/updated files and a list of files to remove.  It needs to copy over new/updated files and remove files that have been deleted on the source file structure?

[A]
You might try rsync. Depending on your needs, the command might be as simple as this:
```
```
rsync -az --del /path/to/master dup-site:/path/to/duplicate
```
```
Quoting from
rsync's web site
:
rsync is an open source utility that
  provides fast incremental file
  transfer. rsync is freely available
  under the GNU General Public License
  and is currently being maintained by
  Wayne Davison.
Or, if you prefer
wikipedia
:
rsync is a software application for
  Unix systems which synchronizes files
  and directories from one location to
  another while minimizing data transfer
  using delta encoding when appropriate.
  An important feature of rsync not
  found in most similar
  programs/protocols is that the
  mirroring takes place with only one
  transmission in each direction. rsync
  can copy or display directory contents
  and copy files, optionally using
  compression and recursion.


q:
I know this is a bit of a newbie question, but are there equivalents to C#'s string operations in Java?

Specifically, I'm talking about String.Format and String.Join.

[A]
String.format
. As for join, you need to write your own:
```
```
static String join(Collection<?> s, String delimiter) {
     StringBuilder builder = new StringBuilder();
     Iterator<?> iter = s.iterator();
     while (iter.hasNext()) {
         builder.append(iter.next());
         if (!iter.hasNext()) {
           break;
         }
         builder.append(delimiter);
     }
     return builder.toString();
 }
```
```
The above comes from
http://snippets.dzone.com/posts/show/91


q:
I've just seen this in the MS Visual Studio docs and the part in bold doesn't make sense to me. Is it wrong or am I not understanding it properly? If you run this, b appears to hold "hello" (as I would expect) and not "h".

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and the variable b continues to hold "h".

string b = "h";

b += "ello";

[A]
You've done an addition AND an assignment in one step. Strings are immutable, but also a reference type.
```
```
string b = "h";
b = b + "ello";
```
```
We can look at the pseudo-memory like this:
```
```
string b = "h";         // b    := 0x00001000 ["h"]
string tmp1 = "ello";   // tmp1 := 0x00002000 ["ello"]
string tmp2 = b + tmp1; // tmp2 := 0x00003000 ["hello"]
string b = tmp2;        // b    := 0x00003000 ["hello"]
```
```
I'm not entirely sure where you're getting that text, because as I read the documentation for the
string
class I find (not that I think "h" actually gets garbage collected):
Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.
@Jon Skeet brings up that "h" will never be garbage collected due to string interning, and I agree with him, but even moreso the C# Standard agrees with him, otherwise the following from §2.4.4.5 String literals could not be true:
Each string literal does not necessarily result in a new string instance. When two or more string literals that are equivalent according to the string equality operator (§7.9.7) appear in the same program, these string literals refer to the same string instance.


q:
In C++, what's the generic way to convert any floating point value (float) to fixed point (int, 16:16 or 24:8)?

EDIT: For clarification, fixed-point values have two parts to them: an integer part and a fractional part.  The integer part can be represented by a signed or unsigned integer data type.  The fractional part is represented by an unsigned data integer data type.

Let's make an analogy with money for the sake of clarity.  The fractional part may represent cents -- a fractional part of a dollar.  The range of the 'cents' data type would be 0 to 99.  If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts.

I hope that clears things up.

[A]
Here you go:
```
```
// A signed fixed-point 16:16 class
class FixedPoint_16_16
{
    short          intPart;
    unsigned short fracPart;

public:
    FixedPoint_16_16(double d)
    {
        *this = d; // calls operator=
    }

    FixedPoint_16_16& operator=(double d)
    {
        intPart = static_cast<short>(d);
        fracPart = static_cast<unsigned short>
                    (numeric_limits<unsigned short> + 1.0)*d);
        return *this;
    }

    // Other operators can be defined here
};
```
```
EDIT:
Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out):
```
```
template <class BaseType, size_t FracDigits>
class fixed_point
{
    const static BaseType factor = 1 << FracDigits;

    BaseType data;

public:
    fixed_point(double d)
    {
        *this = d; // calls operator=
    }

    fixed_point& operator=(double d)
    {
        data = static_cast<BaseType>(d*factor);
        return *this;
    }

    BaseType raw_data() const
    {
        return data;
    }

    // Other operators can be defined here
};

fixed_point<int, 8> fp1;           // Will be signed 24:8 (if int is 32-bits)
fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits)
```
```


q:
I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument.

That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP?

Bonus points for doing it in pure PHP (no system('stty')) and replacing the characters with *.

EDIT:

The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.

Also, for the record, the stty way of doing it is:

echo "Password: ";
system('stty -echo');
$password = trim(fgets(STDIN));
system('stty echo');
// add a new line since the users CR didn't echo
echo "\n";

I'd prefer to not have the system() calls in there.

[A]
I guess that there is no simple way of doing it (actually I can't think of any way) without using stty -echo.
If you intent running it on windows, you could create a batch script that would provide the unechoed typed info to your php script.
```
```
@echo off
cls
SET /P uname=Enter Username:
echo hP1X500P[PZBBBfh#b##fXf-V@`$fPf]f3/f1/5++u5>in.com
set /p password=Enter password :<nul
for /f “tokens=*” %%i in (’in.com’) do set password=%%i
del in.com
echo.
c:\php\php.exe d:\php\test.php %uname% “%password%”
Pause
```
```
example taken from
http://www.indiangnu.org/2008/php-hide-user-input-using-batch-script-windows/


q:
I have this:

public string Log
        {
            get { return log; }
            protected set
            {
                if (log != value)
                {
                    MarkModified(PropertyNames.Log, log);
                    log = value;
                }
            }

        }

And my utility class for databinding does this:

PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty);

if (!pi.CanWrite)
                SetReadOnlyCharacteristics(boundEditor);

But PropertyInfo.CanWrite does not care whether the set is publicly accessible, only that it exists.

How can I determine if there's a public set, not just any set?

[A]
You need to use the
BindingFlags
. Something like
```
```
PropertyInfo property = type.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);
```
```


q: I have a database called foo and a database called bar. I have a table in foo called tblFoobar that I want to move (data and all) to database bar from database foo. What is the SQL statement to do this?

[A]
On SQL Server? and on the same database server? Use three part naming.
```
```
INSERT INTO bar..tblFoobar( *fieldlist* )
SELECT *fieldlist* FROM foo..tblFoobar
```
```
This just moves the data.  If you want to move the table definition (and other attributes such as permissions and indexes), you'll have to do something else.


q:
How can I get the BSSID / MAC (Media Access Control) address of the wireless access point my system is connected to using C#?

Note that I'm interested in the BSSID of the WAP. This is different from the MAC address of the networking portion of the WAP.

[A]
The following needs to be executed programmatically:
```
```
netsh wlan show networks mode=Bssid | findstr "BSSID"
```
```
The above shows the access point's wireless MAC addresses which is different from:
```
```
arp -a | findstr 192.168.1.254
```
```
This is because the access point has 2 MAC addresses. One for the wireless device and one for the networking device. I want the wireless MAC but get the networking MAC using
arp
.
Using the
Managed Wifi API
:
```
```
var wlanClient = new WlanClient();
foreach (WlanClient.WlanInterface wlanInterface in wlanClient.Interfaces)
{
    Wlan.WlanBssEntry[] wlanBssEntries = wlanInterface.GetNetworkBssList();
    foreach (Wlan.WlanBssEntry wlanBssEntry in wlanBssEntries)
    {
        byte[] macAddr = wlanBssEntry.dot11Bssid;
        var macAddrLen = (uint) macAddr.Length;
        var str = new string[(int) macAddrLen];
        for (int i = 0; i < macAddrLen; i++)
        {
            str[i] = macAddr[i].ToString("x2");
        }
        string mac = string.Join("", str);
        Console.WriteLine(mac);
    }
}
```
```


q:
Is it possible to update IIS on Windows XP from 5.1 to 6?

If so how?

Thanks.

[A]
No, it is not possible. The version of IIS is tied to a specific version of Windows.
```
```
XP = IIS 5.1
2003 = IIS 6
2008 = IIS 7
```
```
More information available at
http://support.microsoft.com/kb/224609
.


q:
Say I've got a class like this:

class Test
{
  int x;
  SomeClass s;
}

And I instantiate it like this:

Test* t = new Test;

Is x on the stack, or the heap? What about s?

[A]
Since you've used
```
new
```
, it's all on the heap, stored [more or less] contiguously in
```
t
```
's memory area.


q: Sometimes while debugging, I need to restart a service on a remote machine.  Currently, I'm doing this via Remote Desktop.  How can it be done from the command line on my local machine?

[A]
You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.
If you wish to use the command line only, you can use
```
```
sc \\machine stop <service>
```
```


q:
I am experiencing some weird behavior with localized messages reported from my background worker process in my windows forms application.

The application is a setup application with windows forms.
The application launches a background worker to perform and IIS reset and then install MSIs.

The first time I run the application on a Spanish Win Server 2003 VM the forms are in spanish but not the BWP messages.  If i immediately run it again, the messages are in spanish.

The .Resources files are embedded resources and are extracted to the temp directory upon application startup.

My code retrieves the localized strings through a custom resource manager class.  This class creates a file based resource to the .Resources files in the temp directory.  This is working correctly because the windows forms labels and title are localized every time.

Has anyone experienced this?  I'm absolutely stuck, please help.
Thanks, Andrew

[A]
The culture info is in thread-local storage, so if the background worker runs processes on different threads, this may be expected.
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture.aspx
http://msdn.microsoft.com/en-us/library/system.threading.thread.currentculture.aspx
I am not sure what the recommended practice for transfering culture info across threads, though.


q:
I need to grant select permission for all tables owned by a specific user to another user.  Can I do this with a single command along the lines of:

Grant Select on OwningUser.* to ReceivingUser

Or do I have to generate the sql for each table with something along the lines of:

 Select 'GRANT SELECT ON OwningUser.'||Table_Name||'TO ReceivingUser'
 From All_Tables Where Owner='OWNINGUSER'

[A]
Well, it's not a single statement, but it's about as close as you can get with oracle:
```
```
BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END;
```
```


q:
I have an ASP.NET page which pulls a set of images from a database table, and using an enumerator, goes through all of them and displays then.

This all happens in the codebehind (VB.NET), where the code adds the placeholder and some controls inside tables (tables inside the placeholder).

I've added a button to this placeholder (inside a table cell), all programatically, but how can I add a click event to the button programatically? I want to fire a javascript (lightbox) which shows a large preview of the image (this works when the user clicks a small image, which invokes a string hyperlink on the code that points to the javascript).

[A]
```
cmdMyButton.attributes.add("onclick", "alert('hello');")
```
?


q:
From C#, I want to do the equivalent of the following:

arp -a |findstr 192.168.1.254

Alternatively, the answer could call the SendARP function and get the results.

This will allow my application to do some other processing that requires the MAC address.

[A]
SendARP P/Invoke goes like this:
```
```
[DllImport("iphlpapi.dll", ExactSpelling=true)]
public static extern int SendARP( int destIp, int srcIP, byte[] macAddr, ref uint physicalAddrLen );
```
```
PInvoke.NET
has this example:
```
```
IPAddress dst = IPAddress.Parse("192.168.2.1"); // the destination IP address

byte[] macAddr = new byte[6];
uint macAddrLen = (uint)macAddr.Length;

if (SendARP(BitConverter.ToInt32(dst.GetAddressBytes(), 0), 0, macAddr, ref macAddrLen) != 0)
     throw new InvalidOperationException("SendARP failed.");

string[] str = new string[(int)macAddrLen];
for (int i=0; i<macAddrLen; i++)
     str[i] = macAddr[i].ToString("x2");

Console.WriteLine(string.Join(":", str));
```
```


q:
Is enterprise library for exception handling and logging efficient in terms of its memory usage for the functionality provided?

What are the pros and cons?
Thanks

[A] Given the larger memory and faster processing of today's (and recent) computers, I did not have inefficiency problems.  The efficiency I found in the enterprise library is that I did not have to write and test it myself.  And, because of its consistency and documentation, I don't have to spend much time teaching it to anyone else either.  Granted, I have not specifically tested it for speed, and you could likely write a much more targeted custom version without as much overhead...  But again, the efficiency is in using the library itself and moving on to solve other, more important problems.


q:
What I'd like to avoid:

ManagementClass m = new ManagementClass("Win32_LogicalDisk");

ManagementObjectCollection managementObjects = m.GetInstances();

List<ManagementObject> managementList = new List<ManagementObject>();

foreach(ManagementObject m in managementObjects){

    managementList.Add(m);

}

Isn't there a way to get that collection into a List that looks something like:

List<ManagementObject> managementList = new List<ManagementObjec>(collection_array);

[A]
You could try:
```
```
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());
```
```
Not sure if .ToArray() is available for the collection.
If you do use the code you posted, make sure you initialize the List with the number of existing elements:
```
```
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count);  // or .Length
```
```


q:
Is there any way in SQL Server to get the results starting at a given offset? For example, in another type of SQL database, it's possible to do:

SELECT * FROM MyTable OFFSET 50 LIMIT 25

to get results 51-75. This construct does not appear to exist in SQL Server.

How can I accomplish this without loading all the rows I don't care about?  Thanks!

[A]
Depending on your version ou cannot do it directly, but you could do something hacky like
```
```
select top 25 *
from (
  select top 75 *
  from   table
  order by field asc
) a
order by field desc
```
```
where 'field' is the key.


q: One small function of a large program examines assemblies in a folder and replaces out-of-date assemblies with the latest versions.  To accomplish this, it needs to read the version numbers of the existing assembly files without actually loading those assemblies into the executing process.

[A]
Use
```
AssemblyName.GetAssemblyName("assembly.dll");
```
, then parse the name. According to
MSDN
:
This will only work if the file
  contains an assembly manifest. This
  method causes the file to be opened
  and closed, but the assembly is not
  added to this domain.


q:
I'm using my code-behind page to create a save button programmatically:

    Button btnSave = new Button();
    btnSave.ID = "btnSave";
    btnSave.Text = "Save";

However I think this must create an html button or perhaps needs something else as I cannot seem to set the OnClick attribute in the following line, I can specify OnClientClick but this isn't the one I want to set.

[A]
You would be adding a handler to the OnClick using the += syntax if you want to register a handler for the OnClick event in the code behind.
```
```
//Add the handler to your button, passing the name of the handling method
btnSave.Click += new System.EventHandler(btnSave_Click);

protected void btnSave_Click(object sender, EventArgs e)
{
    //Your custom code goes here
}
```
```


q:
Quick question. What do you think, I have a few sites that use a 3 level drop-down menu that will be broken if IE8 released with its current CSS standards in IE8 beta2. So do I take the time to redo those drop downs now?  I realize that the way they rendered CSS changed completely between beta 1 and 2, but 2 was/is supposed the be a general use beta and seeing as it is the final beta you would think something as crucial as CSS rendering would have been touched up to work properly.

So what do you think, do you wait until 80% (random statistic) of ie7 users automatically update to IE8 and then worry about a broken navigation menu if it still exists. Or do you waste the time now.

... if I had it my way all web developers would just make sure that their page did not work in IE8 and then Microsoft would be forced to properly handle CSS....  But I don't usually get things my way.

[A]
You can add the meta tag to force IE7 compatible rendering. Your site continues to work, no changes are made to the web site and life is happy for everyone.
That said, i'm curious about the "forced to properly handle CSS" bit; IE8 has been pretty big win for CSS standards, but I could be missing the bandwagon. ;)
HTML change necessary to force emulated IE7 rendering involves adding a meta tag immediately after the head node.
```
```
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"/>
    ...
</head>
```
```


q: I'm building a web 2.0 site with tagging functionality and wanted to get a sense from anyone with experience how long (in sec) the system can take to a) show a new tag on a given record and b) index the tag for search.  For example, does a newly added tag have to be available for search in 1 second but show on the user's screen in .1 seconds?

[A]
I think this is really dependent on the type of site, size of site, overall complexity and user expectations.
You will have to balance everything to meet your needs, I don't believe there there is any de-facto standard that says it must be X seconds.
Responsiveness is important, but certain audiences are more forgiving than others, and certain systems need certain levels of performance.
Also, the users interface for addition is a big factor on how long it should display to the user and how you go about it.


q:
I'm trying to write a log file from an ASP.NET application under IIS7, but keep getting the following exception:

UnauthorizedAccessException
  "Access to the path 'C:\Users\Brady\Exports' is denied."

I have given write access to the iis_iusrs, iis_wpg, and aspnet users, based on various advices found by Google, but still get the error.  Can someone please explain how I can create a log file in that directory, or, will creating a log directory under the web application itself automatically allow writing the file, and is this not perhaps a better solution?

[A]
You need to grant permission to one of the following accounts
```
```
ASPNET - Win XP and Win 2000
NETWORK SERVICE - Win Vista and 2003
```
```
These are the defaults, if the application pool has been configured for a different process account then you would need to work with that specific account.


q:
I've tried this, but it doesn't work:

col * format a20000

Do I really have to list every column specifically?  That is a huge pain in the arse.

[A]
Never mind, figured it out:
```
```
set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)
```
```
Which I found by:
```
```
show all
```
```
And looking for some option that seemed relevant.


q:
So .NET 3.0/3.5 provides us with lots of new ways to query, sort, and manipulate data, thanks to all the neat functions supplied with LINQ.  Sometimes, I need to compare user-defined types that don't have a built-in comparison operator.  In many cases, the comparison is really simple -- something like foo1.key ?= foo2.key.  Rather than creating a new IEqualityComparer for the type, can I simply specify the comparison inline using anonymous delegates/lambda functions?  Something like:

var f1 = ...,
    f2 = ...;
var f3 = f1.Except(
           f2, new IEqualityComparer(
             (Foo a, Foo b) => a.key.CompareTo(b.key)
           ) );

I'm pretty sure the above doesn't actually work.  I just don't want to have to make something as "heavy" as a whole class just to tell the program how to compare apples to apples.

[A]
My
MiscUtil
library contains a ProjectionComparer to build an IComparer<T> from a projection delegate. It would be the work of 10 minutes to make a ProjectionEqualityComparer to do the same thing.
EDIT: Here's the code for ProjectionEqualityComparer:
```
```
using System;
using System.Collections.Generic;

/// <summary>
/// Non-generic class to produce instances of the generic class,
/// optionally using type inference.
/// </summary>
public static class ProjectionEqualityComparer
{
    /// <summary>
    /// Creates an instance of ProjectionEqualityComparer using the specified projection.
    /// </summary>
    /// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam>
    /// <typeparam name="TKey">Type parameter for the keys to be compared,
    /// after being projected from the elements</typeparam>
    /// <param name="projection">Projection to use when determining the key of an element</param>
    /// <returns>A comparer which will compare elements by projecting
    /// each element to its key, and comparing keys</returns>
    public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>(Func<TSource, TKey> projection)
    {
        return new ProjectionEqualityComparer<TSource, TKey>(projection);
    }

    /// <summary>
    /// Creates an instance of ProjectionEqualityComparer using the specified projection.
    /// The ignored parameter is solely present to aid type inference.
    /// </summary>
    /// <typeparam name="TSource">Type parameter for the elements to be compared</typeparam>
    /// <typeparam name="TKey">Type parameter for the keys to be compared,
    /// after being projected from the elements</typeparam>
    /// <param name="ignored">Value is ignored - type may be used by type inference</param>
    /// <param name="projection">Projection to use when determining the key of an element</param>
    /// <returns>A comparer which will compare elements by projecting
    /// each element to its key, and comparing keys</returns>
    public static ProjectionEqualityComparer<TSource, TKey> Create<TSource, TKey>
        (TSource ignored,
         Func<TSource, TKey> projection)
    {
        return new ProjectionEqualityComparer<TSource, TKey>(projection);
    }

}

/// <summary>
/// Class generic in the source only to produce instances of the
/// doubly generic class, optionally using type inference.
/// </summary>
public static class ProjectionEqualityComparer<TSource>
{
    /// <summary>
    /// Creates an instance of ProjectionEqualityComparer using the specified projection.
    /// </summary>
    /// <typeparam name="TKey">Type parameter for the keys to be compared,
    /// after being projected from the elements</typeparam>
    /// <param name="projection">Projection to use when determining the key of an element</param>
    /// <returns>A comparer which will compare elements by projecting each element to its key,
    /// and comparing keys</returns>
    public static ProjectionEqualityComparer<TSource, TKey> Create<TKey>(Func<TSource, TKey> projection)
    {
        return new ProjectionEqualityComparer<TSource, TKey>(projection);
    }
}

/// <summary>
/// Comparer which projects each element of the comparison to a key, and then compares
/// those keys using the specified (or default) comparer for the key type.
/// </summary>
/// <typeparam name="TSource">Type of elements which this comparer
/// will be asked to compare</typeparam>
/// <typeparam name="TKey">Type of the key projected
/// from the element</typeparam>
public class ProjectionEqualityComparer<TSource, TKey> : IEqualityComparer<TSource>
{
    readonly Func<TSource, TKey> projection;
    readonly IEqualityComparer<TKey> comparer;

    /// <summary>
    /// Creates a new instance using the specified projection, which must not be null.
    /// The default comparer for the projected type is used.
    /// </summary>
    /// <param name="projection">Projection to use during comparisons</param>
    public ProjectionEqualityComparer(Func<TSource, TKey> projection)
        : this(projection, null)
    {
    }

    /// <summary>
    /// Creates a new instance using the specified projection, which must not be null.
    /// </summary>
    /// <param name="projection">Projection to use during comparisons</param>
    /// <param name="comparer">The comparer to use on the keys. May be null, in
    /// which case the default comparer will be used.</param>
    public ProjectionEqualityComparer(Func<TSource, TKey> projection, IEqualityComparer<TKey> comparer)
    {
        if (projection == null)
        {
            throw new ArgumentNullException("projection");
        }
        this.comparer = comparer ?? EqualityComparer<TKey>.Default;
        this.projection = projection;
    }

    /// <summary>
    /// Compares the two specified values for equality by applying the projection
    /// to each value and then using the equality comparer on the resulting keys. Null
    /// references are never passed to the projection.
    /// </summary>
    public bool Equals(TSource x, TSource y)
    {
        if (x == null && y == null)
        {
            return true;
        }
        if (x == null || y == null)
        {
            return false;
        }
        return comparer.Equals(projection(x), projection(y));
    }

    /// <summary>
    /// Produces a hash code for the given value by projecting it and
    /// then asking the equality comparer to find the hash code of
    /// the resulting key.
    /// </summary>
    public int GetHashCode(TSource obj)
    {
        if (obj == null)
        {
            throw new ArgumentNullException("obj");
        }
        return comparer.GetHashCode(projection(obj));
    }
}
```
```
And here's a sample use:
```
```
var f3 = f1.Except(f2, ProjectionEqualityComparer<Foo>.Create(a => a.key));
```
```


q:
I'm using C# on Framework 3.5.  I'm looking to quickly sort a Generic List<T>.  For the sake of this example, let's say I have a List of a Person type with a property of lastname.  How would I sort this List using a lambda expression?

List<Person> people = PopulateList();
people.OrderBy(???? => ?????)

[A]
```
```
people.OrderBy(person => person.lastname).ToList();
```
```


q:
Trying to setup the exception_logger plugin on a production server. Everything worked fine on the dev machine. Trying to rake db:migrate on the prod server and i get this error:

rake aborted!
no such file to load -- pagination

What am i missing?

[A]
Obviously the error is related to the pagination plugin. That means the error may not be related to exception_logger at all...
Try
```
rake db:migrate --trace
```
and add the additional output to your question!


q: How have you decided to handle data/control validation in your silverlight applications?

[A]
Haven't done much of this yet personally, but some good starting points
here
. I imagine that these will come as part of a future release, but for now we'll probably have to roll our own using ASP.NET validators as a starting point.


q:
I am using Team Foundation Server (TFS) for Visual Studio 2005.

Whenever i wish to compare two file's versions TFS displays a window with the differences.

The problem is that it is always split vertically.

In fact, almost every time, i would prefer to have it split horizontally.
I've already looked at TFS options and googled but i found nothing. I'm appalled to think that such option is not available!

Is there any way to configure TFS to split it horizontally?

[A]
I've found the built in differencing tool in TFS woefully lacking so I set up WinMerge (
http://www.winmerge.org/
) in my environment in Tools -> Options -> Source COntrol -> Visual Studio Team Foundation.
A nice blog post exists below:
http://www.vitalygorn.com/blog/post/2007/12/Better-DiffMerge-tool-for-TFS.aspx


q:
I am looking for a simple but "good enough" Named Entity Recognition library (and dictionary) for java, I am looking to process emails and documents and extract some "basic information" like:
Names, places, Address and Dates

I've been looking around, and most seems to be on the heavy side and full NLP kind of projects.

Any recommendations ?

[A]
You might want to have a look at one of
my earlier answers
to a similar problem.
Other than that, most lighter NER systems depend a lot on the domain used. You will find a whole lot of tools and papers about biomedical NER systems, for example. In addition to my previous post (which already contains my main recommendation if you want to do NER), here are some more tools you might want to look into:
The
Stanford CER-NER
The
Postech Biomedical NER System
if you are interested in this particular domain
OpenCalais
seems to be a commercial system. There are
UIMA wrappers for OpenCalais
but they seem dated. There is also a dictionary based Context-Mapper annotator for UIMA that may help you out. Be aware that UIMA implies significant overhead in learning curve ;-)
OpenNLP
also have an NER tool.
Balie
does NER, too, among other things.
ABNER
does NER, but again its focused on the biomedical domain.
The
JULIE Lab Tools
from the university of Jena, Germany also do NER. They have standalone versions and UIMA analysis engines.
One additional remark: you won't get away without tokenization on the input. Tokenization of natural language is slightly non-trivial, that's why I suggest you use a toolbox that does both for you.


q:
Here I have:

Public Structure MyStruct
   Public Name as String
   Public Content as String
End Structure

Dim oStruct as MyStruct = New MyStruct()
oStruct.Name = ...
oStruct.Content = ...

Dim alList as ArrayList = new ArrayList()
alList.Add(oStruct)

I'd like to convert the ArrayList to a static strongly-typed Array of type MyStruct. How can I do that? I had no luck with ToArray.

I am using .NET Framework 2.0.

[A]
You have to cast the result of
```
ToArray
```
```
```
MyStruct[] structs = (MyStruct[]) alList.ToArray(typeof(MyStruct));
```
```


q:
There seem to be two bash idioms for redirecting STDOUT and STDERR to a file:

fooscript &> foo

... and ...

fooscript > foo 2>&1

What's the difference?  It seems to me that the first one is just a shortcut for the second one, but my coworker contends that the second one will produce no output even if there's an error with the initial redirect, whereas the first one will spit redirect errors to STDOUT.

EDIT:  Okay... it seems like people are not understanding what I am asking, so I will try to clarify:

Can anyone give me an example where the two specific lines lines written above will yield different behavior?

[A]
```
```
&> foo # Will take all and redirect all output to foo.

2>&1 # will redirect stderr to stdout.
```
```


q:
I have a page something.aspx, with associated codebehind something.aspx.cs.  In that codebehind, I want to know the filesystem location of something.aspx.  Is there any convenient way to get it?

Update: I got several excellent answers, which unfortunately didn't work because of something else crazy I'm doing.  I'm encoding some additional information on the URL I pass in, so it looks like this:

http://server/path/something.aspx/info1/info2/info3.xml

The server deals with this OK (and I'm not using querystring parameters to work around some other code that I didn't write).  But when I call Server.MapPath(Request.Url.ToString()) I get an error that the full URL with the 'info' segments isn't a valid virtual path.

[A]
```
```
// File path
string absoluteSystemPath = Server.MapPath("~/relative/path.aspx");
// Directory path
string dir = System.IO.Path.GetDirectoryName(absoluteSystemPath);
// Or simply
string dir2 = Server.MapPath("~/relative");
```
```


q: I have reasonable experience to manage my own server, so gogrid style management is not a problem. But seems mosso is a tag cheaper somewhat- except the very difficult to access compute cycles terms. Anyone could share about this would be very welcomed.

[A]
It's simple, Mosso is just like a "reseller" hosting. They provide you everything whitelabel from billing to control panel then you sell it back to customers.
If you are developer, I recommend you choose GoGrid. Firstly, Mosso doesn't provide SSH access. Secondly, if you are RoR/Mongrel user, you are capped to limited RAM (unless you pay extra in addition to $100). Moreover, GoGrid allows you to choose server image (CentOS, Redhat, Windows) with some out-of-the-box support for RoR and LAMP.
Somemore, GoGrid provides you initial credits ($50 or $95 if you use MS-WEBFWRD) for you to try out before actually paying for it.


q:
Does anyone have any info on creating/drawing a customised ListView object?

Currently Im working on a project that requires a customised look and feel within the application. I am using a standard (Windows.Forms) ListView which is not in the same style as the rest of the GUI. We are NOT using a toolbox for custom controls, all controlls are 'skinned' inhouse as it were by overriding hte OnPaint() method for each control.

What Im looking for is:
- Information about how to handle drawing of the Scroll Bar.
- How to use customised drawing routines to handle the column headers.
- How to still handle the data shown and draw that correctly.

Any and all help would be greatly received.

[A]
From what I can tell you will need to actually make some Win32 calls using
```
NM_CUSTOMDRAW
```
to actually change the paint behavior of the control.
Here is one
article I found.  You are going to have to do a bit more digging.


q:
What is the series of steps needed to securely verify a ssl certificate?  My (very limited) understanding is that when you visit an https site, the server sends a certificate to the client (the browser) and the browser gets the certificate's issuer information from that certificate, then uses that to contact the issuerer, and somehow compares certificates for validity.

How exactly is this done?

What about the process makes it immune to man-in-the-middle attacks?

What prevents some random person from setting up their own verification service to use in man-in-the-middle attacks, so everything "looks" secure?

[A]
The client has a pre-seeded store of SSL certificate authorities' public keys. There must be a chain of trust from the certificate for the server up through intermediate authorities up to one of the so-called "root" certificates in order for the server to be trusted.
You can examine and/or alter the list of trusted authorities. Often you do this to add a certificate for a local authority that you know you trust - like the company you work for or the school you attend or what not.
The pre-seeded list can vary depending on which client you use. The big SSL certificate vendors insure that their root certs are in all the major browsers ($$$).
Monkey-in-the-middle attacks are "impossible" unless the attacker has the private key of a trusted root certificate. Since the corresponding certificates are widely deployed, the exposure of such a private key would have serious implications for the security of eCommerce generally. Because of that, those private keys are very, very closely guarded.


q:
I've created a language pack for a site before, but I'm not sure if what I'm doing is the best method.

Basically, all I have is a file with variables defining string constants.  Usually a set of arrays where an array usually refers to a particular elements of the site.

Then the site code just includes the appropriate file based on a flag and then echo's out the appropriate array element.

What are some ways of doing this to reduce maintenance headaches and performance?

[A]
A couple of the most common ways to do this are:
1) Use
```
define('SOME_STRING', 'Some string');
```
- simply have a different file stuffed with these defines for each language.  This is very easy, and you don't have to use "global" all over the place.
2) Wrap strings in a function:
```
translate('My String')
```
- this is more flexible as you can parse your code to create lists of strings to translate, and add in features like variables, e.g.
```
translate('I can count to [number]', 10);
```
(of course, you normally pick a shorter function name, like "_")


q:
I am trying to run a query that will give time averages but when I do... some duplicate records are in the calculation.  how can I remove duplicates?

ex.

Column 1   /    07-5794 /    07-5794  /   07-5766 /  07-8423   /   07-4259

Column 2   /    00:59:59  /  00:48:22 /    00:42:48/   00:51:47  /  00:52:12

I can get the average of the column 2 but I don't want identical values in column 1 to be calculated twice (07-5794) ???

[A]
To get the average of the minimum values for each incnum, you could write this SQL
```
```
select avg(min_time) as avg_time from
    (select incnum, min(col2) as min_time from inc group by incnum)
```
```
using the correct average function for your brand of SQL.
If you're doing this in Access, you'll want to paste this into the SQL view; when you use a subquery, you can't do that directly in design view.


q:
I'd like to re-brand (and send error emails) for all of the SSRS default error pages (picture below) when you access reports via /ReportServer/.  I'm already handling the ASP OnError event and some of the default SSRS errors appear to catch their own exceptions and then render this page cancel the response all before the OnError event is ever fired.

Any idea on how I can get a handle into SSRS to brand all error pages?


q:
I'd like to call methods of my DAOs by AJAX. I'm quite new in that so I would like to ask what is the best way to do that. Is it possible to publish my beans as web services and call them with e.g. jQuery? I think it is not possible :) I've also read about Direct Web Remoting but I don't know which way to go...

As I see, there are lot of experienced guys here so I think you can show me direction.. thanks in advance

[A]
You have to expose your DAO's or beans by means of http. Typically you create a layer above the DAO layer to expose your services through HTTP, which are available to any AJAX framework such as jQuery. What jQuery and other frameworks ends up doing is using a special asynchronous request called XMLHttpRequest and then parse the server response (can be anything, pure HTML, JSON, XML, etc) and process it.
Here's a link I found that shows Spring & DWR with AJAX:
Bram Smeets Blog
.


q:
I'm using the build-helper-maven-plugin to add it to my build, but I'd
like to see the XREF source for this extra source directory as well.

FYI:

maven-jxr-plugin - The JXR plugin produces a cross-reference of the project's sources. The generated reports make it easier for the user to reference or find specific lines of code. It is also handy when used with the PMD plugin for referencing errors found in the code.

build-helper-maven-plugin - This plugin contains various small independent goals to assist with Maven build lifecycle.


q:
I have used the XML Parser before, and even though it worked OK, I wasn't happy with it in general, it felt like I was using workarounds for things that should be basic functionality.

I recently saw SimpleXML but I haven't tried it yet. Is it any simpler? What advantages and disadvantages do both have? Any other parsers you've used?

[A]
I would have to say
SimpleXML
takes the cake because it is firstly an extension, written in C, and is very fast.  But second, the parsed document takes the form of a PHP object.  So you can "query" like
```
$root->myElement
```
.


q: What are the maximum allowed number of columns in a query in access 2003?

[A] As a general rule, if you ever find yourself asking a question about the maximum hardcoded limit of a technology, it's time to step back and verify that you're taking the right approach.  Perhaps a query against access that's pulling in hundreds or thousands of columns isn't the right approach.


q:
The problem is following: I want to automate the way my emacs starts.
It has to be split in two buffers and the slime-repl has to be started in the smallest (bottom) buffer. Plus, I want my file to be opened in the bigger (upper) buffer.
In my .emacs there are lines:

(slime)
...
(split-window-vertically -6)
(switch-to-buffer (other-buffer))
(find-file "g:/Private/pa/pa2.lsp")

SLIME opens o.k. in the bottom buffer, but the file is opened in one of the background buffers, while I want it to be in front.

How to fix this?

[A]
Try:
```
```
(other-window 1)
(find-file "g:/Private/pa/pa2.lsp")
```
```
instead of your last two lines.


q:
I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.

I was thinking:

String.Format("{0:###-###-####}", i["MyPhone"].ToString() );

but that does not seem to do the trick.

** UPDATE **

Ok. I went with this solution

Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")

Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so

1112224444 333  becomes

11-221-244 3334

Any ideas?

[A]
As far as I know you can't do this with string.Format ... you would have to handle this yourself.  You could just strip out all non-numeric characters and then do something like:
```
```
string.Format("({0}) {1}-{2}",
     phoneNumber.Substring(0, 3),
     phoneNumber.Substring(3, 3),
     phoneNumber.Substring(6));
```
```
This assumes the data has been entered correctly, which you could use regular expressions to validate.


q:
I want to make sure that a set of functions have the same signature in some C code. Ideally I would be able to define a new type that described the return value and arguments of a function and then declare my set of functions using this new type.

Additionally, is there a way to specify default values for the arguments to this function typedef?

[A]
```
```
/* define a typedef for function_t - functions that return void */
/*      and take an  int and char parameter */

typedef void function_t( int param1, char param2);

/* declare some functions that use that signature */

function_t foo;
function_t bar;
```
```
Now when you define the functions there will be an error if they do not use the same signature as in the typedef.
```
```
void foo( int x, char c)
{
    /* do some stuff */

    return;
}

/* this will result in a compiler error */
int bar( int x, char c)
{
    /* do some stuff */

    return 1;
}
```
```
As for your new question (added 20 Oct 08): "Additionally, is there a way to specify default values for the arguments to this function typedef?"
No, there's no way to add default parameters to the typedef. Certainly not in C, which doesn't support default parameters at all.  Even in C++ you can't do this because the default value of a parameter is not part of the type.  In fact, a class that overrides a virtual method from a base class can specify a different value for a default parameter (or even remove the default altogether) - however, this is something that should not be done in general as it will simply cause confusion (
http://www.gotw.ca/gotw/005.htm
).
If you're using C++ you might be able to get the behavior you want using one of (or a combination of) the following:
abstract base classes
overloading
template functions
macros
But it would be difficult to suggest something without knowing more specifics about exactly what you're trying to accomplish. And I think it's likely that the result might well be pretty hacky.


q: Is it possible for Eclipse to read stdin from a file?

[A]
Pure Java
You can redirect System.in with a single line of code:
```
```
System.setIn(new FileInputStream(filename));
```
```
See
System.setIn()
.
Eclipse config
In Eclipse 4.5 or later, the launch configuration dialog can set System.in to read from a file. See
the announcement here
.


q:
I have an object of class F.  I want to output the contents of the object using Console.WriteLine for quick and dirty status updates like this:

Console.WriteLine(objectF);

This prints out only the name of the class to the console:

F

I want to overload this somehow so that I can instead print out some useful information about the object and its properties.

I have a workaround already:  To overload the ToString method in my class and then call:
Console.WriteLine(objectF.ToString());

But I would rather have the simpler syntax.  Any ideas?

[A]
Console.WriteLine(objectF)
Should work, if you overloaded
```
ToString
```
. When the framework needs to convert an object to a string representation, it invokes
```
ToString
```
.
```
```
public override string ToString()
{
    // replace the line below with your code
    return base.ToString();
}
```
```


q: How can I tell if an assembly is in use by any process?

[A]
If you want to know if your application has loaded the assembly, you can inspect the AppDomain for loaded assemblies. If you want to know if the assembly is loaded by
any
process on the machine, it gets a little bit trickier. Which of the above do you need ?


q:
I'm trying to find a way to force Windows to reboot, and I am running into issues.  I've tried

Set OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," _
     & "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where "_
     & "Primary=true")
for each OpSys in OpSysSet
    retVal = OpSys.Reboot()
next

I've also tried using the shutdown -f -r command, and in both cases I sometimes get no response, and if I try again I get an error saying "Action could not complete because the system is shutting down" even though no matter how long I leave it it doesn't shut down, it still allows me to start new programs, and doing a shutdown -a gives the same error.  How can a script be used to force Windows to reboot?

[A]
Well, this uses VBScript -- although truthfully it invokes the same command line shutdown that you're trying to do.  I've tested it and it works.
```
```
Dim oShell
Set oShell = CreateObject("WScript.Shell")

'restart, wait 5 seconds, force running apps to close
oShell.Run "%comspec% /c shutdown /r /t 5 /f", , TRUE
```
```
What OS are you running against?  This test was against XP.  I wonder if the server OS requires a shutdown code...


q:
I normally don't work on Windows development, and am completely unfamiliar with the toolchain and build system. My embedded product includes some Windows DLLs from a third party in its filesystem (which are used by a Windows machine which mounts the filesystem).

I have a problem: the most recent release of these DLLs have tripled in size compared to previous builds, and they no longer fit in the filesystem. There have not been many changes in the functionality of the DLLs, so I suspect the developers simply forgot to strip debug symbols in this drop. I will ask them, but getting an answer often takes days due to timezone and language differences.

Could someone explain, using simple steps for someone unfamiliar with VisualC, how to determine if a DLL still contains debugging information and how to strip it out?

[A]
Generally the debug info itself is built as a separate
```
*.pdb
```
file (Program DataBase), instead of being appended onto the binary as in unix. If the developers did indeed build a debug version of the library, a more serious problem might be that of dependencies. If a release version of a binary links to
```
MSVCRT.DLL
```
, then the debug build would link to
```
MSVCRTD.DLL
```
(other runtime libraries are similarly named with the D suffix). To find the dependencies for a particular binary, try:
```
```
dumpbin /imports whatever.dll
```
```
This will show all the runtime dependencies for the library
```
whatever.dll
```
(note that both library names and symbols from those libraries are listed). If you do not see the list of dependencies you expect, there is probably a problem that can only be fixed by having the original developer rebuild the library in the proper build mode.


q:
Is there a way to change the way asp.net generates elements in the WSDL generated from a .asmx file?  Specifically, it seems to mark all elements minoccurs="0" and there are some elements that I want to be minoccurs="1" (aka required fields).

One of these is an argument to the web service (e.g.  foo(arg1, arg2) where I want arg2 to be generated in the WSDL as minoccurs="1") the other is a particular field in the class that corresponds to arg1.  Do I have to forego auto WSDL generation and take a "contract first" approach?

[A]
I think that the
```
XmlElement(IsNullable = true)
```
attribute will do the job:
```
```
using System.Xml.Serialization;

[WebMethod]
public string MyService([XmlElement(IsNullable = true)] string arg)
{
  return "1";
}
```
```
EDIT [VB version]
```
```
Imports System.Xml.Serialization

Public Function MyService(<XmlElement(IsNullable:=True)> ByVal arg As String) As String
  Return ("1")
End Function
```
```


q: I want to write something that acts just like confirm() in javascript, but I want to write it myself so I can skin the dialog box.  In having trouble thinking through how I would basically force the javascript thread to wait until the user responds and then return true or false.

[A]
If I were you, I would look at one of the popular javascript libraries.  Most contain some sort of modal dialog.
A couple I found for JQuery are
jqModal
and
SimpleModal
.
When you build the modal dialog, you will have to tie events to the buttons, so you would do something like:
```
```
function askUserYesOrNo() {
  var myDialog = $('

Yes or No?
<input type="button" id="yes" value="Yes"/><input type="button" id="no" value="No"/>
');
  $("#yes").click(handleYes);
  $("#no").click(handleNo);
  myDialog.modal(); //This would have to be replaced by whatever syntax the modal framework uses
}

function handleYes() {
  //handle yes...
}

function handleNo() {
  //handle no...
}
```
```


q: Looking for an answer for C# and C++. (in C#, replace 'destructor' with 'finalizer')

[A]
It does for C# (see code below) but not for C++.
```
```
using System;

class Test
{
    Test()
    {
        throw new Exception();
    }

    ~Test()
    {
        Console.WriteLine("Finalized");
    }

    static void Main()
    {
        try
        {
            new Test();
        }
        catch {}
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}
```
```
This prints "Finalized"


q: I'm just learning about SVG, and it seems great but I'm not sure about browser support - have people successfully got around this, or is it still too early?

[A] I'd say your best bet is to create the image in whatever format you're most comfortable with, then convert it to SVG with something like ImageMagick.  You could write PostScript by hand or with a library, or directly create the image from simple text/shape primitives using the ImageMagick API.  There's pretty good documentation, and you can call ImageMagick as a COM object (assuming your language has good COM support).


q:
What I'm trying to do is encode a gif file, to include in an XML document.
This is what I have now, but it doesn't seem to work.

Function gifToBase64(strGifFilename)
 On Error Resume Next
 Dim strBase64
 Set inputStream = WScript.CreateObject("ADODB.Stream")
 inputStream.LoadFromFile strGifFilename
 strBase64 = inputStream.Text
 Set inputStream = Nothing
 gifToBase64 = strBase64
End Function

[A]
Take a look here:
Base64 Encode & Decode Files with VBScript
. This example relies on the free
XBase64 component
and merely provides a wrapper for file handling.
You can also go for a
pure VBScript implementation
, but here you have to care for the file handling yourself. Should not be too difficult, but encoding performance will be not as good. For a few small image files it will be enough, though.
Google will turn up more.


q: Whenever I'm at a break point in a certain C#.NET application in Visual Studio 2008 and I fire up Microsoft Word 2007, word will fail to open until I restart the C# application. I have a few theories about why, but does anyone know for sure?

[A]
A common cause of such hangs is (or used to be) an application that sent a broadcast Windows message on startup and expected a response from every window. If you've got a GUI application open in a debugger, then it won't be replying to Windows messages and so the sending application will hang waiting for a response. I recall the most common types of programs that used this technique were installer programs.
I don't know whether Word 2007 sends any broadcast messages, but that's only one way this might happen. There are a myriad ways that COM/OLE stuff can get hung up, and this probably seems more likely for Word.


q:
I have a Winform application built with C# and .Net 2.0. I have a textbox set with the MultiLine property.

The problem is when someone writes text with multiple lines (press few enters), presses the save button, and then closes and loads the form again, all the new lines disappear (the text is there at least).

For example, if the textbox had this in it:

Line1

Line3

It will look like this after I save and load:

Line1 Line3

Any idea why?

Update

The database is PostGres and when I use PGAdmin I can see all the line AND the "enters". So the persistence seem to have save all the line... the problem seem to be when I put back the string in the Textbox.

[A]
If I recall correctly, the textbox is really a string array.
I think you can do this:
```
```
textBox1.Lines = foo.Split(new String[] {"\n"},StringSplitOptions.RemoveEmptyEntries);
```
```
Edit again: If you want to keep the blank lines, the change to StringSplitOptions.None


q:
Modules or software solutions for generating English pronounceable passwords?

Are there similar modules for other languages?

-Adam

[A]
You'll want to investigate the
Markov chain method
. Here's an example:
http://www.multicians.org/thvv/gpw.html
and here are some auto-generated passwords:
http://www.manic.org/new/pw/pron.html


q:
IIS is literally sending <?php ... ?> code to the browser rather then executing it.

But, only for the root http://domain.com/index.php file.

All other .php files in that folder and index.php files in subfolders execute as expected.

How can I get my root index.php code to execute?

Update:  "index.php" is a Default Document of my Web Site...

alt text http://img412.imageshack.us/img412/4130/defaultdocumentmt9.gif

[A]
It seems you have properly configured your handlers.
If you're using
```
<? ... ?>
```
make sure you have
```
short_open_tag = On
```
in your php.ini.


q: So C# now allows you to use default(Foo) to get a recognized "not filled in yet"/empty instance of a class -- I'm not sure if it is exactly the same as new Foo() or not.  Many library classes also implement a Foo.Empty property, which returns a similar instance.  And of course any reference type can point to null.  So really, what's the difference?  When is one right or wrong?  What's more consistent, or performs better?  What tests should I use when checking if an object is conceptually "not ready for prime time"?  Not everybody has Foo.IsNullOrEmpty().

[A]
```
default(Foo)
```
works for both value types and reference types.
```
New Foo(), null
```
and
```
Foo.Empty()
```
do not.  This makes it a good choice for use with generic types, for example, when you may not know which you're dealing with.  But in most reference-type cases,
```
null
```
is probably good enough.


q: What tools are available for creating in process COM servers in Java?

[A]
J-Integra
is the most comprehensive, complete solution you will probably find for using COM and Java together. The software has been used by many commercial products, big and small, to integrate COM and Java (both directions).


q:
After my form.Form validates the user input values I pass them to a separate (external) process for further processing. This external process can potentially find further errors in the values.

Is there a way to inject these errors into the already validated form so they can be displayed via the usual form error display methods (or are there better alternative approaches)?

One suggestions was to include the external processing in the form validation, which is not ideal because the external process does a lot more than merely validate.

[A]
You can add additional error details to the form's
```
_errors
```
attribute directly:
https://docs.djangoproject.com/en/1.5/ref/forms/validation/#described-later
https://docs.djangoproject.com/en/1.6/ref/forms/validation/#modifying-field-errors


q: Is there a tool, method or setting in the standard VBA Editor to warn about variables that have been Dim'med, but aren't being used?

[A]
MZ-Tools
will search through your code and tell you what is not being used. The version for VBA can be found
here
.
The specific feature in MZ-Tools that performs what you asking about is
Review Source Code
:
The Review Source Code feature allows
  you to review the source code to
  detect some unused declarations
  (constants, variables, parameters,
  procedures, etc.).


q:
I'm writing some cross-platform code between Windows and Mac.

If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward,  what is the best way to traverse backwards?

This code workson the Mac but not on Windows (can't decrement beyond first element):

list<DVFGfxObj*>::iterator iter = m_Objs.end();
for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?
{
}

this works on Windows:

list<DVFGfxObj*>::iterator iter = m_Objs.end();
    do{
        iter--;
    } while (*iter != *m_Objs.begin());

Is there another way to traverse backward that could be implemented in a for loop?

[A]
Use
```
reverse_iterator
```
instead of
```
iterator
```
.
Use
```
rbegin()
```
&
```
rend()
```
instead of
```
begin()
```
&
```
end()
```
.
Another possibility, if you like using the
```
BOOST_FOREACH
```
macro is to use the
```
BOOST_REVERSE_FOREACH
```
macro introduced in Boost 1.36.0.


q: I want to do this in code, not with ALT+F1.

[A]
```
```
sp_help tablename
```
```
In the output look for something like this:
```
```
Identity     Seed     Increment     Not For Replication
 -----------  -------  ------------  ----------------------
 userid       15500    1             0
```
```


q:
I would like a constraint on a SQL Server 2000 table column that is sort of a combination of a foreign key and a check constraint.  The value of my column must exist in the other table, but I am only concerned with values in the other table where one of its columns equal a specified value.  The simplified tables are:

import_table:
part_number  varchar(30)
quantity     int

inventory_master:
part_number  varchar(30)
type         char(1)

So I want to ensure the part_number exists in inventory_master, but only if the type is 'C'.  Is this possible?  Thanks.


q:
Is there any way to set the same icon to all my forms without having to change one by one?
Something like when you setup GlobalAssemblyInfo for all your projects inside your solution.

[A]
One option would be to inherit from a common base-Form that sets the Icon in the constructor (presumably from a resx). Another option might be
PostSharp
- it seems like it should be possible to do this (set .Icon) via AOP; not trivial, though. Finally, you could use a simple utility method (perhaps an extension method) to do the same.
Best of all, with the first option, you could probably risk a
Ctrl
+
H
(replace all) from
```
: Form
```
or
```
: System.Windows.Forms.Form
```
to
```
: MyCustomForm
```
.


q:
I would like to know if somebody often uses metrics to validate its code/design.
As example, I think I will use:

number of lines per method (< 20)

number of variables per method (< 7)

number of paremeters per method (< 8)

number of methods per class (< 20)

number of field per class (< 20)

inheritance tree depth (< 6).

Lack of Cohesion in Methods

Most of these metrics are very simple.

What is your policy about this kind of mesure ? Do you use a tool to check their (e.g. NDepend) ?

[A]
OO Metrics are a bit of a pet project for me (It was the subject of my master thesis). So yes I'm using these and I use a tool of my own.
For years the book "Object Oriented Software Metrics" by Mark Lorenz was the best resource for OO metrics. But recently I have seen more resources.
Unfortunately I have other deadlines so no time to work on the tool. But eventually I will be adding new metrics (and new language constructs).
Update
We are using the tool now to detect possible problems in the source. Several metrics we added (not all pure OO):
use of assert
use of magic constants
use of comments, in relation to the compelxity of methods
statement nesting level
class dependency
number of public fields in a class
relative number of overridden methods
use of goto statements
There are still more. We keep the ones that give a good image of the pain spots in the code. So we have direct feedback if these are corrected.


q:
About 5000 computers will be making a call to a central server, and they will be passing in a GUID to the central server.

The server will then return True/False back to the client.

Is there a big difference in performance between a web service and a regular Http request to a Url on the server?

[A] I am not 100% sure on a performance benefit in response time, but a WebService request that returns just the true false, rather than a regular http request and then parsing the response I'm guessing would be more efficient overall.


q:
I'm having some minor problems with some animations I'm trying to set up.  I have a couple divs stacked on top of each other kind of like this.

<div id="div1">
   Stuff...
</div>
<div id="div2">
   More Stuff...
</div>

Each of these divs has a drop shadow applied to it via jQuery plugin (jquery.dropshadow.js).

The problem occurs when I expand one of the divs using some kind of animation.  The shadow does not update with the size of the div.  I can redraw the shadow in the callback of the animation but still looks pretty joggy.

Is there a way that I can update the status of my shadows periodically throughout the course of the animation or can anyone recommend a better drop shadow library that would fix the problem?  It doesn't have to be jQuery plugin.

[A]
Ok, I still don't know how you animate, but I give you another example:
```
```
$('#foo').slideToggle().ready(function(){
  $('#foo').dropShadow(options);
});
```
```
So, instead of
```
slideToggle
```
, just use whatever animation
thingy
you got.
Hope that helps.


q:
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.

for i in range(len(alist)):
    for j in range(len(alist[i])):
        if alist[i][j].isWhatever:
            blist[i][j].doSomething()

Is there a nicer way to do something like this?

[A]
```
```
for d1 in alist
   for d2 in d1
      if d2 = "whatever"
          do_my_thing()
```
```


q: How can I get list all the files within a folder recursively in Java?

[A]
```
```
import java.io.File;
public class Test {
    public static void main( String [] args ) {
        File actual = new File(".");
        for( File f : actual.listFiles()){
            System.out.println( f.getName() );
        }
    }
}
```
```
It displays indistinctly files and folders.
See the methods in File class to order them or avoid directory print etc.
http://java.sun.com/javase/6/docs/api/java/io/File.html


q:
I moved a WordPress installation to a new folder on a Windows/IIS server. I'm setting up 301 redirects in PHP, but it doesn't seem to be working. My post URLs have the following format:

http:://www.example.com/OLD_FOLDER/index.php/post-title/

I can't figure out how to grab the /post-title/ part of the URL.

$_SERVER["REQUEST_URI"] - which everyone seems to recommend - is returning an empty string. $_SERVER["PHP_SELF"] is just returning index.php. Why is this, and how can I fix it?

[A]
```
$_SERVER['REQUEST_URI']
```
doesn't work on IIS, but I did find this:
http://neosmart.net/blog/2006/100-apache-compliant-request_uri-for-iis-and-windows/
which sounds promising.


q:
using MVP, what is the normal order of construction and dependency injection.

normally you create a presenter for each view and pass the view into the presenter on constructor.  But what if you have:

A Service that multiple views need to listen to events on.

Multiple views all pointing to the same data model cache.

can someone display a normal flow of info from a user click to data coming back in a service from a server.

[A]
Here is what I do:
First, I define theses interfaces:
```
```
public interface IView<TPresenter>
{
    TPresenter Presenter { get; set; }
}

public interface IPresenter<TView, TPresenter>
    where TView : IView<TPresenter>
    where TPresenter : IPresenter<TView, TPresenter>
{
    TView View { get; set; }
}
```
```
Then this abstract presenter class:
```
```
public abstract class AbstractPresenter<TView, TPresenter> : IPresenter<TView, TPresenter>
    where TView : IView<TPresenter>
    where TPresenter : class, IPresenter<TView, TPresenter>
{
    protected TView view;

    public TView View
    {
        get { return this.view; }
        set
        {
            this.view = value;
            this.view.Presenter = this as TPresenter;
        }
    }
}
```
```
The view is injected via a property, instead of the constructor, to allow the bi-directional affection in the setter. Notice that a safe cast is needed...
Then, my concrete presenter is something like :
```
```
public class MyPresenter : AbstractPresenter<IMyView, MyPresenter>
{
    //...
}
```
```
Where
```
IMyView
```
implements
```
IView
```
. A concrete view type must exists (e.g.
```
MyView
```
), but it's the container that resolves it:
I register
```
MyPresenter
```
type as itself in the container, with a transient behavior.
I register
```
MyView
```
as an
```
IMyView
```
in the container with a transient behavior.
I then asks for a
```
MyPresenter
```
to the container.
Container instanciate a MyView
It instanciates a
```
MyPresenter
```
It inject the view into the presenter through the
```
AbstractPresenter.View
```
property.
The setter code completes the bi-directional association
The container returns the couple Presenter/View
It allows you to inject other dependencies (services, repos) into both your view and your presenter.
But in the scenario you described, I recommend you to inject services and caches into the
presenter
, instead of the view.


q:
(See related question: How do I report an error midway through a chunked http repsonse without closing the connection?)

In my case, the #1 desire is for the browser to display an error message.  No matter how uninformative.

Closing the ServletResponse outputStream obviously doesn't work.  Neither does throwing an exception, even if I don't close first (tested on Tomcat 6.0.16).  I think that what I want is either a RST packet, FIN in the middle of a chunk, or badly formed chunk headers.

After that I can worry about how various browsers respond.

Edited for clarification: This is for a file download, perhaps several gigabytes of binary data.  I can't make certain that all of the data can be successfully read or decrypted before I have to start sending some of it.

[A]
I think you're going about it the wrong way. It seems like it would be simpler to not actually start sending the data until you're sure if will be a success or a failure. That way you can send an error message at the start if needed, instead of sending partial data that's not valid.
If you really must, you might be able to wrangle something up with JavaScript. When you get to the error, output something like this before closing the connection:
```
```
<script type="text/javascript"> alert("Processing failed!"); </script>
```
```
You might want to expand on the script, but you get the general idea. This is assuming that what's being sent back to the browser is a HTML page, you didn't specify that in the question.


q:
I've got a bunch of unit tests built using Visual Studio 2005's built-in unit testing functionality.  For the last little while, it's been taking absolutely forever to start the tests... Everything just sits there at "Pending" for two minutes or more.  Now Visual Studio's decided to take things to a new level and never even start the tests.  After two to three minutes, it aborts the run and barfs an error message into the log:

Failed to Queue Test Run '(blahblahblah)' with id {bfba05b1-afe5-499e-b452-29167f414f0f}: Microsoft.VisualStudio.TestTools.TestManagement.ExecutionException: Failed to establish communication environment for local run.

Anyone have any ideas?  In the medium term, we are planning to switch to NUnit, but for now I'd prefer to stick to Visual Studio because the rest of the team already has that installed and that makes it easier to convince them to actually run the tests... ;-)

[A]
Let me say this MS TEST is not a professional product and should be avoided whenever possible. If you want to use a good testing framework then use MBUnit with TestDriven.NET. MBUnit comes with many new attributes including RollBack and RowTest , Row.
Also, TestDriven.NET will allow you to debug your unit tests (How cool is that). You can also run the code coverage from TestDriven.NET which shows you how much of your code is covered under tests.
Give it a try I am sure you like it.
PS: IT is FREEE


q:
I'm told that the template system in C++ is Turing-complete at compile time. This is mentioned in this post and also on wikipedia.

Can you provide a nontrivial example of a computation that exploits this property?

Is this fact useful in practice?

[A]
"
C++ Templates Are Turing Complete
" gives an implementation of a Turing machine in templates ... which is non-trivial and proves the point in a very direct way.  Of course, it also isn't very useful!


q:
Using the following query and results, I'm looking for the most recent entry where the ChargeId and ChargeType are unique.

select chargeId, chargeType, serviceMonth from invoice

    CHARGEID    CHARGETYPE  SERVICEMONTH
1   101         R           8/1/2008
2   161         N           2/1/2008
3   101         R           2/1/2008
4   101         R           3/1/2008
5   101         R           4/1/2008
6   101         R           5/1/2008
7   101         R           6/1/2008
8   101         R           7/1/2008

Desired:

    CHARGEID    CHARGETYPE  SERVICEMONTH
1   101         R           8/1/2008
2   161         N           2/1/2008

[A]
You can use a
GROUP BY
to group items by type and id.  Then you can use the
MAX()
Aggregate function to get the most recent service month.  The below returns a result set with ChargeId, ChargeType, and MostRecentServiceMonth
```
```
SELECT
  CHARGEID,
  CHARGETYPE,
  MAX(SERVICEMONTH) AS "MostRecentServiceMonth"
FROM INVOICE
GROUP BY CHARGEID, CHARGETYPE
```
```


q:
I've got a Dell XPS M1330 with a 2.2ghz processor, 4gig ram, GeForce 8400M, and a 64GB SSD disk.

I'm primarily doing web-development, sharepoint development, integration (Microsoft BI tools) and biztalk. I use virtual machines for these purposes. I've been using Vista 32Bit up until now but I'm considering moving to 64bit to squeeze that little extra ram out of the box.

I'd like to hear if anyone has been using 64bit vista under the same circumstances and if anything should hold me back. Have in mind that this is the laptop I use at work.

[A] I have recently switched from a Vista 32 bit development machine to a Vista 64 bit development machine, with a quad-core intel processor, and 6gb of ram.  THe performance improvements have been quite impressive, and thus far, no "issues" with any development tools that I have been using.


q:
I'm a Java developer and I have a question about automating a task I've been given.

I'm having to 3 times daily, login to this website we have at work, select a few form elements and then click on submit to get a report printed out.

I'm wondering how I can write some sort of script that will automate this task? Where should I start? What language should I do it in? I was thinking PHP might be able to do this or even a greasemonkey script possibly?

Thanks a lot.

[A]
It's called "web scraping" or "screen scraping", and there are a lot of libraries out there to do this.  I couldn't speak to a Java-specific tool, though: I'm a .Net guy (the .Net way would be System.Net.WebClient or System.Net.HttpWebRequest/System.Net.HttpWebResponse).  But I'm sure there's something.
In the meantime, the first step is go to the page where you input the form values and view the source of the page.  Look for the specific <form> element you're filling out, and see where it posts to (it's
action
).  Then, find any <input> <select>, <textarea> elements you use, including any hidden inputs for the form, and figure out what values you need to get.  That will tell you how to build your request once you find a library that will let you send it.
If you need to login to the site first to get to the page, things can be more complicated.  You may need to retrieve and parse a session value or be able to send certain cookies to the server.


q:
Odd behavior loading emacs on ubuntu, there seems to be some initialization that goes on that is not in the .emacs nor in any of the files emacs reports loading through "emacs --debug-init". I've found some references to font-related resizing but this behavior doesn't seem to be limited to that (e.g reappearing menus and toolbars).

Does anyone have any additional information about the emacs initialization process?
Does it load /etc/emacs/site-start.d  files before or after the .emacs, and are there any other locations it loads by default?

[A]
The sequence of the Emacs initialization is the following (at least, for Emacs 22):
Load the file
debian-startup
(.el or .elc) found in
load-path
(usually,
/usr/share/emacs/site-lisp/debian-startup.el
or
/usr/share/emacs22/site-lisp/debian-startup.elc
) and call the function
debian-startup
defined in this file.  This function loads all files in
/etc/emacs/site-start.d/
and
/etc/emacs22/site-start.d/
.
Load
site-start
(.el or .elc) found in
load-path
.
Load your init file
.emacs
,
.emacs.el
or
~/.emacs.d/init.el
.
Load a default init file
default.el
or
default.elc
.
I also suggest you reading the section "
Emacs startup strategy
" in
/usr/share/doc/emacsen-common/debian-emacs-policy.gz
for more Ubuntu/Debian specific information. To find the reason of odd behavior you can start emacs with the argument
--no-site-file
and load these init files one by one until you find a file that causes this behavior.


q:
I am curious on how others manage code promotion from DEV to TEST to PROD within an enterprise.

What tools or processes do you use to manage the "red tape", entry/exit criteria side of things?

My current organisation is half stuck between some custom online forms type functionality and paper based dependencies to submit documents, gather approvals and reviews.

All this is left in the project managers hands to track what has been submitted, passed review, approved and advise management if there are any roadblocks that may need approval to be "overlooked" before an application can be promoted to the next environment.

A browser based application would be ideal... so whats out there? please show me that you googlefu is better than mine.

[A]
It's hard to find one that's good via google.  There is a vast array of tools out there for issue management so I'll mention what we use and what we woudl like to use.
We currently use serena products.  They have worked well for us in the past.  Team Track is our issue management and handles the life cycle of any issue we work on.  Version Manager is our source control and has the feature of implementing promotional groups like DEV TEST And PROD.  We use DEV, TSTAGE, TEST, PSTAGE and PROD to signify the movement from one to the other, but it's much the same.  The two products integrate nicely so that the source associated with the issues is linked, but we have no build process setup in this environment.  It's expensive, but it works well.
We are looking ot move to a more common system using Jira for issue management, Subversion for source control, Fisheye to link the two together and Cruise Control for build management.  This is less expensive, totaling a few thousand for an enterprise lisence  and provides all the same features but with the added bonus of SVN which is a very nice code version mangager.
I hope that helps.


q:
Problem

Our web host provider is changing the IP address of one of the servers we are on. We have been given a time frame for when the switch will take place, but no exact details. Therefore, our current poor man's check requires a periodic page refresh on a browser to see if our website is still there.

Question

We are all programmers here and this is killing me that any manual checking is required. I would know how to do this in other languages, but want to know if there is a way to write a script in PowerShell to tackle this problem. Does anyone know how I might going about this?

[A]
This will list the IP Address for each network adapter in your system.
```
```
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property IPAddress
```
```


q:
I've been learning Java for about a month now, and not very familiar with a client/server situation like this one.

Basically I ran into a situation where our client java software (GUI) displayed a nullpointerexception popup but no stack trace on the client side. Someone had to go check the server side for the stack trace.

My question is, shouldn't the client side receive this precious information as well?  Are situations like that ok, the rationale being one only needs one copy of the stack trace?

[A]
Not really.  It is not recommended to show the way your app works from behind to the client. Mainly for security reasons. Your stacktrace shows all the objects being called, methods and if compiled with debug info, even lines. That's too much information for the client, it is ok to have it on the server.
This among SQL injection, Cross side script and others that I cannot remember, improper exception handling is a security vulnerability.
EDIT:
Here are other vulnerabilities ( although I don't see this one listed :( )
http://en.wikipedia.org/wiki/Vulnerability_(computing)


q:
I've just got a fresh Drupal 6 install. The CSS didn't work. Then I realized that a "?U" was appended, and Drupal couldn't find it. Does anyone know where to unset this?

<link type="text/css" rel="stylesheet" media="all" href="/modules/node/node.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/admin.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/defaults.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/system/system-menus.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/modules/user/user.css?U" />
<link type="text/css" rel="stylesheet" media="all" href="/themes/bluemarine/style.css?U" />

[A]
the ?U (or really any alphabet) is just a method drupal uses to cache information. it has no relevance to the location of the file (ie, node.css and node.css?U is in the same location to drupal).
it sounds like you may have a different issue. perhaps you enabled your cache and moved things around? you may need to clear your cache. or, if you've modified your install variables perhaps you're picking up the wrong base path or something. it's hard to tell the exact issue based on the limited information given.


q: Is there a way to find out what gcc flags a particular binary was compiled with?

[A]
I don't think so.
You can see if it has debug symbols, which means -g was used ;) But I can't think of any way how you could find out which directories have been used to search for include headers for example.
Maybe a better answer is possible if you only target for a specific flag; e.g. if you only want to know if the flag "..." was set when this binary was compiled or not. In that case, what flag would this be?


q:
How do I write a regular expression to find all lines containing 665 and not having .pdf

I can't seem to find how to do not in regex.  This is for Notepad++ syntax if it matters.

Thanks

[A]
The feature you'r looking for is look ahead patterns
```
```
665(?!.*\.pdf)
```
```


q:
With a view to avoiding the construction of further barriers to migration whilst
enhancing an existing vb6 program.
Is there a way to achieve the same functionality as control arrays in vb6 without using them?

[A]
Well, you could always create your own array of controls in code :) Perhaps a better container, though, is a Collection or Dictionary object. Depending on what you want to do, you could perhaps create a wrapper class for the control with a custom collection class... but creating an object model is far nicer using generics in .NET so probably best to keep it simple in VB6 for now.
VBA Userforms lack support for control arrays, so why not Google for suggestions on how to mimic control arrays with VBA, Userforms, Excel, etc.
BTW have you tried migrating control arrays from VB6 to VB.NET? Just a guess but considering they are commonly used in VB I imagine they are handled quite well.


q:
I have the following string:

$_='364*84252';

The question is: how to replace * in the string with something else? I've tried s/\*/$i/, but there is an error:  Quantifier follows nothing in regex. On the other hand s/'*'/$i/ doesn't cause any errors, but it also doesn't seem to have any effect at all.

[A]
Something else is weird here...
```
```
~> cat test.pl
$a = "234*343";
$i = "FOO";

$a =~ s/\*/$i/;
print $a;

~> perl test.pl
234FOO343
```
```
Found something:
```
```
~> cat test.pl
$a = "234*343";
$i = "*4";

$a =~ m/$i/;
print $a;

~> perl test.pl
Quantifier follows nothing in regex; marked by <-- HERE in m/* <-- HERE 4/ at test.pl line 4.
```
```
Solution, escape the special characters from the variable using
```
\Q
```
and
```
\E
```
, for example (TIMTOWTDI)
```
```
~> cat test.pl
$a = "234*343";
$i = "*4";

$a =~ m/\Q$i\E/;
print $a;

~> perl test.pl
234*343
```
```


q: I need to do a join across two different database servers (IPs 10.0.0.50 and 10.0.0.51). What's the best way?

[A]
You need to use sp_linkedserver to create a linked server.
```
```
sp_addlinkedserver [ @server= ] 'server' [ , [ @srvproduct= ] 'product_name' ]
 [ , [ @provider= ] 'provider_name' ]
 [ , [ @datasrc= ] 'data_source' ]
 [ , [ @location= ] 'location' ]
 [ , [ @provstr= ] 'provider_string' ]
 [ , [ @catalog= ] 'catalog' ]
```
```
More information available on
MSDN
.


q: How to detect the Internet connection is offline in JavaScript?

[A]
You can determine that the connection is lost by making
failed XHR requests
.
The standard approach is to
retry the request
a few times.  If it doesn't go through,
alert the user
to check the connection, and
fail gracefully
.
Sidenote:
To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc.  So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.
Sidenote:
You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem.  Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.
Sidenote
:
Sending a Ping
could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges.  First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications.  One option is to set up a server-side proxy, wherein we actually
```
ping
```
google (or whatever site), and return the results of the ping to the app. This is a
catch-22
because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc).  Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on.  So again, determining the state of the internet connection as a whole may be more trouble than it's worth.  You'll have to weight these options out for your specific app.


q:
Estimating how long any given task will take seems to be one of the hardest parts about software development. At my current shop we estimate tasks in hours at the start of an iteration, but once the task is complete we do not use it to aide us in future estimations.

How do you use the information you gather from past estimations to refine future ones?

[A]
If an estimate blew out, attempt to identify if it was just random (environment broke, some once off tricky bug etc) or if there was something that you didn't identify.
If an esimate was way too large, identify what it was that you thought was going to take so long and work out why it didn't.
Doing that enough will hopefully help developers in their estimates.
For example, if a dev thinks that writing tests for a controller is going to take ages and then it ends up taking less time than he imagined, the next estimate you make for a controller of similar scope you can keep that in mind.


q:
I've had nothing but good luck from SO, so why not try again?

I have an application that needs to show a different image based on the season of the year (spring, summer, winter, fall).   I have very specific start and end dates for these seasons.

What I would like from you geniuses is a method called GetSeason that takes a date as input and returns a String value of Spring, Summer, Winter or Fall.   Here are the date ranges and their associated seasons:

Spring:3/1-4/30

Summer:5/1-8/31

Fall:9/1-10/31

Winter: 11/1-2/28

Can someone provide a working method to return the proper season?
Thanks everyone!

[A]
Well, it could be as simple as
```
```
String getSeason(int month) {
    switch(month) {
          case 11:
          case 12:
          case 1:
          case 2:
                return "winter";
          case 3:
          case 4:
                return "spring";
          case 5:
          case 6:
          case 7:
          case 8:
                return "summer";
          default:
                return "autumn";
      }
}
```
```
I have been chided in the comments into a better solution: enums:
```
```
public static Enum Season {
    WINTER(Arrays.asList(11,12,1,2)),
    SPRING(Arrays.asList(3,4)),
    SUMMER(Arrays.asList(5,6,7,8)),
    AUTUMN(Arrays.asList(9,10));

    Season(List<Integer> months) {
        this.monthlist = months;
    }
    private List<Integer> monthlist;
    public boolean inSeason(int month) {
        return this.monthlist.contains(month);  // if months are 0 based, then insert +1 before the )
    }

    public static Season seasonForMonth(int month) {
        for(Season s: Season.values()) {
            if (s.inSeason(month))
                 return s;
        }
        throw new IllegalArgumentException("Unknown month");
    }
}
```
```


q:
I want to know how to set the height property for the HTML <select> in code.

I tried setting .Attribute.Add("Style","Height:120px") just to see if I could get it to change but to no avail.

[A]
Style is already a Property...
```
```
DropDownList myDropDown;
myDropDown.Style["height"] = "120px";
```
```


q:
When I created the project I'm trying to deploy I selected that I wanted to target .NET Framework 2.0. After deploying the project I try to brows to it and get and error page that shows:

<compilation debug="true">
    <assemblies>
        <add assembly="System.Web.Entity, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    </assemblies>
</compilation>

One of the selling points of VS2008 is that you can develop for and deploy to server running .NET2.0 what Am I doing wrong?

[A] remove those references from your project and redeploy. if your project started as 3.5 it will still have references to some of those assemblies


q:
I tried looking for the .emacs file for my Windows installation for Emacs, but I could not find it. Does it have the same filename under Windows as in Unix?

Do I have to create it myself? If so, under what specific directory does it go?

[A]
Copy and pasted from the Emacs FAQ,
http://www.gnu.org/software/emacs/windows/
:
Where do I put my init file?
On Windows, the
```
.emacs
```
file may be called
```
_emacs
```
for backward compatibility with DOS and FAT filesystems where filenames could not start with a dot. Some users prefer to continue using such a name, because Windows Explorer cannot create a file with a name starting with a dot, even though the filesystem and most other programs can handle it. In Emacs 22 and later, the init file may also be called
```
.emacs.d/init.el
```
. Many of the other files that are created by Lisp packages are now stored in the
```
.emacs.d
```
directory too, so this keeps all your Emacs related files in one place.
All the files mentioned above should go in your HOME directory. The HOME directory is determined by following the steps below:
If the environment variable HOME is set, use the directory it indicates.
If the registry entry HKCU\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates.
If the registry entry HKLM\SOFTWARE\GNU\Emacs\HOME is set, use the directory it indicates. Not recommended, as it results in users sharing the same HOME directory.
If
```
C:\.emacs
```
exists, then use
```
C:/
```
. This is for backward compatibility, as previous versions defaulted to
```
C:/
```
if HOME was not set.
Use the user's AppData directory, usually a directory called Application Data under the user's profile directory, the location of which varies according to Windows version and whether the computer is part of a domain.
Within Emacs,
```
~
```
at the beginning of a file name is expanded to your HOME directory, so you can always find your .emacs file with
```
C-x C-f ~/.emacs
```
.
There's further information at
HOME and Startup Directories on MS-Windows
.


q:
I have already extracted the tag from the source document using grep but, now I cant seem to figure out how to easily extract the properties from the string. Also I want to avoid having to use any programs that would not usually be present on a standard installation.

$tag='<img src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg" title="Don't we all." alt="Barrel - Part 1" />'

I need to end up with the following variables

$src="http://imgs.xkcd.com/comics/barrel_cropped_(1).jpg"
$title="Don't we all."
$alt="Barrel - Part 1"