q:
There are a whole raft of questions regarding payment processors for web applications but I haven't seen one yet for desktop applications. What are your experiences?

Perhaps to put this into a little context, the requirements:

Should be customisable

Should be available in Australia at least, if not world wide (less critical).

No storage of credit card details

Recurrent micro payments of varying amounts each time

1-click payment. It's ok for the user to be registered with the payment processor provider.

[A]
Times may be a changing, but I don't think that you can get all of the above.
I do have some experience a couple years back with credit cards in North America.  At the time the company I worked for needed recurring billing for a different amount each month (much like your requirement). At the time, none of the providers I looked into allowed for recurring payments where the amount varied. This may have changed, but I do not know of one.
I suspect your options are either to store credit cards and process your own transactions (not too hard but a path you have to walk carefully) or use recurring billing with a constant amount.


q: I am trying to create controller actions which will return either JSON or partial html depending upon a parameter. What is the best way to get the result returned to an MVC page asynchronously?

[A]
In your action method, return Json(object) to return JSON to your page.
```
```
public ActionResult SomeActionMethod() {
  return Json(new {foo="bar", baz="Blech"});
}
```
```
Then just call the action method using Ajax. You could use one of the helper methods from the ViewPage such as
```
```
<%= Ajax.ActionLink("SomeActionMethod", new AjaxOptions {OnSuccess="somemethod"}) %>
```
```
SomeMethod would be a javascript method that then evaluates the Json object returned.
If you want to return a plain string, you can just use the ContentResult:
```
```
public ActionResult SomeActionMethod() {
    return Content("hello world!");
}
```
```
ContentResult by default returns a text/plain as its contentType.
This is overloadable so you can also do:
```
```
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
```
```

s: huggingface

c: devops

d: intermediate


q:
I have this 'simplified' fortran code

real B(100, 200)
real A(100,200)

... initialize B array code.

do I = 1, 100
  do J = 1, 200
    A(J,I) = B(J,I)
  end do
end do

One of the programming gurus warned me, that fortran accesses data efficiently in column order, while c accesses data efficiently in row order.   He suggested that I take a good hard look at the code, and be prepared to switch loops around to maintain the speed of the old program.

Being the lazy programmer that I am, and recognizing the days of effort involved, and the mistakes I am likely to make, I started wondering if there might a #define technique that would let me convert this code safely, and easily.

Do you have any suggestions?

[A]
Are you sure your FORTRAN guys did things right?
The code snippet you originally posted is already accessing the arrays in row-major order (which is 'inefficient' for FORTRAN, 'efficient' for C).
As illustrated by the snippet of code and as mentioned in your question, getting this 'correct' can be error prone.  Worry about getting the FORTRAN code ported to C first without worrying about details like this.  When the port is working - then you can worry about changing column-order accesses to row-order accesses (if it even really matters after the port is working).


q: I'm a total amateur writing a small App to track to changes in folders. I imagine I'll be keeping information about the directories to watch in one datatable bound to a gridview, when the user clicks a button, the program will create FileSystemWatchers to keep an eye on the directories and they will send their event messages to another datatable bound to another gridview. Where in the wide wide world of OOP should I be declaring, initiating, and manipulating the Datatables? The main form, inside main, in a class, or should I "give up" and use Visual Studio to automagically create a DataSet and stick two tables in it?

[A]
Well horses for courses. For a little utility app you would probably be better off using the VS "Visual/RAD" style of programming. Eg drag and drop tables etc on to the form, like most of the tutorials show.
Strictly speaking, and for a larger app, a more correct way would be to make a separate assembly(.dll) that handles data access and you call the classes within that assembly from the main form. This concept goes under a number of terms, but effectively you want to separate your concerns. In other words, let the UI handle UI interactions, have a separate assembly/project/whatever that handles database interactivity, and another separate assembly/project/whatever that handles business logic etc.
That last couple of sentences can mean different things to different people, and there is no 100% correct way to do things.
Some articles that may help:
link text
link text
link text


q: I've used both and I've found MySql to have several frustrating bugs, limited support for: IDE integration, profiling, integration services, reporting, and even lack of a decent manager. Total cost of ownership of MSSQL Server is touted to be less than MySQL too (.net environment), but maintaining an open mind could someone point out any killer features of MySql?

[A]
I've used MySQL in the past and I'm using MSSQL lately but I can't remember anything that MySQL has and MSSQL can't do.
I think the most killer feature of MySQL it's the simplicity. For some projects you just don't need all the power you can have with a huge system like MSSQL. I have an UNIX heritage and find the simple configuration file like my.ini a killer feature of MySQL.
Also the security system of MySQL is much less robust but it makes the job right for most of applications. I believe MySQL it's killer itself from this point of view, and should stay that way, letting young users being introduced to RDBMS with a simple view first. If your project gets big enough that you are considering switch to a more robust system, then MSSQL can pop as a possibility.
That's what happened to me.


q:
I found this page describing the Muenchian method, but I think I'm applying it wrong.

Consider that this would return a set of ages:

/doc/class/person/descriptive[(@name='age')]/value

1..2..2..2..3..3..4..7

But I would like a nodeset only one node for each age.

1..2..3..4..7

Each of these seem to return all of the values, instead of unique values:

/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::value)]/value
/doc/class/person/descriptive[(@name='age')]/value[not(value=preceding-sibling::value)]

What am I missing?

[A]
Aren't you missing a reference to 'descriptive' right after the preceding-value? Some thing like the following:
```
```
/doc/class/person/descriptive[(@name='age')][not(value=preceding-sibling::descriptive[@name='age']/value)]/value
```
```
(Haven't tested it)


q:
I need to do some large integer math.  Are there any classes or structs out there that represent a 128-bit integer and implement all of the usual operators?

BTW, I realize that decimal can be used to represent a 96-bit int.

[A]
No, there's nothing in .NET <= 3.5. I'm hoping/expecting that
BigInteger
will make its return in .NET 4.0. (It was
cut from .NET 3.5
.)


q: I have a case where a 3rd party ad is bleeding through my modal window implementation. I'd like to up the z-index of the modal overlay as high as possible so the ad won't show on top of it. Is there a limit to z-index values? I'm sure if there is it varies by browser. Anyone know?

[A]
Not really, but you might consider the natural limitations of a system, like an int range. I'd
probably keep it under 32,767
.  I've definitely exceeded that in javascript while working on a similar problem, and didn't encounter any problems on the major browsers and platforms that I was concerned about at the time.
In the case of 3rd party ads and overlays, making sure that
wmode="transparent"
on the flash embed is a common problem along the same lines.  Also worth noting that IE has a bug with stacking z-indexes, so if you're not seeing success, make sure you're not hitting your head up against the wall with that one*.
I always like to keep to some kind of
convention
, and not use arbitrary figures.  For example, maybe everything in my
css falls between 0 and 10
.  Maybe dhtml stuff happens in the 100's place values, with a meaningful z-index for any given module.
*Sidenote:
The IE bug, to be specific, is that IE considers a new instance of document flow to be a new stacking context for z-index.  You need to make sure that your z-indexes aren't being lost in the DOM hierarchy when a child node that would normally be inheriting your z-index is being rendered it's own positioning context.


q:
Someone told me that it's faster to concatenate strings with StringBuilder. I have changed my code but I do not see any Properties or Methods to get the final build string.

How can I get the string?

[A]
Once you have completed the processing using the StringBuilder, use the ToString method to return the final result.
From MSDN:
```
```
using System;
using System.Text;

public sealed class App
{
    static void Main()
    {
        // Create a StringBuilder that expects to hold 50 characters.
        // Initialize the StringBuilder with "ABC".
        StringBuilder sb = new StringBuilder("ABC", 50);

        // Append three characters (D, E, and F) to the end of the StringBuilder.
        sb.Append(new char[] { 'D', 'E', 'F' });

        // Append a format string to the end of the StringBuilder.
        sb.AppendFormat("GHI{0}{1}", 'J', 'k');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());

        // Insert a string at the beginning of the StringBuilder.
        sb.Insert(0, "Alphabet: ");

        // Replace all lowercase k's with uppercase K's.
        sb.Replace('k', 'K');

        // Display the number of characters in the StringBuilder and its string.
        Console.WriteLine("{0} chars: {1}", sb.Length, sb.ToString());
    }
}

// This code produces the following output.
//
// 11 chars: ABCDEFGHIJk
// 21 chars: Alphabet: ABCDEFGHIJK
```
```


q:
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?

Example:

def burninate(b):
    c = []
    for i in range(3):
        c.append(b.pop())
    return c

a = range(6)
d = burninate(a)
print a, d

Output: [0, 1, 2] [5, 4, 3]

Desired output: [0, 1, 2, 3, 4, 5] [5, 4, 3]

Thanks!

[A]
You can call
```
burninate()
```
with a copy of the list like this:
```
d = burninate(a[:])
```
or,
```
d = burninate(list(a))
```
The other alternative is to make a copy of the list in your method:
```
```
def burninate(b):
    c=[]
    b=b[:]
    for i in range(3):
        c.append(b.pop())
    return c

>>> a = range(6)
>>> b = burninate(a)
>>> print a, b
>>> [0, 1, 2, 3, 4, 5] [5, 4, 3]
```
```


q: In my cross-platform architecture, I would like to act on a context menu click (right button click) during a mouse click event.  In Cocoa, can you detect that the user either Ctrl-Clicked or double-tapped on touchpad (right-click equivalent) DURING the mouseDown event?  I am aware of NSView's menuForEvent but do not wish to handle it here.

[A]
If you're using AppKit, and you want to detect a right-click in your view, you should override
```
-[NSResponder rightMouseDown:]
```
.


q:
I have a Rails app that sets a cookie and does a redirect to another server once the user is logged in. However, the cookie that the Rails app sets isn't seen by the server for some reason. I've tried setting http_only to false but I still can't even see the cookie unless the domain is the same as my Rails app. Here's the code I'm using to set the cookie:

cookies[:dev_appserver_login] =
  { :value => "#{email}:#{nick}:#{admin}:#{hsh}",
    :domain => "webserver-to-redirect-to",
    :expires => 30.days.from_now }

redirect_to session[:dest_url]

If I manually create a cookie with the Web Developer extension in Firefox it works fine, but not when Rails does it. Any ideas?

[A]
What are the redirecting and redirected-to servers? You can only set ‘domain’ to the current hostname or a parent domain, so if you're on a.example.com and you're redirecting to b.example.com, you have to set ‘domain’ to .example.com,
not
b.example.com as implied in the code snippet.
(And open domains like the .com TLD aren't themselves allowed as domain values, so if you want to pass a cookie from a.example.com to b.somewhereelse.com you will need a more complicated solution probably involving changing the code on somewhereelse.com.)


q:
I was just writing some quick code and noticed this complier error

Using the iteration variable in a lambda expression may have unexpected results.

  Instead, create a local variable within the loop and assign it the value of the iteration variable.

I know what it means and I can easily fix it, not a big deal.

But I was wondering why it is a bad idea to use a iteration variable  in a lambda?

What problems can I cause later on?

[A]
Assuming you mean C# here.
It's because of the way the compiler implements closures. Using an iteration variable
can
cause a problem with accessing a modified closure (note that I said 'can' not 'will' cause a problem because sometimes it doesn't happen depending on what else is in the method, and sometimes you actually want to access the modified closure).
More info:
http://blogs.msdn.com/abhinaba/archive/2005/10/18/482180.aspx
Even more info:
http://blogs.msdn.com/oldnewthing/archive/2006/08/02/686456.aspx
http://blogs.msdn.com/oldnewthing/archive/2006/08/03/687529.aspx
http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx


q: How do I determine the dependencies of a .NET application? Does Dependency Walker work with managed apps? I've downloaded the latest and tried profiling the app, but it just exits without much of an explanation. If it doesn't work with .NET, then is there some other tool that would help me debug a run-time DLL loading issue?

[A]
Dependency walker works on normal win32 binaries. All .NET dll's and exe's have a small stub header part which makes them look like normal binaries, but all it basically says is "load the CLR" - so that's all that dependency walker will tell you.
To see which things your .NET app actually relies on, you can use the tremendously excellent
.NET reflector
from Red Gate. (EDIT: Note that .NET Reflector is now a paid product.
ILSpy
is free and open source and very similar.)
Load your DLL into it, right click, and chose 'Analyze' - you'll then see a "Depends On" item which will show you all the other dll's (and methods inside those dll's) that it needs.
It can sometimes get trickier though, in that your app depends on X dll, and X dll is present, but for whatever reason can't be loaded or located at runtime.
To troubleshoot those kinds of issues, Microsoft have an
Assembly Binding Log Viewer
which can show you what's going on
at runtime


q:
I just finished a test as part of a job interview, and one question stumped me, even using Google for reference. I'd like to see what the StackOverflow crew can do with it:

The memset_16aligned function requires a 16-byte aligned pointer passed to it, or it will crash.

a) How would you allocate 1024 bytes of memory, and align it to a 16 byte boundary?

b) Free the memory after the memset_16aligned has executed.

{
   void *mem;
   void *ptr;

   // answer a) here

   memset_16aligned(ptr, 0, 1024);

   // answer b) here
}

[A]
Original answer
```
```
{
    void *mem = malloc(1024+16);
    void *ptr = ((char *)mem+16) & ~ 0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}
```
```
Fixed answer
```
```
{
    void *mem = malloc(1024+15);
    void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}
```
```
Explanation as requested
The first step is to allocate enough spare space, just in case.  Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space.  Somewhere in the first 16 bytes, there is a 16-byte aligned pointer.  (Note that
```
malloc()
```
is supposed to return a pointer that is sufficiently well aligned for
any
purpose.  However, the meaning of 'any' is primarily for things like basic types —
```
long
```
,
```
double
```
,
```
long double
```
,
```
long long
```
, and pointers to objects and pointers to functions.  When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)
The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it).  Then add 16 to the start pointer.  Suppose
```
malloc()
```
returned you an impossibly badly aligned pointer: 0x800001.  Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0.  0x0F has the last 4 bits set to one; therefore,
```
~0x0F
```
has all bits set to one except the last four.  Anding that with 0x800011 gives 0x800010.  You can iterate over the other offsets and see that the same arithmetic works.
The last step,
```
free()
```
, is easy: you always, and only, return to
```
free()
```
a value that one of
```
malloc()
```
,
```
calloc()
```
or
```
realloc()
```
returned to you — anything else is a disaster.  You correctly provided
```
mem
```
to hold that value — thank you.  The free releases it.
Finally, if you know about the internals of your system's
```
malloc
```
package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned).  If it was 16-byte aligned, then you'd not need to dink with the values.  However, this is dodgy and non-portable — other
```
malloc
```
packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps.  Within broad limits, this solution is portable.
Someone else mentioned
```
posix_memalign()
```
as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis.  Note that it was convenient that the alignment was a power of 2; other alignments are messier.
One more comment — this code does not check that the allocation succeeded.
Amendment
Windows Programmer
pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that.  So, an amended version of the basic code — converted into a main program, follows.  I've also taken the liberty of adding just 15 instead of 16, as has been pointed out.  I'm using
```
uintptr_t
```
since C99 has been around long enough to be accessible on most platforms.  If it wasn't for the use of
```
PRIXPTR
```
in the
```
printf()
```
statements, it would be sufficient to
```
#include <stdint.h>
```
instead of using
```
#include <inttypes.h>
```
.
[This code includes the fix pointed out by
C.R.
, which was reiterating a point first made by
Bill K
a number of years ago, which I managed to overlook until now.]
```
```
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

int main(void)
{
    void *mem = malloc(1024+15);
    void *ptr = (void *)(((uintptr_t)mem+15) & ~ (uintptr_t)0x0F);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
    return(0);
}
```
```
And here is a marginally more generalized version, which will work for sizes which are a power of 2:
```
```
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

static void test_mask(size_t align)
{
    uintptr_t mask = ~(uintptr_t)(align - 1);
    void *mem = malloc(1024+align-1);
    void *ptr = (void *)(((uintptr_t)mem+align-1) & mask);
    assert((align & (align - 1)) == 0);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

int main(void)
{
    test_mask(16);
    test_mask(32);
    test_mask(64);
    test_mask(128);
    return(0);
}
```
```
To convert
```
test_mask()
```
into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.
Problems with interviewers
Uri
commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?
My response won't fit into a 300-character comment...
It depends, I suppose.  I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes".  If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.
Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful.
Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned.  If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator.
However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction.  (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)
The world moves on
The title of the question has changed recently.  It was
Solve the memory alignment in C interview question that stumped me
.  The revised title (
How to allocate aligned memory only using the standard library?
) demands a slightly revised answer — this addendum provides it.
C11 (ISO/IEC 9899:2011) added function
```
aligned_alloc()
```
:
7.22.3.1 The
```
aligned_alloc
```
function
Synopsis
```
```
#include <stdlib.h>
void *aligned_alloc(size_t alignment, size_t size);
```
```
Description
The
```
aligned_alloc
```
function allocates space for an object whose alignment is
  specified by
```
alignment
```
, whose size is specified by
```
size
```
, and whose value is
  indeterminate. The value of
```
alignment
```
shall be a valid alignment supported by the implementation and the value of
```
size
```
shall be an integral multiple of
```
alignment
```
.
Returns
The
```
aligned_alloc
```
function returns either a null pointer or a pointer to the allocated space.
And POSIX defines
```
posix_memalign()
```
:
```
```
#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);
```
```
DESCRIPTION
The
```
posix_memalign()
```
function shall allocate
```
size
```
bytes aligned on a boundary specified by
```
alignment
```
, and shall return a pointer to the allocated memory in
```
memptr
```
. The value of
```
alignment
```
shall be a power of two multiple of
```
sizeof(void *)
```
.
Upon successful completion, the value pointed to by
```
memptr
```
shall be a multiple of
```
alignment
```
.
If the size of the space requested is 0, the behavior is implementation-defined; the value returned in
```
memptr
```
shall be either a null pointer or a unique pointer.
The
```
free()
```
function shall deallocate memory that has previously been allocated by
```
posix_memalign()
```
.
RETURN VALUE
Upon successful completion,
```
posix_memalign()
```
shall return zero; otherwise, an error number shall be returned to indicate the error.
Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.
Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.


q:
I could use some advice on tracking down the cause of memory leaks in C#. I understand what is a memory leak and I get why they occur in C# but I'm wondering what tools/strategies have you used in the past to resolve them?

I am using .NET Memory Profiler and I've found that one of my huge main objects is staying in memory after I close the window it manages but I'm not sure what to do to severe all links to it.

If I'm not being clear enough just post an answer with a question and I'll edit my question in response. Thanks!

[A]
Break into the debugger and then type this into the Immediate window:
```
```
.load C:\Windows\Microsoft.NET\Framework\v2.0.50727\sos.dll
```
```
The path to sos.dll varies. The way to find out the correct path is to look for mscorwks.dll in the Modules pane. Wherever that is loaded from is the correct path for sos.dll.
Then type this:
```
```
System.GC.Collect()
```
```
That will ensure anything not reachable is collected. Then type this:
```
```
!DumpHeap -type <some-type-name>
```
```
This will show you a table of all existing instances, with addresses. You can find out what is keeping an instance alive like this:
```
```
!gcroot <some-address>
```
```


q:
I'm building an open source project that uses python and c++ in Windows.
I came to the following error message:

 ImportError: No module named win32con

The same happened in a "prebuilt" code that it's working ( except in my computer :P )

I think this is kind of "popular" module in python because I've saw several messages in other forums but none that could help me.

I have Python2.6, should I have that module already installed?
Is that something of VC++?

Thank you for the help.

I got this url http://sourceforge.net/projects/pywin32/  but I'm not sure what to do with the executable :S

[A]
This module contains constants related to Win32 programming.  It is not part of the Python 2.6 release, but should be part of the download of the pywin32 project.
Edit:
I imagine that the executable is an installation program, though the last time I downloaded pywin32 it was just a zip file.


q:
In response to a rightMouse event I want to call a function that displays a context menu, runs it, and responds to the selected menu item.  In Windows I can use TrackPopupMenu with the TPM_RETURNCMD flag.

What is the easiest way to implement this in Cocoa?  It seems NSMenu:popUpContextMenu wants to post an event to the specified NSView.  Must I create a dummy view and wait for the event before returning?  If so, how do I "wait" or flush events given I am not returning to my main ?

[A]
The 'proper' way to do this in Cocoa is to have your menu item's target and action perform the required method. However, if you must do it within your initial call, you can use
```
[NSView nextEventMatchingMask:]
```
to continually fetch new events that interest you, handle them, and loop. Here's an example which just waits until the right mouse button is released. You'll probably want to use a more complex mask argument, and continually call
```
[NSView nextEventMatchingMask:]
```
until you get what you want.
```
```
NSEvent *localEvent = [[self window] nextEventMatchingMask: NSRightMouseUpMask];
```
```
I think you'll find the 'proper' way to go much easier.


q:
We're using HAProxy as a load balancer at the moment, and it regularly makes requests to the downstream boxes to make sure they're alive using an OPTIONS request:

OPTIONS /index.html HTTP/1.0

I'm working with getting nginx set up as a reverse proxy with caching (using ncache).  For some reason, nginx is returning a 405 when an OPTIONS request comes in:

192.168.1.10 - - [22/Oct/2008:16:36:21 -0700] "OPTIONS /index.html HTTP/1.0" 405 325 "-" "-" 192.168.1.10

When hitting the downstream webserver directly, I get a proper 200 response.  My question is: how to you make nginx pass that response along to HAProxy, or, how can I set the response in the nginx.conf?

[A]
In the httpchk option, you can specify the HTTP method like this:
```
```
httpchk GET http://example.com/check.php
```
```
You can also use POST, or a plain URI like /. I have it check PHP, since PHP runs external to Nginx.


q:
I've got an application that needs quite a bit of data (1000s of records) to do appropriate testing.  The only way I've found to get a decent set of testable, sensible data is to use a subset of my production DB.  I've converted this to YAML fixtures in the normal `test/fixtures' location.

This works, but now I have a bunch of seemingly brittle tests and assertions that depend on their being a particular number of records that meet condition X...

example

def test_children_association
  p = Parent.find(1)
  assert_equal 18, p.children.count, "Parent.children isn't providing the right records"
end

This doesn't seem like a good idea to me, but I'm not sure if there is a better / accepted  way to test an application that needs a large hierarchy of data.

[A]
The first thing I'd say is: what are you testing in that example? If it's an ordinary AR has_many association, then I wouldn't bother writing a test for it. All you're doing is testing that AR works.
A better example might be if you had a very complicated query or if there was other processing involved in getting the list of children records. When you get them back, rather than testing for a count you could iterate through the returned list and verify that the children match the criteria you're using.


q:
I have a JSP page that will display the exact content of another web page on a different server. My understanding was that c:import  from the JSTL should be able to include content from files that are not part of the current web application.

I added c:import url="page on my server in a different application" and it works fine, but when I try to include a page from another server it fails.

Any suggestions as to what might be wrong?

EDIT: The exact error is: "The server encountered an internal error () that prevented it from fulfilling this request.". However, requesting a page from the same server, different app works...I get the content of the page.

[A]
An exact code and how "it fails" would be a great help. All mind-readers are currently on vacation.
Meanwhile, take a look at
http://www.ibm.com/developerworks/java/library/j-jsp06173.html
```
```
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
...
<c:import
  url="http://www.truenorthguitars.com/Clients/Richman/index.htm" />
```
```


q:
How do you insert/update a column through Linq To SQL and Linq To SQL use the default values?  In particular I'm concerned with a timestamp field.

I've tried setting that column to readonly and autogenerated, so it stopped trying to put in DateTime.MinValue, but it doesn't seem to be updating on updates.

[A]
The database default value would only insert the value on creating the row.  It would do nothing for update, unless you want to add a triggger.
Alternately, you can add a partial method to your DataContext class.  Add a new file you your project:
```
```
public partial class YourDatabaseDataContext
{
    partial void InsertYourTable(YourTable instance)
    {
        instance.LastUpdateTime = DateTime.Now;

        this.ExecuteDynamicInsert(instance);
    }

    partial void UpdateYourTable(YourTable instance)
    {
        instance.LastUpdateTime = DateTime.Now;

        this.ExecuteDynamicUpdate(instance);
    }
```
```


q:
I've just had to write a string reverse function in C# 2.0 (i.e. LINQ not available) and came up with this:

public string Reverse(string text)
{
    char[] cArray = text.ToCharArray();
    string reverse = String.Empty;
    for (int i = cArray.Length - 1; i > -1; i--)
    {
        reverse += cArray[i];
    }
    return reverse;
}

Personally I'm not crazy about the function and am convinced that there's a better way to do it. Is there?

[A]
Have a look at the wikipedia entry
here
. They implement the String.Reverse extension method. This allows you to write code like this:
```
```
string s = "olleh";
s.Reverse();
```
```
They also use the ToCharArray/Reverse combination that other answers to this question suggest. The source code looks like this:
```
```
public static string Reverse(this string input)
{
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}
```
```


q:
I am after a regular expression that validates a percentage from 0 100 and allows two decimal places.

Does anyone know how to do this or know of good web site that has example of common regular expressions used for client side validation in javascript?

@Tom - Thanks for the questions. Ideally there would be no leading 0's or other trailing characters.

Thanks to all those who have replied so far. I have found the comments really interesting.

[A]
```
(100|[0-9]{1,2})(\.[0-9]{1,2})?
```
That should be the regex you want. I suggest you to read Mastering Regular Expression and download RegexBuddy or The Regex Coach.


q:
I am progamatically creating a SharePoint site using

SPWeb spWeb = spSite.AllWebs.Add(...);

What code do I need run to set the spWeb to turn off the "Show pages in navigation" option?

Answer:

publishingWeb.IncludePagesInNavigation = false;

[A]
Wasn't sure myself but I was able to locate
this
:
Modifying navigation is another common
  branding task since it affects what
  users can see and how they can proceed
  through a site hierarchy. The
  Microsoft.SharePoint.Publishing
  namespace exposes several classes that
  target the Publishing site
  infrastructure, such as PublishingWeb
  and PublishingPage. Using these
  classes, we can easily modify
  navigation for each site. If you want
  a child Web to display as a root level
  site in global navigation, first turn
  off inheritance from the parent site,
  like so:
```
```
publishingWeb.InheritGlobalNavigation = false;
```
```
You might also want to hide all site
  pages from global navigation. Setting
  IncludePagesInNavigation to false
  hides all pages in the site,
  regardless of whether the
  PublishingPage.IncludeInGlobalNavigation
  property is set to true
```
```
// do not show pages in navigation
publishingWeb.IncludePagesInNavigation = false;
```
```
If you are dealing with default sites
  that don't inherit from PublishingWeb,
  it's still possible to hide these
  sites from the global navigation bar.
  For example, if you create a site
  collection using the collaboration
  portal template and want to exclude
  the News site from global navigation,
  add that site to the
  __GlobalNavigationExcludes property of the site:
```
```
string globalNavExcludes = String.Empty;
SPWeb webSite = MSDNSiteCollection.RootWeb;
// _GlobalNavigationExcludes property contains a delimited string of
// GUIDs identifying the Id of each site to be excluded from global
// navigation

if (webSite.AllProperties.ContainsKey("__GlobalNavigationExcludes")) {
  globalNavExcludes =
    webSite.AllProperties["__GlobalNavigationExcludes"].ToString();
}

SPWeb newsSite = MSDNSiteCollection.AllWebs["News"];
// string is delimited "{GUID};{GUID};",
// use format code B to convert to string
globalNavExcludes += String.Concat(currentWeb.ID.ToString("B"), ";");

webSite.AllProperties["__GlobalNavigationExcludes"] = globalNavExcludes;
webSite.Update();
```
```
Adding navigation nodes directly to an
  SPNavigationNodeCollection is a good
  way to display only the nodes you want
  as well as to group nodes and links to
  external sites. Figure 10 shows how to
  add an internal link, external link,
  and a heading to the global navigation
  bar. This example addresses some of
  the properties of the SPNavigation
  class that affect whether the link
  opens in a new window and how to
  handle empty URLs.


q:
When using SubSonic, do you return the data as a dataset or do you put that in a strongly typed custom collection or a generic object?

I ran through the subsonic project and for the four stored procs I have in my DB, it gave me a Sps.cs with 4 methods which return a StoredProcedure object.

If you used a MVC, do you usually use the StoredProcedure object or wrap that around your business logic and return a dataset, list, collection or something else?

Are datasets still the norm or is that replaced by something else?

[A]
If the results of the stored procedure has the same schema as one of your tables, you can build a collection using this code (SubSonic 2.1):
```
```
ProductCollection coll = new ProductCollection();
coll.LoadAndCloseReader(SPs.GetProducts(1).GetReader());
```
```


q:
%AX = (%AH + %AL)

So why not %EAX = (%SOME_REGISTER + %AX) for some register %SOME_REGISTER?

[A]
In the old 8-bit days, there was the A register.
In the 16-bit days, there was the 16 bit AX register, which was split into two 8 bit parts, AH and AL, for those times when you still wanted to work with 8 bit values.
In the 32-bit days, the 32 bit EAX register was introduced, but the AX, AH, and AL registers were all kept. The designers did not feel it necessary to introduce a new 16 bit register that addressed bits 16 through 31 of EAX.


q:
How do you handle update refresh rate from your worker function to your UI ?

Sending everything to the UI or maybe using a timer (from which side ? worker or UI ?)


q:
Let's say we have 2 php variables:

$name = 'caption';

$url = 'http://domain.com/photo.jpg';

The input string of '{@url,<img src="," alt="{@name}" />}' should return:

'<img src="http://domain.com/photo.jpg" alt="caption" />'

The {tag} takes up to 3 parameters: {@variable[,text_before][,text_after]}.

What regex would be needed to make this happen? The tricky part is that a {@..} tag is nested within another.

[A]
It's for a CMS. Admins can add column fields, then add template code for how it will be displayed on the listing page. The {@tags} are used to output the dynamic column values. This template code:
```
<p>Link: <a href="{@url}">{@name}</a> - {@date}</p>
```
would create a listing page like:
Link:
link one
- 2 July 2008
Link:
link two
- 14 June 2008
Link:
link three
- 9 February 2007
...
I figured that people might want to use column values within others, hence the "alt" tag example from the first post. So using regex for this would be a bad idea?


q:
http://blogs.msdn.com/drnick/archive/2007/03/23/preventing-anonymous-access.aspx

Can someone clarify whether it is possible to use wsHttpBinding in WCF and disable anonymous access in IIS without transport (ssl) or message security being required?

[A]
we want to use windows integrated security. If you disable anonymous access in IIS and allow just windows, you cannot seem to use wsHttpBinding with WCF without using some security mode (e.g. transprot security which requires ssl).
We only want to use windows authentication we don't necessarily want to use ssl for transport security.
I was a little amazed this wasn't possible out of the box (as seemed to be confirmed by my link) as it would seem quite a common scenario for intern applications.
We don't want to downgrade to basicHttpBinding which would support windows authentication only.


q:
The large network (of small world graph type) I wish to deal with is dynamic in nature, new nodes are added and subtracted frequently. Presumably using D* over A* would be a better way to detect paths in this dynamic environment?

How solid is D*? has it had any real world experience? like a cryptographic algorithm - is  D* hardened by lots of peer review and testing? Would you use D* for this problem?

[A]
As I understand, the first time you run D* it finds the same path as A* with nearly the same runtime.  However, when a node changes it's edge value or nodes are added A* recomputes ALL of the path while D* simply recomputes the inconsistent nodes the second time around rather than the whole thing.
Anthony Stentz's D* algorithm (original whitepaper
here
) has largely been deprecated by derivatives of his work.  D* Lite and LPA* are the most commonly found and are much easier to code/implement.
As far as real world experience,  Joseph Carsten and Art Rankin from NASA's Jet Propulsion Laboratory installed a version of Field D* using elements of D* Lite on the mars rovers "Spirit" and "Opportunity" (slideshow of rovers using D*
here
).  In Feburary 2007 it was used to fully navigate the mars rover autonomously.
alt text http://asm.arc.nasa.gov/Gallery/images/generic/rover.jpg
Apparently D* is really useful in the robotics domain because the robots on-board sensors are constantly re-evaluating edge values.  That would make it pretty "battle tested" in my own opinion.
Similarly, I found another
whitepaper
that mentions the use of the D* Lite algorithm in Mobile Gaming.
I'll end this answer by stating that I've never implemented D* before, only A*.  Because of the significant increase in complexity I would say that D* (or D* Lite) should only be used in cases where there is a significant and frequent changes in the graph.  You described your situation as being similar to that so I would say definately go for D* Lite.  If NASA uses it you could safely bet it has been thoroughly investigated.


q:
I want to read all thumbnails from a folder with images in Windows XP.
But if I read image file to get thumbnail, it seems a bit slow, so I wish I can first read the windows image thumbnail cache:thumb.db.
Is there any lib in c++ or c to read thumbnails from thumb.db.

[A]
The Thumbs.db file is stored in OLE
Compound Document
format, the same format that many Microsoft Office products use.
You could also try to look into
ThumbsDBLib
.  It is in C# but you can probably see what they do to read the data and convert it to C++.
Note: Windows Vista and later doesn't use Thumbs.db.  See the
IThumbnailCache interface
for Vista and later.
For Vista and later they are stored here: %homedrive%\Users\%username%\AppData\Local\Microsoft\Windows\Explorer


q:
I am using a navigation controller, and I have the style set to :

navController.navigationBar.barStyle = UIBarStyleBlackTranslucent;

But when I run my program, the navigation controller looks like it is on top of a white background, not my background. When I push a controller, left or right, all my view, the current one, shifts to the top exactly the size of the navigation bar. And it is there where I can see my background through the navigation controller bar. Any ideas? When my barStyle is  set to opaque, everything looks fine. I was thinking on setting my view frame a negative 'y' value, but I think there should a more elegant way.

[A]
I believe the UINavigationController assumes that your controller view frames don't include the area beneath the navigation bar.
UIBarStyleBlackTranslucent is more often used for UIToolbar, so Apple probably didn't make it easy to use it nicely with UINavigationBar. You'll probably need to abandon the UINavigationController, or start hacking the frames (careful with rotations), if you want to reliably render under the bar area.
Also, if your intention is to hide the navigation bar after a few seconds, you'll have a
much
easier time if you make it fade out (like the Photos app) instead of trying to slide it up (like Mobile Safari). Trust me on that one... that took me a
lot
of time to learn the hard way.


q:
On an embedded target I use far pointers to access some parts of the memory map.

near pointer (without explicitely specifying __near):

unsigned int *VariableOnePtr;

Pointer to near pointer:
unsigned int **VariableOnePtrPtr;

far pointer:
unsigned int *__far VariableTwoPtr;

What is the correct way to declare a pointer to a far pointer? Does this pointer have to be a far pointer itself?

[A]
I believe you would do this:
```
```
unsigned int * __far *VariableThreePtrPtr;
```
```
A far pointer to a far pointer would be:
```
```
unsigned int * __far * __far VariableFourPtrPtr;
```
```


q: A lambda expression which takes a function (of one argument) and a number, and applies the function to twice the number.

[A]
Applying the function to twice the number:
```
```
(lambda (f x) (f (* 2 x)))
```
```
Applying the function to the number twice (which is what you may have intended to ask):
```
```
(lambda (f x) (f (f x)))
```
```


q: Why do computers use RGB (red, green, and blue) values for color composition rather than the primary hues, red, yellow, and blue?

[A]
The hues of magenta, yellow, and cyan are primary for subtractive combination (e.g. paints or inks) rather than additive combination such as light where red, green, and blue are primary.
Wikipedia has more detail on the whys and wherefores
.


q:
I have the following query:

SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;

I have the following questions:

Is the USING syntax synonymous with ON syntax?

Are these joins evaluated left to right?  In other words, does this query say: x = companies JOIN users; y = x JOIN jobs; z = y JOIN useraccounts;

If the answer to question 2 is yes, is it safe to assume that the companies table has companyid, userid and jobid columns?

I don't understand how the WHERE clause can be used to pick rows on the companies table when it is referring to the alias "j"

Any help would be appreciated!

[A]
SEE
http://dev.mysql.com/doc/refman/5.0/en/join.html
AND start reading here:
Join Processing Changes in MySQL 5.0.12
Beginning with MySQL 5.0.12, natural joins and joins with USING, including outer join variants, are processed according to the SQL:2003 standard. The goal was to align the syntax and semantics of MySQL with respect to NATURAL JOIN and JOIN ... USING according to SQL:2003. However, these changes in join processing can result in different output columns for some joins. Also, some queries that appeared to work correctly in older versions must be rewritten to comply with the standard.
These changes have five main aspects:
The way that MySQL determines the result columns of NATURAL or USING join operations (and thus the result of the entire FROM clause).
Expansion of SELECT * and SELECT tbl_name.* into a list of selected columns.
Resolution of column names in NATURAL or USING joins.
Transformation of NATURAL or USING joins into JOIN ... ON.
Resolution of column names in the ON condition of a JOIN ... ON.


q: I am working on rails project and I am trying to get exceptions to be logged to the rails log files.  I know I can call logger.error $! to get the first line of the exception logged to the file.  But, I want to get the entire trace stack logged as well.  How do I log the entire trace back of an exception using the default rails logger?

[A]
```
logger.error caller.join("\n")
```
should do the trick.


q:
Taking over some code from my predecessor and I found a query that uses the Like operator:

SELECT * FROM suppliers
WHERE supplier_name like '%'+name+%';

Trying to avoid SQL Injection problem and parameterize this but I am not quite sure how this would be accomplished. Any suggestions ?

note, I need a solution for classic ADO.NET - I don't really have the go-ahead to switch this code over to something like LINQ.

[A]
Simply parameterize your query:
```
```
SELECT * FROM suppliers WHERE supplier_name like '%' + @name + '%'
```
```
Now you can pass your "name" variable into the @name parameter and the query will execute without any danger of injection attacks. Even if you pass in something like "'' OR true --" it'll still work fine.


q: I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability?

[A]
You can use:
```
```
System.getProperty("os.name")
```
```
P.S. You may find this code useful:
```
```
class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}
```
```
All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)


q:
The goal: Any language. The smallest function which will return whether a string is a palindrome. Here is mine in Python:

R=lambda s:all(a==b for a,b in zip(s,reversed(s)))

50 characters.

The accepted answer will be the current smallest one - this will change as smaller ones are found. Please specify the language your code is in.

[A]
Here's mine; it's written in a domain-specific language I invented, called 'palindrome'.
```
```
p
```
```
Edit:
Less flippant version (i386 asm, AT&T syntax)
```
```
xor %eax, %eax
mov %esi, %edi
#cld    not necessary, assume DF=0 as per x86 ABI
repne scasb
scan:
    dec %edi
    cmpsb
    .byte 0x75, 6    #jnz (short) done
    dec %edi
    cmp %esi, %edi
    .byte 0x72, -9    #jb (short) scan
inc %eax
done:
```
```
16 bytes, string pointer goes in ESI, result is in EAX.


q:
Is there someway to set the default file permission in Linux? That is, the file permission for a newly created file (regardless of the context for which it was created
). I know about putting umask in the shell startup but that only works for shell sessions. When I transfer files to a Linux box using pscp, the file is always created with permissions of 664 (rw-rw-r--). The has occurred across every flavor of Linux that I've used. This is especially annoying when I pscp a file to shared Linux machine (like my ISP). Until I can shell in and chmod the permission, the file is basically sitting there with read access for everyone, which is not exactly secure.

[A]
Put the umask in the non-interactive shell startup (
```
.bash_profile
```
,
```
.zshenv
```
,
```
.tcshrc
```
depending on your shell). Then it'll run for non-login sessions.


q:
I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of

function editRecord()
{
  var gridView = document.getElementById("<%= GridView.ClientID %>");
  var id = // somehow get the id here ???
  window.open("edit.aspx?id=" + id);
}

The question is how do I retrieve the selected records ID in javascript?

[A]
1) change your javascript function to use a parameter
```
```
function editRecord(clientId)
{ ....
```
```
2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple
```
```
<input type="button" onclick="editRecord(your-rows-client-id-goes-here)" />
```
```


q:
currently i obtain  the below result from the following C# line of code when in es-MX Culture

   Thread.CurrentThread.CurrentCulture =
     Thread.CurrentThread.CurrentUICulture = new
                CultureInfo("es-mx");

  <span><%=DateTime.Now.ToLongDateString()%></span>

miércoles, 22 de octubre de 2008

i would like to obtain the following

Miércoles, 22 de Octubre de 2008

do i need to Build my own culture?

[A]
The pattern of LongDate for Spanish (Mexico) is
```
dddd, dd' de 'MMMM' de 'yyyy
```
according to
Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongDatePattern
. I guess you just have to manually convert the initial letters of the day and month to uppercase or you can use
Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase
and then replace "De" with "de".


q:
A couple of the options are:

$connection = {my db connection/object};

function PassedIn($connection) { ... }

function PassedByReference(&$connection) { ... }

function UsingGlobal() {
    global $connection;
    ...
}

So, passed in, passed by reference, or using global. I'm thinking in functions that are only used within 1 project that will only have 1 database connection. If there are multiple connections, the definitely passed in or passed by reference.

I'm thining passed by reference is not needed when you are in PHP5 using an object, so then passed in or using global are the 2 possibilities.

The reason I'm asking is because I'm getting tired of always putting in $connection into my function parameters.

[A]
None of the above.
All the
```
mysql
```
functions take the database connection argument
optionally
. If you leave that argument out, the last connection by mysql_connect() is assumed.


q:
Can anybody explain the idea behind JSP custom tag libraries and the JSP 2 tag files?

Are they just different ways to do the same thing?

How do they compare? What are their pros and cons, and which is better?

[A]
Problems Developing Custom Tags
Traditional custom tags require Java programming
skills.
All but the simplest custom tags are not easy to write.
The purpose of JSP, in contrast to servlets, is to use
markup language to manage layout with embedded
dynamic content.
Having to write complex Java code
in custom tags that focus on markup language is going
backwards.
We might want to use the JSP expression language or
other custom tags when implementing a new custom
tag.
The Solution
JSP 2.0 Tag Files
Tag files are one of the important new concepts introduced with JSP 2.0.
Tag files permit easier and more rapid development of custom tags.
Tag files are developed using normal JSP syntax,including scripting elements, and used just like any other custom tag.
Each custom tag is a separate tag file.
How Do Tag Files Differ?
Written using JSP syntax.
Not all JSP directives are permitted in a tag file.
Supported by new tag file specific directives, actions and implicit objects.
Identified by either a
.tag
or
.tagx
suffix.
Intended to provide custom tag developers ease of development without loss of functionality.
One of the lead developers of JSTL has commented thatif she had the time, she would rewrite all of JSTL using tag files.


q:
I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right?

My only experience with garbage collection was on a couple of cheap eighties home computers, where it meant that the system would freeze up for a few seconds every so often. I'm sure it has improved since then, but as you can guess, that didn't leave me with a high opinion of it.

What advantages could garbage collection offer an experienced C++ developer?

[A]
The committee isn't adding garbage-collection, they are adding a couple of features that allow garbage collection to be more safely implemented. Only time will tell whether they actually have any effect whatsoever on future compilers. The specific implementations could vary widely, but will most likely involve reachability-based collection, which could involve a slight hang, depending on how it's done.
One thing is, though, no standards-conformant garbage collector will be able to call destructors - only to silently reuse lost memory.


q:
This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:

    private long sum(Node<T> thisNode)
    {
        if (thisNode.Left == null && thisNode.Right == null)
            return 0;
        if (node.Right == null)
            return sum(thisNode.Left);
        if (node.Left == null)
            return sum(thisNode.Right);

        return sum(thisNode.Left) + sum(thisNode.Right);
    }

Within my Node class I have Data which stores Size and Name in their given properties. I'm just trying to sum the entire size. Any suggestions or ideas?

[A]
Maybe you meant
```
```
if (thisNode.Left == null && thisNode.Right == null)
        return thisNode.Size;
```
```
?


q:
I'm looking for syntatic examples or common techniques for doing regular expression style transformations on words instead of characters, given a procedural language.

For example, to trace copying, one would want to create a document with similar meaning but with different word choices.

I'd like to be able to concisely define these possible transformations that I can apply to a text stream.

Eg.  "fast noun" to "rapid noun", but "go fast." wouldn't get transformed (no noun afterwards.

Or:  "Alice will sing song"  to "song will be sung by Alice"

I'd expect this to be done in grammatical checkers, such as detecting passive voice.

A C# implementation for this sort of language-processing would be really neat, but I think the bulk of any effort is coming up with the right rules - Keeping the rules clear and understandable seems like a place to begin.

[A]
A good place to start would be SIL's
CARLAStudio
for its "Computer Assisted Related Language Adaptation" suite. Alternatively SIL's
Adapt It
. SIL has a huge range of linguistic analysis software, which is the direction you appear to be going. It's certainly a big jump from regular expressions, which don't care about the meaning, to something that can handle linguistic analysis.


q: I want to continuously sample from my PC's audio line in using C# (then process that data). What is the best way to do the sampling?

[A]
There are no built-in libraries in the .NET framework for dealing with sound, but if you're on Win32, you can use an unmanaged library like DirectSound to do it.
Ianier Munoz shows
how to write a full-duplex audio player in C# using
waveIn
via P/Invoke
on CodeProject.  He mentions
Managed DirectSound
as a more general method.


q:
I would like to send some keystrokes from a C++ program into another window.

For that reason I would like to have the user select the target window similar to how it is done in the Spy++ utility that comes with Visual Studio (drag a crosshair cursor over target window and have target window highlighted by a frame).

How is this dragging and selecting done in Windows? I am completely lost as to where I might start to look for a mechanism to implement this feature.

[A]
Here's how it's usually done:
Capture the mouse using
SetCapture
. This will cause all mouse messages to be routed toward your app's window.
Handle the
WM_MOUSEMOVE
message. In your handler code, grab the window underneath the mouse using
WindowFromPoint
. That will get you the HWND of the window the mouse is currently over.
Now that you've got the window, you need a device context (HDC). You can get one using
GetWindowDC
for the specified window.
Now you can draw into the DC using typical GDI functions.
There are some things you have to look out for - cleanly erasing the selection rectangle and so forth, but that's one way to do it.
You could also draw into a screen DC to do this, but in any case you'll need the window handle in order to get the window rect.
If you Google around Spy++ source code you'll see a few examples of this technique.


q:
If I have a source.c file with a struct:

struct a {
    int i;
    struct b {
        int j;
    }
};

How can this struct be used in another file (i.e. func.c)?

Should I create a new header file, declare the struct there and include that header in func.c?

Or should I define the whole struct in a header file and include that in both source.c and func.c?  How can the struct be declared extern in both files?

Should I typedef it? If so, how?

[A]
a.h:
```
```
#ifndef A_H
#define A_H

struct a {
    int i;
    struct b {
        int j;
    }
};

#endif
```
```
there you go, now you just need to include a.h to the files where you want to use this structure.


q:
Say I have the classic 4-byte signed integer, and I want something like

print hex(-1)

to give me something like

0xffffffff

In reality, the above gives me -0x1. I'm dawdling about in some lower level language, and python commandline is quick n easy.

So.. is there a way to do it?

[A]
This will do the trick:
```
```
>>> print(hex (-1 & 0xffffffff))
0xffffffff
```
```
or, a variant that always returns fixed size (there may well be a better way to do this):
```
```
>>> def hex3(n):
...     return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x00000011
```
```
Or, avoiding the hex() altogether, thanks to Ignacio and bobince:
```
```
def hex2(n):
    return "0x%x"%(n&0xffffffff)

def hex3(n):
    return "0x%s"%("00000000%x"%(n&0xffffffff))[-8:]
```
```


q:
Now that Silverlight 2 has finally shipped. I'm wondering if anyone has put together any logging frameworks for it, maybe something like enterprise library logging or log4net? I'm interesting in something that can perform tracing client side and also log messages to the server.

So far the only project I have found is Clog on CodeProject. Has anyone used this? What were your thoughts on it?

[A]
I am about to delve into something similar myself for a product we've written. I'm considering using PostSharp for Silverlight to add client-side logging as an aspect.
I have used the NLog project with great success before under the full .NET Framework and the Compact Framework so I'll most likely take the existing framework code and add some logging targets:
A standard System.Diagnostics target to enable capturing using DebugView, etc.
An asynchronous Web service target similar to the one in NLog.
An isolated storage target with deferred transfer to server semantics.
I've briefly looked at Clog and it seems to suffer from one major flaw - it can't log a connection failure. So assuming your Web server is online all the time, yes it will work, but when problems occur upstream or on the server itself, the logging data is all lost and might even crash your application.


q:
Im creating a report using crystal report in vb.net.

The report contained a crosstab which I have 3 data:
1. Dealer - row field
2. Month - column
3. Quantity Sales - summarize field

How can I arrange this by ascending order based on the
Quantity Sales - summarize field?

thanks

[A]
Depending on how you're working with it, you can adjust the input to order the data ascending.
```
```
SELECT customer, sum(amountdue) AS total FROM invoices
GROUP BY customer
ORDER BY total ASC
```
```
If you're doing in a way that you can't change that information, could you provide a little more insight?


q:
The coding is done using VS2008
There are two divs in my page namely "dvLeftContent" and "dvRightContent".
I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here)
Is there a client side function(javascript or jquery) that takes the height of the right div and assigns it to left div?


q:
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?

This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other languages I could just do letter++ and increment my way through the alphabet, but thus far I haven't come across a way to do that in python.

def alphCount(text):
  lowerText = text.lower()
  for letter in allTheLetters:
    print letter + ":", lowertext.count(letter)

[A]
Something like this?
```
```
for letter in range(ord('a'), ord('z') + 1):
  print chr(letter) + ":", lowertext.count(chr(letter))
```
```


q: I know that there are a lot of CUDA language bindings, such as PyCUDA, but are there any good bindings for .Net? The only one I've seen is this one, but I'd like to know if there are any others.

[A]
Here's another library:
http://sourceforge.net/projects/brahma-fx/
Edit
: I've been looking at the documentation for the project you initially listed, and can say that the interface makes me think: what is the point of using .Net.  The project I've listed has a cleaner interface but no documentation.  The project you listed seems to be more dedicated in the development path ( a recent 2.1 release), but the SVN of Brahma isn't too old (5 wks).
Another poster listed the Accelerator framework.  It looks
very
promising, although its license is non-commercial (you must contact them if you intend to use it for any commercial work), and when I installed it, it said it installed right and I can't find it on my system (this could have been a Vista issue)!
EDIT
: I have looked into the various libraries, and can say here is my "recommendations":
If you are planning on using LINQ and only .Net 3.5, use Brahma.
If you are non-commercial in your goal, use the Accelerator project that the other poster gave (Tim, I believe).  It is higher level than the project you mentioned.
If you don't care about low-level details, but very active project and documentation is desired then go with the project you listed.


q:
(mingw32, windows xp)
Hello, I am attempting to migrate from Java to c++. I am confused and frustrated about finding, installing, and compiling non-standard c++ libraries. in Java it's so convenient they stuffed every functionality and documentation ever needed in java's standard api. Is there a list of essential c++ library such as Threading, gui, networking, image\ audio processing, xml, etc.etc. in one place? or possibly, offered as a single package?

I tried installing QT library for weeks and it wont even compile. in Java i used to learn by trial-and-error to learn new aspect of functionality, but that would be impossible if i can't fetch and run new api in the first place.

please, i need your suggestion, originally i wanted to break free of Java's abstraction, but now i just want to be able to use c++ before I decided shooting myself in the head.

[A]
The C++ standard library is extremely light. It contains nowhere near the functionality offered by the Java runtimes or by the .NET CLR.
The
Boost
libraries add a whole bunch of functionality to C++, but not much (if any) in the area of user interface.
For UI, there's the question of which platform you're targetting. If it's Win32, then you can use the straight Win32 API (mostly designed for C, but there are some C++ wrappers for parts of it). If you want cross-platform, then you're looking at QT or GTK (although there are others).
But, as Andrew already said: "why do you want to learn C++ anyway?". Don't get me wrong: I program in C++ for a living, and actually enjoy it (although I'm beginning to suspect a case of Stockholm Syndrome). If I had to start again, I'd go with a more modern language and environment (Java or C#; or Ruby or Python).


q:
I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.

If I pass in a char-array of characters from 0 to J, and set length to 5, I want results like 00000, 00001, 00002... HJJJJ, IJJJJJ, JJJJJ.

Here is the base, please help me expand:

protected void Main()
{
    char[] chars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };

    BruteForce(chars, 5);
}

private void BruteForce(char[] chars, int length)
{
    // for-loop (?) console-writing all possible combinations from 00000 to JJJJJ
    // (when passed in length is 5)
    // TODO: Implement code...
}

[A]
Google for permutations.
If however you are just dealing with that 'hex' range, just do the following:
```
```
for (int i = 0; i < (1 << 24); i++)
  string s = i.ToString("X6");
```
```


q:
I need a little help on this subject.

I have a Web application written in ASP.NET plus I have the .bak file of the SQL Express database, my question is: How can I install this in a simple click and go way in the client?

how can I write a script that will create a new database, restore the bak file into that database, set up IIS and ... well, that's it :)

I do this all manually, and I do this a lot, so I was just asking if there is a way to prevent do all this steps manually.

Thanks.

[A]
You could use
WiX
to create a .msi that you can use to install your application at your clients.  WiX takes a bit to get used to, but once you get the hang of it, you'll meet your needs above, and be able to extend them as your application grows or increases in complexity from the installation point of view.
I read your question to mean you have several clients where you install your application, if that is not the case, and your app exists in one place, there are better solutions, and better people to give them to you!


q: what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?

[A]
When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:
lang.en.js
lang.it.js
lang.fr.js
Each of the files declares an object which is basically just a map from key word to language phrase:
```
```
// lang.en.js
lang = {
    greeting : "Hello"
};

// lang.fr.js
lang = {
    greeting : "Bonjour"
};
```
```
Dynamically load one of those files and then all you need to do is reference the key from your map:
```
```
document.onload = function() {
    alert(lang.greeting);
};
```
```
There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.
```
```
var l = new Language('en');
l.get('greeting');
```
```


q:
We are a small company and would like to know the best possible (and affordable) hardware and software configuration we ought to be using for our development environment. At this moment we are a team of four people who work remotely from different locations and each one of us uses a laptop and ADSL connection to work on our projects.

This question should help us identify a path towards optimizing our hardware and software so as to make the most of these development environments. Do we need to run everything locally on the laptops or some sort of distributed solution is possible? Which software versions do you recommend given that both Windows 2008 and SQL Server 2008 are available options? Do we use a central server or run these locally on our laptops?

We're a young team so any help would be welcome and much appreciated! Thanks!

Ym

[A]
For a team, I would suggest that you set up the local environments (laptops) as development environments, with a local DB copy and running CF developer version.  Version control (VSS, Subversion, Git, etc.) is pretty much mandatory.
Have a testing/staging/QA server with the same configuration as the live version (as much as this is possible).  It should have its own CF license to follow the licensing agreement.  You should put checked-in code here for everyone to test and to check integration.  Several version control systems offer ways to automate this, or you could do this manually.
Production, obviously, should be its own thing.  I would suggest that you separate the database and app/web server on two separate boxes.
I know this might be a little more/less than you were asking, so feel free to ask for clarification.


q:
Okay I know I asked about this before, and the answer was basically cache data that doesn't change often.

Well what does one do when at least 99.9% of the data changes?

In my project the only tables that doesn't get updated or won't get updated frequently would be the member profile info (name/address, and settings)

So how does one still enable some kind of caching but keep and make sure the data being viewed is updated when changes are applied?

[A]
I guess, it's not really 99.9% of all data that changes, but it's in 99.9% of all data locations that changes happen.
For example, if you are running a bulletin board, that means that there will be a steady stream of new posts, but old posts will remain the same, and even old threads will stay unchanged for a long, long time.
In that case, you'll need a way to invalidate old cached data, so that you can build a cache as soon as a thread (in the example) is viewed. If there is a change to ONE of these threads (i.e. when someone adds a new post), this one cached item is deleted/marked outdated, so the next time it is viewed, it will be rebuilt. Other items that still haven't changed will use the cache, though.


q: How do you find out the local time of the user browsing your website in ASP.NET?

[A] You have to use JavaScript in the client side that will get the local time and pass that value to server side. You can pass it using querystring, hidden fields or even AJAX magic.


q: Is there a way to reformat code, i.e. force correct indentation in FlashDevelop as you can do with CTRL-SHIFT-F in Eclipse?

[A] open netbeans 6.5, create an xml file and then paste your mxml code; right click, format code, finally copy this formatted text from netbeans and past it in flex builder. it´s all.... i hope to be usefull


q:
I find System.Monitor very confusing, although I understand threading, locks, deadlocks, race conditions, dining philosophers and all that jazz.  Normally I use a ManualResetEvent() to do inter-thread co-ordination, but I know that that's a heavyweight kernel object, and that System.Monitor (Enter/Pulse, etc.) is much more efficient.  I've Googled and Googled but cannot find a sensible example.

I would be most grateful if the SO crew could explain this potentially wonderful construct to me :-)

[A]
Here's a very simple example; the call to
```
Wait
```
releases the lock (allowing
```
Worker
```
to obtain it) and adds the
```
Main
```
thread to the lock-object's pending queue.
```
Worker
```
then obtains the lock, and calls
```
Pulse
```
: this moves the
```
Main
```
thread into the lock-object's ready queue. When
```
Worker
```
releases
the lock,
```
Main
```
can resume work.
Note that
```
lock(obj) {...}
```
is just compiler-candy for
```
Monitor.Enter
```
/
```
Monitor.Exit
```
in a try/finally block.
[edit: I changed the sample to move
```
lock(sync)
```
earlier, to avoid the (unlikely) risk of a missed Pulse]
```
```
static void Main()
    {
        object sync = new object();
        lock (sync)
        {
            ThreadPool.QueueUserWorkItem(Worker, sync);
            Console.WriteLine("Main sleeping");

            // wait for the worker to tell us it is ready
            Monitor.Wait(sync);
            Console.WriteLine("Main woke up!");
        }
        Console.WriteLine("Press any key...");
        Console.ReadKey();
    }
    static void Worker(object sync)
    {
        Console.WriteLine("Worker started; about to sleep");
        Thread.Sleep(5000);
        Console.WriteLine("Worker about pulse");
        lock (sync)
        { // notify Main that we did something interesting
            Monitor.Pulse(sync);
            Console.WriteLine("Worker pulsed; about to release lock");
        }
        Console.WriteLine("Worker all done");
    }
```
```


q:
I am running the free version of Helicon ISAPI Rewrite on IIS and have several sites running through the same set of rewrite rules. Up 'til now this has been fine as all the rules have applied to all the sites. I have recently added a new site which I don't want to run through all the rules. Is there any way to make requests to this site break out of the rule set after it's executed its own rules.

I've tried the following with no luck; all requests to mysite.com result in a 404. I guess what I'm looking for is a rule that does nothing and is marked as the last rule to execute [L].

## New site rule for mysite.com only
RewriteCond  Host:  (?:www\.)?mysite\.com
RewriteRule  /content([\w/]*)   /content.aspx?page=$1 [L]

## Break out of processing for all other requests to mysite.com
RewriteCond  Host:  (?:www\.)?mysite\.com
RewriteRule (.*) - [L]

## Rules for all other sites
RewriteRule ^/([^\.\?]+)/?(\?.*)?$ /$1.aspx$2 [L]
...

[A]
Rewrite it to itself?
```
```
RewriteCond  Host:  (?:www\.)?mysite\.com
RewriteRule ^(.*)$ $1 [QSA,L]
```
```


q:
Is there a way I can access (for printout) a list of sub + module to arbitrary depth of sub-calls  preceding a current position in a Perl script?

I need to make changes to some Perl modules (.pm's). The workflow is initiated from a web-page thru a cgi-script, passing input through several modules/objects ending in the module where I need to use the data. Somewhere along the line the data got changed and I need to find out where.

[A]
You can use
Devel::StackTrace
.
```
```
use Devel::StackTrace;
my $trace = Devel::StackTrace->new;
print $trace->as_string; # like carp
```
```
It behaves like Carp's trace, but you can get more control over the frames.
The one problem is that references are stringified and if a referenced value changes, you won't see it.  However, you could whip up some stuff with
PadWalker
to print out the full data (it would be huge, though).


q:
$("#dvMyDIV").bind("resize", function(){
    alert("Resized");
});

or

$("#dvMyDIV").resize(function(){
    alert("Resized");
});

The questions

Why is this not working at FireFox, Chrome and Safari?

Can this be considered a jQuery bug since the resize is not handled for other browsers?

Could the only workaround be calling a SetTimeout function checking the clientHeight and clientWidth?

Any workarounds using jQuery?

[A]
I believe the JavaScript resize event only applies to frames or windows, not to DIVs.
e.g. see
this page
:
The onResize even handler is use to execute specified code whenever a user or script resizes a window or frame. This allows you to query the size and position of window elements, dynamically reset SRC properties etc.
So if you want to detect when the window is resized, in jQuery you should probably use
```
$(window).resize(function() { });
```
Edit:
if you want to watch the size of a DIV, it depends on what your intention is. If you're resizing with JavaScript then you could implement a method to perform the resize and have that handle calling any other resize code.
Otherwise, if you're just watching for the DIV to resize when someone resizes the window, wouldn't it just work to attach the resize listener to the window and then check if the DIV had been resized (i.e. store the old values of width / height and check them on resize)?
Finally, you could consider using
watch
on the width / height properties, although I don't know whether this is fully browser-compatible (think this might be Mozilla-only). I did find
this jQuery plugin
which looks like it might do the same thing though (with some slight modification).


q:
How can I convert a relative path to an absolute path in C on Unix?
Is there a convenient system function for this?

On Windows there is a GetFullPathName function that does the job, but I didn't find something similar on Unix...

[A]
Use
realpath()
.
The
```
realpath()
```
function shall derive,
  from the pathname pointed to by
```
file_name
```
, an absolute pathname that
  names the same file, whose resolution
  does not involve '
```
.
```
', '
```
..
```
', or
  symbolic links. The generated pathname
  shall be stored as a null-terminated
  string, up to a maximum of
```
{PATH_MAX}
```
bytes, in the buffer pointed to by
```
resolved_name
```
.
If
```
resolved_name
```
is a null pointer,
  the behavior of
```
realpath()
```
is
  implementation-defined.
The following example generates an
  absolute pathname for the file
  identified by the symlinkpath
  argument. The generated pathname is
  stored in the actualpath array.
```
```
#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;

ptr = realpath(symlinkpath, actualpath);
```
```


q: Is there any free java library which I can use to convert string in one encoding to other encoding, something like iconv? I'm using Java version 1.3.

[A]
```
CharsetDecoder
```
should be what you are looking for, no ?
Many network protocols and files store their characters with a byte-oriented character set such as
```
ISO-8859-1
```
(
```
ISO-Latin-1
```
).
However, Java's native character encoding is
Unicode
UTF16BE (Sixteen-bit UCS Transformation Format, big-endian byte order).
See
```
Charset
```
. That doesn't mean
```
UTF16
```
is the default charset (i.e.: the default "mapping between sequences of sixteen-bit
Unicode code units
and sequences of bytes"):
Every instance of the Java virtual machine has a default charset, which may or may not be one of the standard charsets.
[
```
US-ASCII
```
,
```
ISO-8859-1
```
a.k.a.
```
ISO-LATIN-1
```
,
```
UTF-8
```
,
```
UTF-16BE
```
,
```
UTF-16LE
```
,
```
UTF-16
```
]
The default charset is determined during virtual-machine startup and typically depends upon the locale and charset being used by the underlying operating system.
This example demonstrates how to convert
```
ISO-8859-1
```
encoded bytes in a
```
ByteBuffer
```
to a string in a
```
CharBuffer
```
and visa versa.
```
```
// Create the encoder and decoder for ISO-8859-1
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();

try {
    // Convert a string to ISO-LATIN-1 bytes in a ByteBuffer
    // The new ByteBuffer is ready to be read.
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap("a string"));

    // Convert ISO-LATIN-1 bytes in a ByteBuffer to a character ByteBuffer and then to a string.
    // The new ByteBuffer is ready to be read.
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
} catch (CharacterCodingException e) {
}
```
```


q:
I need to test a web form that takes a file upload.
The filesize in each upload will be about 10 MB.
I want to test if the server can handle over 100 simultaneous uploads, and still remain
responsive for the rest of the site.

Repeated form submissions from our office will be limited by our local DSL line.
The server is offsite with higher bandwidth.

Answers based on experience would be great, but any suggestions are welcome.

[A]
I would perhaps guide you towards using cURL and submitting just random stuff (like, read 10MB out of
```
/dev/urandom
```
and encode it into base32), through a POST-request and manually fabricate the body to be a file upload (it's not rocket science).
Fork that script 100 times, perhaps over a few servers. Just make sure that sysadmins don't think you are doing a DDoS, or something :)
Unfortunately, this answer remains a bit vague, but hopefully it helps you by nudging you in the right track.
Continued as per Liam's comment:
If the server receiving the uploads is not in the same LAN as the clients connecting to it, it would be better to get as remote nodes as possible for stress testing, if only to simulate behavior as authentic as possible. But if you don't have access to computers outside the local LAN, the local LAN is always better than nothing.
Stress testing from inside the same hardware would be not a good idea, as you would do double load on the server: Figuring out the random data, packing it, sending it through the TCP/IP stack (although probably not over Ethernet), and
only then
can the server do its magic. If the sending part is outsourced, you get double (taken with an arbitrary sized grain of salt) performance by the receiving end.


q:
When using something like object.methods.sort.to_yaml I'd like to have irb interpret the \n characters rather than print them.

I currently get the following output:

--- \n- "&"\n- "*"\n- +\n- "-"\n- "<<"\n- <=>\n ...

What I'd like is something similar to this:

---
 - "&"
 - "*"
 - +
 - "-"
 - "<<"
 - <=>

Is this possible? Is there another method I can be calling which will interpret the string perhaps?

[A]
That's just irb -- I don't think you can control the
```
return
```
formatting.
You can still use
```
print
```
or
```
puts
```
to display it as you want.


q: How to convey a bad news to the client?

[A]
What type of bad news?
People in general like to break bad news by stating that the corrections / new timelines will be in place much earlier than we truely can accomplish. Be honest up front and dont give false hope. One instance of bad news is enough... no need to create new promises that you cant keep in the future.
Bottom Line: be honest to your client and yourself to control expectation management.


q:
how to show all values of a particular field in a text box ???
ie. for eg. when u run the SP, u'll be getting 3 rows. and i want to show the (eg.empname)
in a textbox each value separated by a comma.
(ram, john, sita).

[A]
I had this problem the other day. If you are using SQL 2005 you can use the CROSS APPLY function.
Here is a sample;
```
```
Structure;
ID TYPE TEXT
1 1 Ram
2 1 Jon
3 2 Sita
4 2 Joe

Expecteed Output;
ID TYPE TEXT
1 1 Ram, Jon
2 2 Sita, Joe

Query;
SELECT t.TYPE,LEFT(tl.txtlist,LEN(tl.txtlist)-1)
FROM(SELECT DISTINCT TYPE FROM Table)t
CROSS APPLY (SELECT TEXT + ','
             FROM Table
             WHERE TYPE=t.TYPE
             FOR XML PATH(''))tl(txtlist)
```
```
Hope this helps :)
Remember you'll need to select this as something in your sp, then bind that to the textbox on your report. Good luck!


q:
After looking at other questions related to sharing solutions between VS 2005 and VS 2008 it seems that the way to go is to have two solution files (one for VS 2005 and one for VS 2008).

However, if the solution is under source control (VisualSVN in our case), how would we maintain two solution files and not keep overwriting one or the other with each update/commit?

Is it possible to remove just the .sln file from source control and stop the VisualSVN client from checking its status in visual studio?

Thanks

Matt

[A]
I'm not sure I see the problem - if you've got two solution files, why would either of them be overwritten? I do really mean two files, e.g. MyApp2005.sln and MyApp2008.sln, where when you create a new project you do it in the 2005 solution and then just "add existing project" in the 2008 solution.
What would VisualSVN do to mess this up?
(I have the same setup for my
C# in Depth source code
, and I use VisualSVN - I haven't seen any problems.)


q:
The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.

Any help would be much appreciated.

function validate_phone($phone)
{
    $phoneregexp ="^(\+[1-9][0-9]*(\([0-9]*\)|-[0-9]*-))?[0]?[1-9][0-9\- ]*$";

    $phonevalid = 0;

    if (ereg($phoneregexp, $phone))
    {
        $phonevalid = 1;
    }else{
        $phonevalid = 0;
    }
}

[A]
If this is PHP, then the regex must be enclosed in quotes.
Furthermore, what's
```
preg
```
? Did you mean
```
preg_match
```
?
Another thing. PHP knows boolean values. The canonical solution would rather look like this:
```
```
return preg_match($regex, $phone) !== 0;
```
```
EDIT: Or, using
```
ereg
```
:
```
```
return ereg($regex, $phone) !== FALSE;
```
```
(Here, the explicit test against
```
FALSE
```
isn't strictly necessary but since
```
ereg
```
returns a number upon success I feel safer coercing the value into a
```
bool
```
).


q:
I've a WEB application (with pure Java servlet) that have some heavy computational work, with database access, that can be done in asynchronous mode.
I'm planning to use a dedicated server to execute such batch jobs and I'm wondering which tools/techniques/protocols to use for communication between servlets in the WEB server and batch jobs in the new dedicated server.
I'm looking at JMS. Is it the right choice?
There are industry standard and/or widely adopted techniques?
I need also queue and priority handling for multiple simultaneous jobs.

[A]
Messaging is one of the best options.
Make the messaging framework very generic so that it can handle any type of batch jobs.
One approach is to have an event/task manager where you put an event on the queue and the queue consumer processes the event and converts it into a set of tasks. The tasks can then be executed by separate task handlers. A task can also generate some more events that can be again put on the queues to provide a feedback loop. This way you can add work flow like features to the framework and allow your batch jobs to have dependencies on each other.


q:
<div>
<h1>Title</h1>
<table>
...
</table>
</div>

Now, the

<h1>

has a margin: 0;
so it is at the top of the div. The height of the div is 300px.

However I'd like the table to be placed at the bottom of the div, eg. valign="bottom" but for the whole table.

[A]
What about this:
```
```

Title

...

```
```
The only problem is that both the container div and the tableContainer divs need to be absolute positioned. Not sure if this will work for your layout.


q: I find print_r in PHP extremely useful, but wonder if there is anything remotely equivalent in Perl?

[A]
Note @tchrist recommends
Data::Dump
over
Data::Dumper
. I wasn't aware of it, but from the looks of it, seems like it's both far easier to use and producing better looking and easier to interpret results.
Data::Dumper
:
A snippet of the examples shown in the above link.
```
```
use Data::Dumper;

package Foo;
sub new {bless {'a' => 1, 'b' => sub { return "foo" }}, $_[0]};

package Fuz;                       # a weird REF-REF-SCALAR object
sub new {bless \($_ = \ 'fu\'z'), $_[0]};

package main;
$foo = Foo->new;
$fuz = Fuz->new;
$boo = [ 1, [], "abcd", \*foo,
         {1 => 'a', 023 => 'b', 0x45 => 'c'},
         \\"p\q\'r", $foo, $fuz];

########
# simple usage
########

$bar = eval(Dumper($boo));
print($@) if $@;
print Dumper($boo), Dumper($bar);  # pretty print (no array indices)

$Data::Dumper::Terse = 1;          # don't output names where feasible
$Data::Dumper::Indent = 0;         # turn off all pretty print
print Dumper($boo), "\n";

$Data::Dumper::Indent = 1;         # mild pretty print
print Dumper($boo);

$Data::Dumper::Indent = 3;         # pretty print with array indices
print Dumper($boo);

$Data::Dumper::Useqq = 1;          # print strings in double quotes
print Dumper($boo);
```
```


q:
What exactly does null do performance and storage (space) wise in MySQL?

For example:

TINYINT: 1 Byte
TINYINT w/NULL 1 byte + somehow stores NULL?

[A]
It depends on which storage engine you use.
In MyISAM format, each row header contains a bitfield with one bit for each column to encode NULL state.  A column that is NULL still takes up space, so NULL's don't reduce storage.  See
https://dev.mysql.com/doc/internals/en/myisam-introduction.html
In InnoDB, each column has a "field start offset" in the row header, which is one or two bytes per column.  The high bit in that field start offset is on if the column is NULL.  In that case, the column doesn't need to be stored at all.  So if you have a lot of NULL's your storage should be significantly reduced.
See
https://dev.mysql.com/doc/internals/en/innodb-field-contents.html
EDIT:
The NULL bits are part of the row headers, you don't choose to add them.
The only way I can imagine NULLs improving performance is that in InnoDB, a page of data may fit more rows if the rows contain NULLs.  So your InnoDB buffers may be more effective.
But I would be very surprised if this provides a significant performance advantage in practice.  Worrying about the effect NULLs have on performance is in the realm of micro-optimization.  You should focus your attention elsewhere, in areas that give greater bang for the buck.  For example adding well-chosen indexes or increasing database cache allocation.


q:
How do I limit os.walk to only return files in the directory I provide it?

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
    return outputList

[A]
You could use
```
os.listdir()
```
which returns a list of names (for both files and directories) in a given directory. If you need to distinguish between files and directories, call
```
os.stat()
```
on each name.


q:
I would like to do remote deployment from my build machine onto a server. The remoting can be done via ssh commands from a script, but I would rather use phing and a deploy.xml file that would do the automation.

What alternatives do I have to do ssh (and also scp) tasks from within a phing build file?

[A]
I ran into the same problem about a year ago and back then i could not find a task. I ended up doing a exec task, this way it was all in the xml file.
```
```
<exec command="scp -i keys/id_rsa myfile user@$server:myfile" dir="." />
```
```


q: Is it quicker to make one trip to the database and bring back 3000+ plus rows, then manipulate them in .net & LINQ or quicker to make 6 calls bringing back a couple of 100 rows at a time?

[A]
It will entirely depend on the speed of the database, the network bandwidth and latency, the speed of the .NET machine, the actual queries etc.
In other words, we can't give you a truthful general answer. I know which sounds easier to code :)
Unfortunately this is the kind of thing which you can't easily test usefully without having an
exact
replica of the production environment - most test environments are somewhat different to the production environment, which could seriously change the results.


q: Do you always use a second-level cache in Hibernate or do you first try it without and only use it when the performance goes down?

[A]
My usage of Hibernate has always been in the context of another framework (Spring, for example), where enabling caching is nearly trivial.  A number of these projects have made use of caching via
ehcache
for some critical domain classes.
Having said that, this is another area where we have to make trade-offs between resources - balancing retrieval performance against memory usage.  Optimization without measurement has been shown again and again to be poor practice.
Collect metrics about the performance of your application.  Then decide how to address the slow spots.  Caching may be the least of  your worries.


q: When we add a variable to ASP.NET Session, where are those variables actually stored on the client side?

[A]
If you are using the default session in ASP.NET then it is stored in memory inside the ASP.NET worker process. It is a server side cache, nothing at all to do with the client.
There are other session store options available such as dedicated session state machine or sql server. You can also roll your own session provider.
All explained here
http://msdn.microsoft.com/en-us/library/ms972429.aspx


q: What would be the disadvantages (if any) of automating business process for a Enterprise/organization?

[A]
Loosing discretionary error checking, i.e. numbers that look out of line;
Potentially, knowledge of how a process is operated could be lost if it is automated but not documented. More often than not, manual processes are passed on;
Accountability for the process becomes muddled.


q:
Why should I choose to use one instead of the other and in which cases?

I mainly focus on desktop applications and personally speaking I do find the humble dialog box more easy and natural to use.

[A]
In MVC, you would still use your "humble" dialog. Except all the business logic for it would be farmed off to another class somewhere else.
http://en.wikipedia.org/wiki/Model-view-controller
You need to weight up whether the investment in MVC will be worth it - especially if you're only working with a single simple dialog.


q:
As title, I need that to run an import script generated by SQL Server DB Publishing Tool. Would that work on Sql2000 server too? Also I have seen ppl reporting missing library issues related to GAC, which libraries I precisely need to include if I am not controlling the deployment server?

To know how this thing works you can check here in MSDN Forum.
http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3947420&SiteID=1

I tested and indeed it works in my devbox with SQL2005 Express installed.

[A]
Yes, SMO works on SQL Server 2000:
SMO and Sql Server 7.0


q:
<div style="width: 300px">
<div id="one" style="float: left">saved</div><input type="submit" id="two" style="float: right" value="Submit" />
</div>

I would like div#one to be centred in the space between the left edge of the parent div and the left edge of the submit button.

[A]
There are a number of techniques listed
here
However, if you simply wanted the "saved" text to be centred, I think you'll need to give a width to #one, e.g.
```
```

saved

<input type="submit" id="two" style="float: right;width:20%" value="Submit" />

```
```