Question:
I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file.  However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it.

What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a filename.nnn output file, then read up-to the next line-break and write that, then close the output file, etc.  Obviously the last output file just copies to the end of the input file.

Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?

I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)

Answer:
Check out
```
os.stat()
```
for file size and
```
file.readlines([sizehint])
```
. Those two functions should be all you need for the reading part, and hopefully you know how to do the writing :)


Question: What is the regex for a alpha numeric word, at least 6 characters long (but at most 50).

Answer:
With PCRE regex you could do this:
```
```
/[a-zA-Z0-9]{6,50}/
```
```
It would be very hard to do in regex without the min/max quantifiers so hopefully your language supports them.


Question:
I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit Select All it doesn't select all. I can right click and click Select All but CTRL + A doesn't do anything. Why?

wnd = CreateWindow("EDIT", 0,
    WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
    x, y, w, h,
    parentWnd,
    NULL, NULL, NULL);

Answer:
You need to capture that keystroke and do the select all yourself.
Here is some C# code for use with a RichTextBox:
```
```
protected override void OnKeyDown(KeyEventArgs e)
    {
        // Ctrl-A does a Select All in the editor window
        if (e.Control && (e.KeyCode == Keys.A))
        {
            this.SelectAll();
            e.Handled = true;
        }
    }
```
```
Sorry, I don't have Win32 code for you.


Question:
Is there a way to recursively add all "non added" files to SVN?

I want to do something like

svn add trunk/

to add all new files, without getting:

svn: warning: 'trunk' is already under version control

If this is not possible, is there a way to get a list of all files that are not under version control in the directory?

Note that I am only interested in using the command line.

Answer:
Use the --force option.
Example:
```
```
svn add * --force
```
```


Question:
I have a file with several thousand rows and several columns separated with tabs What I'd like to do is loop through each individually, Drop the columns into an array so that I can place them in another application individually, then move onto the next line.  Unfortunately I got about as far as this:

Open mytextfile.txt For Input As #FileHandle
 Do While Not EOF(FileHandle)
 Line Input #FileHandle, IndividualLine
 StringToBreakup = IndividualLine
Loop

So how would I go about breaking individual line up into an array

Answer:
Use the split command
```
```
Dim StringArray as Variant

Open mytextfile.txt For Input As #FileHandle
 Do While Not EOF(FileHandle)
 Line Input #FileHandle, IndividualLine
 StringToBreakup = IndividualLine

 StringArray = Split(StringToBreakup, CHR(9))

 Process array here...

Loop
```
```


Question:
Has anyone found any documentation or research about what data is transfered to Google Analytics when it's added to a site. The main thing I'm wondering about is post data, but the details of exactly what is sent would be useful.

I'm considering implementing it on a sites that have a lot of private data on them. I'm wondering what data Google will capture, if any. (The sites are login only.) I'm needing proof so I can provided to the users.

Answer:
The official information can be found
here
The visitor tracking information that you can get in the Google Analytics reports depends on Javascript code that you include in your website pages, referred to as the Google Analytics Tracking Code (GATC). Initial releases of the GATC used a Javascript file called urchin.js.
That script is then discussed in detail in
that blog
, and Google Analytics Help group can also provide
some details
.
a More detailed list of what that javascript collect is
listed here
.


Question:
For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?

if ($("#navbar .heading").text() > "") {
  $("#navbar .heading").hide();
}

and

var $heading = $("#navbar .heading");

if ($heading.text() > "") {
  $heading.hide();
}

If the selector is more complex I can imagine it's a non-trivial hit.

Answer:
i don't believe jquery does any caching of selectors, instead relying on xpath/javascript underneath to handle that. that being said, there are a number of optimizations you can utilize in your selectors. here are a few articles that cover some basics:
Optimizing jQuery selector performance
Performance analysis of selectors


Question: Is it possible to programmatically either via the win32API (python) or via a command line option set the processor affinity for a process?

Answer:
In C/C++ you can use
SetThreadIdealProcessor()
.  I have no idea if this is accessible in python.
```
```
DWORD processorId = 0;
SetThreadIdealProcessor(GetCurrentThread(),processorId);
```
```


Question: What is the simplest way in VB6 to loop through all the files in a specified folder directory and get their names?

Answer:
```
```
sFilename = Dir(sFoldername)

Do While sFilename > ""

  debug.print sFilename
  sFilename = Dir()

Loop
```
```


Question:
I've got a stock standard ASP.NET website. Anyone can read/view any page (except the admin section) but when someone wants to contribute, they need to be logged in. Just like most contribution sites out there.

So, if i have my OWN login control or username/password/submit input fields, why would i want to have forms auth turned on instead of just none? what does forms auth give me, which having my own code that check my database for a user/pass and my own two input fields + a submit button, does the job perfectly?

(NOTE: i really dislike the asp.net membership stuff that creates all those tables and usp's in the database, so please don't suggest I use that).

Like, with my code, when i authenticate a user (with my own database code), i manually create my own identity, etc.

is all this required? what is the main purpose of this?

cheers!

Answer:
You can authorize your users how ever you want.  FormAuthentication is used to set the session identity and the authentication cookie that allows users to stay logged in until they logout or the session expires.  You don't need to use the membership providers to use FormsAuthentication.  It sounds like you are just replicating this functionality.
```
```
...do your authentication against your DB or Active Directory

if (Request.QueryString["ReturnUrl"] != null)
{
    FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
}
else
{
    FormsAuthentication.SetAuthCookie(userName.Text, false);
}
```
```
Then you need to set up to use it in the web.config
```
```
<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx"
           protection="All"
           timeout="30"
           name="my-auth-cookie"
           path="/"
           requireSSL="false"
           slidingExpiration="true"
           defaultUrl="default.aspx" />
  </authentication>
</system.web>
```
```
You get all the benefits of doing your own authorization and not having to implement the cookie infrastructure.  Note, since your web site only needs to authorize when editing, you'll need to set the permissions that allow everyone to read all pages and implement your own logic to redirect them to the login page when they want to edit.
More information
here
.


Question:
I am using the dojo.io.iframe.send method to send a file to my server. I want to provide a way that the user can cancel the send once it is in progress, in case it is taking too long or the user realizes she sent the wrong file.

I can't figure a way to do this. I could use a timeout to terminate the send if it is taking a long time (that is, the server does not respond quickly), but that is not what I want. I want to terminate any time the user makes a gesture (such as clicking a "Cancel" button.

Thanks!

Answer:
For security reasons JavaScript cannot even access the file you are sending up. All file uploads are done using a form and handled by the browser directly. To my best knowledge there is no direct interface to monitor the progress of upload, nor the way to affect it (e.g., cancel it).
Navigating away may help, but it is still up to the browser to interrupt the transfer or not — there is no specification for that.
To sum it up: not possible to do it reliable in JavaScript in the portable fashion. That means Dojo does not provide this functionality.


Question:
I have to include Groovy classes into existing Java apps, and include Groovy into Ant's build.xml file.

What is the best way to configure Ant's build.xml for it?

Update: Are there more specifics in combining Java and Groovy compilations? Sequence of tasks?

Answer:
To use Groovy in your ant script, you basically have to
declare the Groovy ant task
:
```
```
<project name="groovy-build" default="listSourceFiles">

<taskdef name="groovy"
     classname="org.codehaus.groovy.ant.Groovy"/>
<groovy>
    ant.... // some ant groovy directives
</groovy>
</target>
</project>
```
```
However, you have to be careful, in your ant.xml, to refer to fileset within your
current target
.


Question:
I have a nested function to show/hide paragraphs news-ticker-style.

The problem is that when the loop starts over (line 4), the opacity effects stop working correctly so the paragraphs appear abruptly.

Any jquery masters know about this? Am I making this too hard?

$('#special-ticker p').hide();
var a=0;
function outer() {
    function inner() {
        if(a===$('#special-ticker p').length) { a = 0; }
        $('#special-ticker p').
        eq(a).
        fadeIn(800, function(){
            $(this).animate({opacity:100},10000,null,function(){
                $(this).hide(800,function(){
                    a++;
                    outer();
                });
            });
        });
    }
    return inner();
}
$(function(){
    outer();
});

Answer:
the problem is line 9:
```
```
$(this).animate({opacity:100},10000,null,function(){
//...
```
```
opacity should be "1" (opacity is a value between 0 and 1)
```
```
$(this).animate({ opacity : 1 }, 10000, null, function() {
```
```


Question:
I have a Canvas in a Flex application which has items inside it that cover only about 50% of the area of the main canvas.

i want the canvas to respond to rollOver events for the full area, and not just the area that is covered by the items inside.

I have been setting the following attributes to achieve this :

<mx:Canvas backgroundColor="white"
backgroundAlpha=".01"
rollOver="rollOver(event)">...

This causes the entire canvas to respond to rollOver events. It works great - I'm just not happy with it and figure there must be a better way to achieve it.

Is there a way to force mouse events to act on the entire area of a UIComponent?

Answer:
You could do this:
```
```
import flash.event.MouseEvent;
...
canvas.addEventListener(MouseEvent.ROLL_OVER,function(event:MouseEvent):void {
    ...
});
```
```
where "canvas" is the ID of the canvas in your mxml.


Question:
i did this in msvc 2005.

typedef void (*cleanup_t)();

void func(cleanup_t clean)
{
    cleanup_t();
}

Why does this compile? and not give me a warning? ok, it gave me a unreferenced formal parameter warning but originally i did this when clean was in a class no there was no unreferenced formal parameter when this code gave me problems.

What is cleanup_t(); really doing and what is the point? now for laughs i tried int() and that worked also.

Answer:
I think it's an expression that evaluates to a default value for a cleanup_t type.  In other words, an expression that returns a NULL pointer to a function that returns void.
In C/C++, expressions with no side effects (which this is - I think) are valid statements, just like you can have a statement like:
```
```
1 + 2;
```
```
That's not a syntax error, but some compilers might give a warning.  They don't often give a warning for side-effect-less expressions that return NULL values or are simply variable names because that type of expression is often used in macros for debugging purposes (like the assert() macro).
You can think of it as calling the default constructor for the
```
cleanup_t
```
type.  Having this default constructor-like syntax for built-in types (or typedef's of them) was added to C++ so that templates could set items of the type passed in as a template parameter to default values while still allowing the template type parameter to be a non-user defined type. There might other reasons, but I believe that to be one of them.
Something like:
```
```
template <class T>
class foo
{
    T myT;

    public:

    foo() {
        myT = T();
    };
};

typedef void (*cleanup_t)();

class bar
{
};

int not_quite_a_cleanup_t_func()
{
    return 1;
}

int main()
{
    foo<int> intFoo;
    foo<cleanup_t> cleanup_t_foo;
    foo<bar> barFoo;

    // here I'm going to harp on one of the things I don't like about C++:
    //
    //  That so many things that look like function calls are not or that
    //  the parens cause subtle behavior changes.
    //
    //  I believe this is the reason this question was posted to
    //  stackoverflow, so it's not too far off topic.
    //
    //  Many of these things exist because of backwards compatibility with C or
    //  because they wanted to fit in new features without adding keywords or
    //  new reserved tokens or making the parser even more complex than it already
    //  is.  So there are probably good rationales for them.
    //
    //  But I find it confusing more often than not, and the fact that there
    //  might be a rationale for it doesn't mean I have to like it...

    cleanup_t cleanup1();    // declares a function named cleanup1 that returns a cleanup_t

    cleanup_t cleanup2 = cleanup_t();   // cleanup2 is a variable of type cleanup_t that
                                        //  is default initialized

    cleanup_t* cleanup3 = new cleanup_t;    // cleanup3 is a pointer to type cleanup_t that
                                            //  is initialized to point to memory that is
                                            //  *not* initialized

    cleanup_t* cleanup4 = new cleanup_t();  // cleanup4 is a pointer to type cleanup_t that
                                            //  is initialized to point to memory that *is*
                                            //  initialized (using default intialization)

    cleanup2 = cleanup_t( not_quite_a_cleanup_t_func);  // explicit type conversion using functional notation

    cleanup_t();    // the OP's problem
    cleanup2();     // call the function pointed to by cleanup2
    (*cleanup2)();  // same thing

    class cleanup_class
    {
        cleanup_t cleanup5;

    public:
        cleanup_class() :
            cleanup5() // class member default initialization
        { };
    };
}
```
```


Question:
while exploring jQuery I came up with the following weird script. I don't see myself doing this really however concatenating strings to achieve a variable name is not unusual in JavaScript.

Any feedback welcome.

...
    <script type="text/javascript">
        var a = 'y';
        $(document).ready(function() {
            $('p[id^=' + $('p[id=x]').html() + a + "]").css('color','blue');
        });
    </script>
...

<p id="x">2a</p>
<p id="2ay_">mytext</p>

Answer:
Short answer is no, there aren't side-effects.  Your example is quirky, but as you said you were just exploring to see what you could do.  I have used string concatenation and function value returns inside jQuery selectors before, it can be a useful technique for managing sets of related elements which reside in different parts of the DOM.
I admit I haven't used
```
jQuery.html()
```
inside a selector, but there isn't any inherent reason why that's "bad".  I just can't think of a situation where that'd be strictly necessary.  It does make the code rather... unusual, and hence more difficult to understand and maintain.
If you actually find a use for this in production code, please let us know.  I'd be fascinated to see what it is. :)


Question: Having a relative path, how do I turn it into an absolute one from the location where the elisp file that I'm loading is. That is, I have an elisp file that I'm loading, it has an relative path and I need an absolute one.

Answer:
You can use the
```
expand-file-name
```
function to convert a relative filename or path into an absolute filename/path.  Look
here
for additional information.


Question:
What exactly are the Python scoping rules?

If I have some code:

code1
class Foo:
   code2
   def spam.....
      code3
      for code4..:
       code5
       x()

Where is x found?  Some possible choices include the list below:

In the enclosing source file

In the class namespace

In the function definition

In the for loop index variable

Inside the for loop

Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?

There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.

Answer:
Python resolves your variables with -- generally -- three namespaces available.
At any time during execution, there
  are at least three nested scopes whose
  namespaces are directly accessible:
  the innermost scope, which is searched
  first, contains the local names; the
  namespaces of any enclosing functions,
  which are searched starting with the
  nearest enclosing scope; the middle
  scope, searched next, contains the
  current module's global names; and the
  outermost scope (searched last) is the
  namespace containing built-in names.
There are two functions:
```
globals
```
and
```
locals
```
which show you the contents two of these namespaces.
Namespaces are created by packages, modules, classes, object construction and functions.  There aren't any other flavors of namespaces.
In this case, the call to a function named
```
x
```
has to be resolved in the local name space or the global namespace.
Local in this case, is the body of the method function
```
Foo.spam
```
.
Global is -- well -- global.
The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global.  That's it.
There are no other scopes.  The
```
for
```
statement (and other compound statements like
```
if
```
and
```
try
```
) don't create new nested scopes.  Only definitions (packages, modules, functions, classes and object instances.)
Inside a class definition, the names are part of the class namespace.
```
code2
```
, for instance, must be qualified by the class name.  Generally
```
Foo.code2
```
.  However,
```
self.code2
```
will also work because Python objects look at the containing class as a fall-back.
An object (an instance of a class) has instance variables.  These names are in the object's namespace.  They must be qualified by the object.  (
```
variable.instance
```
.)
From within a class method, you have locals and globals.  You say
```
self.variable
```
to pick the instance as the namespace.  You'll note that
```
self
```
is an argument to every class member function, making it part of the local namespace.
See
Python Scope Rules
,
Python Scope
,
Variable Scope
.


Question: Is the jQuery intellisense plugin available for Visual Studio now?

Answer:
Yes, it is.
Rich Intellisense for JQuery
.


Question:
I've been seeing so much recently about functional programming and Clojure looks particularly interesting. While I 'understand' the basic description of what it is, I can't figure out how I would use it on a day to day basis as a web developer, if I can at all. A lot of what I have read focuses on the maths side of functional programming rather then typical programming situations found in regular OO.

Have I got the wrong end of the stick? Is functional programming totally un-related to web development? If not, are there any examples of it being used 'for the web'?

Answer:
A few examples off the top of my head:
Yahoo! Store is powered by Lisp (originally named
Viaweb
prior to acquisition)
Reddit
was fully prototyped in Lisp, although they
switched to Python
in 2005
Hacker News
is written entirely in Arc (a Lisp dialect)


Question:
I'd like to add a custom title to one of the predefined UITabBarItems. Whenever I select the particular instance I like in Interface Builder -- if I modify the the title it gets preset back to a 'custom' identifier. Ideally I'd like the book icon from the 'Bookmarks' identifier with my own custom title.

Is this level of customization currently supported by the SDK? Am I going to have to ultimately screen scrape the image and apply it as a custom image?

Thanks for any insight or documentation which points me in the right direction.

Answer:
Unfortunately, the only types of UITabBarItems are those supplied and described entirely by the OS (ie, it assigns them icons and titles), and those described entirely by the app, as you've discovered. By far the simplest solution is to pull the icon out of somewhere else and use it with
```
-initWithTitle:image:tag
```
.
http://img369.imageshack.us/img369/8388/openbookwp4.png


Question:
I have seen a lot of ob_get_clean() the last while. Typically I have done $test .= 'test'

I'm wondering if one is faster and/or better than the other.

Here is the code using ob_get_clean():

ob_start();

foreach($items as $item) {
    echo '<div>' . $item . '</div>';
}

$test = ob_get_clean();

Here is the code using $test .= 'test':

$test = '';

foreach($items as $item) {
    $test .= '<div>' . $item . '</div>';
}

Which is better?

Answer:
The results are the same, and I'd imagine the performance differences are negligible if any. Basically, a matter of personal style preference. I would go with concatenation myself - I use output buffering only when concatenation is not an option.
Also, instead of running both
```
ob_get_contents()
```
and
```
ob_clean()
```
simply run
```
ob_get_clean()
```
which performs both at once.


Question:
I stumbled upon this javascript obfuscator called Squash, I want to use it on my ExtJS project to obfuscate my javascript files. I've tried it and the result are totally obfuscated codes. But it seems that I have to obfuscate the ExtJS library too because I got warnings that it couldn't find functions such as Ext.onReady(), Ext.form.FormPanel(), etc.

I just want to ask if any of you guys have successfully used Squash + ExtJS in a project and how did you manage to make it work.

Answer:
Typical rtfm: The
```
@Public
```
annotation on the
```
setDocumentTitle
```
function prevents the function name from being obfuscated so that it can be accessed from unobfuscated code.


Question: How can I delete all the tables in a web page? The tables don't have any ids associated with them.

Answer:
If you're using jQuery it is pretty easy ...
```
```
$(document).ready(function() {
  $("table").remove();
});
```
```
not sure how's you do it in other libraries.
if you're not using a js library, you should be.


Question:
I wanted to grep for java process and then find the max heap memory used.
I tried this

def ex =['sh','-c','ps -aef | grep Xmx']
String str =  ex.execute().text

while str has something like java -Xmx1024M /kv/classes/bebo/ -Xms512M
How do I extract the value 1024M? I was planning to user java regex but thought someone might know a cool way in groovy.

Answer:
In Java:
```
```
String ResultString = null;
Pattern regex = Pattern.compile("-Xmx(\\d+M)");
Matcher regexMatcher = regex.matcher(str);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
}
```
```


Question: VB 6: How can I execute a .bat file but wait until its done running before moving on?

Answer:
You will need to use Win32 API calls to
ShellExecuteEx
and WaitForSingleObject on the process handle returned from ShellExecuteEx in the SHELLEXECUTEINFO structure.  This is old code which I've pulled out of a project. It was working 100% but I may not have included all dependencies. You should be able to edit to your requirements:
```
```
Type SHELLEXECUTEINFO
                cbSize As Long
                fMask As Long
                hwnd As Long
                lpVerb As String
                lpFile As String
                lpParameters As String
                lpDirectory As String
                nShow As Long
                hInstApp As Long
                '  Optional fields'
                lpIDList As Long
                lpClass As String
                hkeyClass As Long
                dwHotKey As Long
                hIcon As Long
                hProcess As Long
        End Type

        Public Declare Function ShellExecuteEx Lib "shell32.dll"
            (lpExecInfo As SHELLEXECUTEINFO) As Long

        Public Declare Function apiShellExecute Lib "shell32.dll" _
            Alias "ShellExecuteA" _
            (ByVal hwnd As Long, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As Long) _
                As Long

        Declare Function WaitForSingleObject Lib "kernel32"
             (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long

        Public Const SEE_MASK_NOCLOSEPROCESS As Long = &H40
        Public Const SEE_MASK_FLAG_DDEWAIT As Long = &H100

        '***App Window Constants***'
        Public Const WIN_NORMAL = 1         'Open Normal'
        Public Const WIN_MAX = 2            'Open Maximized'
        Public Const WIN_MIN = 3            'Open Minimized'

        '***Error Codes***'
        Private Const ERROR_SUCCESS = 32&
        Private Const ERROR_NO_ASSOC = 31&
        Private Const ERROR_OUT_OF_MEM = 0&
        Private Const ERROR_FILE_NOT_FOUND = 2&
        Private Const ERROR_PATH_NOT_FOUND = 3&
        Private Const ERROR_BAD_FORMAT = 11&

' Returns 'True' if file was opened ...'
Public Function fHandleFile(ByVal stFile As String, _
                            ByVal lShowHow As Long, _
                            ByRef stRet As String, _
                            Optional ByVal bWaitForClose As Boolean = False) As Boolean
On Error GoTo err_Handler
    Dim lRet As Long
    Dim ret As Long
    Dim lngProcessHandle As Long
    Dim varTaskID As Variant
    Dim shInfo As SHELLEXECUTEINFO
    Dim retval As Long

    'First try ShellExecute'
    With shInfo
        .cbSize = LenB(shInfo)
        .lpFile = stFile
        .nShow = lShowHow
        If bWaitForClose Then
            .fMask = SEE_MASK_FLAG_DDEWAIT + SEE_MASK_NOCLOSEPROCESS
        End If
        .lpVerb = "open"
    End With

    Call ShellExecuteEx(shInfo)
    lRet = shInfo.hInstApp

    If lRet > ERROR_SUCCESS And bWaitForClose = True Then
        lngProcessHandle = shInfo.hProcess

        Do
            retval = WaitForSingleObject(lngProcessHandle, 0)
            DoEvents
        Loop Until retval <> 258
        ret = CloseHandle(lngProcessHandle)
    End If

    fHandleFile = (lRet > 0)

exit_handler:
    Exit Function

err_Handler:
    RaiseError Err.Number, Err.Source, Err.Description
End Function
```
```


Question:
I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the standard, even as documented on the MSDN site.

My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?

Call the add method differently based on the value of the user agent?

Wrap the select object in a class that provides the proper method signature?

Use a javascript library which does this for you (specify which library)?

Answer:
Adding a new Option type works at least IE6 and up
```
```
function addOption(selectID, display, value)
{
  var obj = document.getElementById(selectID);
  obj.options[obj.options.length] = new Option(display, value);
}
```
```
Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully.  IE4 failed :(


Question:
Is there any real reason not to make a member function virtual in C++?  Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.

On the other hand, I've been bitten a couple of times with forgetting to make a function virtual that should be virtual.  And that seems to be a bigger argument than the performance one.  So is there any reason not to make member functions virtual by default?

Answer:
One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default."  Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual.  Seems to me this would have required more effort in the compiler implementation, and slowed down the adoption of C++ by providing fodder to the performance obsessed (I count myself in that group.)
Another way to read your questions is "Why do C++ programmers do not make every function virtual unless they have very good reasons not to?"  The performance excuse is probably the reason.  Depending on your application and domain, this might be a good reason or not.  For example, part of my team works in market data ticker plants.  At 100,000+ messages/second on a single stream, the virtual function overhead would be unacceptable.  Other parts of my team work in complex trading infrastructure.  Making most functions virtual is probably a good idea in that context, as the extra flexibility beats the micro-optimization.


Question:
I have an idea for a web-based service. The implementation is very complex. There will be very few users, and the traffice will be fairly low, but the server-side code could require a lot of resources. Ideally I'd need to have as much control over the servers as possible.

How should I arrange hosting for this, when it comes time to release it to the public?

Should I do the hosting myself, from my own servers? Trouble is, since I'm not quite an expert on .NET hosting, it might take time to learn and I might make big mistakes.

The trouble with using a hosting company is, they might steal my idea, or else, it might cost a lot. Since I'm an un-funded startup I don't have a lot of money to throw at this.

Answer:
A lot of hosting providers are able to provide you with a dedicated server or VPS (Virtual Private Server) where you run a virtual machine on shared hardware. I have used
HostMySite
for VPS in the past and the service was very good. Dedicated and VPS hosting will cost much more than a shared hosting situation, but probably a safer bet than buying your own hardware, running in the high-speed backbone, dealing with backups, climate control, generators for power outages, etc.
update:
I missed the part about the hosting company stealing your idea. Somebody will take your idea, but ideas alone are worthless... it's all about the execution, and I don't think people at your hosting company would copy your code directly.


Question: I have a team of junior developers and they want to have better understanding and usages of generics.  Anyone recommend good tutorial or articles samples that are good places to start.

Answer:
A few links:
An Introduction to C# Generics
Generics (C# Programming Guide)
Recommended books:
Professional .NET 2.0 Generics
C# in Depth


Question:
In Google groups and some other web sites, there is a 5-star rating component which is pretty neat, such as in this url:
http://groups.google.com/group/Google-Picasa-Data-API/browse_thread/thread/b5a346e6429a70a7?hl=en

I am wondering whether there is an existing 5-star rating component in the iPhone environment. Or if there is not, if anyone has clue where to start?

Thanks

Answer:
I don't know of any free/available components off the top of my head, but if nobody offers one up and/or you can't find one you like, it should be fairly trivial to roll your own. In the simplest terms, you would only have to:
Create/Find a star icon - one outline (unselected), one filled
Create a UIButton and set the icons for the selected/unselected states
Create a container view that held your x stars and when one was selected, the container could set the selected state on any button to the left of the touched button.
Shouldn't take long at all to build...


Question: how good to use 3 point technique for risk assessment.

Answer:
Is this what you mean?
http://www.aof.mod.uk/aofcontent/tactical/risk/content/tpe.htm?zoom_highlight=simulation
If so, it looks like that site's a pretty good overview and analysis.


Question: I'm pretty green with web services and WCF, and I'm using Windows integrated authentication - how do I get the username on the server-side interface? I believe that I'm supposed to implement a custom Behavior, or perhaps something with WCF Sessions? Any clues would be super-handy.

Answer:
have you tried
```
WindowsIdentity.GetCurrent();
```
?


Question: Trying to create a random string, x characters in length using 0-9 and a-z/A-Z and can't seem to find a good example, any ideas?

Answer:
I forgot all my VB6 (thank God) but in pseudocode it's pretty easy:
```
all_chars = an array of all the valid chars
    seed random number generator
    for i = 1 to x do
        random_index = get a random number between 1 and length of all_chars
        'I remember how to concat and comment in VB6 :-)
        string = string & all_chars[random_index]
    end for

    done!
```
So it's just a matter of finding out how to create an array and fill it with characters, how to get the length of the array and how to get a
random number
between the first and last indexes of said array.
Well, all that and looping of course.


Question:
I'm a simple soul with simple needs, and I'm trying to configure a form.  I detest forms.

It needs to have JavaScript to transfer the data, it needs to send an e-mail with the data to an e-mail address, and it needs to redirect visitors to a pdf.  CGI has always been confusing to me, and I don't know much JavaScript.

I've already done the html, but the post action and the JavaScript is killing me.  It's been 4 hours of searching.  Stick a fork in me.  I'm done.

Answer:
OK, first thing's first, we need to clarify you're wording.  JavaScript and Java are two significantly different languages.
In order to send mail, you need to use whichever language you're using in conjunction with an SMTP server, which is what would have to be what actually sends the e-mail, not JavaScript which is client-side.
An example of using JavaScript to post to an SMTP server can be found here (though I wouldn't recommend this method as ActiveX is IE exclusive):
http://www.ostrosoft.com/smtp_component/smtp_javascript.asp
Ultimately with JavaScript, the best method you'd use would just be posting to a non-SMTP server that then sends the data to the SMTP server.
If you're actually using Java, there's an optional library you can add called JavaMail to make it much easier to send mail, though again, you need to communicate with an SMTP server.
An example of JavaMail can be found here:
http://www.javapractices.com/topic/TopicAction.do?Id=144


Question: What are the coolest new features that you guys are looking for, or that you've heard are releasing in c# 4.0.

Answer:
the dynamic keyword looks like it can bridge the gap between dynamic languages like IronRuby or IronPython quite nicely, which will probably help its adoption in the Microsoft monoculture... that excites me.
While I'm intrigued by it, I'm also worried that it will be overused, like Generics and LINQ, SQLCLR, etc :)


Question:
I read through the Wikipedia article Existential types. I gathered that they're called existential types because of the existential operator (∃). I'm not sure what the point of it is, though. What's the difference between

T = ∃X { X a; int f(X); }

and

T = ∀x { X a; int f(X); }

?

Answer:
As I understand it's a math way to describe interfaces/abstract class.
As for T = ∃X { X a; int f(X); }
For C# it would translate to a generic abstract type:
```
```
abstract class MyType<T>{
    private T a;

    public abstract int f(T x);
}
```
```
"Existential" just means that there is some type that obey to the rules defined here.


Question: I have a function which gets a key from the user and generates a Hashtable (on a pattern specified by the key). After creating a Hashtable, I would like to populate a JTable so that each each column represents a key and every rows represents the values associated with the key. I tried everything but couldn't get this work. I'm not creating the table from within the constructor as I need to get input from the user.

Answer:
See
How to Use Tables: Creating a Table Model
.
The JTable constructor used by
  SimpleTableDemo creates its table
  model with code like this:
```
```
new AbstractTableModel() {
    public String getColumnName(int col) {
        return columnNames[col].toString();
    }
    public int getRowCount() { return rowData.length; }
    public int getColumnCount() { return columnNames.length; }
    public Object getValueAt(int row, int col) {
        return rowData[row][col];
    }
    public boolean isCellEditable(int row, int col)
        { return true; }
    public void setValueAt(Object value, int row, int col) {
        rowData[row][col] = value;
        fireTableCellUpdated(row, col);
    }
}
```
```
You basically have to wrap your hashtable in the above manner. Here's an example.
```
```
package eed3si9n.hashtabletable;

import java.awt.BorderLayout;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.JButton;
import java.awt.Dimension;

public class MainForm extends JFrame {

    private static final long serialVersionUID = 1L;
    private JPanel jContentPane = null;  //  @jve:decl-index=0:visual-constraint="23,38"
    private JScrollPane m_scrollPane = null;
    private JTable m_table = null;
    private Hashtable<String, String> m_hash = null;
    private JButton m_btnAdd = null;

    /**
     * This is the default constructor
     */
    public MainForm() {
        super();
        initialize();
        m_hash = new Hashtable<String, String>();
        m_hash.put("Dog", "Bow");
    }

    private void onButtonPressed() {
        m_hash.put("Cow", "Moo");
        m_table.revalidate();
    }

    /**
     * This method initializes this
     *
     * @return void
     */
    private void initialize() {
        this.setSize(409, 290);
        this.setTitle("JFrame");
        this.setContentPane(getJContentPane());
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.setSize(new Dimension(500, 500));
            jContentPane.setPreferredSize(new Dimension(500, 500));
            jContentPane.add(getM_scrollPane(), BorderLayout.NORTH);
            jContentPane.add(getM_btnAdd(), BorderLayout.SOUTH);
        }
        return jContentPane;
    }

    /**
     * This method initializes m_scrollPane
     *
     * @return javax.swing.JScrollPane
     */
    private JScrollPane getM_scrollPane() {
        if (m_scrollPane == null) {
            m_scrollPane = new JScrollPane();
            m_scrollPane.setViewportView(getM_table());
        }
        return m_scrollPane;
    }

    /**
     * This method initializes m_table
     *
     * @return javax.swing.JTable
     */
    private JTable getM_table() {
        if (m_table == null) {
            m_table = new JTable();
            m_table.setModel(new AbstractTableModel(){
    private static final long serialVersionUID = 1L;

    public int getColumnCount() {
        return 2;
    }

    public int getRowCount() {
        return m_hash.size();
    }

    public String getColumnName(int column) {
        if (column == 0) {
            return "Animal";
        } else {
            return "Sound";
        }
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        if (columnIndex == 0) {
            return getKey(rowIndex);
        } else {
            return m_hash.get(getKey(rowIndex));
        } // if-else

    }

    private String getKey(int a_index) {
        String retval = "";
        Enumeration<String> e = m_hash.keys();
        for (int i = 0; i < a_index + 1; i++) {
            retval = e.nextElement();
        } // for

        return retval;
    }

            });
        }
        return m_table;
    }

    /**
     * This method initializes m_btnAdd
     *
     * @return javax.swing.JButton
     */
    private JButton getM_btnAdd() {
        if (m_btnAdd == null) {
            m_btnAdd = new JButton();
            m_btnAdd.setPreferredSize(new Dimension(34, 30));
            m_btnAdd.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    onButtonPressed();
                }
            });
        }
        return m_btnAdd;
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainForm frame = new MainForm();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(500, 500);
                frame.setVisible(true);
            }
        });
    }
}  //  @jve:decl-index=0:visual-constraint="10,10"
```
```


Question: How do I select the unique elements from the list {0, 1, 2, 2, 2, 3, 4, 4, 5} so that I get {0, 1, 3, 5}, effectively removing all instances of the repeated elements {2, 4}?

Answer:
```
```
var nums = new int{ 0...4,4,5};
var distinct = nums.Distinct();
```
```
make sure you're using Linq and .NET framework 3.5.


Question:
I always see the code like this in the blogs:

$.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebService.asmx/HelloWorld",
                    data: "{}",
                    dataType: "json",
                    success: function(msg) {
                        alert(msg.d);
                    }
                });

But I think this is run only with asp.net 3.5. I couldn't run it with 2.0. How can I use such these codes in my Applications?

Answer:
I already know this article, but It couldn't help me.
In my sample app, I use these codes:
my Jquery code:
```
```
$(document).ready(function() {
        $('#clKaydet').click(function() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "WebService.asmx/HelloWorld",
                data: "{}",
                dataType: "json",
                success: function(msg) {
                    alert(msg);
                }
            });

        });

    });
```
```
My Html Code:
```
```
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server" />
    <div>

        <input type="button" id="clKaydet" runat="server" value="Kayıt" onclick="Kayit()" />
    </div>

    </div>
    </form>
```
```
My Webservise Code:
```
```
<WebMethod()> _
Public Function HelloWorld() As String
    Dim sText As String = "Hello"
    Return sText
End Function
```
```
Is there any mistake?


Question:
We are currently working with Flex creating a web application. We are having trouble taking Arabic text from the user and displaying correctly (like in a chat feature). While presumably Flash 10 will solve this problem, we don't want to force our users to upgrade.

Flash flips the order of the sentence's words. so if I wrote something like "Hello World" in the text field, it will appear as "World Hello" in the chat area.

Is there a standard way to work with Right to Left languages in Flash?

*We currently flip the order of the words with a function, but it things get messed up when using English or special characters in the chat like :) or :D *

Answer:
This would appear to be a Unicode issue, and so a quick talaash via Google gave me
Unicode in Flash
, but probably more to the point is
Flash: RTL (right-to-left)
, seeing as it mentions Arabic (along with other RTL languages) as well as
RTL text output class for Flash
.
HTH


Question:
A few years ago client Java was unsuitable for web development because a remarkable part of web users did not have Java installed. ( I don't remember exact numbers, more than 10%).

Now I see the Google Analytics stats for a big site and it tells that >98% of users have Java installed.

Is these stats very biased by Javascript usage? As I understand Google Analytics measure only users that has Javascript.

Is the picture similar on other big sites?

Does client Java have really "stopper" drawbacks compared to Flash?

EDIT: I mean java applets mainly, java WebStart seems to be not suitable for average user.

I mention Javascript only to describe the way Google Analytics works.

Answer:
When I wrote my diploma project, I had to choose between Flash and Java Applets. Here are some pros and cons:
Java Applets:
[plus] you program in Java, which is mature and stable
[plus] you can use the Java GUI frameworks that pack a lot of punch
[minus] the first time the user hits the page with the applet, the JVM must be initialized and this can take up to a few minutes even on a fast computer
[minus] Applets are not meant to be used as animation media; sure, you can do stuff, but it is like programming in C - you do everything from scratch
example: i needed to show a data packet as it moved between two routers. The packet must be a control of some sort, like a button or smth. This animation can be defined in 1 line of code in Flash, where all objects derive from some base object that can be animated. I could not find a suitable solution in Java.
Flash:
[plus] really really focused on animations;
[plus] ActionScript is actually an OO language
[minus] ActionScript is sloppy, bughish and has only a few supporters. If you are stuck, be prepared to search obscure Japanese forums for solutions
[minus] ActionSCript may be OO, but it lacks a lot of features, like Enums, fully fledged interfaces, threads (!!!!) etc.
[minus] Flash was designed to be used by non-tech people - they just use the authoring tool; I wrote code for everything and it worked, but it was a pain.
My conclusion:
I eagerly await a programming paradigm for animations and rich client interfaces.
ps: Silverlight seems to be a disappointment so far, maybe Microsoft will inject some $ into it.


Question:
I want to decode a string that has been encoded using the java.net.URLEncoder.encode() method.

I tried using the unescape() function in javascript, but a problem occurs for blank spaces because java.net.URLEncoder.encode() converts a blank space
to '+' but unescape() won't convert '+' to a blank space.

Answer:
When I wrote my diploma project, I had to choose between Flash and Java Applets. Here are some pros and cons:
Java Applets:
[plus] you program in Java, which is mature and stable
[plus] you can use the Java GUI frameworks that pack a lot of punch
[minus] the first time the user hits the page with the applet, the JVM must be initialized and this can take up to a few minutes even on a fast computer
[minus] Applets are not meant to be used as animation media; sure, you can do stuff, but it is like programming in C - you do everything from scratch
example: i needed to show a data packet as it moved between two routers. The packet must be a control of some sort, like a button or smth. This animation can be defined in 1 line of code in Flash, where all objects derive from some base object that can be animated. I could not find a suitable solution in Java.
Flash:
[plus] really really focused on animations;
[plus] ActionScript is actually an OO language
[minus] ActionScript is sloppy, bughish and has only a few supporters. If you are stuck, be prepared to search obscure Japanese forums for solutions
[minus] ActionSCript may be OO, but it lacks a lot of features, like Enums, fully fledged interfaces, threads (!!!!) etc.
[minus] Flash was designed to be used by non-tech people - they just use the authoring tool; I wrote code for everything and it worked, but it was a pain.
My conclusion:
I eagerly await a programming paradigm for animations and rich client interfaces.
ps: Silverlight seems to be a disappointment so far, maybe Microsoft will inject some $ into it.


Question:
I recently wrote a class for an assignment in which I had to store names in an ArrayList (in java). I initialized the ArrayList as an instance variable private ArrayList<String> names. Later when I checked my work against the solution, I noticed that they had initialized their ArrayList in the run() method instead.

I thought about this for a bit and I kind of feel it might be a matter of taste, but in general how does one choose in situations like this? Does one take up less memory or something?

PS I like the instance variables in Ruby that start with an @ symbol: they are lovelier.

(meta-question: What would be a better title for this question?)

Answer:
In the words of the great Knuth "Premature optimization is the root of all evil".
Just worry that your program functions correctly and that it does not have bugs. This is far more important than an obscure optimization that will be hard to debug later on.
But to answer your question - if you initialize in the class member, the memory will be allocated the first time a mention of your class is done in the code (i.e. when you call a method from it). If you initialize in a method, the memory allocation occurs later, when you call this specific method.
So it is only a question of initializing later... this is called lazy initialization in the industry.


Question:
I have a number of user permissions that are tested throughout my ASP.NET application. These permission values are referenced in an Enum so that I can conveniently test permissions like so:

btnCreate.Enabled = PermissionManager.TestPermission(Permission.AllowCreate);

However, I also have these permissions stored in the database because I need hold more info about them than just their Id. But this creates a horrible dependency between the enum values and those in the database, an ill considered change to either and I have problems throughout my application. Is there a better way around this issue? Has anyone dealt with this before?

Answer:
I do not know what the best solution is, I would like to hear that.
Our solution is to explicitly type the enum like
```
```
public enum MyEnum : int
{
   None =0,
   Value = 1,
   AnotherValue =2
}
```
```
And save the integer value to the database. When for instance the Value 1 is removed, you will still be able to use the enumeration and AnotherValue still has the value 2 in the database.


Question:
I want to discard all remaining characters in a string as soon as one of several unwanted characters is encountered.

As soon as a blacklisted character is encountered, the string before that point should be returned.

For instance, if I have an array:

$chars = array("a", "b", "c");

How would I go through the following string...

log dog hat bat

...and end up with:

log dog h

Answer:
The
strcspn
function is what you are looking for.
```
```
<?php

$mask = "abc";

$string = "log dog hat bat";

$result = substr($string,0,strcspn($string,$mask));

var_dump($result);

?>
```
```


Question:
This follows on from this question where I was getting a few answers assuming I was using files for storing my HTML templates.

Before recently I've always saved 'compiled' templates as html files in a directory (above the root). My templates usually have two types of variable - 'static' variables which are not replaced on every usage but are used across the site - basically for ease of maintenanceif I decide to change the site name for example; and dynamic vars that change on every page load.

I always used to save these as files on the server - but my friend pointed out something I'd overlooked: why have 5-10 filesystem calls when you can have one database call?

What I want to know is which is more efficient? Calling several HTML files from the system or calling several rows of templates from the database (in one query/call).

Answer:
Don't Store Editable HTML In the database
Seriously, because the maintenance overhead for mere changes becomes exhaustive once you realise you can no longer just pop open a text editor.
I worked on many projects which had HTML content in the database, and it was a constant nightmare of "find that row the content is on" and I really would liked to have
shot
the person whom made it.
Also,
DON'T PREMATURELY OPTIMISE
. If you find it a problem thats slowing the project down, then change it. Because making the code exhaustively less maintainable to save a millisecond. But design the code well enough that should you need to change where the content comes from later it should be easy to do.
Surely that can be resolved by having
  a suitable web interface for editing
  the templates?
Erm, really not, unless you're only trying to compete with notepad. Syntax highlighting and all the other full host of features you can get in a standard editor just make your developers suicidal when they find themselves editing web pages by hacking at an undersized text area with awful white on black ( not to mention the extra fun you get with having to worry about entity encoding etc, for instance, try editing html with in a text area where the html content contains a text area element! )
On FileIO
While File IO can be a bottleneck, keep in mind that if you have a proper linux install, and plenty of memory, a handy thing known as "disk-cache" takes effect, which in effect, keeps files used in memory, so file IO becomes mere memcpy.
On the contrary, in real stress tests on any of the code I have used, the biggest slowdowns have been in the database!, primarily the nice slow CONNECT string, query parse time, extra php<->mysql interactions.  You're not really looking at gaining anything. Filesystem lookup is close to database index lookup, and you don't have any unknowns other than "you need to stream it from a disk", no table locking stuff to worry about!
You should probably try something like a caching library, X-Cache comes highly recommended, thats more  likely to give you visible performance gains.


Question:
The MS source server technology uses an initialization file named srcsrv.ini. One of the values identifies the source server location(s), e.g.,

MYSERVER=\\machine\foobar

The docs leave much unanswered about this value. To start with, I haven't been able to find the significance of the value name, i.e., what's on the left side--and I don't see it used anywhere else. Hewardt & Pravat in Advanced Windows Debugging say "The left side ... represents the project name", but that doesn't seem to jibe with MS's "MYSERVER" example.

What is the significance of the left side? Where else is it used? Does the value reference a server or a project, and is there one per server, or one per project?

Answer:
For anyone looking into this in the future, I received the following information from MS:
The name on the left side is the logical name of a version
  control server. The name is also used in the source-indexed symbol files
  (pdb). For example, a symbol file may contain this string value:
MYSERVER=mymachine1.sys-mygroup.corp.microsoft.com:2003
and the source files are referenced like this in pdb:
*MYSERVER*/base/myfolder/mycode.c
When SrcSrv starts, it looks at Srcsrv.ini for values; these values override the information contained in the .pdb file:
"MYSERVER=mymachine.sys-mygroup.corp.microsoft.com:1666" overrides
"MYSERVER=mymachine1.sys-mygroup.corp.microsoft.com:2003"
This enables users to configure a debugger to use an alternative source control server at debug time. The info is documented at
http://msdn.microsoft.com/en-us/library/ms680641.aspx
.
So, it is a logical name for a source server, and its value can be changed at debug time to reference a different server than the one originally used when the PDBs were created.


Question:
I would like such empty span tags (filled with &nbsp; and space) to be removed:

<span> &nbsp; &nbsp; &nbsp; </span>

I've tried with this regex, but it needs adjusting:

(<span>(&nbsp;|\s)*</span>)

preg_replace('#<span>(&nbsp;|\s)*</span>#si','<\\1>',$encoded);

Answer:
.
```
```
qr{<span[^>]*(/>|>\s*?</span>)}
```
```
Should get the gist of them. ( Including XML style-self closing tags ie:  )
But you
really
shouldn't use regex for HTML processing.
Answer only relevant to the context of the question that was visible before the formatting errors were corrected


Question:
Just that... I get a string which contains a path to a file plus some arguments. How can I recognize the path? I thought about the index of the '.' in the file... but I don't like it.

What about using regular expressions? Can anyone point me in the right direction?

Regards

Edit: Theses are valid entries...

somefile.msi /a

C:\MyFolder\SomeFile.exe -i -d

I don't care much about the arguments cause once I have the path I'll assume the rest are arguments

Answer:
Well, before you tackle finding the path in the string, you need to outline a set of rules for what a path in this context
This is, for the operating system, a valid filename: a
Since no directory information is specified, the
current directory
will be used. The file has no extension.
But is still a filename.
Is this a
path
in your context? Or do you mean something that has directory information as well?
Examples of what you need to handle would be useful.


Question:
I have seen the ASP.NET community buzzing about MVC. I know the basics of its origin, and that there are many sites (unless I am mistaken, stack overflow itself) based on ASP.NET MVC.

From everything I have heard and read about MVC it seems to be the future of ASP.NET development. But since I don't usually dabble in .NET web development I am left wondering the following: when is it appropriate to use MVC and when is it not, and why? Examples of great (and terrible) use of MVC would be fascinating.

Though I realize there are other implementations of MVC view other languages like RoR I am more interested on its impact for .NET programmers.

If this has already been gone over, my apologies!

Answer:
Here are my 2 cents about MVC for web applications.  For the sort of GUI apps for which MVC was originally intended, "listener" code was required, so that the UI could be updated when events altered the model data.
In MVC for the web this is unnecessary, you get your listener for free: the web server, and the HTTP request IS the event.  So really MVC for the web should be even simpler.  Indeed, it could be boiled down to the Mediator pattern, where the Controller mediates between the model and the view.
There are two things that there is a lot of confusion about.  Regardless of conventional "wisdom":
Frameworks != MVC
Database Data != "Model"
"Full stack" web development frameworks typically add lots of features, and may or may not be MVC-oriented at their core.  One of the features many frameworks add is database access or object relational mapping functionality, and because frameworks and MVC get confused, subsequently database data and the model facet of MVC also get confused.  The model can generally be viewed as the underlying data for the application, but it does NOT have to come from a database.  A good example might be a wiki, where the underlying model/data consists of file revision data, for instance, from RCS.
Hope this helps and I'm sure others will have plenty to add.


Question: How can I draw a concave corner rectangle in WPF?

Answer:
```
```
do you mean a rectangle with concave corners?, ie:
     ____________________
    |                    |
  __|                    |__
 |                          |
 |                          |
 |                          |
 |__                      __|
    |                    |
    |____________________|
```
```
Given a rectangle of dimension
```
w x h
```
with corner radius
```
r
```
There are 4 corners:
```
```
A :  0,0
B :  w,0
C :  w,h
D :  0,h
```
```
There is an implicit minimum size of
```
```
w = 2r
h = 2r
```
```
There are 4 Circle Centers,
```
A,B,C,D
```
And there's thus a grid of edge points:
```
```
(0,0)--(0+r,0)---(w-r,0)---(w,0)
|                              |
(0,0+r)                  (w,0+r)
|                              |
|                              |
(0,h-r)                  (w,h-r)
|                              |
(0,h)--(0+r,h)---(w-r,h)---(w,h)
```
```
Then its merely a case of computing the arc from one point to another.


Question: As the question says, how do I set the value of a DropDownList control using jQuery?

Answer:
```
```
$("#mydropdownlist").val("thevalue");
```
```
just make sure the value in the options tags matches the value in the val method.


Question:
I have a page that spits out db data in long horizontal tables.

I need to print it nicely so it does not cut off. Any tips ?

Answer:
If it doesn't fit on the paper in a readable font, it just doesn't.. In my opinion, huge horizontal tables (be it a HTML table or an Excel sheet with many columns) don't lend well to printing. For that matter, they don't lend well to viewing on a screen either. Remember vertical scrolling is much easier for your users than horizontal scrolling - all thanks to that little wheel on your mouse.
Worst case, you might need to write a seperate print version which uses a vertical layout.


Question:
Using only MySQL, I'm seeing if it's possible run an insert statement ONLY if the table is new. I successfully created a user variable to see if the table exists. The problem is that you can't use "WHERE" along with an insert statement. Any ideas on how to get this working?

// See if the "country" table exists -- saving the result to a variable
SELECT
    @table_exists := COUNT(*)
FROM
    information_schema.TABLES
WHERE
    TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'country';

// Create the table if it doesn't exist
CREATE TABLE IF NOT EXISTS country (
    id INT unsigned auto_increment primary key,
    name VARCHAR(64)
);

// Insert data into the table if @table_exists > 0
INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands') WHERE 0 < @table_exists;

Answer:
```
```
IF @TableExists > 0 THEN
   BEGIN
       INSERT INTO country (name) VALUES ('Afghanistan'),('Aland Islands');
   END
```
```


Question:
Unlike C++, in C# you can't overload the assignment operator.

I'm doing a custom Number class for arithmetic operations with very large numbers and I want it to have the look-and-feel of the built-in numerical types like int, decimal, etc. I've overloaded the arithmetic operators, but the assignment remains...

Here's an example:

Number a = new Number(55);
Number b = a; //I want to copy the value, not the reference

Is there a workaround for that issue?

Answer:
You won't be able to work around it having the C++ look, since a = b; has other semantics in C++ than in C#. In C#, a = b; makes a point to the same object like b. In C++, a = b changes the content of a. Both has their ups and downs. It's like you do
```
```
MyType * a = new MyType();
MyType * b = new MyType();
a = b; /* only exchange pointers. will not change any content */
```
```
In C++ (it will lose the reference to the first object, and create a memory leak. But let's ignore that here). You cannot overload the assign operator in C++ for that either.
The workaround is easy:
```
```
MyType a = new MyType();
MyType b = new MyType();

// instead of a = b
a.Assign(b);
```
```
Disclaimer
: I'm not a C# developer
You could create a write-only-property like this. then do a.Self = b; above.
```
```
public MyType Self {
    set {
        /* copy content of value to this */
        this.Assign(value);
    }
}
```
```
Now, this is
not
good. Since it violates the principle-of-least-surprise (POLS). One wouldn't expect a to change if one does a.Self = b;


Question: Except perhaps at bigger (or better) shops, the development UI is done by the developers.  In your experience, how much has this impacted the final product, and how much time should we spend getting the development UI right?

Answer:
The interface you're building and showing to your customers is basically all they will ever see. You can sit down with them and talk for hours about what the product is supposed to do, but the number one best method to have the users spot problems or missing functionality, is to show them the interface as it will look like in the final product. You can do this with a prototype or the actual interface as it is being built.
So I would say the interface should look pretty much like what you will be delivering at the end during development. This will guarantee that you get the right feedback, and that the user knows what he is getting. Of course, you can build an interface which doesn't exactly have the style of the final product (colors, window styles, fonts, etc...), but the functionality of the product you're building should be clear as early on as possible.


Question:
In my master pages I have <form ... action="" ...>, in pre SP1, if I viewed the source the action attribute would be an empty string.  In SP1 the action attribute is overridden "MyPage.aspx?MyParams", unfortunately, this causes my postbacks to fail as I have additional pathinfo in the URL (ie. MyPage.aspx\CustomerData?MyParams). I have checked the action attribute in the OnLoad event and it is still blank at this time, so somewhere SP1 is overriding this :(.

Sorry, I just realized that part of my post was missing since I did not use the markdown correctly.

Answer:
Maybe you can find the solution here in
this ASP.NET Forum post
(Known Issues / Breaking Changes for ASP.NET in .NET 3.5 Service Pack 1).
Issue
The HtmlForm action attribute is now honored when defined in declarative markup.
Reason
3.5 SP1 added a settable Action property to the HtmlForm type.  This new feature makes it much easier for developers to explicitly set the form’s action attribute for scenarios where a developer wants to use a different Url than the normal postback-generated Url.  However this change also means that if the action attribute has been set in an .aspx page’s declarative markup, ASP.NET will use the setting from the markup when rendering a
```
<form />
```
element.
Workaround
Previous versions of ASP.NET always ignored the action attribute if it was present in the declarative markup for a
```
<form />
```
element.  Developers should remove the action attribute from their declarative markup to return to the original behavior where ASP.NET renders the postback Url.
Example
Before (the action attribute was ignored by ASP.NET as dead code):
```
```
<form name="form1" method="post" runat="server" action="test.aspx"></form>
```
```
3.5 SP1 (remove the action attribute to have ASP.NET render the postback Url):
```
```
<form name="form1" method="post" runat="server"></form>
```
```


Question:
I am trying to animate an object, let's say its a car. I want it go from point

x1,y1,z1

to point x2,y2,z2 . It moves to those points, but it appears to be drifting rather than pointing in the direction of motion. So my question is: how can I solve this issue in my updateframe() event? Could you point me in the direction of some good resources?

Thanks.

Answer:
You need to work out the initial orientation of the car, and the final orientation of the car at its destination, then interpolate between them to determine the orientation in between for the current timestep.
This
article describes the mathematics behind doing the interpolation, as well as some other things to do with rotating objects that may be of use to you. gamasutra.com in general is an excellent resource for this sort of thing.


Question:
When I create a graph after using range.copy and range.paste it leaves the paste range selected, and then when I create a graph a few lines later, it uses the selection as the first series in the plot.  I can delete the series, but is there a more elegant way to do this?  I tried

Set selection = nothing

but it won't let me set selection.  I also tried selection.clear, but that just cleared the last cells that were selected, and still added an extra series to the plot.

Answer:
I do not think that this can be done. Here is some code copied with no modifications from Chip Pearson's site:
http://www.cpearson.com/excel/UnSelect.aspx
.
UnSelectActiveCell
This procedure will remove the Active Cell from the Selection.
```
```
Sub UnSelectActiveCell()
    Dim R As Range
    Dim RR As Range
    For Each R In Selection.Cells
        If StrComp(R.Address, ActiveCell.Address, vbBinaryCompare) <> 0 Then
            If RR Is Nothing Then
                Set RR = R
            Else
                Set RR = Application.Union(RR, R)
            End If
        End If
    Next R
    If Not RR Is Nothing Then
        RR.Select
    End If
End Sub
```
```
UnSelectCurrentArea
This procedure will remove the Area containing the Active Cell from the Selection.
```
```
Sub UnSelectCurrentArea()
    Dim Area As Range
    Dim RR As Range

    For Each Area In Selection.Areas
        If Application.Intersect(Area, ActiveCell) Is Nothing Then
            If RR Is Nothing Then
                Set RR = Area
            Else
                Set RR = Application.Union(RR, Area)
            End If
        End If
    Next Area
    If Not RR Is Nothing Then
        RR.Select
    End If
End Sub
```
```


Question: I can get simple examples to work fine as long as there's no master page involved. All I want to do is click a button and have it say "hello world" with the javascript in a .js file, using a master page. Any help very much appreciated :)

Answer:
Just move the
```
<script type="text/javascript" src="jquery.js" />
```
tag into the head tag in the master page. Then you can use jquery in all content pages.
There is no magic about using master pages with jQuery.


Question: I have a few ASP.Net database front-end websites where MS Access is the back-end.  I am trying to use ASP.Net dynamic data website.  Should I change this database to SQL Server Express or something else to make it easier or should this work from with MS Access.

Answer:
Pick SQL Express for these reasons:
Scaling
: MS Access will never scale.  Once you get over about 10 concurrent connections you will start to see trouble.  SQL Express will scale.  You can always move SQL Express up to a full-blow SQL Server installation.  While this is somewhat true of Access, some of your SQL statements and data types may not transfer cleanly.
Security
: SQL Server has a much better security model than Access.  You can lock down the schema in your db per user.  You can also better administrate user access (think dev user vs test user vs production user).
Performance
: This is similar to scaling.  If you see a traffic spike to your web site, Access may not handle it while SQL Server Express probably will.
Tools
: Tools and libraries like LINQ are always going to be targeted at SQL Server.  You will get better support and better documentation using them this way.


Question:
I have a Java SOAP data service which sits on top of a Sybase database which, for reasons out of my control, has unreliable performance. The database is part of a vendor package which has been modified by an internal team and most of the issues are caused by slow response times at certain times of the day.

The SOAP service provides data to a calculation grid and when I request data, I need the response time to be both fast and consistent.  The service provides basic CRUD functionality, but the ratio of reads to writes is approximately 100:1.

What is the best strategy to isolate myself from the database's unreliable performance and ensure that the SOAP service is fast and reliable?

Answer:
I have seen this issue a few times, normally with a vendor database.
If this is on Windows, you could create a Windows service as an intermediary between the SOAP service and the database. Then put a message queue (either MSMQ or a JMS implementation such as MQ Series) between the SOAP service and Windows service for asynchronous communications. In this way the database performance issues will no longer affect the SOAP service. This solution does, however, come at the cost of increased complexity.
Note that a .NET web service can be called by, and respond asynchronously to, its clients. I'm not sure if that's possible with a Java SOAP service.
If this is on some flavour of Unix, I assume it has similar functionality to a Windows service - maybe a daemon.


Question:
I am trying to insert a new row into my table which holds the same data as the one I am trying to select from the same table but with a different user_id and without a fixed value for auto_id since that is an auto_increment field, and setting ti to NOW(). Below is my mockup query where '1' is the new user_id. I have been trying many variations but am still stuck, anyone who can help me with turning this into a working query.

INSERT INTO `lins` ( `user_id` , `ad` , `ke` , `se` , `la` , `ra` , `ty` , `en` , `si` , `mo` , `ti` , `de` , `re` , `ti` ) (

SELECT '1', `ad` , `ke` , `se` , `la` , `ra` , `ty` , `en` , `si` , `mo` , `ti` , `de` , `re` , NOW( )
FROM `lins`
WHERE autoid = '4'
AND user_id = '2'
)

Thank you for taking the time to help me out!

Answer:
I think you need to explicitly match the line terminators, as well as handle spaces better as others have suggested.  Assuming the user can choose between \r and \n, try
```
```
@"(?<select>\Aselect .+)[\n\r]" +
@"(?<from>\s*from .+)[\n\r]" +
@"(?<where>\s*where .+)[\n\r]" +
@"(?<groupBy>\s*group by .+)[\n\r]" +
@"(?<having>\s*having .+)[\n\r]"
```
```
As long as you are using regular expressions, you probably want to do a bit better:
```
```
@"\Aselect (?<select>.+)[\n\r]" +
@"\s*from (?<from>.+)[\n\r]" +
@"\s*where (?<where>.+)[\n\r]" +
@"\s*group by (?<groupBy>.+)[\n\r]" +
@"\s*having (?<having>.+)[\n\r]"
```
```
My biggest problem with regular expressions for this sort of use is that the only error message you can give is that things failed.  You can't give the user any further information about what they did wrong.


Question: What type of client is likely to support XP (Extreme Programming) practices?

Answer:
If your team achieves great results with a proven track-record, then companies desiring a successful result.  If the converse is true, only companies who are wandering blindly will be interested.
There is the
odd
case where the client will want a certain practices followed. Like a experienced dev manager outsourcing a project to an external firm, or potentially a client who has heard that XP is good in passing but has no real knowledge or experience with it. In the former the experienced consumer will know what he wants and if you do not provide those services they will go elsewhere.  If you try to fake it, they will know and be most displeased.  The later, it doesn't matter so much as long as they get good results and think it was their own wisdom that brought them forth from the ground.
Either way, it is results that matter.
Now begins my diatribe which so far has inspired much ire:
Would you jeopardize your good practices just to suit a client? If you are staunchly in favour of XP, sell it! If they want you to use a methodology that you strongly disagree with. Tell them that. If you can't come to a consensus, there should be no deal.
Do I tell a baker what grain to use? How hot to have the ovens? Hell no.  If I say I want poppy seeds on the buns I don't care how they are put there so long as they are there. Dp I select a baker based on his methods, or on how damn tasty the bread is? Letting a non programmer tell you how to do your craft is just plain bad.
If you are trying to extol the virtues of XP then be upfront, pitch the cost-benefits and ROI.  Show them why it is better for them in terms of developer efficiency and defect reduction.  If you are working for non-programmers, you are the expert, take the reigns and give advice.
If your team excels at XP and has great results you will have no problem selling any potential client on your practices.  Results matter to clients; if you can prove that you consistently produce high quality products within consistent timelines you should have no problem selling your methodology. (with some exceptions that absolutely require waterfall).


Question:
Based on their work, how do you distinguish a great SQL developer?

Examples might include:

Seldom uses CURSORs, and tries to refactor them away.

Seldom uses temporary tables, and tries to refactor them away.

Handles NULL values in OUTER JOINs with confidence.

Avoids SQL extensions that are not widely implemented.
Knows how to indent with elegance.

Answer:
I don't think that cursors, temporary tables or other SQL practices are inherently bad or that their usage is a clear sign of how good a database programmer is.
I think there is the right tool for every type of problem. Sure, if you only have a hammer, everything looks like a nail. I think a great SQL programmer or database developer is a person who knows which tool is the right one in a specific situation. IMHO you can't generalize excluding specific patterns.
But a rule of thumb may be: a great database developer will find a more
short and elegant solution
for complex situations than the average programmer.


Question: Does anyone know because all the places I've tried seem to timeout!

Answer:
You can download JSTL 1.1
here
and JSTL 1.2
here
.
See also:
JSTL wiki page


Question:
which one of the two is more spread? I want to read out the version number from http://freshmeat.net/projects-xml/mysql/mysql.xml?branch_id=46519 but I want to use the one which more people have.

If you know another way to get the latest stable version number from mysql please tell me ;)

Answer:
For this kind of task, reading the document into a
```
DomDocument
```
and using
```
DomXPath
```
is probably more suitable.
To answer your question, both libraries (as well as
```
DomDocument
```
+
```
DomXPath
```
) are standard outfit with PHP5, so they would be equally fine choices.


Question: Well, what is one?

Answer:
It's a
Universally Unique Identifier


Question:
I need to allow the vertical scrollbar in a multiselect listbox (VB6) however, when the control is disabled, I can't scroll.

I would think there is an API to allow this, but my favorite VB6 site (MVPS VB.NET) does not have a way.

I toyed with pretending it was disabled, and ignore the clicks... but to do that with VB6 code is really ugly... so if this is a solution, I need an API to ignore the clicks.

Thanks for your help.

Answer:
Rather than looking for the API to ignore clicks, can't you just ignore the events? (i.e. just don't do when the user clicks/selects something).
And, I think there is a
```
SelectionMode
```
property to disable multiselect and make it single select.
If you don't want the user to be able to select anything at all, you can try hooking into the
```
SelectionIndexChanged
```
event and set the
```
SelectionIndex
```
to -1.
My VB6 is a bit rustly, so sorry if the event/property name don't match exactly.


Question:
can you set SO_RCVTIMEO and SO_SNDTIMEO socket options in boost asio?

If so how?

Note I know you can use timers instead, but I'd like to know about these socket options in particular.

Answer:
It doesn't appear to be built into Boost.Asio (as of current Boost SVN), but, if you're willing to write your own classes to simulate the
```
boost::asio::detail::socket_option
```
ones, you can always follow the examples in
```
boost/asio/socket_base.hpp
```
and do the following:
```
```
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_SNDTIMEO>
    send_timeout;
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_RCVTIMEO>
    receive_timeout;
```
```
(Obviously, I'm not suggesting you inject the
```
timeval
```
class into the
```
boost::asio::detail::socket_option
```
namespace, but I can't think of a good one to use at the moment. :-P)
Edit: My sample implementation of
```
socket_option::timeval
```
, based on
```
socket_option::integer
```
:
```
```
// Helper template for implementing timeval options.
template <int Level, int Name>
class timeval
{
public:
  // Default constructor.
  timeval()
    : value_(zero_timeval())
  {
  }

  // Construct with a specific option value.
  explicit timeval(::timeval v)
    : value_(v)
  {
  }

  // Set the value of the timeval option.
  timeval& operator=(::timeval v)
  {
    value_ = v;
    return *this;
  }

  // Get the current value of the timeval option.
  ::timeval value() const
  {
    return value_;
  }

  // Get the level of the socket option.
  template <typename Protocol>
  int level(const Protocol&) const
  {
    return Level;
  }

  // Get the name of the socket option.
  template <typename Protocol>
  int name(const Protocol&) const
  {
    return Name;
  }

  // Get the address of the timeval data.
  template <typename Protocol>
  ::timeval* data(const Protocol&)
  {
    return &value_;
  }

  // Get the address of the timeval data.
  template <typename Protocol>
  const ::timeval* data(const Protocol&) const
  {
    return &value_;
  }

  // Get the size of the timeval data.
  template <typename Protocol>
  std::size_t size(const Protocol&) const
  {
    return sizeof(value_);
  }

  // Set the size of the timeval data.
  template <typename Protocol>
  void resize(const Protocol&, std::size_t s)
  {
    if (s != sizeof(value_))
      throw std::length_error("timeval socket option resize");
  }

private:
  static ::timeval zero_timeval()
  {
    ::timeval result = {};
    return result;
  }

  ::timeval value_;
};
```
```


Question: Do I need a UUID to program for the iPhone? I was told I need this, how can I get a UUID

Answer:
It doesn't appear to be built into Boost.Asio (as of current Boost SVN), but, if you're willing to write your own classes to simulate the
```
boost::asio::detail::socket_option
```
ones, you can always follow the examples in
```
boost/asio/socket_base.hpp
```
and do the following:
```
```
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_SNDTIMEO>
    send_timeout;
typedef boost::asio::detail::socket_option::timeval<SOL_SOCKET, SO_RCVTIMEO>
    receive_timeout;
```
```
(Obviously, I'm not suggesting you inject the
```
timeval
```
class into the
```
boost::asio::detail::socket_option
```
namespace, but I can't think of a good one to use at the moment. :-P)
Edit: My sample implementation of
```
socket_option::timeval
```
, based on
```
socket_option::integer
```
:
```
```
// Helper template for implementing timeval options.
template <int Level, int Name>
class timeval
{
public:
  // Default constructor.
  timeval()
    : value_(zero_timeval())
  {
  }

  // Construct with a specific option value.
  explicit timeval(::timeval v)
    : value_(v)
  {
  }

  // Set the value of the timeval option.
  timeval& operator=(::timeval v)
  {
    value_ = v;
    return *this;
  }

  // Get the current value of the timeval option.
  ::timeval value() const
  {
    return value_;
  }

  // Get the level of the socket option.
  template <typename Protocol>
  int level(const Protocol&) const
  {
    return Level;
  }

  // Get the name of the socket option.
  template <typename Protocol>
  int name(const Protocol&) const
  {
    return Name;
  }

  // Get the address of the timeval data.
  template <typename Protocol>
  ::timeval* data(const Protocol&)
  {
    return &value_;
  }

  // Get the address of the timeval data.
  template <typename Protocol>
  const ::timeval* data(const Protocol&) const
  {
    return &value_;
  }

  // Get the size of the timeval data.
  template <typename Protocol>
  std::size_t size(const Protocol&) const
  {
    return sizeof(value_);
  }

  // Set the size of the timeval data.
  template <typename Protocol>
  void resize(const Protocol&, std::size_t s)
  {
    if (s != sizeof(value_))
      throw std::length_error("timeval socket option resize");
  }

private:
  static ::timeval zero_timeval()
  {
    ::timeval result = {};
    return result;
  }

  ::timeval value_;
};
```
```


Question:
I need an algorithm to determine if a sentence, paragraph or article is negative or positive in tone... or better yet, how negative or positive.

For instance:

Jason is the worst SO user I have ever witnessed (-10)

Jason is an SO user (0)

Jason is the best SO user I have ever seen (+10)

Jason is the best at sucking with SO (-10)

While, okay at SO, Jason is the worst at doing bad (+10)

Not easy, huh? :)

I don't expect somebody to explain this algorithm to me, but I assume there is already much work on something like this in academia somewhere. If you can point me to some articles or research, I would love it.

Thanks.

Answer:
This falls under the umbrella of
Natural Language Processing
, and so reading about that is probably a good place to start.
If you don't want to get in to a very complicated problem, you can just create lists of "positive" and "negative" words (and weight them if you want) and do word counts on sections of text.  Obviously this isn't a "smart" solution, but it gets you some information with very little work, where doing serious NLP would be very time consuming.
One of your examples would potentially be marked positive when it was in fact negative using this approach ("Jason is the best at sucking with SO") unless you happen to weight "sucking" more than "best"....  But also this is a small text sample, if you're looking at paragraphs or more of text, then weighting becomes more reliable unless you have someone purposefully trying to fool your algorithm.


Question:
Many products/services we are interact with (including our own) uses XML-over-HTTP or derivatives (like OMA IMPS IM/presence protocol).

I am looking for some tool that will "listen" to a traffic and produce client/server stubs for simulation/testing.

Thanks.

Answer:
That sounds like a good idea for a project.
This is not a solution, but your first step should be to at least support know webservice descriptors.
To do that should sniff the traffic using wireshark or something similar and see the URL's that are being accessed.  If you are lucky these services would be webservices with a retrievable descriptor or schema for the interface.  Check for .xsd, .wsdl, .asmx
Here are some examples:
http://www.webservicex.net/CurrencyConvertor.asmx
http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl
http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd
There are Microsoft tools available that come packaged with the SDL that can provide stubs for these.
I don't know of any drop in solution for you but my approach to solving this problem would be:
- use wireshark to record http conversations for specific webservices.
- parse (or look at) these files to extract the URLs that are invoked and track the message passing + xml documents.
- Create stubs based on what appear to be the parameters.
- Start by creating some simple pattern matchers and transforms (xml + xsl can = code or some page for debug).
You may also need to consider
- communication may not be 2 way xml- it could be HTTP posts with query string one way and xml responses back.
- The XML documents may not be properly formatted XML- test parse each message before trying to generate anything.


Question: Is there any persistence solution for Common Lisp, such as Elephant, that allows function persistence? Currently my app stores an identifier on the db and later searches in a function table which it is, but this method does not allow dynamically created functions to be stored.

Answer:
Functions are opaque objects, so you won't have much luck storing them in files or something like that.  You can, however, store lists and
compile
them upon retrieval from the database.
This won't help you store closures, of course.  That would entail storing the lexical environment along with the code, neither of which you have (portable) access to.  Code that you compile from stored lists will have to rely entirely on global data or data stored in the database.
By the way, note that you can
funcall
symbols, so you don't need a function table for global functions.


Question:
I think I'm pretty good at using semantic markup on my pages but I still have a handful of classes like this:

/**** Aligns ****/
.right_align  { text-align: right; }
.left_align   { text-align: left; }
.center_align { text-align: center; }

Which, technically, is a no-no. But when you just want to position some text in a table, how crazy am I supposed to get with the semantic markup?

Answer:
Semantic markup is an admirable goal, but in the real world, you sometimes have to make compromises. In some cases, the only sensible way to do something is to break semantics and just throw in a
```
right_align
```
.
Edit: People seem to be misunderstanding my point in this. You should use semantic markup where possible. However, there are cases where it really is just a stylistic choice and there is nothing inherent to the data that you can use to describe or classify it. This is most typically true with large sections of tabular data, especially if it is dynamically generated.
I've had cases where clients want to be able to dynamically control what columns appear in data grid. There's no way to know ahead of time what type of data they're going to choose to show. If they want a way to center or right align a dynamically generated column, it's better to have center and right align classes available for them to use than to have them sticking
```
style
```
attributes everywhere.


Question: I am trying to run a java based tool using a command line syntax as the following: java -cp archive.jar archiveFolder.theMainClassName.Although the class I am searching for, a main class, "theMainClassName" is in the archive.jar and in the archiveFolder given at input, I keep getting the error that my class is not seen. Does anybody have any ideas concerning this problem? Thank you in advance

Answer:
Perhaps with
```
java -jar archive.jar
```
?
Of course, it supposes the manifest points to the right class...
You should give the exact message you got, it might shed more light.
EDIT:  See
Working with Manifest Files: The Basics
for information on setting the application entry point (Main class) in your jar manifest file.


Question:
Let's say I have a line of text like this

Small   0.0..20.0   0.00    1.49    25.71   41.05   12.31   0.00    80.56

I want to capture the last six numbers and ignore the Small and the first two groups of numbers.

For this exercise, let's ignore the fact that it might be easier to just do some sort of string-split instead of a regular expression.

I have this regex that works but is kind of horrible looking

^(Small).*?[0-9.]+.*?[0-9.]+.*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+).*?([0-9.]+)

Is there some way to compact that?

For example, is it possible to combine the check for the last 6 numbers into a single statement that still stores the results as 6 separate group matches?

Answer:
If you want to keep each match in a separate backreference, you have no choice but to "spell it out" - if you use repetition, you can either catch all six groups "as one" or only the last one, depending on where you put the capturing parentheses. So no, it's not possible to compact the regex and still keep all six individual matches.
A somewhat more efficient (though not beautiful) regex would be:
```
```
^Small\s+[0-9.]+\s+[0-9.]+\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)\s+([0-9.]+)
```
```
since it matches the spaces explicitly. Your regex will result in a lot of backtracking. My regex matches in 28 steps, yours in 106.
Just as an aside: In Python, you could simply do a
```
```
>>> pieces = "Small   0.0..20.0   0.00    1.49    25.71   41.05   12.31   0.00    80.56".split()[-6:]
>>> print pieces
['1.49', '25.71', '41.05', '12.31', '0.00', '80.56']
```
```


Question:
I'm relatively new to .NET programming (and OOP in general) and I want to make sure I'm not developing bad beginner habits when designing my applications.

If you were hiring a new .NET developer and had to get him up to speed relatively quickly, but also wanted to make sure he adopts best practices (e.g., single responsibility principle, unit testing, separation of concerns), what would be your recommended learning path?

I've been listening to the Polymorphic Podcast lately and, while listening to discussion of best practices is helpful, I'm finding a lack of screencasts and code examples aimed at providing an introduction to these best practices.

Answer:
If, as in your hypothetical example, I was hiring a new .NET developer and wanted to make sure they adopted best practices, I would start by making them look through my current code base.
Then I would recommend they read the following:
The Pragmatic Programmer
Code Complete
Head First Design Patterns
Refactoring
Test-Driven Development by Example
That should give anyone a pretty solid foundation in best OOP practices.


Question:
I'm attempting to create a Wizard type control in VB6 and have run into a stumbling block.

I'd like to allow users of the control to be able to add and manage CWizardPage(s) to the design time control using a property page.

The first approach I used was to add the Wizard pages to the OCX directly using a Collection, however I ran into two problems in that the Collection class is not persistable (and I couldn't find an easy way to make it so) and that VB6 seems very limited in it's ability to instantiate controls at run time - so it would seem to be a struggle to actually re-instantiate them.

My next thought was to just allow the users to draw the wizard pages at design time. This sort of works, however it's far too easy to draw one of the wizard pages inside another wizard page instead of inside the CWizardContainer.

So can anyone please tell me how to add controls to a form at design time without using drag 'n' drop?

Answer:
You can dynamically add controls to a form or other container (such as a UserControl) using the
```
Add
```
method of the container's
```
Controls
```
collection. For example, to add a TextBox named
```
myTextBox
```
to a form called frmMyForm, you could do this:
```
frmMyForm.Controls.Add "VB.TextBox", "myTextBox"
```
Here is a snippet from the VB6 help file:
Add Method (Controls Collection)
Adds a control to the
Controls
collection and returns a reference to
  the control.
Syntax
object
.
Add
(***ProgID, name, container*
)**
The
Add
method syntax has these parts:
object
(Required)
An object expression that evaluates to
  an object in the
Applies To
list.
ProgID
(Required)
A string that
  identifies the control. The ProgID of
  most controls can be determined by
  viewing the Object Browser. The ProgID
  is composed of the Library and Class
  of the control. For example, the
  CommandButton control's ProgID is
  VB.CommandButton. In cases where the
  ProgID differs from that shown in the
  Object Browser, Visual Basic displays
  an error message that contains the
  correct ProgId.
name
(Required)
A string that identifies the member of
  the collection.
container
(Optional)
An object reference that specifies a
  container of the control. If not
  specified or NULL, defaults to the
  container to which the Controls
  collection belongs. You can put a
  control in any existing container
  control (such as the Frame control) by
  specifying this argument. A user
  control or an ActiveX document can
  also be a container.


Question: Suppose I have an interval (a,b), and a number of subintervals {(ai,bi)}i whose union is all of (a,b).  Is there an efficient way to choose a minimal-cardinality subset of these subintervals which still covers (a,b)?

Answer:
Sounds like dynamic programming.
Here's an illustration of the algorithm (assume intervals are in a list sorted by ending time):
```
```
//works backwards from the end
int minCard(int current, int must_end_after)
{
    if (current < 0)
        if (must_end_after == 0)
            return 0; //no more intervals needed
        else
            return infinity; //doesn't cover (a,b)

    if (intervals[current].end < must_end_after)
        return infinity; //doesn't cover (a,b)

    return min( 1 + minCard(current - 1, intervals[current].start),
                    minCard(current - 1, must_end_after) );
    //include current interval or not?
}
```
```
But it should also involve caching (memoisation).


Question: I need to build full-text search functionality into our knowledge base system using C#. How do I start?

Answer:
For example from Lucene:
http://lucene.apache.org/java/docs/
C# port is here
http://incubator.apache.org/lucene.net/
You should also read something about the the information retrieval, and you can start with this one :
http://www.amazon.com/Modern-Information-Retrieval-Ricardo-Baeza-Yates/dp/020139829X


Question:
I have a custom WinForms control (inherits from control, i.e. without user interface jsut as Timer) to which I want to add a custom command add design time.

This could be similar to the "right click and choose 'Edit Items...'" of a menu.

Is this posisble? How?

Also, could you recommend some general reading (online) about improving the design time experience of custom controls?

Answer:
First here is a link to the relevant MSDN doco on the subject
http://msdn.microsoft.com/en-us/library/ms171567(VS.80).aspx
and more specifically
http://msdn.microsoft.com/en-us/library/system.componentmodel.design.menucommand(VS.80).aspx
As for a book that covers this,
Chris Sells Winforms book
is probably the best, however to be honest, I don't think that any of the books out there (on-line or otherwise) cover design time features in the sort of depth that I personally would like.