q: I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.

[A]
Take a look at the
JQuery Validation plugin
this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX.
Also a sample MVC controller method can be found
here
which basically uses the JsonResult action type like:
```
```
public JsonResult CheckUserName(string username)
{
    return Json(CheckValidUsername(username));
}
```
```


q:
I'm trying to fully understand all of Haskell's concepts.

In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway?

I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.

[A]
"Algebraic Data Types" in Haskell support
full parametric polymorphism
, which is the more technically correct name for generics, as a simple example the list data type:
```
```
data List a = Cons a (List a) | Nil
```
```
Is equivalent (as much as is possible, and ignoring non-strict evaluation, etc) to
```
```
class List<a> {
     class Cons : List<a> {
         a head;
         List<a> tail;
     }
     class Nil : List<a> {}
 }
```
```
Of course Haskell's type system allows more ... interesting use of type parameters but this is just a simple example.  With regards to the "Algebraic Type" name, i've honestly never been entirely sure of the exact reason for them being named that, but have assumed that it's due the mathematical underpinnings of the type system.  I
believe
that the reason boils down to the theoretical definition of an ADT being the "product of a set of constructors", however it's been a couple of years since i escaped university so i can no longer remember the specifics.
[Edit: Thanks to Chris Conway for pointing out my foolish error, ADT are of course sum types, the constructors providing the product/tuple of fields]

s: huggingface

c: devops

d: intermediate


q:
It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work

/something to search for/i

[A]
You can also type command
```
-I
```
while less is running. It toggles case sensitivity for searches.


q:
I know there are at least 10 different ways to structure project in version control. I'm curious what some methods being used are and which ones work for you.  I've worked with SVN, TFS, and currently/unfortunately VSS.  I've seen version control implemented very poorly and just OK, but never great.

Just to get the ball rolling, here is a review of things I've seen.

This example is SVN-based, but applies to most VCS's (not so much to distributed version control).

branch the individual projects that are part of site
/division/web/projectName/vb/src/[trunk|branches|tags]

branch the whole site, in the case I've seen, the whole site except for core components was branched.
/division/[trunk|branches|tags]/web/projectName/vb/src/

Use main-line a default, only branch when necessary for huge changes.

[A]
Example for SVN:
trunk/
branch/
tags/
The trunk should be kept at a point where you can always push a release from it. There should be no huge gaping bugs that you know about(of course there will be eventually but that is what you should strive for).
Every time you need to make a new feature, do a design change, whatever, branch. Tag that branch at the start. Then when you are finished with the branch tag it at the end. This helps out with merging back into trunk.
Every time you need to push a release, tag. This way if something goes horribly wrong you can rollback to the previous release.
This setup keeps trunk as clean as possible and allows you to make quick bug fixes and push them out while keeping the majority of your development in branches.
Edit:
For 3rd party stuff it depends. If I can avoid it I do not have it under source control. I keep it in a directory outside source control and include it from there. For things like jquery, I do leave it under source control. The reason is it simplifies my script for pushing. I can simply have it do an svn export and rsync.


q: I am looking for a lightweight source control system for use on "hobby" projects with only one person (myself) working on the project. Does anyone have any suggestions? Ideally it should interface with Visual Studio either naively or through another plug-in, outside of that, anything that works would be nice to be replace Gmail as source control.

[A]
Hobby or Serious project,
SVN 1-Click Setup
(
download
```
Svn1ClickSetup-1.3.3.exe
```
) gives you all you need with ease :)


q:
Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:

Running the tests becomes automate-able and repeatable

You can test at a much more granular level than point-and-click testing via a GUI

Rytmis

My question is, what are the current "best practices" in terms of tools as well as when and where to use unit testing as part of your daily coding?

Lets try to be somewhat language agnostic and cover all the bases.

[A]
The xUnit family are the mainstay of unit testing. They are integrated into the likes of Netbeans, Eclipse and many other IDEs. They offer a simple, structured solution to unit testing.
One thing I always try and do when writing a test is to minimise external code usage. By that I mean: I try to minimise the setup and teardown code for the test as much as possible and try to avoid using other modules/code blocks as much as possible. Well-written modular code shouldn't require too much external code in it's setup and teardown.


q: What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an XSS or SQL injection attack?

[A]
If you are using a framework like
django
, the framework can easily do this for you using standard filters.  In fact, I'm pretty sure django automatically does it unless you tell it not to.
Otherwise, I would recommend using some sort of regex validation before accepting inputs from forms.  I don't think there's a silver bullet for your problem, but using the re module, you should be able to construct what you need.


q: My HTML is all marked up, ready to make it rain CSS.  The problem is that I have to go back and find out what all my id and class names are so I can get started.  What I need is a tool that parses my HTML and spits out a stylesheet with all the possible elements ready to be styled (maybe even with some defaults).  Does such a tool exist?

[A]
I have a poor man's version of this I have used in the past... this requires jquery and firebug...
```
```
<script type="text/javascript">
    $(document).ready(function() {

        $('*[@id]').each(function() {
            console.log('#' + this.id + ' {}');
        });
        $('*[@class]').each(function() {
            $.each($(this).attr('class').split(" "), function() {
                console.log('.' + this + ' {}');
            });
        });
     });
</script>
```
```
it gives you something like this:
```
```
#spinner {}
#log {}
#area {}
.cards {}
.dialog {}
.controller {}
```
```
if you want them in "natural" page order instead...
```
```
<script type="text/javascript">
    $(document).ready(function() {
         $('*').each(function() {
             if($(this).is('[@id]')) {
                 console.log('#' + this.id + ' {}');
             }
             if($(this).is('[@class]')) {
                 $.each($(this).attr('class').split(" "), function() {
                     console.log('.' + this + ' {}');
                 });
             }
         });
     });
</script>
```
```
I just load the page with that script in there, then cut and paste the results out of firebug... then obviously, remove the script :)
you'll need to remove the dups manually or just toss in some simple dup checking logic with a map or array or something.. one for IDs and one for classes.


q:
I would like to rename files and folders recursively by applying a string replacement operation.

E.g. The word "shark" in files and folders should be replaced by the word "orca".

C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe

should be moved to:

C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe

The same operation should be of course applied to each child object in each folder level as well.

I was experimenting with some of the members of the System.IO.FileInfo and System.IO.DirectoryInfo classes but didn't find an easy way to do it.

fi.MoveTo(fi.FullName.Replace("shark", "orca"));

Doesn't do the trick.

I was hoping there is some kind of "genius" way to perform this kind of operation.

[A]
So you would use recursion. Here is a powershell example that should be easy to convert to C#:
```
```
function Move-Stuff($folder)
{
    foreach($sub in [System.IO.Directory]::GetDirectories($folder))
      {
        Move-Stuff $sub
    }
    $new = $folder.Replace("Shark", "Orca")
    if(!(Test-Path($new)))
    {
        new-item -path $new -type directory
    }
    foreach($file in [System.IO.Directory]::GetFiles($folder))
    {
        $new = $file.Replace("Shark", "Orca")
        move-item $file $new
    }
}

Move-Stuff "C:\Temp\Test"
```
```


q: I would like to have a nice template for doing this in development. How do I reset an increment identity's starting value in SQL Server?

[A]
```
```
DBCC CHECKIDENT('TableName', RESEED, 0)
```
```


q: How do I convert a DateTime structure to its equivalent RFC 3339 formatted string representation and/or parse this string representation back to a DateTime structure? The RFC-3339 date-time format is used in a number of specifications such as the Atom Syndication Format.

[A]
This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC).
```
```
using System;
using System.Globalization;

namespace DateTimeConsoleApplication
{
    ///
    /// Provides methods for converting <see cref="DateTime"/> structures to and from the equivalent RFC 3339 string representation.
    ///
    public static class Rfc3339DateTime
    {
        //============================================================
        //  Private members
        //============================================================
        #region Private Members
        ///
        /// Private member to hold array of formats that RFC 3339 date-time representations conform to.
        ///
        private static string[] formats = new string[0];
        ///
        /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format.
        ///
        private const string format = "yyyy-MM-dd'T'HH:mm:ss.fffK";
        #endregion

        //============================================================
        //  Public Properties
        //============================================================
        #region Rfc3339DateTimeFormat
        ///
        /// Gets the custom format specifier that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.
        ///
        /// <value>A DateTime format string that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.</value>
        /// <remarks>
        /// <para>
        /// This method returns a string representation of a <see cref="DateTime"/> that
        /// is precise to the three most significant digits of the seconds fraction; that is, it represents
        /// the milliseconds in a date and time value. The <see cref="Rfc3339DateTimeFormat"/> is a valid
        /// date-time format string for use in the <see cref="DateTime.ToString(String, IFormatProvider)"/> method.
        /// </para>
        /// </remarks>
        public static string Rfc3339DateTimeFormat
        {
            get
            {
                return format;
            }
        }
        #endregion

        #region Rfc3339DateTimePatterns
        ///
        /// Gets an array of the expected formats for RFC 3339 date-time string representations.
        ///
        /// <value>
        /// An array of the expected formats for RFC 3339 date-time string representations
        /// that may used in the <see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/> method.
        /// </value>
        public static string[] Rfc3339DateTimePatterns
        {
            get
            {
                if (formats.Length > 0)
                {
                    return formats;
                }
                else
                {
                    formats = new string[11];

                    // Rfc3339DateTimePatterns
                    formats[0] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK";
                    formats[1] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK";
                    formats[2] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK";
                    formats[3] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK";
                    formats[4] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK";
                    formats[5] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK";
                    formats[6] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK";
                    formats[7] = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK";

                    // Fall back patterns
                    formats[8] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern
                    formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern;
                    formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern;

                    return formats;
                }
            }
        }
        #endregion

        //============================================================
        //  Public Methods
        //============================================================
        #region Parse(string s)
        ///
        /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
        ///
        /// <param name="s">A string containing a date and time to convert.</param>
        /// <returns>A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>.</returns>
        /// <remarks>
        /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
        /// </remarks>
        /// <exception cref="ArgumentNullException"><paramref name="s"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="FormatException"><paramref name="s"/> does not contain a valid RFC 3339 string representation of a date and time.</exception>
        public static DateTime Parse(string s)
        {
            //------------------------------------------------------------
            //  Validate parameter
            //------------------------------------------------------------
            if(s == null)
            {
                throw new ArgumentNullException("s");
            }

            DateTime result;
            if (Rfc3339DateTime.TryParse(s, out result))
            {
                return result;
            }
            else
            {
                throw new FormatException(String.Format(null, "{0} is not a valid RFC 3339 string representation of a date and time.", s));
            }
        }
        #endregion

        #region ToString(DateTime utcDateTime)
        ///
        /// Converts the value of the specified <see cref="DateTime"/> object to its equivalent string representation.
        ///
        /// <param name="utcDateTime">The Coordinated Universal Time (UTC) <see cref="DateTime"/> to convert.</param>
        /// <returns>A RFC 3339 string representation of the value of the <paramref name="utcDateTime"/>.</returns>
        /// <remarks>
        /// <para>
        /// This method returns a string representation of the <paramref name="utcDateTime"/> that
        /// is precise to the three most significant digits of the seconds fraction; that is, it represents
        /// the milliseconds in a date and time value.
        /// </para>
        /// <para>
        /// While it is possible to display higher precision fractions of a second component of a time value,
        /// that value may not be meaningful. The precision of date and time values depends on the resolution
        /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's
        /// resolution is approximately 10-15 milliseconds.
        /// </para>
        /// </remarks>
        /// <exception cref="ArgumentException">The specified <paramref name="utcDateTime"/> object does not represent a <see cref="DateTimeKind.Utc">Coordinated Universal Time (UTC)</see> value.</exception>
        public static string ToString(DateTime utcDateTime)
        {
            if (utcDateTime.Kind != DateTimeKind.Utc)
            {
                throw new ArgumentException("utcDateTime");
            }

            return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo);
        }
        #endregion

        #region TryParse(string s, out DateTime result)
        ///
        /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent.
        ///
        /// <param name="s">A string containing a date and time to convert.</param>
        /// <param name="result">
        /// When this method returns, contains the <see cref="DateTime"/> value equivalent to the date and time
        /// contained in <paramref name="s"/>, if the conversion succeeded,
        /// or <see cref="DateTime.MinValue">MinValue</see> if the conversion failed.
        /// The conversion fails if the s parameter is a null reference (Nothing in Visual Basic),
        /// or does not contain a valid string representation of a date and time.
        /// This parameter is passed uninitialized.
        /// </param>
        /// <returns>true if the <paramref name="s"/> parameter was converted successfully; otherwise, false.</returns>
        /// <remarks>
        /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object.
        /// </remarks>
        public static bool TryParse(string s, out DateTime result)
        {
            //------------------------------------------------------------
            //  Attempt to convert string representation
            //------------------------------------------------------------
            bool wasConverted   = false;
            result              = DateTime.MinValue;

            if (!String.IsNullOrEmpty(s))
            {
                DateTime parseResult;
                if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult))
                {
                    result          = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc);
                    wasConverted    = true;
                }
            }

            return wasConverted;
        }
        #endregion
    }
}
```
```


q: How do you use network sockets in Pascal?

[A]
Here's an example taken from
http://www.bastisoft.de/programmierung/pascal/pasinet.html
```
```
program daytime;

{ Simple client program }

uses
   sockets, inetaux, myerror;

const
   RemotePort : Word = 13;

var
   Sock : LongInt;
   sAddr : TInetSockAddr;
   sin, sout : Text;
   Line : String;

begin
   if ParamCount = 0 then GenError('Supply IP address as parameter.');

   with sAddr do
   begin
      Family := af_inet;
      Port := htons(RemotePort);
      Addr := StrToAddr(ParamStr(1));
      if Addr = 0 then GenError('Not a valid IP address.');
   end;

   Sock := Socket(af_inet, sock_stream, 0);
   if Sock = -1 then SockError('Socket: ');

   if not Connect(Sock, sAddr, sizeof(sAddr)) then SockError('Connect: ');
   Sock2Text(Sock, sin, sout);
   Reset(sin);
   Rewrite(sout);

   while not eof(sin) do
   begin
      Readln(sin, Line);
      Writeln(Line);
   end;

   Close(sin);
   Close(sout);
   Shutdown(Sock, 2);
end.
```
```


q:
I'm trying to find the best way to speed up the delivery of the static images that compose the design of an mvc site. The images are not gzipped, nor cached in the server or on the client (with  content expire). Options are:

Find why images are not cached and gzipped direcly from IIS6

Write a specialized http handler

Register a special route for static images and write a bynary actionresult method

What could be the best solution in terms of performance?

[A]
Best solution is to let IIS do it.
IIS6 Compression
- most likely you need to
specify file types to be compressed
like .jpg, .png, .gif types, etc.
Caching will come from making sure that the correct headers are being sent to the client from code, and i believe there is a setting you can set in IIS that enables it for static content, but i'm not sure on that one.


q:
I have a simple CAML query like

<Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where>

And I have a variable to substitute for Value text. What's the best way to validate/escape the text that is substituted here in the .NET framework?
I've done a quick web search on this problem but all what I found was System.Xml.Convert class but this seems to be not quite what I need here.

I know I could have gone with an XmlWriter here, but it seems like a lot of code for such a simple task where I just need to make sure that the Value text part is formatted well.

[A]
use
```
System.Xml.Linq.XElement
```
and
```
SetValue
```
method. This will format the text
(assuming a string)
, but also allows you to set xml as the value.


q:
I know what yield does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?

(Ideally some problem that cannot be solved some other way)

[A]
actually I use it in a non traditional way on my site
IdeaPipe
```
```
public override IEnumerator<T> GetEnumerator()
{
    // goes through the collection and only returns the ones that are visible for the current user
    // this is done at this level instead of the display level so that ideas do not bleed through
    // on services
    foreach (T idea in InternalCollection)
        if (idea.IsViewingAuthorized)
            yield return idea;
}
```
```
so basically it checks if viewing the idea is currently authorized and if it is it returns the idea.  If it isn't, it is just skipped.  This allows me to cache the Ideas but still display the ideas to the users that are authorized.  Else I would have to re pull them each time based on permissions, when they are only re-ranked every 1 hour.


q: I've got a Palm OS/Garnet 68K application that uses a third-party static library built with CodeWarrior.  Can I rebuilt the application using PRC-Tools, the port of GCC for the Palm OS platform and still link with the third-party library?

[A]
No, CodeWarrior uses a different object file format than PRC-Tools.  Also, the compiler support libraries are different, so even if the code could be linked together, it may use symbols in a different way.
However, if you can wrap the third-party library into a shared library using CodeWarrior, then you should be able to call it from PRC-Tools applications.  The shared library interface works across tools, but shared libraries have limited system support, so you'll need to be sure the original code doesn't use global variables for this to work.


q: I know that IList is the interface and List is the concrete type but I still don't know when to use each one. What I'm doing now is if I don't need the Sort or FindAll methods I use the interface. Am I right? Is there a better way to decide when to use the interface or the concrete type?

[A]
I don't think there are hard and fast rules for this type of thing, but I usually go by the guideline of using the lightest possible way until absolutely necessary.
For example, let's say you have a
```
Person
```
class and a
```
Group
```
class. A
```
Group
```
instance has many people, so a List here would make sense. When I declare the list object in
```
Group
```
I will use an
```
IList<Person>
```
and instantiate it as a
```
List
```
.
```
```
public class Group {
  private IList<Person> people;

  public Group() {
    this.people = new List<Person>();
  }
}
```
```
And, if you don't even need everything in
```
IList
```
you can always use
```
IEnumerable
```
too. With modern compilers and processors, I don't think there is really any speed difference, so this is more just a matter of style.


q:
I've tried to do this several times with no luck.  After reading this post, it made me interested in doing this again.  So can anyone tell me why the following doesn't work?

<?php

$guest = 1;
$editor = 2;
$admin = 4;

$user = $editor;

if( $user == ($editor | $admin) ) {
    echo "Test";
}

?>

[A]
It's been a long time since I used PHP, but I will assume that this will work:
```
```
<?php

    $guest = 1;
    $editor = 2;
    $admin = 4;

    $user = $editor;

    if( ($user == $editor) || ($user == $admin) ) {
        echo "Test";
    }

?>
```
```


q:
In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it.

Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the .bat equivalent of "@echo on".

[A]
Use open instead. Then you can capture the output of the command.
```
```
open(LS,"|ls");
print LS;
```
```


q:
I am creating an ZIP file with ZipFile in Python 2.5, it works OK so far:

import zipfile, os

locfile = "test.txt"
loczip = os.path.splitext (locfile)[0] + ".zip"
zip = zipfile.ZipFile (loczip, "w")
zip.write (locfile)
zip.close()

But I couldn't find how to encrypt the files in the ZIP file.
I could use system and call PKZIP -s, but I suppose there must be a more "Pythonic" way.  I'm looking for an open source solution.

[A]
You can use the
Chilkat
library.  It's commercial, but has a free evaluation and seems pretty nice.
Here's an example I got from
here
:
```
```
import chilkat

# Demonstrates how to create a WinZip-compatible 128-bit AES strong encrypted zip
zip = chilkat.CkZip()
zip.UnlockComponent("anything for 30-day trial")

zip.NewZip("strongEncrypted.zip")

# Set the Encryption property = 4, which indicates WinZip compatible AES encryption.
zip.put_Encryption(4)
# The key length can be 128, 192, or 256.
zip.put_EncryptKeyLength(128)
zip.SetPassword("secret")

zip.AppendFiles("exampleData/*",True)
zip.WriteZip()
```
```


q:
Browse to a webpage with hyperlinks using  IE (I am using IE7) Once on the page, enlarge the fonts using ctl + mouse wheel. Now when  you try to hover over the hyperlinks, they are laterally displaced to the right. To click on the link, i have to move the mouse to the right till the cursor turns into a hand.
Anyone has a comment on this??

I was browsing the following page.

It is the 2nd hyperlink in the body of the article. (the link text is "here")

[A]
All of the links on that page are displaced to the right on my copy of IE7 (7.0.6001.18000) even before I enlarge or shrink the fonts.  Whereas other pages act normally.  (My test page was
http://www.frito-lay.com/fl/flstore/cgi-bin/good_questions.htm
).
It appears to be something specific to the page.


q:
What would be the most efficient way to compare two double or two float values?

Simply doing this is not correct:

bool CompareDoubles1 (double A, double B)
{
   return A == B;
}

But something like:

bool CompareDoubles2 (double A, double B)
{
   diff = A - B;
   return (diff < EPSILON) && (-diff < EPSILON);
}

Seems to waste processing.

Does anyone know a smarter float comparer?

[A]
The comparison with an epsilon value is what most people do (even in game programming).
You should change your implementation a little though:
```
```
bool AreSame(double a, double b)
{
    return fabs(a - b) < EPSILON;
}
```
```
Edit: Christer has added a stack of great info on this topic on a
recent blog post
. Enjoy.


q: In relation to this question on Using OpenGL extensions, what's the purpose of these extension functions? Why would I want to use them? Further, are there any tradeoffs or gotchas associated with using them?

[A]
The OpenGL standard allows individual vendors to provide additional functionality through extensions as new technology is created. Extensions may introduce new functions and new constants, and may relax or remove restrictions on existing OpenGL functions.
Each vendor has an alphabetic abbreviation that is used in naming their new functions and constants. For example, NVIDIA's abbreviation (NV) is used in defining their proprietary function glCombinerParameterfvNV() and their constant GL_NORMAL_MAP_NV.
It may happen that more than one vendor agrees to implement the same extended functionality. In that case, the abbreviation EXT is used. It may further happen that the Architecture Review Board "blesses" the extension. It then becomes known as a standard extension, and the abbreviation ARB is used. The first ARB extension was GL_ARB_multitexture, introduced in version 1.2.1. Following the official extension promotion path, multitexturing is no longer an optionally implemented ARB extension, but has been a part of the OpenGL core API since version 1.3.
Before using an extension a program must first determine its availability, and then obtain pointers to any new functions the extension defines. The mechanism for doing this is platform-specific and libraries such as GLEW and GLEE exist to simplify the process.


q: I've been using OpenGL extensions on Windows the painful way. Is GLEW the easier way to go? How do I get started with it?

[A]
Yes, the
OpenGL Extension Wrangler Library
(GLEW) is a painless way to use OpenGL extensions on Windows. Here's how to get started on it:
Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the
OpenGL Extension Registry
.
Check if your graphic card supports the extensions you wish to use. Download and install the latest drivers and SDKs for your graphics card.
Recent versions of
NVIDIA OpenGL SDK
ship with GLEW. If you're using this, then you don't need to do some of the following steps.
Download
GLEW
and unzip it.
Add the GLEW
bin
path to your Windows
PATH
environment variable. Alternatively, you can also place the
glew32.dll
in a directory where Windows picks up its DLLs.
Add the GLEW
include
path to your compiler's include directory list.
Add the GLEW
lib
path to your compiler's library directory list.
Instruct your compiler to use
glew32.lib
during linking. If you're using Visual C++ compilers then one way to do this is by adding the following line to your code:
```
```
#pragma comment(lib, "glew32.lib")
```
```
Add a
```
#include <GL/glew.h>
```
line to your code. Ensure that this is placed above the includes of other GL header files. (You may actually not need the GL header files includes if you include
```
glew.h
```
.)
Initialize GLEW using
```
glewInit()
```
after you've initialized GLUT or GL. If it fails, then something is wrong with your setup.
```
```
if (GLEW_OK != glewInit())
{
    // GLEW failed!
    exit(1);
}
```
```
Check if the extension(s) you wish to use are now available through GLEW. You do this by checking a boolean variable named
GLEW
_your_extension_name
which is exposed by GLEW.
Example:
```
```
if (!GLEW_EXT_framebuffer_object)
{
    exit(1);
}
```
```
That's it! You can now use the OpenGL extension calls in your code just as if they existed naturally for Windows.


q:
I have a PHP script that runs as a CGI program and the HTTP Authenticate header gets eaten and spit out. So I would like to implement some kind of FORM based authentication. As an added constraint, there is no database so no session data can be stored.

I am very open to having a master username and password. I just need to protect the application from an intruder who doesn't know these credentials.

So how would you implement this?

Cookies?

I could present the form and if it validates, I can send back a cookie that is a hash of the IP address come secret code. Then I can prevent pages from rendering unless the thing decrypts correctly. But I have no idea how to implement that in PHP.

[A]
A few ways you could do this.
htaccess
-- have your webserver handle securing the pages in question (not exactly cgi form based though).
Use cookies and some sort of hashing algorithm (md5 is good enough) to store the passwords in a flat file where each line in the file is username:passwordhash.  Make sure to
salt
your hashes for extra security vs rainbow tables. (This method is a bit naive... be
very
careful with security if you go this route)
use something like a
sqlite
database just to handle authentication.  Sqlite is compact and simple enough that it may still meet your needs even if you don't want a big db backend.
Theoretically, you could also store session data in a flat file, even if you can't have a database.


q:
I have a blogengine.net install that requires privatization.

I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met.

How can I privatize my blogEngine.net install so that readers must log in to read my posts?

[A]
I would think it's possible to do this in the web config file by doing something like the following:
```
```
<system.web>
    <authorization>
      <allow roles="Admin" />
      <deny users="*" />
    </authorization>
</system.web>
```
```


q: How can you make the display frames per second be independent from the game logic? That is so the game logic runs the same speed no matter how fast the video card can render.

[A]
You could make your game loop look like:
```
```
int lastTime = GetCurrentTime();
while(1) {
    // how long is it since we last updated?
    int currentTime = GetCurrentTime();
    int dt = currentTime - lastTime;
    lastTime = currentTime;

    // now do the game logic
    Update(dt);

    // and you can render
    Draw();
}
```
```
Then you just have to write your
```
Update()
```
function to take into account the time differential; e.g., if you've got an object moving at some speed
```
v
```
, then update its position by
```
v * dt
```
every frame.


q:
Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?

class Base {
public:
    bool someGuaranteedResult() { return true; }
};

class Child : public Base {
public:
    bool someGuaranteedResult() { return false; /* Haha I broke things! */ }
};

Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.

[A]
If you address the child class as a type of its parent, then a non-virtual function will call the parent class's version.
ie:
```
```
Parent* obj = new Child();
```
```


q:
Note that this question continues from Is it possible to coax Visual Studio 2008 into using italics for comments?

If the long question title got you, here's the problem:

How to convert the style property of the Consolas Italic font to Bold without actually modifying any of its actual glyphs? That is, we want the font to be still the same (i.e., Italic) we merely want the OS to believe that it's now a Bold font.

Please just don't mention the name of a tool (Ex: fontforge), but describe the steps to achieve this or point to such a description.

[A]
Alright, I've successfully used FontForge to create a copy of Consolas (although this should work with any font) with the bold style actually being italics.
These are the steps that I followed:
Install
FontForge
. It's a lot easier to do this on linux than on windows/cygwin. I used a Ubuntu VM ("sudo apt-get install fontforge").
Open Consola.ttf (the "normal" style font) in FontForge.
Select Element -> Font Info.
Change the Fontname, Family Name, and Name for Humans, all to the same thing. I used 'ConsolasVS'.
Click Ok. Click 'Yes' to let FontForge generate a new GUID for the font.
Select File -> Generate Fonts. Make sure you've got "TrueType" selected. Uncheck "Validate before saving". Click Save.
Now open Consolai.ttf (the italic style font) in FontForge.
Go back to Element -> Font Info.
Change the Font names as before, and where it currently says "Italic", change that to "Bold".
Go to the OS/2 tab, change the font weight to "700 Bold".
Go to the Mac tab, change the style set to Bold.
Click Ok. Allow a new GUID to be generated again.
File -> Generate Fonts, as before.
Copy your two new ttf files into your \Windows\FONTS\ folder.
You can now have nice italic comments with Consolas in VS2008. Hooray!


q:
For my C# app, I don't want to always prompt for elevation on application start, but if they choose an output path that is UAC protected then I need to request elevation.

So, how do I check if a path is UAC protected and then how do I request elevation mid-execution?

[A]
Requesting elevation mid-execution requires that you either:
Use a COM control that's elevated, which will put up a prompt
Start a second process that is elevated from the start.
In .NET, there is currently no way to elevate a running process; you have to do one of the hackery things above, but all that does is give the user the appearance that the current process is being elevated.
The only way I can think of to check if a path is UAC elevated is to try to do some trivial write to it while you're in an un-elevated state, catch the exception, elevate and try again.


q:
Word wrap is one of the must-have features in a modern text editor.

How word wrap be handled? What is the best algorithm for word-wrap?

If text is several million lines, how can I make word-wrap very fast?

Why do I need the solution? Because my projects must draw text with various zoom level and simultaneously beautiful appearance.

The running environment is Windows Mobile devices. The maximum 600 MHz speed with very small memory size.

How should I handle line information? Let's assume original data has three lines.

THIS IS LINE 1.
THIS IS LINE 2.
THIS IS LINE 3.

Afterwards, the break text will be shown like this:

THIS IS
LINE 1.
THIS IS
LINE 2.
THIS IS
LINE 3.

Should I allocate three lines more? Or any other suggestions?

[A]
With or without hyphenation?
Without it's easy. Just encapsulate your text as wordobjects per word and give them a method getWidth(). Then start at the first word adding up the rowlength until it is greater than the available space. If so, wrap the last word and start counting again for the next row starting with this one, etc.
With hyphenation you need hyphenation rules in a common format like: hy-phen-a-tion
Then it's the same as the above except you need to split the last word which has caused the overflow.
A good example and tutorial of how to structure your code for an excellent text editor is given in the Gang of Four
Design Patterns
book. It's one of the main samples on which they show the patterns.


q: Programmatic solution of course...

[A]
You need to delve into unmanaged code. Here's a static class that I've been using:
```
```
public static class Recycle
{
    private const int FO_DELETE = 3;
    private const int FOF_ALLOWUNDO = 0x40;
    private const int FOF_NOCONFIRMATION = 0x0010;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
    public struct SHFILEOPSTRUCT
    {
        public IntPtr hwnd;
        [MarshalAs(UnmanagedType.U4)]
        public int wFunc;
        public string pFrom;
        public string pTo;
        public short fFlags;
        [MarshalAs(UnmanagedType.Bool)]
        public bool fAnyOperationsAborted;
        public IntPtr hNameMappings;
        public string lpszProgressTitle;
    }

    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    static extern int SHFileOperation(ref SHFILEOPSTRUCT FileOp);

    public static void DeleteFileOperation(string filePath)
    {
        SHFILEOPSTRUCT fileop = new SHFILEOPSTRUCT();
        fileop.wFunc = FO_DELETE;
        fileop.pFrom = filePath + '\0' + '\0';
        fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION;

        SHFileOperation(ref fileop);
    }
}
```
```
Addendum:
Tsk tsk @ Jeff for "using Microsoft.VisualBasic" in C# code.
Tsk tsk @ MS for putting all the goodies in VisualBasic namespace.


q:
I have a table with a 'filename' column.
I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered.  Fortunately they are all '.jpg' images.

How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?

[A]
The solution is:
```
```
UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50
```
```
RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces.  This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field.


q:
We are currently using MySQL for a product we are building, and are keen to move to PostgreSQL as soon as possible, primarily for licensing reasons.

Has anyone else done such a move? Our database is the lifeblood of the application and will eventually be storing TBs of data, so I'm keen to hear about experiences of performance improvements/losses, major hurdles in converting SQL and stored procedures, etc.

Edit: Just to clarify to those who have asked why we don't like MySQL's licensing. We are developing a commercial product which (currently) depends on MySQL as a database back-end. Their license states we need to pay them a percentage of our list price per installation, and not a flat fee. As a startup, this is less than appealing.

[A]
Steve, I had to migrate my old application the way around, that is PgSQL->MySQL. I must say, you should consider yourself lucky ;-)
Common gotchas are:
SQL is actually pretty close to language standard, so you may suffer from MySQL's dialect you already know
MySQL quietly truncates varchars that exceed max length, whereas Pg complains - quick workaround is to have these columns as 'text' instead of 'varchar' and use triggers to truncate long lines
double quotes are used instead of reverse apostrophes
boolean fields are compared using IS and IS NOT operators, however MySQL-compatible INT(1) with = and <> is still possible
there is no REPLACE, use DELETE/INSERT combo
Pg is pretty strict on enforcing foreign keys integrity, so don't forget to use ON DELETE CASCADE on references
if you use PHP with PDO, remember to pass a parameter to lastInsertId() method - it should be sequence name, which is created usually this way: [tablename]_[primarykeyname]_seq
I hope that helps at least a bit. Have lots of fun playing with Postgres!


q:
I know this is not programming directly, but it's regarding a development workstation I'm setting up.

I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time.  One of them is a 10.17.x.x LAN and the other is 10.16.x.x

The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on that specific LAN.

I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do.  Is there a better way of doing this?  Any good software for segmenting your LAN access?

[A]
If you don't move your network cables around and can assign yourself a static IP address on the 10.16.x.x network, you can refrain from assigning a gateway address on that network.  If there is no gateway, internet packets will not be routed on that interface.
If you use DHCP, static record to recognize your MAC address and not provide a gateway IP address.
As for using advanced windows routing, the route you are looking for is the 0.0.0.0 route (default route).  The important number is the metric value, which is the cost for the route, where the lower metric tends to be used first.  You can set the metric at the interface level directly in the GUI.
https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/i/tr/cms/contentPics/tcpip-F.gif
I believe if you set the interface metric to a high value on the 10.16.x.x interface, it will not be used as a gateway.
Personally I use the method where I refrain from defining a gateway IP.


q:
I wanted to show the users Name Address (see www.ipchicken.com), but the only thing I can find is the IP Address. I tried a reverse lookup, but didn't work either:

IPAddress ip = IPAddress.Parse(this.lblIp.Text);
string hostName = Dns.GetHostByAddress(ip).HostName;
this.lblHost.Text = hostName;

But HostName is the same as the IP address.

Who know's what I need to do?

Thanks.
Gab.

[A]
Not all IP addresses need to have hostnames. I think that's what is happening in your case. Try it ouy with more well-known IP/hostname pairs eg:
Name: google.com Address: 72.14.207.99
Name: google.com Address:
  64.233.187.99
Name: google.com Address:
  64.233.167.99
...I might just be wrong


q:
I am currently developing a .NET application, which consists of 20 projects. Some of those projects are compiled using .NET 3.5, some others are still .NET 2.0 projects (so far no problem).

The problem is that if I include an external component I always get the following warning:

Found conflicts between different versions of the same dependent assembly.

What exactly does this warning mean and is there maybe a possibility to exclude this warning (like using #pragma disable in the source code files)?

[A]
Basically this happens when the assemblies you're referencing have "Copy Local" set to "True", meaning that a copy of the DLL is placed in the bin folder along with your exe.
Since Visual Studio will copy all of the dependencies of a referenced assembly as well, it's possible to end up with two different builds of the same assembly being referred to. This is more likely to happen if your projects are in separate solutions, and can therefore be compiled separately.
The way I've gotten around it is to set Copy Local to False for references in assembly projects. Only do it for executables/web applications where you need the assembly for the finished product to run.
Hope that makes sense!


q: Any recommendations for a javascript form validation library. I could try and roll my own (but I'm not very good at javascript). Needs to support checking for required fields, and preferably regexp validation of fields.

[A]
I've used
this library
for a couple of personal projects. It's pretty good, though I have had to make my own modifications to it a couple of times - nothing major, though, and it's easy enough to do so.
I'm sure you already do this, but also validate all of your information on the server-side, as well. Client-side-only validation is rarely, if ever, a good idea.


q:
I'm working on a setup which wants to include the Microsoft.Web.Services3 (WSE 3.0) DLL. However, I typically do not like including Microsoft DLL's in our installs except by way of Microsoft's redistributables. There is both a developer and a redist install package available from Microsoft.

So, as a best practice, should I include the single DLL in my install or refer them to one of the WSE 3.0 installs (assuming they do not already have it installed)?

[A]
If you don't include it you should at the very least link to it directly on your site or have your installer open the web browser to it (or even download it automatically).  Or better yet, include the redistributable in your software package.
However, if the DLL is not very large and you suspect that few users will have it, in the interest of a better user I would prepackage it in the default installer.  However, you can always have an installer that does not include it for those who want a smaller installer... a great deal of other vendors do this all the time.


q:
Is there a way to select data where any one of multiple conditions occur on the same field?

Example: I would typically write a statement such as:

select * from TABLE where field = 1 or field = 2 or field = 3

Is there a way to instead say something like:

select * from TABLE where field = 1 || 2 || 3

Any help is appreciated.

[A]
Sure thing, the simplest way is this:
```
```
select foo from bar where baz in (1,2,3)
```
```


q:
Just looking for the first step basic solution here that keeps the honest people out.

Thanks,
Mike


q:
I asked a couple of coworkers about AnkhSVN and neither one of them was happy with it. One of them went as far as saying that AnkhSVN has messed up his devenv several times.

What's your experience with AnkhSVN? I really miss having an IDE integrated source control tool.

[A]
Older AnkhSVN (pre 2.0) was very crappy and I was only using it for shiny icons in the solution explorer. I relied on Tortoise for everything except reverts.
The newer Ankh is a complete rewrite (it is now using the Source Control API of the IDE) and looks & works much better. Still, I haven't forced it to any heavy lifting. Icons is enough for me.
The only gripe I have with 2.0 is the fact that it slaps its footprint to
.sln
files. I always revert them lest they cause problems for co-workers who do not have Ankh installed. I don't know if my fears are groundless or not.
addendum:
I have been using v2.1.7141 a bit more extensively for the last few weeks and here are the new things I have to add:
No ugly crashes that plagued v1.x. Yay!
For some reason, "Show Changes" (diff) windows are limited to only two. Meh.
Diff windows do not allow editing/reverting yet. Boo!
Updates, commits and browsing are MUCH faster than Tortoise. Yay!
All in all, I would not use it standalone, but once you start using it, it becomes an almost indispensable companion to Tortoise.


q: How do I create a self signed SSL certificate for an Apache Server to use while testing a web app?

[A]
Use OpenSSL (
http://www.openssl.org/
)
Here's a tutorial:
http://novosial.org/openssl/self-signed/
Here is the good tutorial to start with:
SSH localhost
.


q:
What's the cleanest, most effective way to validate decimal numbers in JavaScript?

Bonus points for:

Clarity. Solution should be clean and simple.

Cross-platform.

Test cases:

01. IsNumeric('-1')      => true
02. IsNumeric('-1.5')    => true
03. IsNumeric('0')       => true
04. IsNumeric('0.42')    => true
05. IsNumeric('.42')     => true
06. IsNumeric('99,999')  => false
07. IsNumeric('0x89f')   => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3')   => false
10. IsNumeric('')        => false
11. IsNumeric('blah')    => false

[A]
This way seems to work well:
```
```
function IsNumeric(input){
    var RE = /^-{0,1}\d*\.{0,1}\d+$/;
    return (RE.test(input));
}
```
```
In one line:
```
```
const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);
```
```
And to test it:
```
```
const IsNumeric = (num) => /^-{0,1}\d*\.{0,1}\d+$/.test(num);

    function TestIsNumeric(){
        var results = ''
        results += (IsNumeric('-1')?"Pass":"Fail") + ": IsNumeric('-1') => true\n";
        results += (IsNumeric('-1.5')?"Pass":"Fail") + ": IsNumeric('-1.5') => true\n";
        results += (IsNumeric('0')?"Pass":"Fail") + ": IsNumeric('0') => true\n";
        results += (IsNumeric('0.42')?"Pass":"Fail") + ": IsNumeric('0.42') => true\n";
        results += (IsNumeric('.42')?"Pass":"Fail") + ": IsNumeric('.42') => true\n";
        results += (!IsNumeric('99,999')?"Pass":"Fail") + ": IsNumeric('99,999') => false\n";
        results += (!IsNumeric('0x89f')?"Pass":"Fail") + ": IsNumeric('0x89f') => false\n";
        results += (!IsNumeric('#abcdef')?"Pass":"Fail") + ": IsNumeric('#abcdef') => false\n";
        results += (!IsNumeric('1.2.3')?"Pass":"Fail") + ": IsNumeric('1.2.3') => false\n";
        results += (!IsNumeric('')?"Pass":"Fail") + ": IsNumeric('') => false\n";
        results += (!IsNumeric('blah')?"Pass":"Fail") + ": IsNumeric('blah') => false\n";

        return results;
    }

console.log(TestIsNumeric());
```
```
```
```
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
```
I borrowed that regex from
http://www.codetoad.com/javascript/isnumeric.asp
. Explanation:
```
```
/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string
```
```


q:
We are investigating using CruiseControl.NET as both a Continues Integration build provider, as well as automating the first part of our deployment process.

Has anyone modified CruiseControl.NET's dashboard to add custom login and user roles (IE, Separate out access to forcing a build to only certain individuals on a per project basis?

The dashboard is a .NET App, but I believe it uses the nVelocity view engine instead of web forms, which I don't have experience with.

Can you mix nVelocity and Webforms,or do I need to spend a day learning something new =)

[A]
Why do you need to? Do you really need to limit users in the way with an integration server. I think that's why CC.Net doesn't have that sort of support built in.
You can always see who forced a build, and control it that way.
I find that continuous integration works best with regular builds and regular unit test runs (our rather large C# app + test run takes 25 mins and checks hourly), so for me forcing a build is rarely an issue.
If you want some users to have some kind of report-only access you could limit them so that they can't access the CC.Net web application at all.
All the results (MSBuild, NCover, NUnit, FxCop, etc) are in XML, so you can build relativity simple report pages out of XSLT.


q:
In a world where manual memory allocation and pointers still rule (Borland Delphi) I need a general solution for what I think is a general problem:

At a given moment an object can be referenced from multiple places (lists, other objects, ...). Is there a good way to keep track of all these references so that I can update them when the object is destroyed?

[A]
I can't quite figure out why you'd want to do this. Surely you would just check a reference in not Nil before using it?
Anwyays, two possible solutions I would consider are:
Have objects manager their own reference counts.
Create a reference counting manager class.
I would probably add AddRef() and ReleaseRef() functions to either the manager or the reference-aware class. You can then use these to check how many references exist at any point. COM does it this way.
The reference-aware class would manage only it's own reference count. The manager could use a Map to associate pointers with an integer for counting.


q:
So the ADO.NET Entity Framework has gotten a little bit of bad press (in the form of blog entries and a petition) but I don't want to rush to judgement. I'm limited in time for experimentation but I was wondering has anyone worked with it yet with more empirical feedback?

Finally, what are thoughts on using NHibernate which has been around for a long time and may be more mature than the ADO.NET Entity Framework.

[A]
Microsoft have all but admitted that the ADO.Net Entity Framework isn't an ORM (I can't find a reference currently). So if you think of the Entity Framework as a query engine then apparently it is really good at what it does. For a complete ORM solution you might want to look elsewhere however.
The following blog post seems to bear out this difference:
http://blogs.msdn.com/dsimmons/archive/2008/05/17/why-use-the-entity-framework.aspx


q: So I'm getting a new job working with databases (Microsoft SQL Server to be precise).  I know nothing about SQL much less SQL Server.  They said they'd train me, but I want to take some initiative to learn about it on my own to be ahead.  Where's the best place to start (tutorials, books, etc)?  I want to learn more about the SQL language moreso than any of the fancy point and click stuff.

[A]
SQL:
http://www.google.com/search?hl=en&q=introduction+to+sql
->
http://www.w3schools.com/SQL/sql_intro.asp
MSSQL:
http://www.google.com/search?hl=en&safe=off&q=introduction+to+ms+sql
->
http://www.intermedia.net/support/SQL/sqltut.asp
The best way to learn? Write a lot of queries and read up on the
Entity-relationship model


q:
How do you test the usability of the user interfaces of your applications - be they web or desktop?  Do you just throw it all together and then tweak it based on user experience once the application is live?  Or do you pass it to a specific usability team for testing prior to release?

We are a small software house, but I am interested in the best practices of how to measure usability.

Any help appreciated.

[A]
I frequently take any new interface I'm working on to one of our technical support people.  They've heard every complaint about interfaces that you could ever imagine, so if anyone is going to think up potential problems, they will.
Also, and I'm not kidding about this, I often take the least computer literate person I know (you're mother is often a good choice...but they have to have
used
a computer before, otherwise it's going to by pointless) and let them loose on the interface with no instruction.  If they can't figure out where things are intuitively, then your GUI likely needs work.  Remember,
Don't make them think!
(yes, I know this is for web design, but it applies)


q:
I'm a long time hobbyist programmer interested in getting into web application development. I have a fair amount of personal experience with various non-web languages, but have never really branched over to web applications.

I don't usually have any issues learning new languages or technologies, so I'm not worried about which is the "best" language or web stack to work with. Instead, I'd like to know of any recommended resources (books, articles, web sites, maybe even college courses) that discuss web application design: managing and optimizing server interaction, security concerns, scalability, and other topics that fall under design rather than implementation.

What would you recommend for a Standalone Application Developer wanting to branch out into Web Development?

[A]
A lot of languages have web counterparts. JSP for Java, Rails for Ruby, Django for Python, etc. That might be a lead.
If you want to go for the platform with arguably the biggest user base (and with that, the biggest pile of tutorials and examples), go for PHP.
I strongly advise on looking into various frameworks though. For every web-oriented language there's bound to be a lot of resources that take away the trouble of writing all the low-level plumbing code, so you can focus on the stuff that matters. Personally I almost exclusively use .NET, but I've heard about a bunch of nice PHP frameworks, like the Zend platform and CakePHP (for MVC development).
If you intend to also use javascript in your applications to give that nice web 2.0 feel to your applications, please, use a library that hides the messy browser details. You'll go nuts if you try to do all the cross-browser scripts yourself. Some good ones are Prototype and jQuery.


q:
I'm wondering how the few Delphi users here are doing unit testing, if any?  Is there anything that integrates with the IDE that you've found works well?  If not, what tools are you using and do you have or know of example mini-projects that demonstrate how it all works?

Update:

I forgot to mention that I'm using BDS 2006 Pro, though I occasionally drop into Delphi 7, and of course others may be using other versions.

[A]
DUnit
is a xUnit type of unit testing framework to be used with win32 Delphi. Since Delphi 2005 DUnit is integrated to a certan point into the IDE. Other DUnit integration tools for the Delphi IDE can be found
here
. DUnit comes with
documentation with examples
.


q:
When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad.  For example, you can't do this:

for name in names:
    if name[-5:] == 'Smith':
        names.remove(name)

I usually end up doing something like this:

toremove = []
for name in names:
    if name[-5:] == 'Smith':
        toremove.append(name)
for name in toremove:
    names.remove(name)
del toremove

This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one?

How about one that works with dictionaries?

[A]
Well, this is clearly an issue with the data structure you are using. Use a hashtable for example. Some implementations support multiple entries per key, so one can either pop the newest element off, or remove all of them.
But this is, and what you're going to find the solution is, elegance through a different data structure, not algorithm. Maybe you can do better if it's sorted, or something, but iteration on a list is your only method here.
edit:
one does realize he asked for 'efficiency'... all these suggested methods just iterate over the list, which is the same as what he suggested.


q:
I'm looking for a simple way to encrypt my soap communication in my C# Web-Service.

I was looking into WSE 3.0 but it seems Microsoft dropped support for it, and therefore it's not straightforward to use.

It seems WCF could've been an option but I prefer not to upgrade from .NET 2.0 .

Any simple, straightforward encryption method?

[A]
Perhaps I'm being naive, but would forcing the communication to be via https be acceptable?
I develop web services that run on 2.0 and have had success with just getting IIS to enforce https on the virtual directory.
Alternatively, or in addition, you can check the
HttpRequest.IsSecureConnection property
.


q:
For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?

Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?

[A]
Store everything as UTC.  You can do conversions at the client level, or on the server side using client settings.
php - date
mysql - utc-timestamp


q:
What is the best way to authorize all users to one single page in a asp.net website.

For except the login page and one other page, I deny all users from viewing pages in the website.

How do you make this page accessible to all users?

[A]
I've been using forms authentication and creating the necessary GenericIdentity and CustomPrincipal objects that allows me to leverage the User.IsInRole type functions you typically only get with Windows authentication.
That way in my web.config file, I can do stuff like...
```
```
<location path="Login.aspx">
   <system.web>
      <authorization>
         <allow users ="*" />
      </authorization>
   </system.web>
</location>

<location path="ManagementFolder">
   <system.web>
      <authorization>
         <allow roles ="Administrator, Manager" />
      </authorization>
   </system.web>
</location>
```
```


q: In an application that I am currently working on, a requirement is to bring a window of an external application to the foreground.  Making Win32 API calls such as BringWindowToTop and SetForeground window do not work all the time.  This is due to some restrictions within Windows XP.  What I would like to do instead is send simulate a mouse click the window's button on the taskbar which I am hoping will bring the window to the front.  Does anyone know how this is possible?

[A]
It's possible. But it's extremely sketchy. Your application may also break with the next version of Windows, since it's undocumented. What you need to do is find the window handle of the taskbar, then find the window handle of the child window representing the button, then send it a WM_MOUSEDOWN (I think) message.
Here's a bit on finding the window handle of the taskbar:
http://www.codeproject.com/
FWIW, the restrictions on BringWindowToTop/SetForeground are there because it's irritating when a window steals focus. That may not matter if you're working on a corporate environment. Just keep it in mind. :)


q:
I have a list of integers, List<Integer> and I'd like to convert all the integer objects into Strings, thus finishing up with a new List<String>.

Naturally, I could create a new List<String> and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?

[A]
As far as I know, iterate and instantiate is the only way to do this.  Something like (for others potential help, since I'm sure you know how to do this):
```
```
List<Integer> oldList = ...
/* Specify the size of the list up front to prevent resizing. */
List<String> newList = new ArrayList<>(oldList.size());
for (Integer myInt : oldList) {
  newList.add(String.valueOf(myInt));
}
```
```


q:
I've found myself increasingly unsatisfied with the DataSet/DataTable/DataRow paradigm in .Net, mostly because it's often a couple of steps more complicated than what I really want to do.  In cases where I'm binding to controls, DataSets are fine.  But in other cases, there seems to be a fair amount of mental overhead.

I've played a bit with SqlDataReader, and that seems to be good for simple jaunts through a select, but I feel like there may be some other models lurking in .Net that are useful to learn more about.  I feel like all of the help I find on this just uses DataSet by default.  Maybe that and DataReader really are the best options.

I'm not looking for a best/worst breakdown, just curious what my options are and what experiences you've had with them.  Thanks!

-Eric Sipple

[A]
Since .NET 3.5 came out, I've exclusively used LINQ. It's really that good; I don't see any reason to use any of those old crutches any more.
As great as LINQ is, though, I think any ORM system would allow you to do away with that dreck.


q:
I'd like some sorthand for this:

Map rowToMap(row) {
    def rowMap = [:];
    row.columns.each{ rowMap[it.name] = it.val }
    return rowMap;
}

given the way the GDK stuff is, I'd expect to be able to do something like:

Map rowToMap(row) {
    row.columns.collectMap{ [it.name,it.val] }
}

but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?

[A]
I can't find anything built in... but using the ExpandoMetaClass I can do this:
```
```
ArrayList.metaClass.collectMap = {Closure callback->
    def map = [:]
    delegate.each {
        def r = callback.call(it)
        map[r[0]] = r[1]
    }
    return map
}
```
```
this adds the collectMap method to all ArrayLists... I'm not sure why adding it to List or Collection didn't work.. I guess that's for another question... but now I can do this...
```
```
assert ["foo":"oof", "42":"24", "bar":"rab"] ==
            ["foo", "42", "bar"].collectMap { return [it, it.reverse()] }
```
```
from List to calculated Map with one closure... exactly what I was looking for.
Edit: the reason I couldn't add the method to the interfaces List and Collection was because I did not do this:
```
```
List.metaClass.enableGlobally()
```
```
after that method call, you can add methods to interfaces.. which in this case means my collectMap method will work on ranges like this:
```
```
(0..2).collectMap{[it, it*2]}
```
```
which yields the map: [0:0, 1:2, 2:4]


q:
Possible Duplicate:

  How do I calculate someone's age in C#?

Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age?

Maybe

DateTime dt1 = DateTime.Now;
TimeSpan dt2;
dt2 = dt1.Subtract(new DateTime(1975, 12, 01));
double year = dt2.TotalDays / 365;

The result of year is 32.77405678074

Could this code be OK?

[A]
Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, doesn't it better to calculate the exact age?
My guess would be that this is a localization issue, though I don't know how it would happen, since (at least for me) the profile has you fill out your age in the format "YYYY/MM/DD".  But your birthday is one that reads as a valid date (January 12th) in traditional U.S. settings, so this is the area I'd look into.  I was born in 1975, also, and my birthday is next month, and it's got my age right.


q:
Unit testing and ASP.NET web applications are an ambiguous point in my group. More often than not, good testing practices fall through the cracks and web applications end up going live for several years with no tests.

The cause of this pain point generally revolves around the hassle of writing UI automation mid-development.

How do you or your organization integrate best TDD practices with web application development?

[A]
I layer out the application and at least unit test from the presenter/controller (whichever is your preference, mvc/mvp) to the data layer. That way I have good test coverage over most of the code that is written.
I have looked at FitNesse, Watin and Selenium as options to automate the UI testing but I haven't got around to using these on any projects yet, so we stick with human testing. FitNesse was the one I was leaning toward but I couldn't introduce this as well as introducing TDD (does that make me bad? I hope not!).


q:
I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.

For example purposes, consider the following namespaces and classes:

namespace Protocol
{
  public abstract class Message { }
  public abstract class Driver { }
}
namespace Protocol.Tcp
{
  public class TcpMessage : Message { }
  public class TcpDriver : Driver { }
}
namespace Protocol.Ftp
{
  public class FtpMessage : Message { }
  public class FtpDriver : Driver { }
}

What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace.

[A]
I think you are perhaps worrying too much!
Does it make sense logically? Do you know where to find your code within the namespaces?
I would much rather see a codebase like the above with a small number of classes, relevant to the name with a hierarchy, than one large namespace where everything is interrelated..
Remember, namespacing is there for precisely this, to
organise your codebase logically
What you have seems logical :)
EDIT:
As an example:
```
```
using System.Data;
using System.Data.Sql;
```
```
;)


q: How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

[A]
Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.
Edit
```
tomcat/conf/server.xml
```
.
Specify a bind address for that connector:
```
<Connector
    port="8080"
    protocol="HTTP/1.1"
    address="127.0.0.1"
    connectionTimeout="20000"
    redirectPort="8443"
  />
```


q:
Is it possible to get UI text from an external application in C#.

In particular, is there a way to read Unicode text from a label (I assume it's a normal Windows label control) from an external Win32 app that was written by a 3rd party? The text is visible, but not selectable by mouse in the UI.

I assume there is some accessibility API (e.g. meant for screen readers) that allows this.

Edit: Currently looking into using something like the Managed Spy App but would still appreciate any other leads.

[A]
You could do it if that unicode text is actually a window with a caption by sending a
WM_GETTEXT
message.
```
```
[DllImport("user32.dll")]
public static extern int SendMessage (IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text);

System.Text.StringBuilder text = new System.Text.StringBuilder(255) ;  // or length from call with GETTEXTLENGTH
int RetVal = Win32.SendMessage( hWnd , WM_GETTEXT, text.Capacity, text);
```
```
If it is just painted on the canvas you might have some luck if you know what framework the application uses. If it uses WinForms or Borland's VCL you could use that knowledge to get to the text.


q: Anyone know a quick easy way to migrate a SQLite3 database to MySQL?

[A]
I recently had to migrate from MySQL to JavaDB for a project that our team is working on.  I found a
Java library written by Apache called DdlUtils
that made this pretty easy.  It provides an API that lets you do the following:
Discover a database's schema and export it as an XML file.
Modify a DB based upon this schema.
Import records from one DB to another, assuming they have the same schema.
The tools that we ended up with weren't completely automated, but they worked pretty well.  Even if your application is not in Java, it shouldn't be too difficult to whip up a few small tools to do a one-time migration.  I think I was able to pull of our migration with less than 150 lines of code.


q:
I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.

How would I do that?

[A]
To get a random integer value between 1 and N (inclusive) you can use the following.
```
```
CInt(Math.Ceiling(Rnd() * n)) + 1
```
```


q: Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?

[A]
Here is the php code for the same:
```
```
function time_since($since) {
    $chunks = array(
        array(60 * 60 * 24 * 365 , 'year'),
        array(60 * 60 * 24 * 30 , 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24 , 'day'),
        array(60 * 60 , 'hour'),
        array(60 , 'minute'),
        array(1 , 'second')
    );

    for ($i = 0, $j = count($chunks); $i < $j; $i++) {
        $seconds = $chunks[$i][0];
        $name = $chunks[$i][1];
        if (($count = floor($since / $seconds)) != 0) {
            break;
        }
    }

    $print = ($count == 1) ? '1 '.$name : "$count {$name}s";
    return $print;
}
```
```
The function takes the number of seconds as input and outputs text such as:
10 seconds
1 minute
etc


q:
Our company is currently writing a GUI automation testing tool for compact framework applications. We have initially searched many tools but none of them was right for us.

By using the tool you can record test-cases and group them together to test-suites. For every test-suite there is generated an application, which launches the application-under-test and simulates user-input.

In general the tool works fine, but as we are using window handles for simulation user input, you can't do very many things. For example it is impossible for us to get the name of a control (we just get the caption).

Another problem using window handles is checking for a change. At the moment we simulate a click on a control and depending on the result we know if the application has gone to the next step.

Is there any other (simpler) way for doing such things (for example the message queue or anything else)?

[A]
If the Automated GUI testing tool has knowledge about the framework the application is written in it could use that information to make better or more advanced scripts.
TestComplete
for example knows about Borland's VCL and WinForms. If you test applications build using Windows Presentation Foundation has advanced support for this
build in
.


q:
I'm writing some documentation in Markdown, and creating a separate file for each section of the doc.  I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing.  I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck.  It seems like it should be simple to write something so I could just run:

markdown-batch ./*.markdown

Any ideas?

[A]
I use this in a .bat file:
```
```
@echo off
for %i in (*.txt) python markdown.py "%i"
```
```


q:
The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both.

However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData.

So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null?

Should I include the operation in the view data as an enum?

Should I surround all the subtle differences with <% if( ViewData.Model.Op == Ops.Editing ) { %> ?

Or is there a better way?

[A]
I don't like the Views to become too complex, and so far I have tended to have separate views for Edit and Add. I use a user control to store the common elements to avoid repetition. Both of the views will be centered around the same ViewData, and I have a marker on my data to say whether the object is new or an existing object.
This isn't any more elegant than what you have stipulated, so I wonder if any of the Django or Rails guys can provide any input.
I love asp.net mvc but it is still maturing, and still needs more sugar adding to take away some of the friction of creating websites.


q: When you have a query or stored procedure that needs performance tuning, what are some of the first things you try?

[A]
Look at the where clause - verify use of indexes / verify nothing silly is being done
```
```
where SomeComplicatedFunctionOf(table.Column) = @param --silly
```
```


q:
I'm looking for shell scripts files installed on my system, but find doesn't work:

$ find /usr -name *.sh

But I know there are a ton of scripts out there.  For instance:

$ ls /usr/local/lib/*.sh
/usr/local/lib/tclConfig.sh
/usr/local/lib/tkConfig.sh

Why doesn't find work?

[A]
Try quoting the wildcard:
```
```
$ find /usr -name \*.sh
```
```
or:
```
```
$ find /usr -name '*.sh'
```
```
If you happen to have a file that matches
*.sh
in the current working directory, the wildcard will be expanded before find sees it.  If you happen to have a file named tkConfig.sh in your working directory, the
find
command would expand to:
```
```
$ find /usr -name tkConfig.sh
```
```
which would only find files named tkConfig.sh.  If you had more than one file that matches
*.sh
, you'd get a syntax error from
find
:
```
```
$ cd /usr/local/lib
$ find /usr -name *.sh
find: bad option tkConfig.sh
find: path-list predicate-list
```
```
Again, the reason is that the wildcard expands to both files:
```
```
$ find /usr -name tclConfig.sh tkConfig.sh
```
```
Quoting the wildcard prevents it from being prematurely expanded.
Another possibility is that /usr or one of its subdirectories is a symlink.
find
doesn't normally follow links, so you might need the
-follow
option:
```
```
$ find /usr -follow -name '*.sh'
```
```


q:
Does anyone here know of good batch file code indenters or beautifiers?

Specifically for PHP, JS and SGML-languages.

Preferably with options as to style.


q:
So I am writing a registration form and I need the display name to be only numbers, letters and underscores.

Have a look at my code and tell me what I'm doing wrong.

<form method="post" action="/" onsubmit="return check_form()">
    <input type="text" id="display-name" name="display-name" maxlength="255" />
    <input type="submit" />
</form>
<script type="text/javascript">
<!--
    var name_regex = /^([a-zA-Z0-9_])+/

    function check_form()
    {
        if (!name_regex.test(document.forms[0].elements[0].value))
        {
            document.forms[0].elements[0].focus()
            alert("Your display name may only contain letters, numbers and underscores")
            return false
        }
    }
-->
</script>

It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.

[A]
My regexp would go along the lines of:
```
/^[a-zA-Z0-9_]+$/
```
edit: I think it's the lack of a line end
```
$
```
that makes it fail.


q: I am running a Qt 4.5 commercial snapshot and want to use a plugin that I downloaded (it's a .so file) in my QWebView.  Is there a specific location where I need to place this file?  Can I grab it using the QWebPluginFactory?

[A]
Have you tried putting in the
standard library directories
? It should be picked up by the
linker
if it's in one of those directories.
For example:
```
```
/lib/
/usr/lib/
/usr/share/lib/
/usr/local/lib/
```
```


q: Is anyone working on or know if there exists a SQL 2k8 Dialect for NHibernate?


q:
I know in JavaScript, objects double as hashes, but I have been unable to find a built-in function to get the keys:

var h = {a:'b', c:'d'};

I want something like

var k = h.keys() ; // k = ['a', 'c'];

It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?

I keep feeling it must be a simple built in function that I missed but I can't find it!

[A]
This is the best you can do, as far as I know...
```
```
var keys = [];
for (var k in h)keys.push(k);
```
```


q:
When opening a file from your hard drive into your browser, where is the document root?  To illustrate, given the following HTML code, if the page is opened from the local machine (file:///) then where should the css file be for the browser to find it?

<link href="/temp/test.css" rel="stylesheet" type="text/css" />

[A]
It depends on what browser you use, but Internet Explorer, for example, would take you to the root directory of your harddrive (eg.
```
C:/
```
), while browsers such as Firefox does nothing.


q:
I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).

The rows, of course, will not be perfect duplicates because of the existence of the RowID identity field.

MyTable

RowID int not null identity(1,1) primary key,
Col1 varchar(20) not null,
Col2 varchar(2048) not null,
Col3 tinyint not null

How can I do this?

[A]
There's a good article on
removing duplicates
on the Microsoft Support site. It's pretty conservative - they have you do everything in separate steps - but it should work well against large tables.
I've used self-joins to do this in the past, although it could probably be prettied up with a HAVING clause:
```
```
DELETE dupes
FROM MyTable dupes, MyTable fullTable
WHERE dupes.dupField = fullTable.dupField
AND dupes.secondDupField = fullTable.secondDupField
AND dupes.uniqueField > fullTable.uniqueField
```
```


q:
I am developing a J2ME application that has a large amount of data to store on the device (in the region of 1MB but variable). I can't rely on the file system so I'm stuck the Record Management System (RMS), which allows multiple record stores but each have a limited size. My initial target platform, Blackberry, limits each to 64KB.

I'm wondering if anyone else has had to tackle the problem of storing a large amount of data in the RMS and how they managed it? I'm thinking of having to calculate record sizes and split one data set accross multiple stores if its too large, but that adds a lot of complexity to keep it intact.

There is lots of different types of data being stored but only one set in particular will exceed the 64KB limit.

[A]
I think the most flexible approach would be to implement your own file system on top of the RMS. You can handle the RMS records in a similar way as blocks on a hard drive and use a
inode structure
or similar to spread logical files over multiple blocks. I would recommend implementing a byte or stream-oriented interface on top of the blocks, and then possibly making another API layer on top of that for writing special data structures (or simply make your objects serializable to the data stream).
Tanenbaum's classical book on operating systems
covers how to implement a simple file system, but I am sure you can find other resources online if you don't like paper.


q:
I want to use Lucene (in particular, Lucene.NET) to search for email address domains.

E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.

Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word.

How can I do this?

[A]
No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers.
The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for "@gmail.com" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created.
Here's the source code, it's actually very simple:
```
```
class WhitespaceAndAtSymbolTokenizer : CharTokenizer
{
    public WhitespaceAndAtSymbolTokenizer(TextReader input)
        : base(input)
    {
    }

    protected override bool IsTokenChar(char c)
    {
        // Make whitespace characters and the @ symbol be indicators of new words.
        return !(char.IsWhiteSpace(c) || c == '@');
    }
}

internal class WhitespaceAndAtSymbolAnalyzer : Analyzer
{
    public override TokenStream TokenStream(string fieldName, TextReader reader)
    {
        return new WhitespaceAndAtSymbolTokenizer(reader);
    }
}
```
```
That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index:
```
```
IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer());
index.AddDocument(myDocument);
```
```
Performing searches should use the analyzer as well:
```
```
IndexSearcher searcher = new IndexSearcher(indexDirectory);
Query query = new QueryParser("TheFieldNameToSearch", new WhitespaceAndAtSymbolAnalyzer()).Parse("@gmail.com");
Hits hits = query.Search(query);
```
```


q:
After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available.

When attempting to run it manually, I get this error:

The application has failed to start because its side-by-side configuration is incorrect.
Please see the application event log for more detail

The application log shows this

Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll".
Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found.
Please use sxstrace.exe for detailed diagnosis.

[A]
I remembered I'd seen this thing before just after posting to SO
It seems that later versions of TortoiseSVN are built with Visual Studio 2008 SP1 (hence the 9.0.30411.0 build number)
Installing the
VC2008 SP1 Redistributable
fixes it


q:
I have a project that utilizes the javax.mail.internet.MimeMessage and other related classes that does mime parsing for emails that we receive. This needs to be ported to .NET.

What .Net 3rd party or built in library can I use to replace the Java classes that I'm using?

EDIT: Anything change in the last 9 months since I asked this question?

[A]
I've not used javax.mail.internet.MimeMessage, so I can't say how any of this compares, but .NET 2.0 and beyond does have a
System.Net.Mime
namespace which might have something useful for you.
Otherwise, I used
Chilkat MIME .NET
a long time ago and was happy with it.


q:
I'm asking with regards to c#, but I assume its the same in most other languages.

Does anyone have a good definition of expressions and statements and what the differences are?

[A]
Expressions can be evaluated to get a value, whereas statements don't return a value (they're of type
void
).
Function call expressions can also be considered statements of course, but unless the execution environment has a special built-in variable to hold the returned value, there is no way to retrieve it.
Statement-oriented languages require all procedures to be a list of statements. Expression-oriented languages, which is probably all functional languages, are lists of expressions, or in tha case of LISP, one long S-expression that represents a list of expressions.
Although both types can be composed, most expressions can be composed arbitrarily as long as the types match up. Each type of statement has its own way of composing other statements, if they can do that all. Foreach and if statements require either a single statment or that all subordinate statements go in a statement block, one after another, unless the substatements allow for thier own substatements.
Statements can also include expressions, where an expression doesn't really include any statements. One exception, though, would be a lambda expression, which represents a function, and so can include anything a function can iclude unless the language only allows for limited lambdas, like Python's single-expression lambdas.
In an expression-based language, all you need is a single expression for a function since all control structures return a value (a lot of them return NIL). There's no need for a return statement since the last-evaluated expression in the function is the return value.


q:
Using C# and WPF under .NET (rather than Windows Forms or console), what is the correct way to create an application that can only be run as a single instance?

I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.

The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.

[A]
From
here
.
A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Here's how it's done:
```
```
class OneAtATimePlease {

  // Use a name unique to the application (eg include your company URL)
  static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");

  static void Main()
  {
    // Wait 5 seconds if contended – in case another instance
    // of the program is in the process of shutting down.
    if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false))
    {
        Console.WriteLine("Another instance of the app is running. Bye!");
        return;
    }

    try
    {
        Console.WriteLine("Running - press Enter to exit");
        Console.ReadLine();
    }
    finally
    {
        mutex.ReleaseMutex();
    }
  }
}
```
```
A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.


q: How would one create an iterative function (or iterator object) in python?

[A]
First of all the
itertools module
is incredibly useful for all sorts of cases in which an iterator would be useful, but here is all you need to create an iterator in python:
yield
Isn't that cool?  Yield can be used to replace a normal
return
in a function.  It returns the object just the same, but instead of destroying state and exiting, it saves state for when you want to execute the next iteration.  Here is an example of it in action pulled directly from the
itertools function list
:
```
```
def count(n=0):
    while True:
        yield n
        n += 1
```
```
As stated in the functions description (it's the
count()
function from the itertools module...) , it produces an iterator that returns consecutive integers starting with n.
Generator expressions
are a whole other can of worms (awesome worms!).  They may be used in place of a
List Comprehension
to save memory (list comprehensions create a list in memory that is destroyed after use if not assigned to a variable, but generator expressions can create a Generator Object... which is a fancy way of saying Iterator). Here is an example of a generator expression definition:
```
```
gen = (n for n in xrange(0,11))
```
```
This is very similar to our iterator definition above except the full range is predetermined to be between 0 and 10.
I just found
xrange()
(suprised I hadn't seen it before...) and added it to the above example.
xrange()
is an iterable version of
range()
which has the advantage of not prebuilding the list.  It would be  very useful if you had a giant corpus of data to iterate over and only had so much memory to do it in.


q:
Does anyone use Accurev for Source Control Management? We are switching (eventually) from StarTeam to Accurev.

My initial impression is that the GUI tool is severely lacking, however the underlying engine, and the branches as streams concept is incredible.

The biggest difficulty we are facing is assessing our own DIY tools that interfaced with starteam, and either replacing them with DIY new tools, or finding and purchasing appropriate replacements.

Additionally, is anyone using the AccuWork component for Issue management? Starteam had a very nice change request system, and AccuWork does not come close to matching it. We are evaluating either using Accuwork, or buying a 3rd party package such as JIRA.

Opinions?

[A]
At a previous employer we reviewed Accurev and Plastic SCM. At the end of the day, I was not impressed with Accurev's interface, or the so-called "streams". We went with Plastic, and nobody complained.
@Jonathan
The streams are interesting,but I don't see how any version control can magically avoid collisions when two people touch the same code in the same file. Accurev's model was intriguing, but at the end of the day, nice clean branching and merging with a drop dead easy interface made Plastic the choice for us. Plastic's timeline view (I forget the actual name), showing the branch/merge/check-in history made it very simple to review the history of the project from a bird's eye view.


q:
In my code behind I wire up my events like so:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    btnUpdateUser.Click += btnUpateUserClick;
}

I've done it this way because that's what I've seen in examples.

Does the base.OnInit() method need to be called?

Will it be implicitly be called?

Is it better to call it at the beginning of the method or at the end?

What would be an example where confusion over the base method can get you in trouble?

[A]
In this case, if you don't call the base OnInit, then the Init even will not fire.
In general, it is best practice to ALWAYS call the base method, unless you specifically know that you do not want the base behaviour to occur.
Whether its called at the start or the end depends on how you want things to work. In a case like this, where you are using an override instead of hooking up an event handler, calling it at the start of the method makes more sense. That way, your code will run after any handlers, which makes it more emulate a "normal" event handler.


q:
I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.

I'm specifically refering to something that would work with the jstl tags such as

<fmt:setlocale>
<fmt:bundle>
<fmt:setBundle>
<fmt:message>

I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.

[A]
Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already..
or am I completely missing your point?
edit:
to be more explicit... I usually implement a three column table... language, key, value... where "value" contains potentially foreign language words or phrases... "language" contains some language key and "key" is an english key (i.e. login.error.password.dup)... language and key are indexed...
I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and "dirty" markers and all the other stuff you need to enable translators and data entry folk to make use of it..
Edit 2:
Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on
theserverside
...
```
```
HttpSession session = .. [get hold of the session]
ResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream]
Locale locale = .. [get hold of the locale]
javax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle ,locale));
```
```