q:
I'm looking for a graph algorithm with some unusual properties.

Each edge in the graph is either an "up" edge or a "down" edge.

A valid path can go an indefinite number of "up"'s followed by an indefinite number of "down"'s, or vice versa. However it cannot change direction more than once.

E.g., a valid path might be A "up" B "up" C "down" E "down" F
an invalid path might be A "up" B "down" C "up" D

What is a good algorithm for finding the shortest valid path between two nodes? What about finding all of the equal length shortest paths?

[A]
Assuming you don't have any heuristics, a variation of
dijkstra's algorithm
should suffice pretty well. Every time you consider a new edge, store information about its "ancestors". Then, check for the invariant (only one direction change), and backtrack if it is violated.
The ancestors here are all the edges that were traversed to get to the current node, along the shortest path. One good way to store the ancestor information would be as a pair of numbers. If U is up, and D is down, a particular edge's ancestors could be
```
UUUDDDD
```
, which would be the pair
```
3, 4
```
. You will not need a third number, because of the invariant.
Since we have used dijkstra's algorithm, finding multiple shortest paths is already taken care of.


q:
I frequently find myself writing code like this:

List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
    Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();

Better would be something like this:

List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);

I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block?

[A]
Do this:
```
```
list.ForEach(i => Console.Write("{0}\t", i));
```
```
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)

s: huggingface

c: devops

d: intermediate


q:
I was wondering if anyone could point to an Open Source date utility class that is fairly robust. I find myself rolling my own when I want to do a lot of things I take for granted in C# and Java. For instance I did find a decent example of a DateDiff() function that I tore apart and another DatePart() function. Another examples would be parsing different date/time formats. I'm trying to avoid reinventing something if it's already built.

Another possibility may be a nice set of Javascript files that I can convert to ActionScript 3. So far I've found DateJS but I want to get a good idea of what is out there.

[A]
as3corelib
has the
DateUtil
class and it should be pretty reliable since it's written by some Adobe employees. I haven't encountered any problems with it.


q:
I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:

before: File.h

after: file.h

I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?

[edit]
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope.

[A]
Since version 1.5.6 there is an
```
ignorecase
```
option available in the
```
[core]
```
section of
```
.git/config
```
e.g. add
```
ignorecase = true
```
To change it for just one repo, from that folder run:
```
```
git config core.ignorecase true
```
```
To change it globally:
```
```
git config --global core.ignorecase true
```
```


q: So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader.  Any fields that aren't in the reader would be left null on the resulting object.  How do you test if a reader contains a specific field without just wrapping it in a try/catch?

[A]
You can't just test reader["field"] for null or DBNull because a IndexOutOfRangeException is thrown if the column isn't in the reader.
The code I use in my mapping layer for creating domain objects and the stored procedures that use the mapping layer might have different column names is below; you could modify it to not throw an exception if the column isn't found and return default(t) or null.
I understand this isn't the most elegant or optimal solution (and really, if you can avoid it then you should), however, legacy stored procedures or Sql queries might warrant a work-around.
```
```
/// <summary>
    /// Grabs the value from a specific datareader for a list of column names.
    /// </summary>
    /// <typeparam name="T">Type of the value.</typeparam>
    /// <param name="reader">Reader to grab data off of.</param>
    /// <param name="columnNames">Column names that should be interrogated.</param>
    /// <returns>Value from the first correct column name or an exception if none of the columns exist.</returns>
    public static T GetColumnValue<T>(IDataReader reader, params string[] columnNames)
    {
        bool foundValue = false;
        T value = default(T);
        IndexOutOfRangeException lastException = null;

        foreach (string columnName in columnNames)
        {
            try
            {
                int ordinal = reader.GetOrdinal(columnName);
                value = (T)reader.GetValue(ordinal);
                foundValue = true;
            }
            catch (IndexOutOfRangeException ex)
            {
                lastException = ex;
            }
        }

        if (!foundValue)
        {
            string message = string.Format("Column(s) {0} could not be not found.",
                string.Join(", ", columnNames));

            throw new IndexOutOfRangeException(message, lastException);
        }

        return value;
    }
```
```


q:
Right now my ant task looks like.

<javadoc sourcepath="${source}" destdir="${doc}">
    <link href="http://java.sun.com/j2se/1.5.0/docs/api/" />
</javadoc>

And I'm getting this warning:

javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list

How do I get the javadoc to properly link to the API?  I am behind a proxy.

[A]
You probably need the
http.proxyHost and http.proxyPort system properties
set. For example,
```
ANT_OPTS="-Dhttp.proxyHost=proxy.y.com" ant doc
```
Alternatively, you could set the "offline" flag and provide a package list, but that could be a pain for the Java core.


q: What is the best way to sort the results of a sql query into a random order within a stored procedure?

[A]
```
```
select foo from Bar order by newid()
```
```


q:
I have a team lead who seems to think that business logic is very subjective, to the point that if my stored procedure has a WHERE ID = @ID — he would call this “business logic”

What approach should I take to define “business logic” in a very objective way without offending my team lead?

[A]
I really think you just need to agree on a clear definition of what you mean when you say "business logic".  If you need to be "politically sensitive", you could even craft the definition around your team lead's understanding, then come up with another term ("domain rules"?) that defines what you want to talk about.
Words and terms are relatively subjective -- of course, once you leave that company you will need to 're-learn' industry standards, so it's always better to stick with them if you can, but the main goal is to communicate clearly and get work done.


q: How do I setup an Ant task to generate Emma code coverage reports?

[A]
To answer questions about where the source and instrumented directories are (these can be switched to whatever your standard directory structure is):
```
```
<property file="build.properties" />
<property name="source" location="src/main/java" />
<property name="test.source" location="src/test/java" />
<property name="target.dir" location="target" />
<property name="target" location="${target.dir}/classes" />
<property name="test.target" location="${target.dir}/test-classes" />
<property name="instr.target" location="${target.dir}/instr-classes" />
```
```
Classpaths:
```
```
<path id="compile.classpath">
  <fileset dir="lib/main">
    <include name="*.jar" />
  </fileset>
</path>

<path id="test.compile.classpath">
  <path refid="compile.classpath" />
  <pathelement location="lib/test/junit-4.6.jar" />
  <pathelement location="${target}" />
</path>

<path id="junit.classpath">
  <path refid="test.compile.classpath" />
  <pathelement location="${test.target}" />
</path>
```
```
First you need to setup where Ant can find the Emma libraries:
```
```
<path id="emma.lib" >
    <pathelement location="${emma.dir}/emma.jar" />
    <pathelement location="${emma.dir}/emma_ant.jar" />
</path>
```
```
Then import the task:
```
```
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
```
```
Then instrument the code:
```
```
<target name="coverage.instrumentation">
    <mkdir dir="${instr.target}"/>
    <mkdir dir="${coverage}"/>
    <emma>
        <instr instrpath="${target}" destdir="${instr.target}" metadatafile="${coverage}/metadata.emma" mode="copy">
            <filter excludes="*Test*"/>
        </instr>
    </emma>
    <!-- Update the that will run the instrumented code -->
    <path id="test.classpath">
        <pathelement location="${instr.target}"/>
        <path refid="junit.classpath"/>
        <pathelement location="${emma.dir}/emma.jar"/>
    </path>
</target>
```
```
Then run a target with the proper VM arguments like:
```
```
<jvmarg value="-Demma.coverage.out.file=${coverage}/coverage.emma" />
<jvmarg value="-Demma.coverage.out.merge=true" />
```
```
Finally generate your report:
```
```
<target name="coverage.report" depends="coverage.instrumentation">
    <emma>
        <report sourcepath="${source}" depth="method">
            <fileset dir="${coverage}" >
                <include name="*.emma" />
            </fileset>
            <html outfile="${coverage}/coverage.html" />
        </report>
    </emma>
</target>
```
```


q:
I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.

Is there some way to group together several files and include them all at once?

[A]
Yes, take a look at the "6.4 Packages" section in
http://docs.python.org/tut/node8.html
:
Basically, you can place a bunch of files into a directory and add an __init__.py file to the directory.  If the directory is in your PYTHONPATH or sys.path, you can do "import directoryname" to import everything in the directory or "import directoryname.some_file_in_directory" to import a specific file that is in the directory.
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as "string", from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.


q:
Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs

Does anyone know for sure where these come from, and what they are used for?

[A]
According to MSDN
:
[The
```
Project
```
] statement contains the
  unique project GUID and the project
  type GUID. This information is used by
  the environment to find the project
  file or files belonging to the
  solution, and the VSPackage required
  for each project. The project GUID is
  passed to IVsProjectFactory to load
  the specific VSPackage related to the
  project, then the project is loaded by
  the VSPackage.


q:
In python, there are some special variables and filenames that are surrounded by double-underscores.  For example, there is the

__file__

variable.  I am only able to get them to show up correctly inside of a code block.  What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis?

[A]
__file__
Put a backslash before the first underscore.
Like this:
```
```
\__file__
```
```


q: We are currently looking to adopt some type of "standard" developer framework and have looked into using the Enterprise Library.  Would you recommend using these blocks as the foundation for software development, or should we do something home grown?

[A]
Like all good answers to architecture and programming questions, the answer is "it depends".
It depends on how unique your data access and object design needs are.  It may also depend on how you plan on supporting your application in the long term.  Finally, it greatly depends on the skill level of your developers.
There isn't a one-size-fits-all answer to this question, but generally, if your main focus is on cranking out software that provides some business value, pick out an existing framework and run with it.  Don't spend your cycles building something that won't immediately drive business profits (i.e. increases revenues and/or decreases costs).
For example, one of my organization's projects is core to the operations of the company, needs to be developed and deployed as soon as possible, and will have a long life.  For these reasons, we picked CSLA with some help from Enterprise Library.  We could have picked other frameworks, but the important thing is that we picked a framework that seemed like it would fit well with our application and our developer skillset and we ran with it.
It gave us a good headstart and a community from which we can get support.  We immediately started with functionality that provided business value and were not banging our heads against the wall trying to build a framework.
We are also in the position where we can hire people in the future who have most likely had exposure to our framework, giving them a really good headstart.  This should reduce long-term support costs.
Are there things we don't use and overhead that we may not need?  Perhaps.  But, I'll trade that all day long for delivering business value in code early and often.


q: I am writing a DDL script to drop a number of tables but need to identify all dependencies for those tables first. Those dependencies include foreign key constraints, stored procedures, views, etc. Preferably, I want to programmatically script out dropping those dependencies using the system tables/views before dropping the dependent table.

[A]
You can use the sp_depends stored procedure to do this:
```
USE AdventureWorks
GO
EXEC sp_depends @objname = N'Sales.Customer' ;
```
http://msdn.microsoft.com/en-us/library/ms189487(SQL.90).aspx


q: Can anyone point me to a good introduction to coding against the paypal API?

[A]
I would suggest you start by downloading the SDK:
https://www.paypal.com/IntegrationCenter/ic_sdk-resource.html
The SDK includes the following:
Client libraries that call PayPal APIs
API documentation for SDK components
Sample code for Website Payments Pro and various administrative APIs
Testing console that can verify connectivity to PayPal and submit API calls
You may also want to take a look at
Encore Systems .NET* Class Library for PayPal SOAP API


q: Does filling out HTML meta description/keyword tags matter for SEO?

[A]
Google will use meta tags, but the description, to better summarize your site.  They won't help to increase your page rank.
See:
http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=79812
EDIT
: @Petr, are you sure that meta tags influence page rank?  I am pretty sure that they don't, but if you have some references, I'd love to learn more about this.  I have seen
this
, from the Official Google Webmaster Central Blog, which is what leads me to believe that they don't:
Even though we sometimes use the
  description meta tag for the snippets
  we show, we still don't use the
  description meta tag in our ranking.


q:
From the Immediate Window in Visual Studio:

> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"

It seems that they should both be the same.

The old FileSystemObject.BuildPath() didn't work this way...

[A]
Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:
```
```
urljoin('/some/abs/path', '../other') = '/some/abs/other'
```
```
This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence.


q:
In trying to figure out this problem (which is still unsolved and I still have no clue what is going on), I am wondering if maybe an external reference to the table in question is causing the problem.  For example, a trigger or view or some other such thing.

Is there an easy way to find all references to a given database table?  Including all views, triggers, constraints, or anything at all, preferably from the command line, and also preferably without a 3rd party tool (we are using db2).

[A]
Wow, I wouldn't have thought it, but there seems to be.. Good ole DB2.
I find the publib db2 docs view very very handy by the way:
http://publib.boulder.ibm.com/infocenter/db2luw/v8//index.jsp
I just found the "SYSCAT.TABDEP" catalog view in it, which seems to contain more or less what you asked for. I suspect for anything not covered there you'll have to trawl through the rest of the syscat tables which are vast. (Unfortunately I can't seem to link you to the exact page on SYSCAT.TABDEP itself, the search facility should lead you to it fairly easily though).
Most databases these days have a set of tables which contain data about the layout of your actual schema tables, quite handy for this sort of thing.


q: What do you use to capture webpages, diagram/pictures and code snippets for later reference?

[A]
Evernote
http://www.evernote.com
and delicious
http://www.delicious.com


q:
what I'm after is something I can feed a number into and it will return the highest order bit.  I'm sure there's a simple way.  Below is an example output (left is the input)

1 -> 1
2 -> 2
3 -> 2
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
...
63 -> 32

[A]
Continually remove the low order bit comes to mind...
```
```
int highest_order_bit( int x )
{
    int y = x;
    do {
        x = y;
        y = x & (x-1); //remove low order bit
    }
    while( y != 0 );
    return x;
}
```
```


q:
Given:

e = 'a' + 'b' + 'c' + 'd'

How do I write the above in two lines?

e = 'a' + 'b' +
    'c' + 'd'


q:
I have two elements:

<input a>
<input b onclick="...">

When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so document.getElementsByName is out. Looking into the event object, I thought event.target.parentNode would have some function like getElementsByName, but this does not seem to be the case with <td>s. Is there any simple way to do this?

[A]
If
```
a
```
and
```
b
```
are next to each other and have the same parent, you can use the
```
prevSibling
```
property of
```
b
```
to find
```
a
```
.


q: I'm trying to use the Optiflag package in my Ruby code and whenever I try to do the necessary require optiflag.rb, my program fails with the standard no such file to load -- optiflag message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas?

[A]
is it a gem? Are you doing
```
```
require 'rubygems'
require 'optiflag'
```
```
or equivalent?


q:
I'm trying to use some data from a PlanPlusOnline account.  They only provide a java web services API.  The server for the site where the data will be used does not allow me to install Tomcat (edit: or a JVM for that matter).  I'm not going to lie, I am a Java software engineer, and I do some web work on the side.  I'm not familiar with web services or servlets, but I was willing to give it a shot.  I'd much rather they have JSON access to the data, but as far as I know they don't.  Any ideas?

EDIT: to clarify.   The web service provided by planplusonline is Java based.  I am trying to access the data from this web service without using Java.  I believe this is possible now, but I need to do more research.  Anyone who can help point me in the right direction is appreciated.

[A]
Are you trying to implement a client to a web service hosted somewhere else?  If so, Java's not necessary.  You can do web service clients in
.NET
,
PHP
,
Ruby
, or pretty much any modern web technology out there.  All you need is a WSDL document to provide metadata about how to invoke the services.


q: I come from a world that favors building your own rather than rely on libraries and frameworks built by others. After escaping this world I have found the joy, and ease, of using such tools as Typed DataSets within Visual Studio. So besides the loss of flexibility what else do you lose? Are there performance factors (disregarding the procs vs dynamic sql debate)? Limitations?

[A]
Performance is improved with typed datasets over untyped datasets (though I've never found  performance issues with trivial things like that worth worrying about).
I'd say the biggest pain is just keeping them in sync with your database--I can't speak for VS 2008 but prior versions do not provide good support for this. I literally drag the procs onto the designer everytime the resultset's schema changes. Not fun.
But, you do get compile time type checking which is great and things like Customer.Name instead of Dataset.Tables(0).Rows(0)("Name").
So, if your schema is relatively static, they may be worth it, but otherwise, I wouldn't bother.
You could also look into a real ORM.


q:
Does anyone have examples of how to use DBMS_APPLICATION_INFO package with JBOSS?

We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.

I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.

Has anyone done this before?

[A]
yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
```
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
```
Change it to:
```
public class LoggingConnectionPool extends ConnectionPool{
    public OracleConnection getConnection(String datasourceName, String module, String action){
        OracleConnection conn=getConnection(datasourceName);
        CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
        try{
            call.setString(1,module);
            call.setString(2,action);
            call.execute();
        finally{
            call.close();
        }
        return new WrappedOracleConnection(conn);
    }
```
Note the use of WrappedOracleConnection above. You need this because you need to trap the close call
```
public class WrappedOracleConnection extends OracleConnection{
    public void close(){
        CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
        try{
            call.setNull(1,Types.VARCHAR);
            call.setNull(2,Types.VARCHAR);
            call.execute();
        finally{
            call.close();
        }
    }

    // and you need to implement every other method
    //for example
    public CallableStatement prepareCall(String command){
        return super.prepareCall(command);
    }
    ...
}
```
Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool).


q: An OleDB provider is a binary implementing COM interfaces provided by Microsoft. From that it seems to be possible to create a provider using C#. Is that correct? Is there a sample demonstrating that? If not, would you discourage me from doing that? I see that there are multiple unmanaged samples but I can't find any managed.

[A]
I am not sure I really understand your question?! There already
is
a managed OleDBProvider?!
```
```
using System.Data.OleDb;
```
```
I would certainly discourage writing a provider that exists and works absolutely fine! :)
But in answer to your first question, you can of course create your own. The
Data Provider Roadmap
may be a good place to start for an overview and links  to samples etc.


q:
If starting a new project what would you use for your ORM NHibernate or LINQ and why.  What are the pros and cons of each.

edit: LINQ to SQL not just LINQ (thanks @Jon Limjap)

[A]
Errr... there's
LINQ for NHibernate
.
Perhaps what you mean is which to use:
LINQ to SQL
NHibernate
I prefer NHibernate.
LINQ to SQL is fairly lightweight, but it's a little bit more tightly coupled to your data structure, as opposed to NHibernate which is pretty flexible in terms of the types of object definitions that can be mapped to your table structures.
Of course that's not to say that LINQ to SQL has no uses: this very website uses it. I believe that it's quite useful to get up and running in small applications where the database schema is not as massive.


q:
I want to wrap a piece of code that uses the Windows Impersonation API into a neat little helper class, and as usual, I'm looking for a way to go test-first. However, while WindowsIdentity is a managed class, the LogonUser call that is required to actually perform the logging in as another user is an unmanaged function in advapi32.dll.

I think I can work around this by introducing an interface for my helper class to use and hiding the P/Invoke calls in an implementation, but testing that implementation will still be a problem. And you can imagine actually performing the impersonation in the test can be a bit problematic, given that the user would actually need to exist on the system.

[A]
Guideline: Don't test code that you haven't written.
You shouldn't be concerned with WinAPI implementation not working (most probably it works as expected).
Your concern should be testing the 'Wiring' i.e. if your code makes the right WinAPI call. In which case, all you need is to mock out the interface and let the mock framework tell if you the call was made with the right params. If yes, you're done.
Create IWinAPIFacade (with relevant WinAPI methods) and implementation CWinAPIFacade.
Write a test which plugs in a mock of IWinAPIFacade and verify that the appropriate call is made
Write a test to ensure that CWinAPIFacade is created and plugged in as a default (in normal functioning)
Implement CWinAPIFacade which simply blind-delegates to Platform Invoke calls - no need to auto-test this layer. Just do a manual verification. Hopefully this won't change that often and nothing breaks. If you find that it
does
in the future, barricade it with some tests.


q:
I have IIS 5.1 installed on Windows XP Pro SP2. Besides I have installed VS 2008 Express with .NET 3.5. So obviously IIS is configured for ASP.NET automatically for .NET 3.5

The problem is whenever I access http://localhost IE & Firefox both presents authentication box. Even if I enter Administrator user and its password, the authentication fails. I have already checked the anonymous user access (with IUSR_ user and password is controlled by IIS) in Directory Security options of default website.

However other deployed web apps work fine (does not ask for any authentication).

In IE this authentication process stops if I add http://localhost in Intranet sites option.

Please note that the file system is FAT32 when IIS is installed.

Regards,
Jatan

[A]
It could be because of couple of Browser settings. Try with these options checked..
Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)
Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon
Worst case, try adding localhost to the Trusted sites.
If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.


q:
I have some Ruby code which takes dates on the command line in the format:

-d 20080101,20080201..20080229,20080301

I want to run for all dates between 20080201 and 20080229 inclusive and the other dates present in the list.

I can get the string 20080201..20080229, so is the best way to convert this to a Range instance? Currently, I am using eval, but it feels like there should be a better way.

@Purfideas I was kind of looking for a more general answer for converting any string of type int..int to a Range I guess.

[A]
assuming you want the range to iterate properly through months etc, try
```
```
require 'date'

ends = '20080201..20080229'.split('..').map{|d| Date.parse(d)}
(ends[0]..ends[1]).each do |d|
  p d.day
end
```
```


q:
I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:

<p height="30">

I want to apply a class="h30" to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an id or class. Help?

[A]
Attributes are just properties (usually). So just try:
```
```
for (e in ...) {
    if (e.height == 30) {
        e.className = "h30";
    }
}
```
```
Or use something like jquery to simplify this kind of stuff.


q: I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall?

[A]
A quick Google resulted in this answer. In the root shell type:
```
```
mysqladmin -u root password <password>
```
```


q:
How do I enable external access to MySQL Server? I can connect locally but I cannot connect from another box on the network.

I just tried

grant all privileges on *.* to root@'%' identified by '*****' with grant option;

And restarted MySQL Server with no success.

[A]
You probably have to edit the configuration file (usually my.cnf) to listen in the external interface instead of on localhost only.
Change the
```
bind-address
```
parameter to your machine's IP address.
If this is an old MySQL installation, you should comment out the skip-networking parameter.
Afterwards, restart MySQL and you'll be set


q: I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible?

[A]
The
CreateToolhelp32Snapshot Function
has a Process32First method that will allow you to read a
PROCESSENTRY32 Structure
. The structure has a property that will get you the information you want:
th32ParentProcessID
- The identifier
  of the process that created this
  process (its parent process).
This article will help you get started using the ToolHelpSnapshot function:
http://www.codeproject.com/KB/cs/IsApplicationRunning.aspx


q: If I use restful_authentication in my ruby on rails app are passwords transfered between the broswer and the server in paintext? And if so how worried should I be about it?

[A]
Well, you need to be worried if you are not hosting it over HTTPS... because if it is straight HTTP, then yes it is being passed in plaintext.
I don't know Rails specifically, but I'm pretty sure it has nothing to do with whether you host it via HTTP or HTTPS.
Edit: I found
this link
which apparently provides an example Rails app over HTTPS.
Further Edit: Here is
another link
discussing HTTPS with Rails.


q:
For example, if passed the following:

a = []

How do I check to see if a is empty?

[A]
```
```
if not a:
    print("List is empty")
```
```
Using the
implicit booleanness
of the empty
```
list
```
is quite Pythonic.


q: What are some of the ways? What frameworks can you use?

[A]
Well, I presume you mean unit testing your code that hits the database, in which case, there is
NDbUnit
, which appears to be a DbUnit clone for .NET.  I've never used it, but I have used DbUnit, and it is quite useful.
Edit: I assumed you were using .NET because you mentioned MSSQL.  If however you are actually using Java, there is
DbUnit
.


q:
I have a bunch of servlets running under the Tomcat servlet container. I would like to separate test code from production code, so I considered using a test framework.
JUnit is nicely integrated into Eclipse, but I failed to make it run servlets using a running Tomcat server. Could you please recommend a unit testing framework that supports testing Tomcat servlets? Eclipse integration is nice but not necessary.

[A]
Okay.  Ignoring the 'tomcat' bit and coding to the servlet, your best bet is to create mocks for the response and request objects, and then tell it what you expect out of it.
So for a standard empty doPost, and using
EasyMock
, you'll have
```
```
public void testPost() {
   mockRequest = createMock(HttpServletRequest.class);
   mockResponse = createMock(HttpServletResponse.class);
   replay(mockRequest, mockResponse);
   myServlet.doPost(mockRequest, mockResponse);
   verify(mockRequest, mockResponse);
}
```
```
Then start adding code to the doPost.  The mocks will fail because they have no expectations, and then you can set up the expectations from there.
Note that if you want to use EasyMock with classes, you'll have to use the EasyMock class extension library.  But it'll work the same way from then on.


q:
Is it possible to order results in SQL Server 2005 by the relevance of a freetext match? In MySQL you can use the (roughly equivalent) MATCH function in the ORDER BY section, but I haven't found any equivalence in SQL Server.

From the MySQL docs:

For each row in the table, MATCH() returns a relevance value; that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.

So for example you could order by the number of votes, then this relevance, and finally by a creation date. Is this something that can be done, or am I stuck with just returning the matching values and not having this ordering ability?

[A]
If you are using
```
FREETEXTTABLE
```
then it returns a column name
```
Rank
```
, so
```
order by Rank
```
should work. I don't know if other freetext search methods are also returning this value or not. You can have a try.


q: Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?

[A]
If you
do
find you need to write unique code for an environment, use pythons
```
```
import mymodule_jython as mymodule

import mymodule_cpython as mymodule
```
```
have this stuff in a simple module (''module_importer''?) and write your code like this:
```
```
from module_importer import mymodule
```
```
This way, all you need to do is alter
```
module_importer.py
```
per platform.


q: Ulimately I just wanted to extract strings from the .rc file so I could translate them, but anything that goes with .rc files works for me.

[A]
Maybe this helps? (
http://social.msdn.microsoft.com/forums/en-US/regexp/thread/5e87fce9-ec73-42eb-b2eb-c821e95e0d31/
)
They are using the following regex to find the stringtable in the rc source:
(?<=\bSTRINGTABLE\s+BEGIN\s+).*?(?=\s+END\b)
Edit - And you can read the key values pairs with the following statement with the MultiLine option:
@"\s+(.*?)\s+""(.*)""";


q:
I've started using Vim to develop Perl scripts and am starting to find it very powerful.

One thing I like is to be able to open multiple files at once with:

vi main.pl maintenance.pl

and then hop between them with:

:n
:prev

and see which file are open with:

:args

And to add a file, I can say:

:n test.pl

which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type :args I only have test.pl open.

So how can I add and remove files in my args list?

[A]
Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say
```
:tabe [filename]
```
to open a file in a new tab. Cycling between tabs is done by clicking on the tab or by the key combinations [
n
]
```
gt
```
and
```
gT
```
. Graphical Vim even has graphical tabs.


q:
When trying to connect to an ORACLE user via TOAD (Quest Software) or any other means (Oracle Enterprise Manager) I get this error:

ORA-011033: ORACLE initialization or shutdown in progress

[A]
After some googling, I found the advice to do the following, and it worked:
```
```
SQL> startup mount

ORACLE Instance started

SQL> recover database

Media recovery complete

SQL> alter database open;

Database altered
```
```


q:
I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.

Is there some way to do an XSS attack even if HTML Encode is used?

[A]
I don't believe so. Html Encode converts all functional characters (characters which could be interpreted by the browser as code) in to entity references which cannot be parsed by the browser and thus, cannot be executed.
```
```
<script/>
```
```
There is no way that the above can be executed by the browser.
**Unless their is a bug in the browser ofcourse.*


q:
I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well

This:

\#\#

prints:

\#\#

I would like:

##

[A]
Maybe, the following site helps?
http://velocity.apache.org/tools/1.4/generic/EscapeTool.html


q:
What was the motivation for having the reintroduce keyword in Delphi?

If you have a child class that contains a function with the same name as a virtual function in the parent class and it is not declared with the override modifier then it is a compile error. Adding the reintroduce modifier in such situations fixes the error, but I have never grasped the reasoning for the compile error.

[A]
When the ancestor class also has a method with the same name, and it is not necessarily declared virtual, you would see a compiler warning (as you would hide this method).
In other words: You tell the compiler that you know that you hide the ancestor function and replace it with this new function and do so deliberately.
And why would you do this? If the method is virtual in the parent class, the only reason is to prevent polymorphism. Other then that just override and do not call inherited. But if the parent method is not declared virtual (and you cannot change that, because you do not own the code for example), you can inherit from that class and let people inherit from your class without seeing a compiler warning.


q:
Java has a convenient split method:

String str = "The quick brown fox";
String[] results = str.split(" ");

Is there an easy way to do this in C++?

[A]
Here is a sample tokenizer class that might do what you want
```
```
//Header file
class Tokenizer
{
    public:
        static const std::string DELIMITERS;
        Tokenizer(const std::string& str);
        Tokenizer(const std::string& str, const std::string& delimiters);
        bool NextToken();
        bool NextToken(const std::string& delimiters);
        const std::string GetToken() const;
        void Reset();
    protected:
        size_t m_offset;
        const std::string m_string;
        std::string m_token;
        std::string m_delimiters;
};

//CPP file
const std::string Tokenizer::DELIMITERS(" \t\n\r");

Tokenizer::Tokenizer(const std::string& s) :
    m_string(s),
    m_offset(0),
    m_delimiters(DELIMITERS) {}

Tokenizer::Tokenizer(const std::string& s, const std::string& delimiters) :
    m_string(s),
    m_offset(0),
    m_delimiters(delimiters) {}

bool Tokenizer::NextToken()
{
    return NextToken(m_delimiters);
}

bool Tokenizer::NextToken(const std::string& delimiters)
{
    size_t i = m_string.find_first_not_of(delimiters, m_offset);
    if (std::string::npos == i)
    {
        m_offset = m_string.length();
        return false;
    }

    size_t j = m_string.find_first_of(delimiters, i);
    if (std::string::npos == j)
    {
        m_token = m_string.substr(i);
        m_offset = m_string.length();
        return true;
    }

    m_token = m_string.substr(i, j - i);
    m_offset = j;
    return true;
}
```
```
Example:
```
```
std::vector <std::string> v;
Tokenizer s("split this string", " ");
while (s.NextToken())
{
    v.push_back(s.GetToken());
}
```
```


q:
Can a Linq query retrieve BLOBs from a Sql Database?

And how do they come out?

[A]
If I'm not mistaken LINQ to SQL teats BLOB as System.Byte[]
I recall that there was some problem with SqlMetal, it generated wrong type for BLOB, but MSVS dmbl designer should work.


q:
Programming in vim I often go search for something, yank it, then go back to where I was, insert it, modify it.

The problem is that after I search and find, I need to MANUALLY find my way back to where I was.

Is there an automatic way to go back to where I was when I initiated my last search?

[A]
I've always done by it setting a mark.
In command-mode, press
m
[letter]
.  For example,
m
a
sets a mark at the current line using
a
as the mark identifier.
To get back to the mark press
'
[letter]
.  For example,
'
a
takes you back to the line mark set in step 1.  To get back to the column position of the row where you marked the line, use
`
a
(
back-tick
[letter]
).
To see all of the marks that currently set, type
```
:marks
```
.
On a slightly unrelated note, I just discovered another nifty thing about marks.
Let's say you jump to mark
b
by doing
m
b
.  Vim automatically sets the mark
'
(that's a single-quote) to be whichever line you were on before jumping to mark
b
.
That means you can do
'
b
to jump to that mark, then do
''
(2 single-quotes) to jump back to wherever you were before.
I discovered this accidentally using the
```
:marks
```
command, which shows a list of all marks.


q: I'm trying to produce sheets of photographs with captions arranged in a grid using XSLT and XSL-FO. The photo URLs and captions are produced using a FOR XML query against an SQL Server database, and the number of photos returned varies from sheet to sheet. I want to lay the photos out in four columns, filling the grid from left to right and from top to bottom. In HTML I'd do this by putting each photo and caption into a div and using "float: left" to make them flow into the grid. Is there a similarly elegant method using XSL-FO?

[A]
To keep life simple I would normally setup a table for this, it's quite simple and will ensure that things get laid out right. If you wanted to do it similarly to how you would do it in HTML then you should layout block-container elements.
However you decide to do it I would always recommend using the
ZVON Reference
site. Nice lookup of elements and available attributes, and while their XSL-FO doesn't include much in the way of explanation every page deep links to the standards document.


q:
I'm running Visual Studio 2008 with the stuff-of-nightmares awful MS test framework.  Trouble is that it's sending my CPU to 100% (well 25% on a quad-core).

My question is why can't Visual Studio run on more than one core?  Surely M$ must have a sufficient handle on threading to get this to work.

[A]
I have VS2008 running on all 4 CPUs. Just set this environment variable / project flag.
/MP
(It can be set in C/C++ Settings, Advanced. In project settings)
Edit: The MP flag can also accept a number, e.g. /MP2 which means it will only run on 2 cores. Leaving it as just /MP means it will run on the maximum amount of cores.
Edit2: The MP flag is probably for the compiler only.


q:
Is there a way to convert a HTML string into a Image .tiff file?

I am using C# .NET 3.5. The requirement is to give the user an option to fact a confirmation. The confirmation is created with XML and a XSLT. Typically it is e-mailed.

Is there a way I can take the HTML string generated by the transformation HTML string and convert that to a .tiff or any image that can be faxed?

3rd party software is allowed, however the cheaper the better.

We are using a 3rd party fax library, that will only accept .tiff images, but if I can get the HTML to be any image I can covert it into a .tiff.

[A]
A starting point might be the software of
WebSuperGoo
, which provide rich image editing products, cheap or for free.
I know for sure their PDF Writer can do basic HTML (
http://www.websupergoo.com/helppdf6net/source/3-concepts/b-htmlstyles.htm
). This should not be too hard to convert to TIFF.
This does not include the full HTML subset or CSS. That might require using Microsofts IE ActiveX component.


q:
I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?

I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?

[A]
As Google Web Toolkit is a
subset of Java
it works best when you Java at the backend too.  Since Google App Engine is currently
Python only
I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.
jQuery seems to be the most popular JavaScript library option in the
AJAX Tag at DjangoSnippets.com
.
Edit:
The above is only true of Google App Engine applications written in Python.  As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end.
Google even have a tutorial showing you how to do it.


q:
Migrating a project from ASP.NET 1.1 to ASP.NET 2.0 and I keep hitting this error.

I don't actually need Global because I am not adding anything to it, but after I remove it I get more errors.

[A]
There are a few things you can try with this, seems to happen alot and the solution varies for everyone it seems.
If you are still using the IIS virtual directory make sure its pointed to the correct directory and also check the ASP.NET version it is set to, make sure it is set to ASP.NET 2.0.
Clear out your bin/debug/obj all of them. Do a
Clean solution
and then a
Build Solution
.
Check your project file in a text editor and make sure where its looking for the global file is correct, sometimes it doesnt change the directory.
Remove the global from the solution and add it back after saving and closing. make sure all the script tags in the ASPX file point to the correct one after.
You can try running the
Convert to Web Application
tool, that redoes all of the code and project files.
IIS Express is using the wrong root directory (see answer in
VS 2012 launching app based on wrong path
)
Make sure you close VS after you try them.
Those are some things I know to try. Hope one of them works for you.


q:
how can i create an application to read all my browser (firefox) history?
i noticed that i have in

C:\Users\user.name\AppData\Local\Mozilla\Firefox\Profiles\646vwtnu.default

what looks like  a sqlite database (urlclassifier3.sqlite) but i don't know if its really what is used to store de history information.
i searched for examples on how to do this but didn't find anything.

ps: although the title is similar i believe this question is not the same as "How do you access browser history?"

[A]
I believe
```
places.sqlite
```
is the one you should be looking into for history (Firefox 3). Below are a couple of Mozilla wiki entries that have some info on the subject.
Mozilla 2: Unified Storage
Browser History
(see especially section "Database Design" here)
In earlier versions of Firefox they stored history in a file called
```
history.dat
```
, which was encoded in a format called "Mork".
This perl script by Jamie Zawinski
can be used to parse Mork files.


q:
I've been trying to figure out a regex to allow me to search for a particular string while automatically skipping comments.  Anyone have an RE like this or know of one?  It doesn't even need to be sophisticated enough to skip #if 0 blocks; I just want it to skip over // and /* blocks.  The converse, that is only search inside comment blocks, would be very useful too.

Environment: VS 2003

[A]
This is a harder problem than it might at first appear, since you need to consider comment tokens inside strings, comment tokens that are themselves commented out etc.
I wrote a string and comment parser for C#, let me see if I can dig out something that will help... I'll update if I find anything.
EDIT:
... ok, so I found my old 'codemasker' project.  Turns out that I did this in stages, not with a single regex.  Basically I inch through a source file looking for start tokens, when I find one I then look for an end-token and mask everything in between.  This takes into account the context of the start token... if you find a token for "string start" then you can safely ignore comment tokens until you find the end of the string, and vice versa. Once the code is masked (I used guids as masks, and a hashtable to keep track) then you can safely do your search and replace, then finally restore the masked code.
Hope that helps.


q:
We have an ASP.NET application that manages it's own User, Roles and Permission database and we have recently added a field to the User table to hold the Windows domain account.

I would like to make it so that the user doesn't have to  physically log in to our application, but rather would be automatically logged in based on the currently logged in Windows domain account DOMAIN\username.  We want to authenticate the Windows domain account against our own User table.

This is a piece of cake to do in Windows Forms, is it possible to do this in Web Forms?

I don't want the user to be prompted with a Windows challenge screen,  I want our system to handle the log in.

Clarification: We are using our own custom Principal object.

Clarification: Not sure if it makes a difference or not, but we are using IIS7.

[A]
```
```
using System.Security.Principal;
...
WindowsPrincipal wp = (WindowsPrincipal)HttpContext.Current.User;
```
```
to get the current domain user. Of course you have to make sure that the IIS is set up to handle Windows Authentication.


q:
Are there any free tools available to view the contents of the solution user options file (the .suo file that accompanies solution files)?

I know it's basically formatted as a file system within the file, but I'd like to be able to view the contents so that I can figure out which aspects of my solution and customizations are causing it grow very large over time.

[A]
I don't know any tool, but you can try to access user settings via
IVsPersistSolutionOpts
interface


q:
Say I have a linked list of numbers of length N. N is very large and I don’t know in advance the exact value of N.

How can I most efficiently write a function that will return k completely random numbers from the list?

[A]
I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your random numbers once.
If you somehow don't know the length of your linked list (how?), then you could grab the first k into an array, then for node r, generate a random number in [0, r), and if that is less than k, replace the rth item of the array. (Not entirely convinced that doesn't bias...)
Other than that: "If I were you, I wouldn't be starting from here." Are you sure linked list is right for your problem? Is there not a better data structure, such as a good old flat array list.


q: I'm looking at a new computer which will probably have vista on it.  But there are so many editions of vista; are there any weird restrictions on what you can run on the various editions?  For instance you couldn't run IIS on Windows ME.  Can you still run IIS on the home editions of vista?


q:
Surprisingly as you get good at vim, you can code even faster than standard IDEs such as Eclipse. But one thing I really miss is code completion, especially for long variable names and functions.

Is there any way to enable code completion for Perl in vim?

[A]
Ctrl
-
P
(Get Previous Match) and
Ctrl
-
N
(Get Next Match) are kind of pseudo code completion.  They basically search the file (Backwards for
Ctrl
-
P
, Forwards for
Ctrl
-
N
) you are editing (and any open buffers, and if you are using TAGS anything in your TAG file) for words that start with what you are typing and add a drop down list.  It works surprisingly well for variables and function names, even if it isn't intellisense.  Generally I use
Ctrl
-
P
as the variable or function I am looking for is usually behind in the code.  Also if you keep the same copy of Vim open, it will search the files you have previously opened.


q:
Database? Page variables? Enum?

I'm looking for opinions here.

[A]
IF the menu is dynamic
per-user
then you'll have to hit the database for each user.  From then on I would probably store it in session to avoid future round-trips to the database.
If it's dynamic, but the entire site sees the same items, then put it in the database and cache the results


q:
How does the comma operator work in C++?

For instance, if I do:

a = b, c;

Does a end up equaling b or c?

(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)

Update:  This question has exposed a nuance when using the comma operator.  Just to document this:

a = b, c;    // a is set to the value of b!

a = (b, c);  // a is set to the value of c!

This question was actually inspired by a typo in code.  What was intended to be

a = b;
c = d;

Turned into

a = b,    //  <-  Note comma typo!
c = d;

[A]
It would be equal to
```
b
```
.
The comma operator has a lower precedence than assignment.


q: There is a lot of buzz about Microsoft Silverlight, especially after the Olympics. Also H264 will be supported in a future version. Where do you think Silverlight will be 1 year from now?

[A]
100% more.
(so about 4 people)


q:
How to implement Repository pattern withe LinqToEntities
how to implement the interface

[A]
No, they aren't (or at least you can't assume they are). Having said that, there are some tricks to do this atomically, but they typically aren't portable (see
Compare-and-swap
).


q:
I am developing a web app which requires a username and password to be stored in the web.Config, it also refers to some URLs which will be requested by the web app itself and never the client.

I know the .Net framework will not allow a web.config file to be served, however I still think its bad practice to leave this sort of information in plain text.

Everything I have read so far requires me to use a command line switch or to store values in the registry of the server.  I have access to neither of these as the host is online and I have only FTP and Control Panel (helm) access.

Can anyone recommend any good, free encryption DLL's or methods which I can use?  I'd rather not develop my own!

Thanks for the feedback so far guys but I am not able to issue commands and and not able to edit the registry.  Its going to have to be an encryption util/helper but just wondering which one!

[A]
Encrypting and Decrypting Configuration Sections
(ASP.NET) on MSDN
Encrypting Web.Config Values in ASP.NET 2.0
on ScottGu's
blog
Encrypting Custom Configuration Sections
on K. Scott Allen's
blog
EDIT:
If you can't use asp utility, you can encrypt config file using
SectionInformation.ProtectSection
method.
Sample on codeproject:
Encryption of Connection Strings inside the Web.config in ASP.Net 2.0


q:
I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx".

Path.Combine didn't fix it. Is there a function to clean this path up?

[A]
You could create a helper class which wrapped the UriBuilder class in System.Net
```
```
public static class UriHelper
{
    public static string NormalizeRelativePath(string path)
    {
        UriBuilder _builder = new UriBuilder("http://localhost");
        builder.Path = path;
        return builder.Uri.AbsolutePath;
    }
}
```
```
which could then be used like this:
```
```
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
```
```
It is a bit hacky but it would work for the specific example you gave.
EDIT: Updated to reflect Andrew's comments.


q:
Using Vim I often want to replace a block of code with a block that I just yanked.

But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.

So what is the slickest and quickest way to replace text in Vim?

is there a way to delete text without putting it into the register?

is there a way to say e.g. "replace next word" or "replace up to next paragraph"

or is the best way to somehow use the multi-register feature?

[A]
Well, first do this command:
```
```
:h d
```
```
Then you will realize that you can delete into a specific register. That way you won't alter what is in your default register.


q:
Let's say you work someplace where every change to source code must be associated with a bug-report or feature-request, and there is no way to get that policy reformed.  In such an environment, what is the best way to deal with code refactorings (that is, changes that improve the code but do not fix a bug or add a feature)?

Write up a bug-report and associate the refactoring with it.

Write up a feature-request and associate the refactoring with it.

Sneak in the refactorings while working on code that is associated with a bug-report/feature-request.

Just don't do any refactoring.

Other

Note that all bug reports and feature descriptions will be visible to managers and customers.

[A] I vote for the "sneak in refactorings" approach, which is, I believe, the way refactoring is meant to be done in the first place.  It's probably a bad idea to refactor just for the sake of "cleaning up the code."  This means that you're making changes for no real reason.  Refactoring is, by definition, modifying the without the intent of fixing bugs or adding features.  If you're following the KISS principle, any new feature is going to need at least some refactoring because you're not really thinking about how to make the most extensible system possible the first time around.


q: Sure, we can use a simple bulleted list or a mindmap.  But, there must be a better, more interactive way.  What do you use when starting your website architecture?

[A]
By "architecture", do you mean the initial site map? If not, please post a clarification and I'll edit my response.
Our tech team starts development after our creative department has done their stuff. Part of what we get is output from the information architect. He passes off a graphical sitemap, a detailed sitemap as an Excel sheet, and a set of wireframes in a PDF.


q:
The following SQL:

SELECT notes + 'SomeText'
FROM NotesTable a

Give the error:

The data types nvarchar and text are incompatible in the add operator.

[A]
The only way would be to convert your text field into an nvarchar field.
```
```
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
```
```
Otherwise, I suggest doing the concatenation in your application.


q: We have an ASP.NET application running at a customer site that uses ActiveDirectory for user login via the ActiveDirectoryMembershipProvider. Their primary domain controller that we were pointing to went down this morning, and in getting everything set back up the client was wondering if we could have a redundant connection to two domain controllers; i.e. specifying a primary and a backup AD server. A Google search proved fruitless - does anyone know if this can be done?

[A]
It can be done, it will just take some work.
You will need to create a class that inherits off of the ActiveDirectoryMemberhsipProvider and use it has your provider instead.  That way you can maintain most of the functionality.  Then setup a way to specify two connectionStringName properties, one for primary and one for secondary.  You will also need to create the code to read the information from the config since you are changing it.  Then just override the methods where you need to catch when the primary is down and switch to the secondary.  This will be the most reusable way of doing it.
There's probably other ways of doing it, but it will probably be hacky and not very reusable.  Like testing the connection before each request and then setting the connectionstring that way.
Based on the
MSDN documentation
on the class, this will probably be the only way to do it.  They don't provide the functionality internal.


q:
I have a set of calculation methods sitting in a .Net DLL.  I would like to make those methods available to Excel (2003+) users so they can use them in their spreadsheets.

For example, my .net method:

public double CalculateSomethingReallyComplex(double a, double b) {...}

I would like enable them to call this method just by typing a formula in a random cell:

=CalculateSomethingReallyComplex(A1, B1)

What would be the best way to accomplish this?

[A]
There are two methods - you can used Visual Studio Tools for Office (VSTO):
http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx
or you can use COM:
http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx
I'm not sure if the VSTO method would work in older versions of Excel, but the COM method should work fine.


q:
As I develop more with vim, I find myself wanting to copy in blocks of useful code, similar to "templates" in Eclipse.

I was thinking of making a separate file for each code chunk and just reading them in with

:r code-fornext

but that just seems kind of primitive. Googling around I find vim macros mentioned and something about "maps" but nothing that seems straightforward.

What I am looking for are e.g. something like Eclipse's "Templates" so I pop in a code chunk with the cursor sitting in the middle of it.
Or JEdit's "Macros" which I can record doing complicated deletes and renaming on one line, then I can play it again on 10 other lines so it does the same to them.

Does vim have anything like these two functionalities?

[A]
To record macros in Vim, in the command mode, hit the
```
q
```
key and another key you want to assign the macro to. For quick throw away macros I usually just hit
```
qq
```
and assign the macro to the
```
q
```
key. Once you are in recording mode, run through your key strokes. When you are done make sure you are back in command mode and hit
```
q
```
again to stop recording. Then to replay the macro manually, you can type
```
@q
```
. To replay the previously run macro you can type
```
@@
```
or to run it 10 times you could type
```
10@q
```
or
```
20@q
```
, etc..
In summary:
```
```
+----------------------------------+-------------------------------------+
| start recording a macro          | qX (X = key to assign macro to)     |
+----------------------------------+-------------------------------------+
| stop recording a macro           | q                                   |
+----------------------------------+-------------------------------------+
| playback macro                   | @X (X = key macro was assigned to)  |
+----------------------------------+-------------------------------------+
| replay previously played macro   | @@                                  |
+----------------------------------+-------------------------------------+
```
```
In regards to code chunks, I have found and started using a Vim plug-in called snipMate, which mimics TextMate's snippets feature. You can get the plug-in here:
http://www.vim.org/scripts/script.php?script_id=2540
And a short article on using snipMate (along with a short screencast showing it in use):
http://www.catonmat.net/blog/vim-plugins-snipmate-vim/
Hope you find this helpful!


q:
I need to retrieve all rows from a table where 2 columns combined are all different. So I want all the sales that do not have any other sales that happened on the same day for the same price. The sales that are unique based on day and price will get updated to an active status.

So I'm thinking:

UPDATE sales
SET status = 'ACTIVE'
WHERE id IN (SELECT DISTINCT (saleprice, saledate), id, count(id)
             FROM sales
             HAVING count = 1)

But my brain hurts going any farther than that.

[A]
```
```
SELECT DISTINCT a,b,c FROM t
```
```
is
roughly
equivalent to:
```
```
SELECT a,b,c FROM t GROUP BY a,b,c
```
```
It's a good idea to get used to the GROUP BY syntax, as it's more powerful.
For your query, I'd do it like this:
```
```
UPDATE sales
SET status='ACTIVE'
WHERE id IN
(
    SELECT id
    FROM sales S
    INNER JOIN
    (
        SELECT saleprice, saledate
        FROM sales
        GROUP BY saleprice, saledate
        HAVING COUNT(*) = 1
    ) T
    ON S.saleprice=T.saleprice AND s.saledate=T.saledate
 )
```
```


q:
If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?

Consider:

myprogram -f filename -d directory -r regex

How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)

[A]
I don't know of any documented "patterns" for processing.
I believe one of the oldest libraries/APIs for handling arguments is getopt.  Googling "getopt" shows lots of man pages and links to implementations.
Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with.  Arguments are then translated into something in this service that the application than then query.  This could be as simple as a dictionary of settings (like a string setting named "filename").


q:
Like the Delicious submission bookmark-let, I'd like to have some standard JavaScript I can use to submit any visited URL to a 3rd party site when that's possible by URL.  Suggestions?

For example, I've been using

javascript:void(location.href="http://www.yacktrack.com/home?query="+encodeURI(location.href))

so far but wonder if there's something more sophisticated I could use or better practice.

[A]
```
```
document.location = "http://url_submitting_to.com?query_string_param=" + window.location;
```
```


q:
I need to enumerate all the user defined types created in a SQL Server database with CREATE TYPE, and/or find out whether they have already been defined.

With tables or stored procedures I'd do something like this:

if exists (select * from dbo.sysobjects where name='foobar' and xtype='U')
    drop table foobar

However I can't find the equivalent (or a suitable alternative) for user defined types! I definitely can't see them anywhere in sysobjects.

Can anyone enlighten me?

[A]
Types and UDTs don't appear in sys.objects.
You should be able to get what you're looking for with the following:
```
```
select * from sys.types
where is_user_defined = 1
```
```


q:
How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:

123.45 -> 123.45
99.0   -> 99
23.2   -> 23.2
45.0   -> 45

Edit: I forgot to mention - I'm still on Java 1.4 - sorry!

[A]
If you use
DecimalFormat
and specify # in the pattern it only displays the value if it is not zero.
See my question
How do I format a number in java?
Sample Code
```
```
DecimalFormat format = new DecimalFormat("###.##");

    double[] doubles = {123.45, 99.0, 23.2, 45.0};
    for(int i=0;i<doubles.length;i++){
        System.out.println(format.format(doubles[i]));
    }
```
```


q:
Alright, so I'm working on an application which will use a Linux back-end running PostgreSQL to serve up images to a Windows box with the front end written in C#.NET, though the front-end should hardly matter.  My question is:

What is the best way to deal with storing images in Postgres?

The images are around 4-6 megapixels each, and we're storing upwards of 3000.  It might also be good to note: this is not a web application, there will at most be about two front-ends accessing the database at once.

[A]
In the database, there are two options:
bytea.  Stores the data in a column, exported as part of a backup.  Uses standard database functions to save and retrieve.  Recommended for your needs.
blobs.  Stores the data externally, not normally exported as part of a backup.  Requires special database functions to save and retrieve.
I've used bytea columns with great success in the past storing 10+gb of images with thousands of rows.  PG's TOAST functionality pretty much negates any advantage that blobs have.  You'll need to include metadata columns in either case for filename, content-type, dimensions, etc.


q:
How do I create a windows application that does the following:

it's a regular GUI app when invoked with no command line arguments

specifying the optional "--help" command line argument causes the app to write usage text to stdout then terminate

it must be a single executable.  No cheating by making a console app exec a 2nd executable.

assume the main application code is written in C/C++

bonus points if no GUI window is created when "--help" is specified.  (i.e., no flicker from a short-lived window)

In my experience the standard visual studio template for console app has no GUI capability, and the normal win32 template does not send its stdout to the parent cmd shell.

[A]
Microsoft designed console and GUI apps to be mutually exclusive.
This bit of short-sightedness means that there is no perfect solution.
The most popular approach is to have two executables (eg. cscript / wscript,
java / javaw, devenv.com / devenv.exe etc) however you've indicated that you consider this "cheating".
You've got two options - to make a "console executable" or a "gui executable",
and then use code to try to provide the other behaviour.
GUI executable:
```
cmd.exe
```
will assume that your program does no console I/O so won't wait for it to terminate
before continuing, which in interactive mode (ie not a batch) means displaying the next ("
```
C:\>
```
") prompt
and reading from the keyboard. So even if you use AttachConsole your output will be mixed
with
```
cmd
```
's output, and the situation gets worse if you try to do input. This is basically a non-starter.
Console executable:
Contrary to belief, there is nothing to stop a console executable from displaying a GUI, but there are two problems.
The first is that if you run it from the command line with no arguments (so you want the GUI),
```
cmd
```
will still wait for it to terminate before continuing, so that particular
console will be unusable for the duration. This can be overcome by launching
a second process of the same executable (do you consider this cheating?),
passing the DETACHED_PROCESS flag to CreateProcess() and immediately exiting.
The new process can then detect that it has no console and display the GUI.
Here's C code to illustrate this approach:
```
```
#include <stdio.h>
#include <windows.h>

int main(int argc, char *argv[])
{
    if (GetStdHandle(STD_OUTPUT_HANDLE) == 0) // no console, we must be the child process
    {
        MessageBox(0, "Hello GUI world!", "", 0);
    }
    else if (argc > 1) // we have command line args
    {
        printf("Hello console world!\n");
    }
    else // no command line args but a console - launch child process
    {
        DWORD dwCreationFlags = CREATE_DEFAULT_ERROR_MODE | DETACHED_PROCESS;
        STARTUPINFO startinfo;
        PROCESS_INFORMATION procinfo;
        ZeroMemory(&startinfo, sizeof(startinfo));
        startinfo.cb = sizeof(startinfo);
        if (!CreateProcess(NULL, argv[0], NULL, NULL, FALSE, dwCreationFlags, NULL, NULL, &startinfo, &procinfo))
            MessageBox(0, "CreateProcess() failed :(", "", 0);
    }
    exit(0);
}
```
```
I compiled it with cygwin's gcc - YMMV with MSVC.
The second problem is that when run from Explorer, your program will for a split second
display a console window. There's no programmatic way around this because the console is
created by Windows when the app is launched, before it starts executing. The only thing you can
do is, in your installer, make the shortcut to your program with a "show command" of
SW_HIDE (ie. 0). This will only affect the console unless you deliberately honour the wShowWindow field of STARTUPINFO
in your program, so don't do that.
I've tested this by hacking cygwin's "mkshortcut.exe". How you accomplish
it in your install program of choice is up to you.
The user can still of course run your program by finding the executable in Explorer and
double-clicking it, bypassing the console-hiding shortcut and seeing the brief black flash of a console window. There's nothing you can do about it.


q:
Assemblies A and B are privately deployed and strongly named.  Assembly A contains references to Assembly B.  There are two versions of Assembly B: B1 and B2.  I want to be able to indicate for Assembly A that it may bind to either B1 or B2 -- ideally, by incorporating this information into the assembly itself.  What are my options?

I'm somewhat familiar with versioning policy and the way it applies to the GAC, but I don't want to be dependent on these assemblies being in the GAC.

[A]
You can set version policy in your app.config file.  Alternatively you can manually load these assemblies with a call to
```
Assembly.LoadFrom()
```
when this is done assembly version is not considered.


q:
So I'm refactoring my code to implement more OOP.  I set up a class to hold page attributes.

class PageAtrributes
{
  private $db_connection;
  private $page_title;

    public function __construct($db_connection)
    {
        $this->db_connection = $db_connection;
        $this->page_title = '';
    }

    public function get_page_title()
    {
        return $this->page_title;
    }

    public function set_page_title($page_title)
    {
        $this->page_title = $page_title;
    }
}

Later on I call the set_page_title() function like so

function page_properties($objPortal) {
    $objPage->set_page_title($myrow['title']);
}

When I do I receive the error message:

Call to a member function set_page_title() on a non-object

So what am I missing?

[A]
It means that
```
$objPage
```
is not an instance of an object.  Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of
PHPs type-hinting feature
Docs
to get the error when your logic is violated:
```
```
function page_properties(PageAtrributes $objPortal) {
    ...
    $objPage->set_page_title($myrow['title']);
}
```
```
This function will only accept
```
PageAtrributes
```
for the first parameter.


q:
I've got an JComboBox with a custom inputVerifyer set to limit MaxLength when it's set to editable.

The verify method never seems to get called.

The same verifyer gets invoked on a JTextField fine.

What might I be doing wrong?

[A]
Show us a small section of your code.
```
```
package inputverifier;

import javax.swing.*;

    class Go {
    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
            runEDT();
        }});
    }
    private static void runEDT() {
        new JFrame("combo thing") {{
            setLayout(new java.awt.GridLayout(2, 1));
            add(new JComboBox() {{
                setEditable(true);
                setInputVerifier(new InputVerifier() {
                    @Override public boolean verify(JComponent input) {
                        System.err.println("Hi!");
                        return true;
                    }
                });
            }});
            add(new JTextField());
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            pack();
            setVisible(true);
        }};
    }
}
```
```
Looks like it's a problem with JComboBox being a composite component.
I'd suggest avoiding such nasty UI solutions.


q: In what scenarios is it better to use a struct vs a class in C++?

[A]
The differences between a
```
class
```
and a
```
struct
```
in C++ are:
```
struct
```
members and base classes/structs are
```
public
```
by default.
```
class
```
members and base classes/structs are
```
private
```
by default.
Both classes and structs can have a mixture of
```
public
```
,
```
protected
```
and
```
private
```
members, can use inheritance, and can have member functions.
I would recommend you:
use
```
struct
```
for plain-old-data structures without any class-like features;
use
```
class
```
when you make use of features such as
```
private
```
or
```
protected
```
members, non-default constructors and operators, etc.


q:
Multiple approaches exist to write your unit tests when using Rhino Mocks:

The Standard Syntax

Record/Replay Syntax

The Fluent Syntax

What is the ideal and most frictionless way?

[A]
Interesting question!  My own preference is the for the reflection-based syntax (what I guess you mean by the Standard Syntax).  I would argue that this is the most frictionless, as it does not add much extra code: you reference the stubs directly on your interfaces as though they were properly implemented.
I do also quite like the Fluent syntax, although this is quite cumbersome.  The Record/Replay syntax is as cumbersome as the Fluent syntax (if not more so, seemingly), but less intuitive (to me at least).  I've only used NMock2, so the Record/Replay syntax is a bit alien to me, whilst the Fluent syntax is quite familiar.
However, as
this post
suggests, if you prefer separating your expectations from your verifications/assertions, you should opt for the Fluent syntax.  It's all a matter of style and personal preference, ultimately :-)


q:
Sending a message from the Unix command line using mail TO_ADDR results in an email from $USER@$HOSTNAME. Is there a way to change the "From:" address inserted by mail?

For the record, I'm using GNU Mailutils 1.1/1.2 on Ubuntu (but I've seen the same behavior with Fedora and RHEL).

[EDIT]

$ mail -s Testing chris@example.org
Cc:
From: foo@bar.org

Testing
.

yields

Subject: Testing
To: <chris@example.org>
X-Mailer: mail (GNU Mailutils 1.1)
Message-Id: <E1KdTJj-00025z-RK@localhost>
From: <chris@localhost>
Date: Wed, 10 Sep 2008 13:17:23 -0400

From: foo@bar.org

Testing

The "From: foo@bar.org" line is part of the message body, not part of the header.

[A]
Here are some options:
If you have privelige enough, configure sendmail to do rewrites with the generics table
Write the entire header yourself (or mail it to yourself, save the entire message with all headers, and re-edit, and send it with rmail from the command line
Send directly with sendmail, use the "-f" command line flag and don't include your "From:" line in your message
These aren't all exactly the same, but I'll leave it to you look into it further.
On my portable, I have sendmail authenticating as a client to an outgoing mail server and I use generics to make returning mail come to another account.  It works like a charm.
I aggregate incoming mail with fetchmail.


q: I have a large legacy codebase with very complicated makefiles, with lots of variables.  Sometimes I need to change them, and I find that it's very difficult to figure out why the change isn't working the way I expect.  What I'd like to find is a tool that basically does step-through-debugging of the "make" process, where I would give it a directory, and I would be able to see the value of different variables at different points in the process.  None of the debug flags to make seem to show me what I want, although it's possible that I'm missing something.  Does anyone know of a way to do this?

[A]
Have you been looking at the output from running
```
make -n
```
and
```
make -np
```
, and the biggie
```
make -nd
```
?
Are you using a fairly recent version of
```
gmake
```
?
Have you looked at the free chapter on
Debugging Makefiles
available on O'Reilly's site for their excellent book "Managing Projects with GNU Make" (
Amazon Link
).


q: For example, I want to populate a gridview control in an ASP.NET web page with only the data necessary for the # of rows displayed. How can NHibernate support this?

[A]
How about using Linq to NHibernate as discussed in
this blog post
by Ayende?
Code Sample:
```
```
(from c in nwnd.Customers select c.CustomerID)
        .Skip(10).Take(10).ToList();
```
```
And here is a detailed post by the NHibernate team blog on
Data Access With NHibernate
including implementing paging.


q: In C# WinForms, what's the proper way to get the backward/forward history stacks for the System.Windows.Forms.WebBrowser?

[A]
It doesn't look like it's possible.
My suggestion would be to catch the
Navigated
event and maintain your own list. A possible problem with that is when the user clicks
back
in the browser, you don't know to unwind the stack.


q:
Does anyone know of a good (preferably open source) library for dealing with the Modbus protocol? I have seen a few libraries, but I am looking for some people's personal experiences, not just the top ten Google hits. I figure there has to be at least one other person who deals with PLCs and automation hardware like I do out there.

Open to any other materials that might have been a help to you as well...

[A]
I have done a lot of communication with devices for the past few years, since I work for a home automation company, but we don't use Modbus.  We do communication in a standard and open way using Web Services for Devices(WSD) which is also know as
Devices Profile for Web Services(DPWS)
.
During this time at one point, I did hear of a project called
NModbus
.  It is an open source library for working with modbus.  I have not used it, but looking at the site and the
changesets
on Google Code, it looks pretty active.  You may want to give it a look and even get involved in.  This is the only library that I have heard of that targets .Net.


q: What is the difference between old style and new style classes in Python?  When should I use one or the other?

[A]
From
New-style and classic classes
:
Up to Python 2.1, old-style classes were the only flavour available to the user.
The concept of (old-style) class is unrelated to the concept of type:
  if
```
x
```
is an instance of an old-style class, then
```
x.__class__
```
designates the class of
```
x
```
, but
```
type(x)
```
is always
```
<type
  'instance'>
```
.
This reflects the fact that all old-style instances, independently of
  their class, are implemented with a single built-in type, called
  instance.
New-style classes were introduced in Python 2.2 to unify the concepts of class and type
.
  A new-style class is simply a user-defined type, no more, no less.
If x is an instance of a new-style class, then
```
type(x)
```
is typically
  the same as
```
x.__class__
```
(although this is not guaranteed – a
  new-style class instance is permitted to override the value returned
  for
```
x.__class__
```
).
The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model
.
It also has a number of immediate benefits, like the ability to
  subclass most built-in types, or the introduction of "descriptors",
  which enable computed properties.
For compatibility reasons, classes are still old-style by default
.
New-style classes are created by specifying another new-style class
  (i.e. a type) as a parent class, or the "top-level type" object if no
  other parent is needed.
The behaviour of new-style classes differs from that of old-style
  classes in a number of important details in addition to what type
  returns.
Some of these changes are fundamental to the new object model, like
  the way special methods are invoked. Others are "fixes" that could not
  be implemented before for compatibility concerns, like the method
  resolution order in case of multiple inheritance.
Python 3 only has new-style classes
.
No matter if you subclass from
```
object
```
or not, classes are new-style
  in Python 3.


q: What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.

[A]
You should be catching the exception in a try-catch block.
```
```
e.getStackTrace();
```
```
That returns StackTraceElement[] that you can then interpret.
Also:
```
```
e.printStackTrace()
```
```
will...print the stacktrace.


q:
I have an ArrayList<String> that I'd like to return a copy of.  ArrayList has a clone method which has the following signature:

public Object clone()

After I call this method, how do I cast the returned Object back to ArrayList<String>?

[A]
```
```
ArrayList first = new ArrayList ();
ArrayList copy = (ArrayList) first.clone ();
```
```


q: Is it possible, in Java, to make a JPanel skip drawing its background thus being transparent except for the components on it?

[A]
```
setOpaque(false)
```
It'll pass off painting the background to its parent, which may draw its own background.
You can do a screen capture and then use that to paint the background of the panel.


q: Which scenarios, areas of an application/system, etc. are best suited for 'classic' state based testing versus using mock objects?

[A] You should be using mocks for dependencies.  I don't think that its an either-or; Usually you will create mocks for dependencies, set expectations (whether it is calls or state) on them, then run the unit under test.  Then you would check its state, and verify the expectations on the mocks, afterwards.


q:
How would I go about replacing Windows Explorer with a third party tool such as TotalCommander, explorer++, etc?

I would like to have one of those load instead of win explorer when I type "C:\directoryName" into the run window. Is this possible?

[A]
From a comment on the first LifeHacker link,
How to make x² your default folder application
As part of the installation process, x² adds "open with xplorer2" in the context menu for
filesystem folders.
If you want to have this the default action (so that folders always open in x2 when you click on
them) then make sure this is the default verb, either using Folder Options ("file folder" type) or
editing the registry:
```
```
[HKEY_CLASSES_ROOT\Directory\shell]
@="open_x2"
```
```
If you want some slightly different command line options, you can add any of the supported
options by editing the following registry key:
```
```
[HKEY_CLASSES_ROOT\Directory\shell\open\command]
@="C:\Program files\zabkat\xplorer2\xplorer2_UC.exe" /T /1 "%1"
```
```
Notes:
Please check your installation folder first: Your installation path may be different.
Secondly, your executable may be called
```
xplorer2.exe
```
, if it is the non-Unicode version.
Note that
```
"%1"
```
is required (including the quotation marks), and is replaced by the folder path you are trying to open.
The
```
/T
```
switch causes no tabs to be restored and the
```
/1
```
switch puts x² in single pane mode. (You do not have to use these switches, but they make sense).
(The above are from xplorer2 user manual)


q: Is it possible to change the hostname in Windows 2003 from the command line with out-of-the-box tools?

[A]
I don't know of a command to do this, but you could do it in VBScript or something similar.
Somthing like:
```
```
sNewName = "put new name here"

Set oShell = CreateObject ("WSCript.shell" )

sCCS = "HKLM\SYSTEM\CurrentControlSet\"
sTcpipParamsRegPath = sCCS & "Services\Tcpip\Parameters\"
sCompNameRegPath = sCCS & "Control\ComputerName\"

With oShell
.RegDelete sTcpipParamsRegPath & "Hostname"
.RegDelete sTcpipParamsRegPath & "NV Hostname"

.RegWrite sCompNameRegPath & "ComputerName\ComputerName", sNewName
.RegWrite sCompNameRegPath & "ActiveComputerName\ComputerName", sNewName
.RegWrite sTcpipParamsRegPath & "Hostname", sNewName
.RegWrite sTcpipParamsRegPath & "NV Hostname", sNewName
End With ' oShell

MsgBox "Computer name changed, please reboot your computer"
```
```
Original


q:
When a user on our site loses his password and heads off to the Lost Password page we need to give him a new temporary password. I don't really mind how random this is, or if it matches all the "needed" strong password rules, all I want to do is give them a password that they can change later.

The application is a Web application written in C#. so I was thinking of being mean and going for the easy route of using part of a Guid. i.e.

Guid.NewGuid().ToString("d").Substring(1,8)

Suggesstions? thoughts?

[A]
This is a lot larger, but I think it looks a little more comprehensive:
http://www.obviex.com/Samples/Password.aspx
```
```
///////////////////////////////////////////////////////////////////////////////
// SAMPLE: Generates random password, which complies with the strong password
//         rules and does not contain ambiguous characters.
//
// To run this sample, create a new Visual C# project using the Console
// Application template and replace the contents of the Class1.cs file with
// the code below.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
//
// Copyright (C) 2004 Obviex(TM). All rights reserved.
//
using System;
using System.Security.Cryptography;

/// <summary>
/// This class can generate random passwords, which do not include ambiguous
/// characters, such as I, l, and 1. The generated password will be made of
/// 7-bit ASCII symbols. Every four characters will include one lower case
/// character, one upper case character, one number, and one special symbol
/// (such as '%') in a random order. The password will always start with an
/// alpha-numeric character; it will not start with a special symbol (we do
/// this because some back-end systems do not like certain special
/// characters in the first position).
/// </summary>
public class RandomPassword
{
    // Define default min and max password lengths.
    private static int DEFAULT_MIN_PASSWORD_LENGTH  = 8;
    private static int DEFAULT_MAX_PASSWORD_LENGTH  = 10;

    // Define supported password characters divided into groups.
    // You can add (or remove) characters to (from) these groups.
    private static string PASSWORD_CHARS_LCASE  = "abcdefgijkmnopqrstwxyz";
    private static string PASSWORD_CHARS_UCASE  = "ABCDEFGHJKLMNPQRSTWXYZ";
    private static string PASSWORD_CHARS_NUMERIC= "23456789";
    private static string PASSWORD_CHARS_SPECIAL= "*$-+?_&=!%{}/";

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random. It will be no shorter than the minimum default and
    /// no longer than maximum default.
    /// </remarks>
    public static string Generate()
    {
        return Generate(DEFAULT_MIN_PASSWORD_LENGTH,
                        DEFAULT_MAX_PASSWORD_LENGTH);
    }

    /// <summary>
    /// Generates a random password of the exact length.
    /// </summary>
    /// <param name="length">
    /// Exact password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    public static string Generate(int length)
    {
        return Generate(length, length);
    }

    /// <summary>
    /// Generates a random password.
    /// </summary>
    /// <param name="minLength">
    /// Minimum password length.
    /// </param>
    /// <param name="maxLength">
    /// Maximum password length.
    /// </param>
    /// <returns>
    /// Randomly generated password.
    /// </returns>
    /// <remarks>
    /// The length of the generated password will be determined at
    /// random and it will fall with the range determined by the
    /// function parameters.
    /// </remarks>
    public static string Generate(int   minLength,
                                  int   maxLength)
    {
        // Make sure that input parameters are valid.
        if (minLength <= 0 || maxLength <= 0 || minLength > maxLength)
            return null;

        // Create a local array containing supported password characters
        // grouped by types. You can remove character groups from this
        // array, but doing so will weaken the password strength.
        char[][] charGroups = new char[][]
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
            PASSWORD_CHARS_SPECIAL.ToCharArray()
        };

        // Use this array to track the number of unused characters in each
        // character group.
        int[] charsLeftInGroup = new int[charGroups.Length];

        // Initially, all characters in each group are not used.
        for (int i=0; i<charsLeftInGroup.Length; i++)
            charsLeftInGroup[i] = charGroups[i].Length;

        // Use this array to track (iterate through) unused character groups.
        int[] leftGroupsOrder = new int[charGroups.Length];

        // Initially, all character groups are not used.
        for (int i=0; i<leftGroupsOrder.Length; i++)
            leftGroupsOrder[i] = i;

        // Because we cannot use the default randomizer, which is based on the
        // current time (it will produce the same "random" number within a
        // second), we will use a random number generator to seed the
        // randomizer.

        // Use a 4-byte array to fill it with random bytes and convert it then
        // to an integer value.
        byte[] randomBytes = new byte[4];

        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);

        // Convert 4 bytes into a 32-bit integer value.
        int seed = BitConverter.ToInt32(randomBytes, 0);

        // Now, this is real randomization.
        Random  random  = new Random(seed);

        // This array will hold password characters.
        char[] password = null;

        // Allocate appropriate memory for the password.
        if (minLength < maxLength)
            password = new char[random.Next(minLength, maxLength+1)];
        else
            password = new char[minLength];

        // Index of the next character to be added to password.
        int nextCharIdx;

        // Index of the next character group to be processed.
        int nextGroupIdx;

        // Index which will be used to track not processed character groups.
        int nextLeftGroupsOrderIdx;

        // Index of the last non-processed character in a group.
        int lastCharIdx;

        // Index of the last non-processed group.
        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

        // Generate password characters one at a time.
        for (int i=0; i<password.Length; i++)
        {
            // If only one character group remained unprocessed, process it;
            // otherwise, pick a random character group from the unprocessed
            // group list. To allow a special character to appear in the
            // first position, increment the second parameter of the Next
            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
            if (lastLeftGroupsOrderIdx == 0)
                nextLeftGroupsOrderIdx = 0;
            else
                nextLeftGroupsOrderIdx = random.Next(0,
                                                     lastLeftGroupsOrderIdx);

            // Get the actual index of the character group, from which we will
            // pick the next character.
            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

            // Get the index of the last unprocessed characters in this group.
            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

            // If only one unprocessed character is left, pick it; otherwise,
            // get a random character from the unused character list.
            if (lastCharIdx == 0)
                nextCharIdx = 0;
            else
                nextCharIdx = random.Next(0, lastCharIdx+1);

            // Add this character to the password.
            password[i] = charGroups[nextGroupIdx][nextCharIdx];

            // If we processed the last character in this group, start over.
            if (lastCharIdx == 0)
                charsLeftInGroup[nextGroupIdx] =
                                          charGroups[nextGroupIdx].Length;
            // There are more unprocessed characters left.
            else
            {
                // Swap processed character with the last unprocessed character
                // so that we don't pick it until we process all characters in
                // this group.
                if (lastCharIdx != nextCharIdx)
                {
                    char temp = charGroups[nextGroupIdx][lastCharIdx];
                    charGroups[nextGroupIdx][lastCharIdx] =
                                charGroups[nextGroupIdx][nextCharIdx];
                    charGroups[nextGroupIdx][nextCharIdx] = temp;
                }
                // Decrement the number of unprocessed characters in
                // this group.
                charsLeftInGroup[nextGroupIdx]--;
            }

            // If we processed the last group, start all over.
            if (lastLeftGroupsOrderIdx == 0)
                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // There are more unprocessed groups left.
            else
            {
                // Swap processed group with the last unprocessed group
                // so that we don't pick it until we process all groups.
                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                {
                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                    leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                leftGroupsOrder[nextLeftGroupsOrderIdx];
                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                }
                // Decrement the number of unprocessed groups.
                lastLeftGroupsOrderIdx--;
            }
        }

        // Convert password characters into a string and return the result.
        return new string(password);
     }
}

/// <summary>
/// Illustrates the use of the RandomPassword class.
/// </summary>
public class RandomPasswordTest
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        // Print 100 randomly generated passwords (8-to-10 char long).
        for (int i=0; i<100; i++)
            Console.WriteLine(RandomPassword.Generate(8, 10));
    }
}
//
// END OF FILE
///////////////////////////////////////////////////////////////////////////////
```
```