Question:
I am currently validating a client's HTML Source and I am getting a lot of validation errors for images and input files which do not have the Omittag. I would do it manually but this client literally has thousands of files, with a lot of instances where the  is not .

This client has validated some img tags (for whatever reason).

Just wondering if there is a unix command I could run to check to see if the  does not have a Omittag to add it.

I have done simple search and replaces with the following command:

find . \! -path '*.svn*' -type f -exec sed -i -n '1h;1!H;${;g;s/<b>/<strong>/g;p}' {} \;

But never something this large. Any help would be appreciated.

Answer:
Try this. It'll go through your files, make a
```
.orig
```
backup of each file (perl's
```
-i
```
operator), and replace
```
<img>
```
and
```
<input>
```
tags with
```
<img />
```
and
```
<input >
```
.
```
```
find . \! -path '*.svn*' -type f -exec perl -pi.orig -e 's{ ( <(?:img|input)\b ([^>]*?) ) \ ?/?> }{$1\ />}sgxi' {} \;
```
```
Given input:
```
```

<input>  <input/>  <input id="..">  <input id="" >
```
```
It changes the file to:
```
```

<input />  <input />  <input id=".." />  <input id="" />
```
```
Here's what the regexp is doing:
```
```
s{(<(?:img|input)\b ([^>]*?)) # capture "<img" or "<input" followed by non-">" chars
  \ ?/?>}                     # optional space, optional slash, followed by ">"
{$1\ />}sgxi                  # replace with: captured text, plus " />"
```
```


Question:
I am using WCF to upload data to a server.

If the communication fails, is there any way to resume the upload?

Answer:
You will probably have to do some level of sanitisation. For example, the
perlre
man page describes the following construct:
```
```
(?{ code })
```
```
which allows executable code inside a pattern match.


Question:
How is Silverlight going to change the internet in the next 10 years?

Is this going to be a scene changer or just another blip?

Answer:
It will be another blip.  It's not seriously cross-platform, unlike Flash or any of its other competition, and no one seems particularly interested in it.  It might be neat and shiny but I haven't seen any real reason to move past playing around with it.
Put another way, it's a cool toy but not much else.


Question:
How is profiling different from logging?

Is it just that profiling is used for performance measurements to see how long each function takes?  Or am I off?

Typically, how are profiling libraries used?

What types of stats are obtained by profiling?

Answer:
I see profiling as performance measurement, and you don't have to profile every piece of code running, it's sometimes better to target specific areas.
Logging is storing information for later use, information which may relate to profiling but not necessarily.  It may just be to log what happened.
All the profiling stuff I've ever used basically allows you to store a start time and end time for a 'transaction' and later manipulate the data to see what's taking the most time.


Question:
I understand object oriented programming, and have been writing OO programs for a long time.  People seem to talk about aspect-oriented programming, but I've never really learned what it is or how to use it.  What is the basic paradigm?

This question is related, but doesn't quite ask it:

Aspect-Oriented Programming vs. Object Oriented Programming

Answer:
AOP addresses the problem of
cross-cutting concerns
, which would be any kind of code that is repeated in different methods and can't normally be completely refactored into its own module, like with logging or verification. So, with AOP you can leave that stuff out of the main code and define it vertically like so:
```
```
function mainProgram()
{
   var x =  foo();
   doSomethingWith(x);
   return x;
}

aspect logging
{
    before (mainProgram is called):
    {
       log.Write("entering mainProgram");
    }

    after (mainProgram is called):
    {
       log.Write(  "exiting mainProgram with return value of "
                  + mainProgram.returnValue);
    }
 }

aspect verification
{
    before (doSomethingWith is called):
    {
       if (doSomethingWith.arguments[0] == null)
       {
          throw NullArgumentException();
       }

       if (!doSomethingWith.caller.isAuthenticated)
       {
          throw Securityexception();
       }
    }
 }
```
```
And then an
aspect-weaver
is used to compile the code into this:
```
```
function mainProgram()
{
   log.Write("entering mainProgram");

   var x = foo();

   if (x == null) throw NullArgumentException();
   if (!mainProgramIsAuthenticated()) throw Securityexception();
   doSomethingWith(x);

   log.Write("exiting mainProgram with return value of "+ x);
   return x;
}
```
```


Question: I have a page with a "Print" link that takes the user to a printer-friendly page.  The client wants a print dialog box to appear automatically when the user arrives at the print-friendly page.  How can I do this with javascript?

Answer:
```
```
window.print();
```
```
unless you mean a custom looking popup.


Question:
I required to write a small web application that allow customer to select predefined layout template in html and be able to modify it. The application need to allow customer to add block text to pre defined area and images. The block texts need to be able to reorder based on customer need. eg. move up , move down or move to sidebar. THe complete layout will be able to convert to table layout and inline css due to email program doesn't like div & css. I don't know where should I looking for the information to make this happen, could anyone show me how to do this.

Thank you

Answer:
I'm not sure why someone downvoted you, but check out a javascript framework like
script.aculo.us
or
Yahoo's YUI
Those will go a long way towards creating the interface you need.  Also they have a lot of examples.
The Yahoo framework has an inplace html editor (I think that is what you are asking for).  Another editing is the
fckeditor
.


Question:
I always hear that programmers try to pick the right tool for the job.  I've never programmed in Java, so I was wondering What are its benefits?  Why is it so popular?  What should I use it for?

I just program recreationally.  Is there anything about it that makes it particularly fun??

Answer:
Cross platform is in my opinion the most relevant benefit.
The main goal of Java was to create a programming language that could run anywhere. The target was GUI apps. This however never happen because the environment was too slow at the beginning ( now it has been improved )  but it prove true in the server side where the cost of development reduced a lot because the product development can be done in PCs and the deployment in very expensive hardware.
It brought easy of development also, because it was designed to have C++ like syntax but running on a virtual platform to avoid platform specific code.  At first the penalty was the execution speed, because it was interpreted, but release after release the interpreters became more and more faster that even MS model its next generation of development after java and call it .net
Additionally
You can have a read of the Java design goals
here


Question:
I am digging into LINQ--trying to understand basic models (it seems pretty cool to me). The code below is the code to perform before committing an update.

   Linq01.Account acc = context.Accounts.Single( pc => pc.AccountID == AccountID );
   acc.Name = textboxAccountNameRead.Text.Trim();
   context.SubmitChanges();

So far, so good. But what do you do if the Single() method failed--if the account ID wasn't found?

Thank you!

Answer:
You should use
```
SingleOrDefault
```
, if the query does not return a value you can check it against null:
```
```
var acc = context.Accounts.SingleOrDefault(pc => pc.AccountId == AccountId);
if(acc != null)
{
  acc.Name = textboxAccountNameRead.Text.Trim();
  context.SubmitChanges();
}
```
```


Question:
While surfing, I came to know that somebody has done Tower of Hanoi using vim. WOW!!!

Can you people share what all cool things you have been doing in vim.

Edit: Not sure about the Tower of Hanoi solution using vim being all that useful. But I think this question should be re-opened to allow people to comment on any useful things that they've done using vim. For me? See my answer below. (-:

Answer:
I was working on a system that had massive log files. We're talking 30,000 10MB logs.
Per day!
Distinguishing between log messages that were coming from the middleware (same company but custom rolled) and our application was getting tedious.
That is until I wrote some custom vim syntax parsing so that anything vim displayed in green was from the middleware (done by the guys in Sophia Antipolis near Cannes) as opposed to anything vim displayed in blue that was from our application software that sat over the top of the SA code.
I also added highlighting to really make exceptions stand out with white lettering on a read background!
Made life so much easier! And it wasn't that hard to do!
Thanks vim!


Question:
I'm running Windows Server 2008 64-bit "workstation" and would like to get corflags.exe. Which SDK do I need to download?

I know about .NET Framework 2.0 Software Development Kit (SDK) (x64) and Windows SDK for Windows Server 2008 and .NET Framework 3.5 but I was hoping to find something smaller as these are quite large downloads.

Also the note about 2.0 SDK seems to suggest to download the 3.5 one, should I follow that?

Answer:
If you install the .NET framework (you should already have it), it'll be at C:\Program Files (x86)\Microsoft.NET\SDK\v2.0\Bin\corflags.exe
Come to think of it, you may need to install
the Microsoft .NET 2.0 SDK from
.NET Framework 2.0 Software Development Kit (SDK) (x64)
-- check for that file first.


Question: Visual Studio 2005 is very slow with a solution with 21 projects.  Any ideas how to speed it up?

Answer:
a) Buy more memory
b) Break up into different solutions
c) Upgrade to VS 2008
d)
Link


Question:
Is there a way to bind a Generic List to a multicolumn listbox, yes listbox...I know but this is what I am stuck with and can't add a grid or listview.

Thanks

Answer:
You could bind a list to a listbox like this:
```
```
List<int> list = new List<int> { 1, 2, 4, 8, 16 };
listBox1.DataSource = list;
```
```
As for multicolumn listbox documentation says
ListBox.MultiColumn
only places items into as many columns as are needed to make vertical scrolling unnecessary.
If you want to show several columns of information for which an entire row will get selected you could use
Multi Column List Box
by Chris Rickard.


Question:
I want this page to return 200 whilst still sending the redirect...

<script>
    sub page_load
        'Get the parameters
         dim content As String
         content = request.querystring("text")
         response.redirect ("http://100.200.100.10/test1/Default.aspx?CommandParm=" + content)
    end sub
</script>
<html>
    <head>
    </head>
    <body>
        <form runat="server">
        </form>
    </body>
</html>

Answer:
No way with
```
Response.Redirect()
```
. I... think. Maybe setting
```
Response.Status = "200 OK"
```
after calling
```
Redirect()
```
works, I've never tried.
You could fake it by setting the "Location" header manually in an otherwise empty response. Not sure what that is good for, though. ;-)
```
```
Response.AddHeader("Location", "http://100.200.100.10/test1/Default.aspx?CommandParm=" + content)
Response.End()
```
```
(And, for the record: You would be producing an invalid HTTP header constellation. Should not break anything, but still.)


Question:
I want create a drop shadow around the canvas component in flex. Technically speaking it will not be a shadow, as I want it to wrap around the component giving the component a floating look. I may be able to do it with glow, but can anyone drop an line or two who has already done it?

Thanks in advance.

Answer:
I actually solved it by doing this:
```
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml"
        width="780" height="100%" borderStyle="solid" borderColor="gray"
            creationComplete="init();" backgroundColor="white">

  <mx:Script>
        <![CDATA[
            import mx.styles.StyleManager;

            private function init():void {
                var glow:GlowFilter = new GlowFilter();
                glow.color = StyleManager.getColorName("gray");
                glow.alpha = 0.8;
                glow.blurX = 4;
                glow.blurY = 4;
                glow.strength = 6;
                glow.quality = BitmapFilterQuality.HIGH;

                this.filters = [glow];
            }
        ]]>
    </mx:Script>

</mx:Canvas>
```
```


Question:
I am developing iPhone application and In that application I've one TableViewController,
and that TableViewController made up of Custom table cell.

into those cell I am loading image from URL, but the scrolling is not that smooth, (because each cell load images every time when scrolling happen).

So I decided to store those images into application document folder, but I don't know how to use document folder in iPhone when application is in running state.

Any suggestion?

And on other forums I found that SQLITE has blob datatype to store binary data,

Which method is efficient, document folder or sqlite to store image?

Answer:
You could use
```
NSFileManager
```
's
```
createFileAtPath
```
to save any
```
NSData
```
into a file.
To get the Documents directory, use this:
```
```
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
```
```


Question:
I want to autowire a bean partially - that is, I want some args to be autowired but other to be explicitly set. For example:

public MyClient(Service svc, boolean b)

In the case of this constructor, I would like to specify in my xml the value for b, but have svc autowired. Is that possible?

Thanks,
Lowell

Answer:
I don't think it is possible with constructors, but with explicit setters it certainly is. Just annotate the ones you want autowired with @Autowired, and set the others in your config-file
Something like:
```
```
public MyClient() {}

@Autowired
public setService (Service svc) {...}

public setBoolean (boolean b) {...}
```
```
and then in your config
```
```
<context:annotation-config />

<bean id="service">...</bean>

<bean id="yourbean" class="MyClient">
    <property name="b" value="true"/>
</bean>
```
```


Question:
I have the following classes

public interface InterfaceBase
{
}

public class ImplementA:InterfaceBase
{
}

public class ImplementB:InterfaceBase
{
}

public void TestImplementType<T>(T obj) where T: InterfaceBase
{
}

How to infer what the T is whether ImplementA or ImplementB? I tried to use

typeof(T) is ImplementA

but this expression is always evaluated to false.

Edit: And how am I going to cast obj to ImplementA or ImplementB?

Answer:
```
obj is ImplementA
```


Question:
I have two lists that are of the same length, is it possible to loop through these two lists at once?

I am looking for the correct syntax to do the below

foreach itemA, itemB in ListA, ListB
{
  Console.WriteLine(itemA.ToString()+","+itemB.ToString());
}

do you think this is possible in C#? And if it is, what is the lambda expression equivalent of this?

Answer:
[edit]: to clarify; this is useful in the generic LINQ /
```
IEnumerable<T>
```
context, where you
can't use
an indexer, because a: it doesn't exist on an enumerable, and b: you can't guarantee that you can read the data more than once. Since the OP mentions lambdas, it occurs that LINQ might not be too far away (and yes, I do realise that LINQ and lambdas are not quite the same thing).
It sounds like you need the missing
```
Zip
```
operator; you can spoof it:
```
```
static void Main()
{
    int[] left = { 1, 2, 3, 4, 5 };
    string[] right = { "abc", "def", "ghi", "jkl", "mno" };

    // using KeyValuePair<,> approach
    foreach (var item in left.Zip(right))
    {
        Console.WriteLine("{0}/{1}", item.Key, item.Value);
    }

    // using projection approach
    foreach (string item in left.Zip(right,
        (x,y) => string.Format("{0}/{1}", x, y)))
    {
        Console.WriteLine(item);
    }
}

// library code; written once and stuffed away in a util assembly...

// returns each pais as a KeyValuePair<,>
static IEnumerable<KeyValuePair<TLeft,TRight>> Zip<TLeft, TRight>(
    this IEnumerable<TLeft> left, IEnumerable<TRight> right)
{
    return Zip(left, right, (x, y) => new KeyValuePair<TLeft, TRight>(x, y));
}

// accepts a projection from the caller for each pair
static IEnumerable<TResult> Zip<TLeft, TRight, TResult>(
    this IEnumerable<TLeft> left, IEnumerable<TRight> right,
    Func<TLeft, TRight, TResult> selector)
{
    using(IEnumerator<TLeft> leftE = left.GetEnumerator())
    using (IEnumerator<TRight> rightE = right.GetEnumerator())
    {
        while (leftE.MoveNext() && rightE.MoveNext())
        {
            yield return selector(leftE.Current, rightE.Current);
        }
    }
}
```
```


Question:
I know how to move a layer based on touch. But I would also like to be able to rotate the image.

Is there any sample code that shows how to do this? Or can anyone give me some advice?

Thanks!

Answer:
You would use the view's transform property.
There's some example code for rotating the view in the iPhone OS Programming Guide, under
Launching in Landscape Mode


Question:
I am trying to compare two decimal values in Java script. I have two objects as  one assogned value "3" and the other as "3.00". When i say if (obj1 == obj2) it does not pass the condition as it is does the string comparision.

I would instead want it to do a decimal comparision where 3 = 3.00. Please let me know how to do this.

Answer:
This page
describes how to convert a string to a floating-point number; I believe that is what you want. This would let you compare the numbers as numbers, which I think is what you mean by "decimally". Beware that doing an exact comparison between two floating-point numbers is often considered a bit "hazardous", since there are precision issues that might cause two numbers that you would consider "equal" to not compare as such. See, for instance,
What Every Computer Scientist Should Know About Floating-Point Arithmetic
, which is a classic text on the topic. Perhaps a bit on the advanced side, but try searching for something more basic in that case.


Question: This is a question I have wondered about for quite some time, yet I have never found a suitable solution. If I run a script and I come across, let's say an IndexError, python prints the line, location and quick description of the error and exits. Is it possible to automatically start pdb when an error is encountered? I am not against having an extra import statement at the top of the file, nor a few extra lines of code.

Answer:
This isn't the debugger, but probably just as useful(?)
I know I heard Guido mention this in a speech somewhere.
I just checked python -?, and if you use the -i command you can interact where your script stopped.
So given this script:
```
```
testlist = [1,2,3,4,5, 0]

prev_i = None
for i in testlist:
    if not prev_i:
        prev_i = i
    else:
        result = prev_i/i
```
```
You can get this output!
```
```
PS D:\> python -i debugtest.py
Traceback (most recent call last):
  File "debugtest.py", line 10, in <module>
    result = prev_i/i
ZeroDivisionError: integer division or modulo by zero
>>>
>>>
>>> prev_i
1
>>> i
0
>>>
```
```
To be honest I haven't used this, but I should be, seems very useful.


Question: How can I generate a report in access with the data from a recordset (instead of a query or table). I have updates to the recordset that also must be shown in the report.

Answer:
Please explain in more detail. For example, do you wish to show what the field was and what it is now? If so, you will need an audit trail. Here is an example from Microsoft:
http://support.microsoft.com/kb/q197592/
What do you mean by report? If you mean a printed paper document, Access has a good report builder. If you mean you wish to view the data, you can use a form. If you are unfamilar with building reports and forms, there are wizards.
It is always wise to study the Northwind sample database that ships with every version of Access.


Question:
private const int THE_ANSWER = 42;

or

private const int theAnswer = 42;

Personally I think with modern IDEs we should go with camelCase as ALL_CAPS looks strange. What do you think?

Answer:
Leave Hungarian to the Hungarians.
In the example I'd even leave out the definitive article and just go with
```
```
private const int Answer = 42;
```
```
Is that answer or is that the answer?
*Made edit as Pascal strictly correct, however I was thinking the question was seeking more of an answer to
life, the universe and everything
.


Question:
I have MainViewController calling WebViewController (From UICatalog sample application)
In WebViewController I make some function setValue(){...} to set some value passed as parameter to the variable (NSString *value) from WebViewController.h but when I try from MainViewController something like WebViewController targetViewController...
targetViewController.setValue(value), it says: "error: request for member 'setValue' in something not s structure or union"...

Answer:
If you have a property named "value", and use @sythesize to create a method for you, in which case you call using that "." notation:
```
```
targetViewController.value = whatever;
```
```
Or you can call the setter outright regardless of you or the @synthesize writing the method:
```
```
[targetViewController setValue:whatever];
```
```
The property syntax (class.property = whatever) is really just a shortcut of calling a "setValue:" method, and in return the @property and @synthesize mechanisms of properties are just writing a helpful bit of code for you.
Edit:  I had said before if you just wrote a "setValue:" method you could call it using the "class.value = newValue" notation, but that was incorrect - you have to define an @property to use "." notation.


Question:
I have a long URL with tons of parameters that I want to open in the default browser from Java on a Windows system using

Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler "+url)

For short URLs like "http://www.google.com" this works fine. But for long URLs (say, 2000 characters), this simply does absolutely nothing at all: no exception or anything of the sort, it is simply ignored.

Is there a character limit a) for a Runtime.exec command or b) for the rundll32 url.dll command? If so, what is the limit?

Answer:
You will be running up against
this (archived)
operating system/browser specific maximum URL length problem:
For "rundll32 url.dll" (i.e. Microsoft IE) you will be limited to 2,083 characters (including http://).
From where I sit you have two alternatives:
Build (or use) a TinyURL-style service
that turns your long-urls into
short, redirected ones. However even
here you are going to run into the
same URL length issue, just within
the browser itself rather than your
Runtime() statement. e.g. The browser window would open, go to the short-URL which would perform the redirect to the long-URL and fail.
Use a POST request and bury some or
all of your URL parameters within
it. Rather than using a GET call you
can supply very long parameters
within the body of an HTTP POST request. This
would not be as simple as your example code. In fact this maybe quite tricky (or impossible) with the rundll32 url.dll combination (I am not familiar with it)...


Question: How can I draw a 2D rubber band rectangle in DirectX? Preferable using C#.

Answer:
The classic way to do rubberbanding is to:
Draw the regular scene, i.e. the "background"
Switch to "XOR mode", where your pen will XOR the pixels already in the framebuffer. It is important that the mode here is XOR, since XOR is losslessly "revertable", unlike for instance an add operation.
While "rubberbanding":
Draw the rubberband rectangle in its current coordinates
On the next frame, draw the rectangle again, still using XOR, using its previous coordinates. This removes the rectangle, leaving the framebuffer intact.
Update the rectangle's coordinates
Details on how to do this "with DirectX" are a bit harder ... I believe DirectDraw, the "old school" way of doing 2D in DirectX is obsolete, so I guess you must be using Direct3D. Unfortunately I'm not sure on the details, there. It might be that you're out of luck with finding pre-defined functionality to do XOR drawing, and need to roll your own. Hopefully someone can provide better details on that. Apologies if you were already up to speed on the rubberbanding theory itself.


Question:
This is probably a simple question but how can I best use an AJAX loader in ASP.NET to provide a loading dialog whilst the page is being built?

I currently have an UpdatePanel with an associated UpdateProgressPanel which contains the loading message and gif in a ProgressTemplate.

Currently I have a page that onLoad() goes and gets the business entities and then displays them. While it is doing this I would like to display an AJAX loader.

Would it be better to have nothing in the page load and have a hidden button that is triggered onLoadComplete or unLoad() which would then wait for the button click method to complete displaying the UpdateProgressPanel?

Answer:
You can do it in HTML outside of .Net.  In your ASPX page you have code like:
```
<div id="loading">
<!-- Animated GIF or other indication that stuff is happening -->
</div>
```
At the very bottom of your page, right before the  you can have a code snippet that looks like this:
```
<script language="javascript">
document.getElementById("loading").style.display = "none";
</script>
```
The graphic--- as long as it's at the top of the page--- will render first.  Then all of your onLoad stuff will happen, and finally the inline JavaScript will happen last since it's at the bottom of the page.
A lot of times I'll disable the buttons in their unloaded state and enable them in that bottom JavaScript too.  That prevents the user from getting click happy and triggering events before the page is ready.


Question: Is it possible to make a POST request from Ruby with open-uri?

Answer:
Unfortunately
```
open-uri
```
only supports the
```
GET
```
verb.
You can either drop down a level and use
```
net/http
```
, or use
```
rest-open-uri
```
, which was designed to support
```
POST
```
and other verbs. You can do
```
gem install rest-open-uri
```
to install it.


Question: Is it possible to disable the browsers vertical and horizontal scrollbars using jQuery or javascript?

Answer:
Try CSS
```
```
<body style="overflow: hidden">
```
```


Question:
A classic ASP.NET app - AppSrv + MS SQL DB. Both servers are heavy-lifters 8 cores, 20 GB of RAM. When load testing, the throughput goes somewhere to 400 VirtualUsers (according to LoadRunner) with CPU being approximately 30% utilized an DB server primarily idling - response times go dramatically up, to the point of unresponsive.

The usual suspects, such as Max Pool being exhausted and conn limit on ASP.NET set are not at fault: Max Pool is set to 200 and about 80 conns are used; conn limit is set to 0.

I ran with ANTS profiler the code and it showed that Thread blocking did not contribute significantly.

Ideas very very welcome!

Answer:
Does the host utilize App Pool?
Did you try increase the number to 5 to 10 in
```
```
An Application Pool -> Performance ->
Web Garden -> Max Number of worker processes
```
```


Question: When I launch perfmon and try to add a counter, the displayed performance objects are all numbers. How can I reset these Performance objects?

Answer:
What do you mean my "reset"? What's the behavior you're expecting?
The perfmon "System Monitor" view shows the (near) real time value of the counter. Since these measurements are always being taken there will (almost) always be a number there.
If you want to be able to control the collection of these measurements, you need to create a Counter Log. Additionally, you can use the logman command to manage the log from the command line or a script.


Question:
today1 = new Date();
today2 = Date.parse("2008-28-10");

To compare the time (millisecond) values of these I have to do the following, because today2 is just a number.

if (today1.getTime() == today2)

Why is this?

Answer:
If I remember correctly, Date gives you a value down to the millisecond you created the Date object. So unless this code runs exactly on 2008-28-10 at 00:00:00:000, they won't be the same.
Just an addition: Date.parse() by definition returns a long value representing the millisecond value of the Date, and not the Date object itself. If you want to hold the Date object itself, just build it like so:
```
```
var newDate = new Date();
newDate.setFullYear(2008,9,28);
```
```
For more reference check out:
the Date class reference


Question:
Whilst investigating a memory leak I discovered that it was caused by calling NewRow() on a Table inside a loop many times. However the DataRow created was never added to the Table Rows collection and the Table Rows Count never got above zero.

My question is why does this use up more memory every time NewRow is called even though the newly created DataRow never gets added to the Rows collection and the DataRow returned from NewRow is always assigned to the same local variable (thereby apparently discarding the last new row).

Please ignore the issue of why the code is creating DataRows that don't get added to the table!

Answer:
I think your two issues are related.
Table.NewRow creates a new data row that has the same column format as the initial Table.
This new row needs to be added to the table using table.Rows.Add(newRow). Your loop will be creating objects that are never used and hence will eat up memory.
See this article for more information
http://msdn.microsoft.com/en-us/library/system.data.datatable.newrow.aspx


Question:
Omitting details of methods to calculate primes, and methods of factorisation.

Why bother to factorise ?

What are its applications ?

Answer:
Wow, so much fighting in this thread.
Ironically, this question HAS a major valid answer.
Factorization is actually used heavily in encryption/decryption algorithms, so much so that the RSA regularly conducts competitions wherein the task is to factorize certain large numbers that are multiples of very large prime numbers.
This is, in turn, because several encryption/decryption algorithms are based on the premise that factorization takes a very long time, which (supposedly) makes it difficult and/or impractical to crack certain encryption/decryption algorithms given the assumption that the hacker/cracker does not have access to public/private keys.
Factorization algorithms can then be used to verify just how strong any given encryption/decryption algorithm is.


Question:
I have one aspx page with some controls.
Also i have one DIV which is dynamically populated from AJAX call.
This AJAX call return couple of controls, for example HtmlInputText1 and HtmlInputText2.

When page is submitted, I can get values from this controls through Request.Form.
If possible access to the attributes of this control on pege code behind (for example HtmlInputText1.Height, etc).

I think that is impossible, but I am not sure.
I can use hidden field. Is any other way?

Answer:
The data you want the server to know can be set by the javascript within the form.
Then You can process postback data for the target values manually.
You can write some javascript which modify the value of the server control within browser.
```
```
<script language="javascript" type="text/javascript">
function changeValue() {
    var txtControlClient = document.getElementById('<%= txtControl.ClientID %>');
    txtControlClient.value = "modified text";
}
</script>
```
```
In the expected event, you call changeValue() function before the postback, then you can just use server control object txtControl to obtain the value or property you have altered.


Question:
Do you have any examples of real life applications of mutation testing? Does it work better than simple test coverage tools? Or is it useless?

What are the advantages/disadvantages of mutation testing in the real world?

Answer:
I looked at mutation test some time ago as a method for checking the efficacy of my automated regression testing scripts.  Basically, a number of these scripts had missing checkpoints, so while they were exercising the application being tested correctly, they weren't verifying the results against the baseline data.  I found that a far simpler method than changing the code was to write another application to introduce modifications to a copy of the baseline, and re-run the tests against the modified baseline.  In this scenario, any test that passed was either faulty or incomplete.
This is not genuine mutation testing, but a method that uses a similar paradigm to test the efficacy of test scripts.  It is simple enough to implement, and IMO does a good job.


Question:
I need to implement a SSO between a SharePoint site and a custom PHP-based site which resides on a different domain. I need to use the SharePoint user accounts to log in the PHP site. (I'll have a full control over the PHP source)

Is this possible? Any tips and tricks?

Answer:
I don't know much about this area but hopefully this might help point you in the right direction.
Investigate LDAP...
You can set up PHP to use LDAP credentials. If your SharePoint site uses Active Directory, then you can expose this directory as an LDAP source and use that in the PHP application.
Automated sign-in...
Having the sign in happen automatically between each site is a very different matter. e.g. I'm logged into MOSS already, click on a link that goes to the PHP app and find that I'm already logged in there as well. For this you will need to investigate using something like Kerberos keys/authentication. It's a messy and difficult area.


Question:
I am trying to write a replacement regular expression to surround all words in quotes except the words AND, OR and NOT.

I have tried the following for the match part of the expression:

(?i)(?<word>[a-z0-9]+)(?<!and|not|or)

and

(?i)(?<word>[a-z0-9]+)(?!and|not|or)

but neither work. The replacement expression is simple and currently surrounds all words.

"${word}"

So

This and This not That

becomes

"This" and "This" not "That"

Answer:
This is a little dirty, but it works:
```
```
(?<!\b(?:and| or|not))\b(?!(?:and|or|not)\b)
```
```
In plain English, this matches any word boundary not preceded by and not followed by "and", "or", or "not". It matches whole words only, e.g. the position after the word "sand" would not be a match just because it is preceded by "and".
The space in front of the "or" in the zero-width look-behind assertion is necessary to make it a fixed length look-behind. Try if that already solves your problem.
EDIT: Applied to the string "except the words AND, OR and NOT." as a global replace with single quotes, this returns:
```
```
'except' 'the' 'words' AND, OR and NOT.
```
```


Question:
Which SQL statement is faster?

SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price
FROM Table1 AS c1, Table2 AS c2, ..... Table49 AS c49, Table50 AS c50
WHERE c1.Date = c2.Date AND c2.Date = c3.Date ..... c49.Date = c50.Date
ORDER BY c1.ID DESC

        OR

SELECT TOP 2 c1.Price, c2.Price, ..... c49.Price, c50.Price
FROM (Table1 AS c1
 INNER JOIN (Table2 AS c2
    ........
  INNER JOIN (Table49 AS c49
   INNER JOIN Table50 AS c50
  ON c49.Date = c50.Date)
    ........
 ON c2.FullDate__ = c3.FullDate__)
ON c1.FullDate__ = c2.FullDate__)
ORDER BY c1.ID DESC";

Basically I need to extract 2 rows from each table to produce a summary periodically.
Which statement is faster?

Answer:
WHERE would usually be better but the best way is
case by case
and throw this into profiler, or simpler yet
display execution plan
.  Folk often have very strong opinions on which approach is fastest/best in theory but there is no replacement for actually tuning according to the data you actually deal with as theories applicable change depending on your data load.
If you do not have
real data
in your app yet, try and create some realistic stress data.  This will continue to be useful for testing.  Then schedule time to tune once the application is live.


Question:
I think this must be simple but I can't get it right...

I have an MxM triangular matrix, the coefficients of which are stored in a vector, row by row.
For example:

M =   [ m00 m01 m02 m03 ]
      [     m11 m12 m13 ]
      [         m22 m23 ]
      [             m33 ]

is stored as

coef[ m00 m01 m02 m03 m11 m12 m13 m22 m23 m33 ]

Now I'm looking for a non-recursive algorithm that gives me for matrix size M and coefficient array index i

unsigned int row_index(i,M)

and

unsigned int column_index(i,M)

of the matrix element that it refers to. So,
row_index(9,4) == 3, column_index(7,4) == 2 etc. if the index counting is zero-based.

EDIT: Several replies using an iteration have been given. Does anyone know of algebraic expressions?

Answer:
Took me some time to understand what you needed! :)
```
```
unsigned int row_index(int i, int m)
{
    int iCurrentRow = 0;
    int iTotalItems = 0;
    for(int j = m; j > 0; j--)
    {
        iTotalItems += j;

        if( (i+1) <= iTotalItems)
            return iCurrentRow;

        iCurrentRow ++;
    }

    return -1; // Not checking if "i" can be in a MxM matrix.
}
```
```
Sorry forgot the other function.....
```
```
unsigned int column_index(int i, int m)
{
    int iTotalItems = 0;
    for(int j = m; j > 0; j--)
    {
        iTotalItems += j;

        if( (i+1) <= iTotalItems)
            return m - (iTotalItems - i);
    }

    return -1; // Not checking if "i" can be in a MxM matrix.
}
```
```


Question:
My client wants to send email announcements and reports for customers. Now. The python-side code doesn't seem too hard but there's the rest of the story.

What do I require in order to send such emails that won't end up getting blocked by email servers and clients?

Answer:
There's no sure fire way, as email filters can do as they wish, but a few recommendations:
Use a real SMTP server, usually your client's (Authenticating if needs be). By real I mean one that's in real usage not a special one to send your emails only.
Send from a real account able to receive responses.
Avoid HTML if possible, if not possible, send a
multipart message
.
Send all mandatory headers plus some headers usually sent by common MUAs.
Generally, check the common spam
detection rules
to get a feel what's common in spam mails.


Question:
How do you split a string?

Lets say i have a string "dog, cat, mouse,bird"

My actual goal is to insert each of those animals into a listBox, so they would become items in a list box.

but i think i get the idea on how to insert those items if i know how to split the string. or does anyone know a better way to do this?

im using asp c#

Answer:
```
```
string[] tokens = text.Split(',');

    for (int i = 0; i < tokens.Length; i++)
    {
          yourListBox.Add(new ListItem(token[i], token[i]));
    }
```
```


Question:
Recently developers highlighted that it is bit hard for them to keep track of which document has been updated. And they thus suggested that using SVN to keep track of document changes will be better as they will be able to know if document if being updated when doing checking out of the project.

But i also highlighted the several cons that may occur

Binary file using up alot of diskspace everytime word, excel document is commited

Checkout a project will take much more time although we can separate the documents into another project in the repository

It will take time to teach personnel on how to use SVN.

Another feature is that for these kind of functional documents, it should be locked while editing.

Anyone have any idea on how to go about it? Or what are the pros and cons to it. Please feel free to share with me.

Answer:
We use Subversion for document management at work. It works great.
Don't worry about the disk space. Revisions are stored compressed anyway.
Checking out a project with documentation doesn't take much more time than one without. Unless your documents are absolutely huge, this shouldn't be a problem.
Training time is a consideration. Fortunately, TortoiseSVN makes this easy.
To manage Word documents so they can only be edited by one person at a time, use the
```
svn:needs-lock
```
property. This will make the files appear as read-only on a normal checkout, and read-write when a developer has locked them for editing. After commit, the file will be unlocked and read-only again.
An additional benefit of TortoiseSVN is that it can do diffs of Word documents and present the differences in Word itself. This alone is a killer feature for me.


Question:
When I add the textBox.TextChanged to watch list I get a message saying
The event 'System.Windows.Forms.Control.TextChanged'
can only appear on the left hand side of += or -=

Is there any way to check what event's are called on text change?

Answer:
We use Subversion for document management at work. It works great.
Don't worry about the disk space. Revisions are stored compressed anyway.
Checking out a project with documentation doesn't take much more time than one without. Unless your documents are absolutely huge, this shouldn't be a problem.
Training time is a consideration. Fortunately, TortoiseSVN makes this easy.
To manage Word documents so they can only be edited by one person at a time, use the
```
svn:needs-lock
```
property. This will make the files appear as read-only on a normal checkout, and read-write when a developer has locked them for editing. After commit, the file will be unlocked and read-only again.
An additional benefit of TortoiseSVN is that it can do diffs of Word documents and present the differences in Word itself. This alone is a killer feature for me.


Question:
My account is in the securityadmin role and I cannot grant myself sysadmin permission. I wish to gain access to a database so I can add my account to a particular role within it.

As I don't yet have access to the database I can't use the UI.

Does anyone know if this is possible and what SQL commands will achieve this in SQL Server 2005?
Thanks!

Answer:
The
sysadmin role
, as the name implies, can do anything within SQL Server. It has complete rights over the SQL Server. It is the only role that can add others to the sysadmin role. There isn’t anything within SQL Server a sysadmin role member can’t do.
You could use the system stored procedure
add_srvrolemember
to assign users to this role.
Example:
```
```
EXEC sp_addsrvrolemember 'BUILTIN\Administrators', 'sysadmin'
```
```


Question:
There is div named "dvUsers". there is an anchor tag "lnkUsers".

When one clicks on anchortag, the div must open like a popup div just below it.

Also the divs relative position should be maintained at window resize and all.
How to do that using javascript/jquery?

Answer:
```
```
$(document).ready(function(){ $("#lnkUsers").click(function(){ $("#dvUser").show("slow"); });
```
```
style="display: none" should be applied to dvUser at the first place to make it invisible.


Question:
Recently I've been seeing a lot of this:

<a href='http://widget-site-example.com/example.html'>
    <img src='http://widget-site-example.com/ross.jpg' alt='Ross&#39;s Widget' />
</a>

Is it valid to use single quotes in HTML? As I've highlighted above it's also problematic because you have to escape apostrophes.

Answer:
It's certainly valid to use single quotes (
HTML 4.01, section 3.2.2
). I haven't noticed such a trend, but perhaps there's some framework that powers web sites you've visited that happens to quote using single quotes.


Question:
How can I create an Oracle stored procedure which accepts a variable number of parameter values used to feed a IN clause?

This is what I am trying to achieve. I do not know how to declare  in PLSQL for passing a variable list of primary keys of the rows I want to update.

FUNCTION EXECUTE_UPDATE
  ( <parameter_list>
   value IN int)
  RETURN  int IS
BEGIN
    [...other statements...]
    update table1 set col1 = col1 - value where id in (<parameter_list>)

    RETURN SQL%ROWCOUNT ;
END;

Also, I would like to call this procedure from C#, so it must be compatible with .NET capabilities.

Thanks,
Robert

Answer:
I've not done it for Oracle, but with SQL Server you can use a function to convert a CSV string into a table, which can then be used in an IN clause. It should be straight-forward to re-write this for Oracle (I think!)
```
```
CREATE Function dbo.CsvToInt ( @Array varchar(1000))
returns @IntTable table
    (IntValue nvarchar(100))
AS
begin

    declare @separator char(1)
    set @separator = ','

    declare @separator_position int
    declare @array_value varchar(1000)

    set @array = @array + ','

    while patindex('%,%' , @array) <> 0
    begin

      select @separator_position =  patindex('%,%' , @array)
      select @array_value = left(@array, @separator_position - 1)

        Insert @IntTable
        Values (Cast(@array_value as nvarchar))

      select @array = stuff(@array, 1, @separator_position, '')
    end

    return
end
```
```
Then you can pass in a CSV string (e.g. '0001,0002,0003') and do something like
```
```
UPDATE table1 SET
       col1 = col1 - value
WHERE id in (SELECT * FROM csvToInt(@myParam))
```
```


Question:
I need to write a regular expression that finds javascript files that match

<anypath><slash>js<slash><anything>.js

For example, it should work for both :

c:\mysite\js\common.js (Windows)

/var/www/mysite/js/common.js (UNIX)

The problem is that the file separator in Windows is not being properly escaped :

pattern = Pattern.compile(
     "^(.+?)" +
     File.separator +
     "js" +
     File.separator +
     "(.+?).js$" );

Throwing

java.util.regex.PatternSyntaxException: Illegal/unsupported escape sequence

Is there any way to use a common regular expression that works in both Windows and UNIX systems ?

Answer:
Does
```
Pattern.quote(File.separator)
```
do the trick?
EDIT: This is available as of Java 1.5 or later. For 1.4, you need to simply escape the file separator char:
```
```
"\\" + File.separator
```
```
Escaping punctuation characters will not break anything, but escaping letters or numbers unconditionally will either change them to their special meaning or lead to a
PatternSyntaxException
.
(Thanks
Alan M
for pointing this out in the comments!)


Question:
console.log("double"); vs. console.log('single');

I see more and more JavaScript libraries out there using single quotes when handling strings. What are the reasons to use one over the other?

I thought they're pretty much interchangeable.

Answer:
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.
Using the other type of quote as a literal:
```
```
alert('Say "Hello"');
alert("Say 'Hello'");
```
```
This can get complicated:
```
```
alert("It's \"game\" time.");
alert('It\'s "game" time.');
```
```
Another option, new in ECMAScript 6, is
template literals
which use the
backtick
character:
```
```
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
```
```
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
Note that
JSON
is formally specified to use double quotes, which may be worth considering depending on system requirements.


Question:
Why would someone use WHERE 1=1 AND <conditions> in a SQL clause (Either SQL obtained through concatenated strings, either view definition)

I've seen somewhere that this would be used to protect against SQL Injection, but it seems very weird.

If there is injection WHERE 1 = 1 AND injected OR 1=1 would have the same result as injected OR 1=1.

Later edit: What about the usage in a view definition?

Thank you for your answers.

Still,
I don't understand why would someone use this construction for defining a view, or use it inside a stored procedure.

Take this for example:

CREATE VIEW vTest AS
SELECT FROM Table WHERE 1=1 AND table.Field=Value

Answer:
If the list of conditions is not known at compile time and is instead built at run time, you don't have to worry about whether you have one or more than one condition. You can generate them all like:
```
```
and <condition>
```
```
and concatenate them all together. With the
```
1=1
```
at the start, the initial
```
and
```
has something to associate with.
I've never seen this used for any kind of injection protection, as you say it doesn't seem like it would help much. I
have
seen it used as an implementation convenience. The SQL query engine will end up ignoring the
```
1=1
```
so it should have no performance impact.


Question:
We are developing a new web service and are looking into the "best practice" for returning errors in the soap response.

We were looking into creating a error response object which every response would contain as a property.  This seems a little heavy however and are wondering if it is possible to use the SOAP header to carry this information?  How do you normally deal with custom errors using SOAP?

Answer:
Soap already uses custom headers for error info, all you need to do is throw an exception on the server side, and exception is raised on the client side as a
SoapException
.
You can thrown SoapExceptions on the serverside if you want more control over the exception message/info.
Edit:
For extra information along with the request, custom soap headers can be used. Here's an
example article on CodeProject
that used custom soap headers for authentication, but custom soap headers can be used for other purposes like sending extra info that is not necessarily an error condition (can be business logic info)


Question:
I know that there has been a couple questions about tutorials on moq. But I am wondering if there are any sample apps out there that use moq in the context of an n-tier business application using ado.net.

I find the tutes good, but they don't seem to bring everything all together into the big picture. Thus, I am looking for a sample app that brings the full picture together.

Also, I think there is a little bit of a lack of examples which specifically deal with mocking and testing the logic in the data access layer.

Cheers
Anthony

Answer:
Moq, like all unit testing frameworks, should not have much a concept of n-tier-ness about it.
One would typically use unit testing to test each individual class one-at-a-time. When a particular class is a little more complex and relies on having references to component classes and calling methods on these component classes, one might use a mocking framework such as Moq to create these constituent components, and to have the class-under-test use these mocked components instead of the real deals.
It looks like you are looking for how to use Moq in integration testing, where you bring all the components together and test the whole shebang all at once, including the data-access components. For doing whole-shebang tests, typically you need the real components, not mocked versions of them.


Question:
We have an application that use MSSQL, when we move to 2005, basically we recommend to our client to apply the backward compatibility package and that’s it, but somebody ask me what to do to be 100% compatible on 2005.
I was thinking on
1. Compatibility level: SQL Server 2005 (90)
2. Remove any DMO reference, and replaced by SMO
3. Connect using ADO

I am not sure if this is the correct answer.

Answer:
Actually you are talking about two different things.
One is to update the database to SQL 2005 level, to be able to use the functions only available there. It can be done easily by setting the compatibility level. However in this case SQL 2000 clients can have problems with it.
Second is to upgrade your application to use only SQL 2005 related libraries. This is also easy, basically the steps what you have written. In this case your application can also work with SQL 2000 databases (except if you use some SQL 2005 specific feature) because the libraries are backward compatible.
End words: you are either way
compatible
with SQL 2005, the only difference is that you can use SQL 2005
specific features
or not.
Why not change to SQL 2008 already?
Here is a thread
about this topic.


Question: I want my application to clean all the temp files it used, the problem is that not all the  temp files are under my control, so I just want to "brutally" unlock them in order to delete them programatically.

Answer:
Surely, of your application is wanting to clean up the temp files it owns, then you have full control to unlock these files and delete them!
If you're wanting to delete all TEMP files, whether owned by your application or otherwise, you should be VERY careful.  The original application probably applied the lock because it wants to use the file!
If you truly need to, you could always spawn a command-line application rather than trying to replicate the functionality of existing tools which will be difficult in C#.


Question:
Currently I use the "One Page Project Manager" Excel Template for project status reports. It contains a summary of last week's work and a forecast for the next week. For all important tasks we track, if they are comleted or not. Everything on one page. I send this report every week to all participants/stakeholders. (hint: I do not work in an agile environment)

How do you report your project status?

Answer:
Status reporting should be brief (nobody likes to sit there for ages while every member of the team goes on and on about their status) so I'm a big fan of SOFT reports:
Successes
- what have you achieved since the last status meeting: tasks directly off the project schedule. If possible I tried to avoid reporting x% done -- it's either done, or it's not. Reporting by % means that tasks will sit at 95% for
weeks
. This also encourages the project manager/tech lead to break down the work breakdown structure into tasks that are no longer than a few days.
Opportunities
- have you identified any opportunities: things that will help the project that aren't being considered yet (e.g.: found a better way to script something, a library that will save the project from implementing something themselves, etc)
Future Work
- what are you working on between now and the next status meeting: again, directly off the project schedule.
Threats
- have you identified anything that will impact your ability to get your scheduled work done? e.g.: a previously-unidentified hole in the requirements, support calls are taking a big chunk of your time, implementing something turns out to be harder than expected, etc.
Ideally I would try and avoid doing this stuff in a big project meeting since 90% of the material is irrelevant to half the people in the room. I like to collect SOFT reports before the meeting, spend some time looking at them before the meeting and then discuss specific issues that are probably relevant to everybody during the actual meeting.


Question:
Due to the nature of the live server I deploy to, my mail settings are using deliveryMethod="PickupDirectoryFromIis". I'm using log4net to send logs via email and I need find a way of getting it to do the same thing.

I can see from the docs that there is an SmtpPickupDirAppender, which has a pickupDir setting. If I set this to whatever pickup directory IIS uses, I'm sure everything will work OK. However what I really want is to just tell log4net to use IIS's setting and leave it there. That way if it ever changes we won't have to change the log4net config too, something we're likely to forget. Is there a way to do this?

Answer:
AFAIK, that's not possible. Although it sounds like a good idea.
One of the greatest things about log4net is that you can change your configuration without having to restart or recompile the application (check the
FAQ
), so you don't need to worry about having a downtime in your logging.
I don't know if you can query the IIS for the SMTP pick up directory, maybe if this is possible you can add some background job that queries the IIS for this information?


Question:
I know there are already a few questions regarding recommendations for C++ unit test frameworks, but all the answers did not help as they just recommend one of the frameworks but do not provide any information about a (feature) comparison.

I think the most interesting frameworks are CppUnit, Boost and the new Google testing framework. Has anybody done any comparison yet?

Answer:
See this question
for some discussion.
They recommend the articles:
Exploring the C++ Unit Testing Framework Jungle
, By Noel Llopis.
And the more recent:
C++ Test Unit Frameworks
I have not found an article that compares googletest to the other frameworks yet.


Question:
I have a problem, and was hoping I could rely on some of the experience here for advice and a push in the right direction. I have an MS Access file made by propietary software. I only want to take half the columns from this table, and import into new(not yet setup)mysql database.

I have no idea how to do this or what the best way is. New data will be obtained each night, and again imported, as an automatic task.

One of the columns in the access database is a url to a jpeg file, I want to download this file and import into the database as a BLOB type automatically.

Is there a way to do this automatically? This will be on a windows machine, so perhaps it could be scripted with WSH?

Answer:
This is a bash script
linux
example using
mdbtools
for automatic extraction and import from a mdb file to mysql.
```
```
#!/bin/bash

MDBFILE="Data.mdb"

OPTIONS="-H -D %y-%m-%d"
mdb-export $OPTIONS $MDBFILE  TableName_1 >  output_1.txt
mdb-export $OPTIONS $MDBFILE  TableName_2 >  output_2.txt

mdb-export $OPTIONS $MDBFILE  TableName_n >  output_n.txt

MYSQLOPTIONS=' --fields-optionally-enclosed-by=" --fields-terminated-by=, -r '
mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_1.txt
mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_2.txt
mysqlimport $MYSQLOPTIONS -L -uuser -ppasword database output_n.txt
```
```
You can use some others mysqlimport options:
--delete: to delete previous Data from the target mysql table.
--ignore: ignore duplicates
--replace: replace if a duplicate is found
It's not a windows solution but i Hope it helps.


Question:
How can I add a plaintext into encrypted ciphertext?

For example, I would like to add number 4 into encrypted(5)

Answer:
@Bill the lizard:
Well you can, if you are using ECB or any other block mode where the n+1 block doesn't require much knowledge about block n you can chain on an extra block (or even insert a block as in the case of ecb).
However this leaves you open to mitm-attacks and so on...


Question: Does the HTML "select" element have an on select event? what exactly is the name of the event?

Answer:
Is
```
onchange
```
what you're looking for?


Question:
I have two tables, one stores the products and quantity we have bought, the other stores the sells. The current stock is therefore the sum of all the quantity columns in the bought table minus the number of rows in the sells table. How can this be expressed in MySQL. Remember that there are many different products.

EDIT:
To make it harder, I have another requirement. I have the bought table, the sold table, but I also have the products table. I want a list of all the products, and I want to know the quantity available of each product. The problem with the current answers is that they only return the products that we have sold or bought already. I want all the products.

Answer:
Try this
```
```
SELECT inv_t.product_id, inventory_total-nvl(sales_total,0)
FROM
  (SELECT product_id, sum(quantity) as inventory_total
   FROM inventory
   GROUP BY product_id) inv_t LEFT OUTER JOIN
  (SELECT product_id, count(*) AS sales_total
   FROM sales
   GROUP BY product_id) sale_t
  ON (inv_t.product_id = sale_t.product_id)
```
```
This is a better solution than a few of the other ones posted, which do not account for the fact that some products may not have any corresponding rows in the sales table.  You want to make sure that such products also show up in the results.
NVL is an Oracle-specific function that returns the value of the first argument, unless it's null, in which case it returns the value of the second argument.  There are equivalent functions in all commercial DBMSes -- you can use CASE in MySQL to the same effect.


Question:
What does Java do with long variables while performing addition?

Wrong version 1:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = speeds.size() + estimated; // time = 21; string concatenation??

Wrong version 2:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long time = estimated + speeds.size(); // time = 12; string concatenation??

Correct version:

Vector speeds = ... //whatever, speeds.size() returns 2
long estimated = 1l;
long size = speeds.size();
long time = size + estimated; // time = 3; correct

I don't get it, why Java concatenate them.

Can anybody help me, why two primitive variables are concatenated?

Greetings, guerda

Answer:
I suspect you're not seeing what you think you're seeing. Java doesn't do this.
Please try to provide a
short but complete program
which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your "wrong" code (i.e. a counterexample).
```
```
import java.util.*;

public class Test
{
    public static void main(String[] args)
    {
        Vector speeds = new Vector();
        speeds.add("x");
        speeds.add("y");

        long estimated = 1l;
        long time = speeds.size() + estimated;
        System.out.println(time); // Prints out 3
    }
}
```
```


Question:
I'm using a Response.Redirect to redirect users to another server to download a file, and the other server is checking the header to ensure it came from the correct server... however it seems Response.Redirect strips the headers from the Response.

Does anybody know how i can add the headers back?  I've tried:

Response.AddHeader("Referer", "www.domain.com");

But the receiving page tests false when i check if the Referrer header is set.

Any suggestions how i can get this working, other than displaying a button for the user to click on (i'd like to keep the url hidden from the user as much as possible).

Answer:
I don't think it's possible.  What you are sending back to the client is a Location header that tells the client to load the page referred to instead of the page it originally requested.  In this case the client is not coming from a link and thus does not set the referrer header.  It's basically as if the user typed the redirect url in the location bar in his browser.
You may be able to save the referrer in the session, or encode it in the URL as a query parameter.  Like the Forms login does with ReturnUrl.


Question:
Any links/Turorials avalable? I want to write a simple ISAPI plugin for IIS6.0.

Prefered language c++

Answer:
Below is a quick (and simple) ISAPI Filter example. I found it very useful when trying to write my first ISAPI plugin.
http://blogs.msdn.com/rakkimk/archive/2007/03/01/writing-a-simple-isapi-filter.aspx
Best of luck.


Question:
Is it possible to get a list of control events that are going to fire before they happen, say inside the Page_Load handler?

For example if a button was clicked can I figure this out before the button_click event handler is called?

Answer:
The following contains the mangled id for a button when clicked.
```
```
Page.Request.Form["__EVENTTARGET"]
```
```


Question:
On a website, everything is tagged with keywords assigned by the staff (it's not a community driven site, due to its nature). I am able to determine which tags a user is most active in (or, what tags they view the most). However, I'm not sure how to choose the list. A few options present themselves, but they don't seem right to me.

Take the top n (or m < n if they have fewer than n viewed tags) tags

Take the top n tags where n is a percentage of the total tags viewed

Take the top n tags with m views where n and m are percentages of total tags viewed and total page views

Take all of the tags, regardless of views

The goal is to identify what is most interesting to the user and show them other things that they might be interested in, with respect to the tags that are assigned to the content.

Answer:
You could look at machine learning algorithms to find algorithms with which to evaluate the effectiveness of your choice.
Like for instance:
http://en.wikipedia.org/wiki/Supervised_learning#Approaches_and_algorithms
Stuff like nearest neighbour and bayes could help you improve your suggestions.
This is however overkill for just suggesting "Would you like to look at this too?", but it's an interesting approach to providing better tie-ins. It would, however require some method to figure out whether or not your users value your suggestions (e.g. "I like this!"-links or log-analysis based on time spent on links, etc.)


Question:
I have a key that appears to be an empty string, however using unset($array[""]); does not remove the key/value pair. I don't see another function that does what I want, so I'm guessing it's more complicated that just calling a function.

The line for the element on a print_r is [] => 1, which indicates to me that the key is the empty string.

Using var_export, the element is listed as '' => 1.

Using var_dump, the element is listed as [""]=>int(1).

So far, I have tried all of the suggested methods of removal, but none have removed the element. I have tried unset($array[""]);, unset($array['']);, and unset($array[null]); with no luck.

Answer:
My guess is that it's not an empty string.  Try the following to see what you get:
```
```
foreach ($array as $index => $value) {
    echo $index;
    echo ' is ';
    echo gettype($index);
    echo "\n";
}
```
```


Question:
The thing is I've been using the lock statement to protect a critical part of my code, but now, I realize I could allow concurrent execution of that critical code is some conditions are met.

Is there a way to condition the lock?

Answer:
```
```
Action doThatThing = someMethod;

if (condition)
{
  lock(thatThing)
  {
     doThatThing();
  }
}
else
{
  doThatThing();
}
```
```


Question:
From what I understand, if you have multiple web servers, then you need some kind of load balancer that will split the traffic amongst your web servers.

Does this mean that the load balancer is the main connecting point on the network? ie. the load balancer has the IP address of the domain name?

If this is the case, it makes it really easy to add new hardware since you don't have to wait for any dns propogation right?

Answer:
There are several solutions to this "problem".
You could round-robin at the DNS-level. I.e. have www.yourdomain.com point to several IP-addresses (well all your servers).
This doesn't give you any intelligence in the load balancing, but the load will be more or less randomly distributed, but you wouldn't be resilient to hardware failures as they would still require changes to DNS.
On the other hand you could use a proxy or a loadbalancing proxy that has a single IP but then distributes the traffic to several back-end boxes. This gives you a single point of failure (the proxy, you could of course have several proxies to defeat that problem) and would also give you the added bonus of being able to use some metric to divide the load more evenly and intelligently than with just round-robin dns.
This setup can also handle hardware failure in the back-end pretty seamlessly. The end user never sees the back-end, just the front-end.
There are other issues to think about as well, if your page uses sessions or other smart logic, you can run into synchronisation problems when your user (potentially) hits different servers on every access.


Question:
I have a set of tables that are used to track bills. These tables are loaded from an SSIS process that runs weekly.

I am in the process of creating a second set of tables to track adjustments to the bills that are made via the web. Some of our clients hand key their bills and all of those entries need to be backed up on a more regular schedule (the SSIS fed data can always be imported again so it isn't backed up).

Is there a best practice for this type of behavior? I'm looking at implementing a DDL trigger that will parse the ALTER TABLE call and change the table being called. This is somewhat painful, and I'm curious if there is a better way.

Answer: I personally would have the SSIS-fed tables in one database (set to simple recovery mode) and the other tables in a separate database on the same server which is set to full recovery mode,. Then I would set up backups on the second datbase on a regular schedule. A typical backup schedule would be full backup once a week, differntials nightly  and transaction backups every 15-30 minutes depending on how much data is being input.) Be sure to periodically test recovering the backups, learning how to do that when the customer is screaming becasue the datbase is down isn;t a good thing.


Question:
I'm looking to improve my PHP coding and am wondering what PHP-specific techniques other programmers use to improve productivity or workaround PHP limitations.

Some examples:

Class naming convention to handle namespaces: Part1_Part2_ClassName maps to file Part1/Part2/ClassName.php

if ( count($arrayName) ) // handles $arrayName being unset or empty

Variable function names, e.g. $func = 'foo'; $func($bar); // calls foo($bar);

Answer:
My experience with PHP has taught me a few things. To name a few:
Always output errors. These are the first two lines of my typical project (in development mode):
```
```
ini_set('display_errors', '1');
error_reporting(E_ALL);
```
```
Never use
automagic
. Stuff like autoLoad may bite you in the future.
Always require dependent classes using
```
require_once
```
. That way you can be sure you'll have your dependencies straight.
Use
```
if(isset($array[$key]))
```
instead of
```
if($array[$key])
```
. The second will raise a warning if the key isn't defined.
When defining variables (even with
```
for
```
cycles) give them verbose names (
```
$listIndex
```
instead of
```
$j
```
)
Comment, comment, comment. If a particular snippet of code doesn't seem obvious, leave a comment. Later on you might need to review it and might not remember what it's purpose is.
Other than that, class, function and variable naming conventions are up to you and your team. Lately I've been using
Zend Framework's naming conventions
because they feel right to me.
Also, and when in development mode, I set an error handler that will output an error page at the slightest error (even warnings), giving me the
full backtrace
.


Question:
Does anyone have experience with developing for Sharepoint 2003 using Visual Studio 2008?

I need to upgrade to VS2008 because of Vista issues but need to support Sharepoint 2003 webparts. The webparts are all pretty simple. Will I be able to support those webparts using VS2008?

Answer:
I've created .net 2.0 assemblies using vs2008, and linked with sharepoint 2007 libraries and then deployed on sharepoint servers.  You won't be able to create .net 1.1 assemblies with vs2008 out of the box - so if you need to target .net 1.1 your best bet is to stick with a virtual server setup.
Developing for sharepoint on vista (or xp for that matter) is challenging because you can't debug line by line unless you attach remotely to server2k3.  My recommendation for sharepoint developers is to install virtual server on vista, and then install vstudio on the virtual server with sharepoint.  If you are going to do this, you can stick with your current version of visual studio, and then debugging is much easier than from vista.
Depending on whether your company has an msdn subscription, this can be more costly if you have to buy a virtual server license, etc...  but it is well worth it to make development easier, in my opinion.


Question:
Did someone ever used a BIRT report in a desktop application. I'm comming from the .NET environment and there you can use Crystal Reports to show reports in desktop apps. Is this possible with BIRT too, without having to set up a server environment?

Can you give me some advice how to reach this goal?

Thanks in advance.

Answer:
Yes, it is possible. I used it in a project I did about 1-2 years ago so I'll have to get back to you with the details. (Though things might have changed since then)
Here are the plugins
I
needed:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
    <classpathentry kind="var" path="JUNIT_HOME/junit.jar" sourcepath="JUNIT_SRC_HOME/junitsrc.zip"/>
    <classpathentry kind="lib" path="lib/log4j-1.2.14.jar"/>
    <classpathentry kind="lib" path="lib/swt.jar"/>
    <classpathentry kind="con" path="SWT_CONTAINER"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.device.extension_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.device.swt_2.1.1.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.engine_2.1.2.v20070205-1728.jar" sourcepath="C:/Programme/eclipse/plugins/org.eclipse.birt.chart.source_2.2.0.v20070209/src"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.engine.extension_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.runtime_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.core_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.emf.common_2.2.1.v200609210005.jar"/>
    <classpathentry kind="lib" path="org.eclipse.emf.ecore_2.2.1.v200609210005.jar"/>
    <classpathentry kind="lib" path="org.eclipse.emf.ecore.xmi_2.2.1.v200609210005.jar"/>
    <classpathentry kind="lib" path="js.jar"/>
    <classpathentry kind="lib" path="com.ibm.icu_3.4.5.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.ui_2.1.1.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="org.eclipse.birt.chart.ui.extension_2.1.2.v20070205-1728.jar"/>
    <classpathentry kind="lib" path="lib/hsqldb.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>
```
```


Question:
I remember hearing Joel say he has 2 different locations where the servers are located, each location has 2 front end servers and 1 back end server.

If a one of the hosting facilities goes down, how can he switch over to the other one?  (Or is it just going to be a DNS change that will take 24-72 hours to propagate?).

How can a single SQL Server instance have so many databases on it?  FB has a completely separate database per account.  I can't see a single SQL Server instance having more than say 200-250 databases on it!  And I'm sure they have more customers than that.

Answer:
They talked about this in one of the Stack Overflow podcasts, but I can't find it in the transcripts.
1) Each of the two centers handles approximately 1/2 of the users. Fairly often (hourly, I think Joel said) they ship transaction logs to the other site. If site A goes down, they bring up the db backups on site B, and do the DNS switchover. It won't be instantaneous or automated, nor do they want it to be, because they'll be coming up with slightly stale data, and want to avoid that if it's at all possible to bring the broken site back up.
I'm not sure how they handle the DNS situation, but you can set the TTL on DNS records to mere seconds to limit caching, and have failover occur very quickly.
2) Why not? I'm not sure of the hard limit of databases per instance, but there's also nothing keeping you from running multiple instances of SQL Server on your box. I would imagine you're more limited by hardware than software. (You can also run Fogbugz with a MySQL database backend).


Question: I am using a ASP/.Net webpage and i want to upload a pdf file into a SQL Database as a binary    I am uping the build in upload control, can you please suggest a way of doing this. I also need to no how to read the pdf back and display it in a web browser. I will be using linq to upload and query my sql database.

Answer:
You can use the
```
VARBINARY(MAX)
```
type in your database, create a LINQ to SQL mapping and use the
```
Binary
```
type with the
```
byte[]
```
type containing your PDF file's content.


Question:
Windows Mobile pops up a "busy wheel" - a rotating colour disk - when things are happening .  I can't find in the documentation how this is done - can someone point me in the right direction?

We have a situation where we need to prompt the user to say we're doing stuff for a while, but we don't know how long it will take. So we can't do a progress bar, hence the proposal to use this busy wheel.

Answer:
I'm just guessing here, but I'd imagine it is
CWaitCursor
.  Basically, you just create one on the stack, it appears, and disapppears when it is destructed as it goes out of scope e.g.
```
```
void DoSomethingSlow()
{
  CWaitCursor cw;
.
.
.
.
}
```
```


Question:
I was wondering how to unit test abstract classes, and classes that extend abstract classes.

Should I test the abstract class by extending it, stubbing out the abstract methods, and then test all the concrete methods? Then only test the methods I override, and test the abstract methods in the unit tests for objects that extend my abstract class?

Should I have an abstract test case that can be used to test the methods of the abstract class, and extend this class in my test case for objects that extend the abstract class?

Note that my abstract class has some concrete methods.

Answer:
I would argue against "abstract" tests. I think a test is a concrete idea and doesn't have an abstraction. If you have common elements, put them in helper methods or classes for everyone to use.
As for testing an abstract test class, make sure you ask yourself what it is you're testing. There are several approaches, and you should find out what works in your scenario. Are you trying to test out a new method in your subclass? Then have your tests only interact with that method. Are you testing the methods in your base class? Then probably have a separate fixture only for that class, and test each method individually with as many tests as necessary.


Question: I'm launching a Weblogic application inside Eclipse via the BEA Weblogic Server v9.2 runtime environment. If this were running straight from the command-line, I'd do a ctrl-BREAK to force a thread dump. Is there a way to do it in Eclipse?

Answer:
Did you try to launch your eclipse with java.exe instead of javaw.exe (in your
eclipse.ini
) ?
That might give you the console you need, as described in
this bug
and in
this message
.
Other ideas (in term of java options) could be derived from this
other SO question
.


Question: Does everyone just use XML in the message? Are there any good alternatives to XML?  If you do use XML, do you define an XML Schema so clients know how to send messages to your service?

Answer:
We use XML, but I think the important thing is to tailor the solution to the problem.  The reason we use XML is that we are basically sending an object across in the message.  There's no reason it can't be plain text, if applicable for the message you are sending, using headers to send along properties if appropriate.
We haven't defined an XSD or DTD for our XML messages, but we do have a formal document describing their composition so that other teams can use our feeds without bugging us.


Question:
State should include at least the following:

All settings set via
SetStreamResource()

Indices

I have a class whose Draw() function will call SetStreamResource, set Indices and eventually call DrawIndexedPrimitive(). I would like to restore the device state before Draw() returns.

I am looking for something along the lines of GDI's SaveDC()/RestoreDC().

Answer:
Looks like these will do it:
```
```
Microsoft::DirectX::Direct3D::Device::BeginStateBlock
Microsoft::DirectX::Direct3D::Device::EndStateBlock
```
```


Question:
I launch my program in C#, which then calls some unmanaged C++.

When I break on a line in the unmanaged C++, the 'New Data Breakpoint' menu item is grayed out.

Is there anyway around this?

Answer:
To set a data breakpoint in the native portion of a mixed mode process, see the
answer posted by jyoung
.
Visual Studio disables data breakpoints when running anything but pure, native code. See
this
post for a partial explanation why from a VS Program Manager.


Question:
Is it ever OK to use Environment.TickCountto calculate time spans?

int start = Environment.TickCount;
// Do stuff
int duration = Environment.TickCount - start;
Console.WriteLine("That took " + duration " ms");

Because TickCount is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful.

I'm using DateTime.Now instead. Is this the best way to do this?

DateTime start = DateTime.Now;
// Do stuff
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("That took " + duration.TotalMilliseconds + " ms");

Answer:
Use Stopwatch class. There is a decent example on msdn:
http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
```
```
Stopwatch stopWatch = Stopwatch.StartNew();
    Thread.Sleep(10000);
    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
```
```


Question:
Is there a way to quickly list which sites are on which IP address in IIS 7?

If I remember correctly you could sort a view of domains by IP in IIS 6 which was a big help to me in seeing which IPs I had available.

Answer:
You can try this script:
```
```
MachineName = "localhost"
IIsObjectPath = "IIS://" & MachineName & "/w3svc"

WScript.Echo "Checking : " & IISObjectPath

Set IIsObject = GetObject(IIsObjectPath)
for each obj in IISObject
    if (Obj.Class = "IIsWebServer") then
        BindingPath = IIsObjectPath & "/" & Obj.Name

        Set IIsObjectIP = GetObject(BindingPath)
        wScript.Echo BindingPath & " - " & IISObjectIP.ServerComment

        ValueList = IISObjectIP.Get("ServerBindings")
                ValueString = ""
        For ValueIndex = 0 To UBound(ValueList)
            value = ValueList(ValueIndex)
            Values = split(value, ":")
            IP = values(0)
            if (IP = "") then
                IP = "(All Unassigned)"
            end if
            TCP = values(1)
            if (TCP = "") then
                TCP = "80"
            end if
            HostHeader = values(2)

            if (HostHeader <> "") then
                    wScript.Echo "    IP = " & IP & " TCP/IP Port = " & TCP & ", HostHeader = " & HostHeader
            else
                    wScript.Echo "    IP = " & IP & " TCP/IP Port = " & TCP
            end if
                Next
        wScript.Echo ""
        set IISObjectIP = Nothing
    end if
next
set IISObject = Nothing
```
```
(source www.iisfaq.com)


Question:
How do I programmatically reset the Excel Find and Replace dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")?

I am using Application.FindFormat.Clear and Application.ReplaceFormat.Clear to reset find and replace cell formats.

Interestingly, after using expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords), the FindWhat string shows in the Find and Replace dialog box but not the ReplaceWhat parameter.

Answer:
You can use the following command to open the "Replace" dialog with fields filled:
Application.Dialogs(xlDialogFormulaReplace).Show -arguments here-
the argument list is
find_text, replace_text, look_at, look_by, active_cell, match_case, match_byte
So far, the only way I've found to 'click' the buttons is with SendKey.
After much research and testing, I now know exactly what you want to do, but don't think it can be done (without SendKey).  It appears that there is a bug in Excel, that won't reset the replacement value (from VBA), no matter what you try and set it to.
I did find this 'faster' way someone posted on MSDN, so you might give it a try.
Faster than Replace


Question: Is there anything I should know before converting a large C++ program from VS2005 to VS2008?

Answer: Is there a difference in the syntax that you can't just simply recompile? VS will convert the .sln and vcproj files for you automatically. The rest is just code, and unless you are doing something really strange, it should just recompile as-is.


Question:
I was reading about parsers and parser generators and found this statement in wikipedia's LR parsing -page:

Many programming languages can be parsed using some variation of an LR parser. One notable exception is C++.

Why is it so? What particular property of C++ causes it to be impossible to parse with LR parsers?

Using google, I only found that C can be perfectly parsed with LR(1) but C++ requires LR(∞).

Answer:
There is an interesting thread on
Lambda the Ultimate
that discusses the
LALR grammar for C++
.
It includes a link to a
PhD thesis
that includes a discussion of C++ parsing, which states that:
"C++ grammar is ambiguous,
  context-dependent and potentially
  requires infinite lookahead to resolve
  some ambiguities".
It goes on to give a number of examples (see page 147 of the pdf).
The example is:
```
```
int(x), y, *const z;
```
```
meaning
```
```
int x;
int y;
int *const z;
```
```
Compare to:
```
```
int(x), y, new int;
```
```
meaning
```
```
(int(x)), (y), (new int));
```
```
(a comma-separated expression).
The two token sequences have the same initial subsequence but different parse trees, which depend on the last element. There can be arbitrarily many tokens before the disambiguating one.


Question:
I need to set the fetch mode on my hibernate mappings to be eager in some cases, and lazy in others. I have my default (set through the hbm file) as lazy="true". How do I override this setting in code? MyClass has a set defined of type MyClass2 for which I want to set the FetchMode to EAGER.

Currently, I have something like:

Session s = HibernateUtil.getSessionFactory().openSession();
MyClass c = (MyClass)session.get(MyClass.class, myClassID);

Answer:
You could try something like this: (code off the top of my head)
```
```
Criteria crit = session.createCriteria(MyClass.class);
crit.add(Restrictions.eq("id", myClassId));
crit.setFetchMode("myProperty", FetchMode.EAGER);
MyClass myThingy = (MyClass)crit.uniqueResult();
```
```
I believe that FetchMode.JOIN or FetchMode.SELECT should be used instead of FetchMode.EAGER, though.


Question:
How would I expose an Objective-C method within JavaScript when using the iPhone SDK when using the UIWebView?

Any help would be appreciated!

Answer:
The best way to do this would be through a custom link, and then use the UIWebView delegate method
```
-webView:shouldStartLoadWithRequest:navigationType:
```
to trap requests. When you see a request come through with your link in it, you know your action has been triggered.


Question:
I was mapping a relation using something like the following

<map name="Foo" cascade="all-delete-orphan" lazy="false">
  <key column="FooId"/>
  <index column="FooType" type="Domain.Enum.FooType, Domain"/>
  <element column ="FooStatus" type="Domain.Enum.FooStatus, Domain"/>
</map>

The class is like this

namespace Domain {
    public class Enum {
        public enum FooType {
            Foo1,
            Foo2,
            ...
      Foo50}
       public enum FooStatus {
           NotNeeded,
           NeededFor1,
           NeededFor2,
      NeededFor3,
      NiceToHave}
    }
}

Can I do this using Fluent Nhibernate?
If not can I map a class mixing Fluent and XML?

Answer:
Forget to add
```
```
namespace Domain
{
public virtual IDictionary<FooType, FooStatus> MyFoo { set; get; }
}
```
```


Question: I have a .Net app that will allow the users to attach files to a SQL Server 2005 database.  I want to limit the filesize to 10MB, so from what I can tell, I have to declare the datatype varbinary(max), since the max size I can actually specify is 8000 bytes.  But the ~2GB filesize varbinary(max) allows seems like overkill.  Is there a way for me to limit it at 10MB in the database, or do I just need to check that they're not trying to attach something larger on the frontend.

Answer:
I think you need to make it in the frontend. You can limit the HTTP request size in the web.config like that:
```
```
</configuration>
   </system.web>
      <httpRuntime maxRequestLength="60000"/>
   </system.web>
</configuration>
```
```
You may also need to explicitly check the posted file size when the user try to upload a file more than the specified threshold.


Question:
How would one go about capturing users keystrokes in the SMS composer on the Symbian OS, specifically for a Nokia N73 (or any of the symbian supported devices http://en.wikipedia.org/wiki/Symbian_OS#Devices_that_have_used_the_Symbian_OS)? I'm new to symbian development and I'm trying to write an application to analyse writing styles of those who send SMSs. Any information (or push in the right direction) would be great.

Many Thanks,

A

Answer:
Well, there are several levels to answering to your question.
The keystrokes are actually captured by the message editor application. So, either it provides an API to feed you all its keystrokes (you can look for one on
http://forum.nokia.com
. You'll find the message editor API but it will be mostly about re-using GUI controls and not what you're looking for) or you would need a transparent application of your own that stays in the foreground and captures keystrokes before feeding them back to whatever application happens to be right behind. Fortunately (for obvious security reasons), Symbian OS will not allow you to do the later.
You can, however, have your own application read messages when they are saved in the  phone memory: when they are saved in the Draft folder or in the SMS Outbox.
The obligatory shameless plug: I would advise reading the messaging chapter of
http://www.quickrecipesonsymbianos.com
in order to understand how to use the Symbian Message Store
The classes of interest in your case are : CmsvEntry, CMsvSession, MMsvSessionObserver, CMsvOperation and CSmsClientMtm.


Question:
Does anyone know what is wrong with this query?

 SELECT DISTINCT c.CN as ClaimNumber,
         a.ItemDate as BillReceivedDate, c.DTN as
 DocTrackNumber
         FROM ItemData a,
         ItemDataPage b,
         KeyGroupData c
         WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
         AND a.ItemNum = b.ItemNum
         AND b.ItemNum = c.ItemNum
         ORDER BY a.DateStored DESC;

I have done T-Sql most of my career and this looks correct to me, however this query is for an Oracle database and Toad just places the cursor on the a.DateStored in the Order By section. I'm sure this is elementary for anyone doing PL/SQL.

Thanks!

[EDIT] For future reference, the error given by SQL*Plus was: "ORA-01791: not a SELECTed expression"

Answer:
Nevermind, executing in SQL Plus gave me a more informative answer. The DateStored needs to be in the select statement so this works:
```
```
SELECT DISTINCT c.CN as ClaimNumber,
a.ItemDate as BillReceivedDate,
c.DTN as DocTrackNumber,
a.DateStored
FROM ItemData a,
ItemDataPage b,
KeyGroupData c
WHERE a.ItemTypeNum in (112, 113, 116, 172, 189)
AND a.ItemNum = b.ItemNum
AND b.ItemNum = c.ItemNum
ORDER BY a.DateStored DESC;
```
```


Question: How can I find out which row in a JTable the user just clicked?

Answer:
Try this:
```
aJTable.rowAtPoint(evt.getPoint());
```


Question:
The database type is PostGres 8.3.

If I wrote:

SELECT field1, field2, field3, count(*)
FROM table1
GROUP BY field1, field2, field3 having count(*) > 1;

I have some rows that have a count over 1. How can I take out the duplicate (I do still want 1 row for each of them instead of +1 row... I do not want to delete them all.)

Example:

1-2-3
1-2-3
1-2-3
2-3-4
4-5-6

Should become :

1-2-3
2-3-4
4-5-6

The only answer I found is there but I am wondering if I could do it without hash column.

Warning
I do not have a PK with an unique number so I can't use the technique of min(...). The PK is the 3 fields.

Answer:
One possible answer is:
```
```
CREATE <temporary table> (<correct structure for table being cleaned>);
BEGIN WORK;   -- if needed
INSERT INTO <temporary table> SELECT DISTINCT * FROM <source table>;
DELETE FROM <source table>
INSERT INTO <source table> SELECT * FROM <temporary table>;
COMMIT WORK;  -- needed
DROP <temporary table>;
```
```
I'm not sure whether the 'work' is needed on transaction statements, nor whether the explicit BEGIN is necessary in PostgreSQL.  But the concept applies to any DBMS.
The only thing to beware of is referential constraints and in particular triggered delete operations.  If those exist, this may prove less satisfactory.


Question:
consider this code block

public void ManageInstalledComponentsUpdate()
        {
            IUpdateView view = new UpdaterForm();
            BackgroundWorker worker = new BackgroundWorker();
            Update update = new Update();
            worker.WorkerReportsProgress = true;
            worker.WorkerSupportsCancellation = true;
            worker.DoWork += new DoWorkEventHandler(update.DoUpdate);
            worker.ProgressChanged += new ProgressChangedEventHandler(view.ProgressCallback);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(view.CompletionCallback);
            worker.RunWorkerAsync();
            Application.Run(view as UpdaterForm);
        }

It all works great but I want to understand why the objects (worker,view and update) don't get garbage collected

Answer:
Threads count as root objects; I don't know exactly how BackgroundWorker operates, but it seems likely that the primary thread method is going to access state on the worker instance; as such, the worker thread itself will keep the BackgroundWorker instance alive until (at least) the thread has exited.
Of course; collection also requires that all other (live) objects have de-referenced the worker object; note also that collection of stack variables can be different in debug/release, and with/without a debugger attached.
[edit]
As has also been noted; the event handlers on the worker (in your code) will keep the "view" and "update" objects alive (via the delegate), but not the other way around. As long as the worker has a shorter life than the "view" and "update", you don't need to get paranoid about unsubscribing the events. I've edited the code to include a "SomeTarget" object that isonly referenced by the worker: you should see this effect (i.e. the target dies with the worker).
Re worker getting collected when the thread dies: here's the proof; you should see "worker finalized" after the worker reports exit:
```
```
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
class Demo : Form
{
    class ChattyWorker : BackgroundWorker
    {
        ~ChattyWorker()
        {
            Console.WriteLine("Worker finalized");
        }
    }
    class SomeTarget
    {
        ~SomeTarget()
        {
            Console.WriteLine("Target finalized");
        }
        public SomeTarget()
        {
            Console.WriteLine("Target created");
        }
        public void Foo(object sender, EventArgs args)
        {
            Console.WriteLine("Foo");
        }
    }
    static void Collect(object sender, EventArgs args)
    {
        Console.WriteLine("Collecting...");
        GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
    }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
        timer.Interval = 100;
        timer.Tick += Collect;
        timer.Start();

        ChattyWorker worker = new ChattyWorker();
        worker.RunWorkerCompleted += new SomeTarget().Foo;
        worker.DoWork += delegate
        {
            Console.WriteLine("Worker starting");
            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(250);
                Console.WriteLine(i);
            }
            Console.WriteLine("Worker exiting");
        };
        worker.RunWorkerAsync();
    }
    [STAThread]
    static void Main()
    { // using a form to force a sync context
        Application.Run(new Demo());
    }
}
```
```