q: I have an HTTPHandler that is reading in a set of CSS files and combining them and then GZipping them.  However, some of the CSS files contain a Byte Order Mark (due to a bug in TFS 2005 auto merge) and in FireFox the BOM is being read as part of the actual content so it's screwing up my class names etc.  How can I strip out the BOM characters?  Is there an easy way to do this without manually going through the byte array looking for "ï»¿"?

[A]
Expanding on
Jon's comment
with a sample.
```
```
var name = GetFileName();
var bytes = System.IO.File.ReadAllBytes(name);
System.IO.File.WriteAllBytes(name, bytes.Skip(3).ToArray());
```
```


q: According to the C# compiler and the Silverlight 2 documentation, Silverlight doesn't provide a FindName method for the DataTemplate class.  I want to find a Border that's inside a ContentPresenter.  What's the best way in SilverLight 2?

[A]
Not totally sure I understand the scenario, but since you mention the DataTemplate I'm assuming you're using a template.
If you're using a template then what you do is give your border a name (x:Name="border") and then override the OnApplyTemplate method. In that method you use GetTemplateChild and pass the name you used. This will return a reference to your border.
If you're not use a template and have a reference to the ContentPresenter then you could write a recursive function that looks at the Content property of the child and if it isn't a border then calls your same function on its content.

s: huggingface

c: devops

d: intermediate


q:
I would like to include some code coverage into our nightly build process. We're using CruiseControl, Ant, and Buckminster. Buckminster drives checkout from multiple repositories, and the PDE building and packaging of the product.

Has any one any experience integrating code coverage into an RCP headless build?

I have been looking at Cobertura, EMMA/EclEMMA, DbUnit though am very interested to hear of any experiences with these or any other tools.

[A]
Cobertura seemed to be able to do the job for us.
Once the unit tests were running (a question all to itself), I was able to:
instrument the bundles as standalone Jars.
re-run the unit tests with a cobertura on the parent class loader class path.
The trick here is to use
```
osgi.parentClassloader=app
```
in the config.ini file used to run the unit test.
```
ext
```
== Java extensions
```
boot
```
== the boot class loader (default)
```
fwk
```
== framework?
```
app
```
== application, i.e. just like a normal application, with a classpath specified on the command line.
The instrumented code needed runtime access to the cobertura jar, so this last step was imperative.


q:
I'm trying to watch the execution of a VB6 app and I'm running into an issue because once I enter the debugger and then hit Continue, it no longer lets me step through the code until I hit another break point.  I want to be able to execute a program without  stepping through something until I hit a point where I want to watch it execute.  Ideally this would be something to the effect of holding a key down while I pressed a button to 'step into' that function.

Thanks in advance!

[EDIT]: I'm aware that I can use break points to stop the execution.  To be more clear, the problem is that I don't know where the execution is going to, so I can't set the break point there (because I don't know where there is).  That's why I essentially want to be able to say, 'after this next thing that I do, break, no matter what'.  It sounds like this functionality does not exist, but I'm still keeping my fingers crossed.

[A]
You can press the F8 key to step through the code line by line.  Alternatively, you can press SHIFT-F8 to step through line by line.
F8 will step you in to a function, where SHIFT-F8 will step you over the function.  If you click on the DEBUG menu in the VB IDE, you will see other options too.
EDIT:
You can also put a permanent break point in your code by using:
```
```
Debug.Assert False
```
```
By doing it this way, the 'breakpoint' is saved in your code.  When you compile the app, debug code is ignored.


q:
Say we are traversing a graph and want to quickly determine if a node has been seen before or not. We have a few set preconditions.

Nodes have been marked with integers values 1..N

Graph is implemented with nodes having an adjacency list

Every integer value from 1..N occurs in the graph, which is of size N

Any ideas for doing this in a purely functional way?(No Hash tables or arrays allowed).

I want a data structure with two functions working on it; add(adds an encountered integer) and lookup(checks if integer has been added). Both should preferably take O(n) time amortized for N repetitions.

Is this possible?

[A]
You can use a
Data.Set
. You add an element by creating a new set from the old one with
```
insert
```
and pass the new set around. You look up whether an element is a member of the set with
```
member
```
. Both operations are O(log n).
Perhaps, you could consider using a state monad to thread the passing of the set.


q:
I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...

is there a way to simplify a c++ integration function like this:

// Integral Function
double integrate(double a, double b, double (*f)(double))
{
    double sum = 0.0;

    // Evaluate integral{a,b} f(x) dx
    for(int n = 0 ; n <= 100; ++n)
    {
        double x = a + n*(b-a)/100.0;
        sum += (*f)(x) * (b-a)/101.0;
    }
    return sum;
}

by using c# and lambda expressions?

[A]
What about this:
```
```
public double Integrate(double a,double b, Func<double, double> f)
{
    double sum = 0.0;

    for (int n = 0; n <= 100; ++n)
    {
        double x = a + n * (b - a) / 100.0;
        sum += f(x) * (b - a) / 101.0;
    }
    return sum;
}
```
```
Test:
```
```
Func<double, double> fun = x => Math.Pow(x,2);
    double result = Integrate(0, 10, fun);
```
```


q: Where should I be logging exceptions? At the data service tier(ExecuteDataSet, etc.) and/or at the data access layer and/or at the business layer?

[A]
If you are throwing the exception you should log it when it occurs and then  bubble it up.  Otherwise only the end user should log an exception (you may have lots of tracing on of course in which case it may get logged quite a bit).
The end user may be a UI component or a Service or something...
If you handle an exception in you code somewhere - then that is the end user and you should log it there.  In most apps and in most cases it should be logged by the UI when it displays the error message to the user.


q: I want to write a little app for myself which notifies me if there is a new version of php or mysql but I would need a feed or an xml file to read it from.

[A]
PHP.net provides one
http://www.php.net/releases/index.php?serialize=1
An alternative that may allow you to add additional software later is looking into the feeds provided by freshmeat:
http://freshmeat.net/projects/mysql/


q: Are there any Code Generators that would take a well-formed XML document, and write out an XSD schema based on how the XML document is structured?

[A]
The XSD.exe utility (which is installed with Visual Studio) is capable of creating an XSD file from an XML file.
Here's the link on
MSDN
I believe it may also part of the .NET SDK, meaning you would not need a full-blown Visual Studio installation.


q: In graph theory, what is the distinction between minimal distance (which Dijkstra's algorithm finds), and minimal path (which I'm not sure what it is)?

[A] I'm not 100% sure, but it sounds like the minimal path would be the list of vertices visited when traversing the minimal distance path from vertex A to vertex B.


q: what's the easiest way to bulk load my iTunes library xml into an existing SQL Server database?

[A]
bcp with xml flag.
http://msdn.microsoft.com/en-us/library/ms162802.aspx
It really depends how you want it in there and what you're purposes are, which you haven't explained.


q:
I have a JavaScript variable which holds an HTML page and due to the setup I need to extract everything between <div id="LiveArea"> and </div> from that variable using JavaScript.

Any help is greatly appreciated.

[A]
I'm not sure I follow you when you say, "Javascript variable which holds an html page", but If you need to extract the HTML between such a div, you can use the element's innerHTML property.
```
```
var e = document.getElementById('LiveArea');
if(e) alert(e.innerHTML);
```
```


q:
Here's some code I have:

MyClass* MyClass::getInstance()
{
   static MyClass instance;
   return &instance;
}

I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.

My question then is how to refer to this instance variable from a global scope. I've tried referring to it as MyClass::getInstance::instance but that doesn't work. I'm guessing getInstance has to be decorated somehow. Anyone know how?

This is in Visual Studio 2008.

[A]
In gdb, you can put a watchpoint on the mangled name of the variable.
For example, with this function:
```
```
int f() {
    static int xyz = 0;
    ++xyz;

    return xyz;
}
```
```
I can watch _ZZ1fvE3xyz (as mangled by gcc 3.2.3 or gcc 4.0.1).


q:
In Websphere when you do an LDAP query using LdapContext are the transmission of credentials encrypted?

LdapContext ctx = new InitialLdapContext (env, null);

Lets say I make an LdapContext for a web app to do some custom LDAP calls.

How do I know if my call is secure / encrypted?

[A]
In order to secure/encrypt your LDAP calls you need to issue the "Start TLS" operation.
Otherwise I think transport is plain text.
For more:
http://java.sun.com/products/jndi/tutorial/ldap/ext/starttls.html
Obviously the Java API is based on LDAP itself.  So you could learn more about how the protocol itself handles it...i.e.:
http://en.wikipedia.org/wiki/Ldap#StartTLS


q: I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future

[A]
If the content to be TOGGLEd is displayed (visible) when the page is rendered the functions would be in the following order, if the content is hidden originally then reverse the functions
```
```

Upper div

Lover Div

```
```


q: Does anyone have a suggestions as to the best way to allow users to select which columns appear in a datagrid?  I would like them to be able to set this up.  It would be stored with the user in a profile and loaded each time the user loads the grid.  I was thinking about something with ASP.NET personalization.

[A]
There are several options for you here.
Add an 'X' image to the header for each column and with a javascript onclick event do a web method call to remove that column from the user's profile of what columns to load.
Have a customization flyout page where by there would be a checkbox list of all the columns and the user could either add or remove what columns from the grid.
There are a few more but they are less AJAX and more page reloading.


q: Does anyone know of a good alternative to cron?  I would like something that can be run with  different time zones.

[A]
You may consider
Quartz
(a java-based solution), that can take advantage of
```
Date
```
build in the appropriate TimeZone
.


q: Can anybody tell me when Application_End is triggered in a lifecycle of an application? When all sessions are ended, will Application_End be triggered automatically? + Are there any other reasons why Application_End could be triggered?

[A]
The
```
application_end
```
event primarily fires when the IIS pool is recycled or the application itself is unloaded. One other thing to note, that a change to a dependent file (say web.config) will cause the application to reload itself, which will in cause the application_end event to fire while it is closing itself off.
To note, the only instance I found of the application end event firing when the last user session times out is in some old documentation dated 2001. I'm not sure if that criteria still applies.


q:
So if I have:

public class ChildClass : BaseClass
{
    public new virtual string TempProperty { get; set; }
}

public class BaseClass
{
    public virtual string TempProperty { get; set; }
}

How can I use reflection to see that ChildClass is hiding the Base implementation of TempProperty?

I'd like the answer to be agnostic between c# and vb.net

[A]
Correction, if you are using VB the property you are looking for is "IsHideBySig".  This will be false in the case that the "new" keyword was used to define a method/property.
In the C# case, both instances are outputted as "hidebysig".  Thanks for pointing that out Greg.  I didn't realize I only tested this in VB.  Here's sample VB code that will repro this behavior.
```
```
Module Module1

    Class Foo
        Public Function SomeFunc() As Integer
            Return 42
        End Function
    End Class

    Class Bar
        Inherits Foo
        Public Shadows Function SomeFunc() As Integer
            Return 36
        End Function
    End Class

    Sub Main()
        Dim type = GetType(Bar)
        Dim func = type.GetMethod("SomeFunc")
        Stop
    End Sub

End Module
```
```


q:
I have two system calls GetSystemTime() and GetThreadTimes() that I need to calculate the CPU utilization by a given Win32 thread.

For the sake of accuracy, I need to ensure that both GetSystemTime() and GetThreadTimes() are executed atomically; i.e. there should be no context switch in between a call to GetSystemTime() & GetThreadTimes().

The reason is that occasionally I end up with a percentage of over 100% (~ 1 in 500).

How can I ensure an atomic execution of the 2 function calls?

Thanks,
Sachin

[A]
I'm not so sure you can. Unless you know what the underlying operations are in each function, and since they happen to be Windows API calls... good luck.
Would it not be possible to just adjust for percentages over 100?
```
```
perc = ( perc > 100.0f ) ? 100.0f : perc;
```
```


q:
Do any of the existing JavaScript frameworks have a non-regex replace() function,
or has this already been posted on the web somewhere as a one-off function?

For example I want to replace "@!#$123=%" and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added.

[A]
i may be misunderstanding your question, but javascript does have a
```
replace()
```
```
```
var string = '@!#$123=%';
var newstring = string.replace('@!#$123=%', 'hi');
```
```
edit
: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i
link directly
to it. here's the relevant part:
The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds.
If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.


q:
Trying to establish a connection between my windows box (2003 server) and the oracle (11g) database.

I'm able to successfully ping the oracle host from the windows box. However tnsping command fails with the error tns-12532 error.

Any ideas to solve this issue?

[A]
From
the Oracle Error Messages documentation
:
ORA-12532: TNS:invalid argument
Cause:
An internal function received an invalid parameter.
Action:
Not normally visible to the user. For further details, turn on tracing and reexecute the operation. If error persists, contact Oracle Customer Support.
Have you followed that path yet?


q:
If I create a UserControl and add some objects to it, how can I grab the HTML it would render?

ex.

UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());

// ...something happens

return strHTMLofControl;

I'd like to just convert a newly built UserControl to a string of HTML.

[A]
Call its
```
.RenderControl()
```
method.


q:
I am using this code to verify a behavior of a method I am testing:

    _repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
    .Returns(new List<JSOFile>())
    .AtMostOnce()
    .Verifiable();

_repository is defined as:

private Mock<IRepository<JSOFile>> _repository;

When my test is run, I get this exception:

Expression t => (t.STATUS_CD = "A") is not supported.

Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?

Thanks!!

[A]
In Rhino Mocks you would do something like this...
Instead of using an Expect, use a Stub and Ignore the arguments.  Then have --
```
```
Func<JSOFile, bool> _myDelegate;

_repository.Stub(f => FindAll(null)).IgnoreArguments()
   .Do( (Func<Func<JSOFile, bool>, IEnumerable<JSOFile>>) (del => { _myDelegate = del; return new List<JSOFile>();});
```
```
Call Real Code
*Setup a fake JSOFile object with STATUS_CD set to "A" *
```
```
Assert.IsTrue(_myDelegate.Invoke(fakeJSO));
```
```


q:
How Can I put information in a outputstream from tapestry5 ?

I need a page when a user enters it open a dialog for save or open the file with the outputstream information.

I write the next code:

public class Index {

@Inject
private RequestGlobals requestGlobals;

@OnEvent("activate")
public void onActivate() {
    try {
        HttpServletResponse response = requestGlobals.getHTTPServletResponse();
        response.setContentType("text/txt");
        PrintWriter out = response.getWriter();
        out.println("hellooooooo");
        out.flush();
    } catch (IOException ex) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

I hope that the result is only "helloooooooo" but is ("helloooooooo" + my html raw page)

[A]
Your method should have a return type of StreamResponse. You return an implementation of the interface StreamResponse, which simply returns the data you want with the content type you want.
Look it up here:
http://tapestry.apache.org/tapestry5/apidocs/
more info here:
http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html


q:
I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C?

The following code compiles successfully with gcc -std=c89 and gcc -ansi:

#include <stdio.h>
int main() {
    int i;
    for (i = 0; i < 10; i++) {
        char c = (i % 95) + 32;
        printf("%i: %c\n", i, c);
        char *s;
        s = "some string";
        puts(s);
    }
    return 0;
}

Shouldn't the declarations of c and s cause an error in C89/ANSI mode?

[A]
It compiles successfully because GCC allows the declaration of
```
s
```
as a GNU extension, even though it's not part of the C89 or ANSI standard. If you want to adhere strictly to those standards, you must pass the
```
-pedantic
```
flag.
The declaration of
```
c
```
at the start of a
```
{ }
```
block is part of the C89 standard; the block doesn't have to be a function.


q: Is there any plugins for Eclipse for portlet design and deployment? I have never designed portlets so are there any good tutorials on the web as well?

[A]
You do have a
tutorial
about portlet development (not portlet deployment though, that would be through an appropriate
eclipse-maven configuration
)
Portal eclipse
can also help to develop portlet in eclipse.


q:
Can someone explain to me the difference between these 3 approaches to processing messages that fail delivery?

Poison Queue service

Dead-Letter Queue service

Using a response service to handle failures

I have "Programming WCF", but I don't really understand when you would use one of these over another, or when it would make sense to use more than one of them. Thanks!

[A]
Poison message / dead letter message queues are used to place messages that have been determined to be undeliverable in a queue that will not try to deliver them anymore. You would do this if you might want to manually take a look at failed messages and process them at a later point. You use these type of queues when you want to keep bad messages from degrading the performance of your system by retrying over and over again.
On the other hand, a response service would be used to notify the sender that there was an error processing the message. Typically in this case you aren't planning on manually processing the bad message and need to let the system that sent the message in that the request has been rejected.
Note that these aren't exclusive. If you are using queues, there is always the chance that the message serialization might change enough to break messages that are in the queue in which case you might still want to have a dead letter queue even if you are using a response service.


q:
I am trying to link the as3corelib library to use their JSON functionality following this tutorial. But am having trouble compiling it. My command looks like:

mxmlc --strict=true -library-path+=as3corelib.swc --file-specs  myapp.mxml

But I am getting this error:

_divided_mx_managers_SystemManager.as(13): col: 14 Error: Interface method getVisibleApplicationRect in namespace mx.managers:ISystemManager not implemented by
class _divided_mx_managers_SystemManager.

public class _divided_mx_managers_SystemManager

What is the problem?

Update: Is this because I am using Flex 3? The tutorial seems to be for Flex 2. If so, what do I need to do for Flex 3?

[A]
Are you using the flex Gubmo sdk?
Looks like the method it's complaining about is in an interface that's part of Gumbo.
If so, then as3corelib probably won't work with it.


q: Does Xcode support anything akin to Visual Studio style #region directives for arbitrary code folding?

[A]
No, you can only fold code on various defined scoping levels in Xcode.
You can use little tricks to make navigating via the function menu easier, though.
```
```
#pragma mark
```
```
Allows you to create a grouping where the label following mark will show up in the function menu. If the label is a hyphen, a separator is inserted into the function menu.
Also, the following labels in comments will show up in the function menu:
```
```
// MARK:
// TODO:
// FIXME:
// !!!:
// ???:
```
```
Obviously since #pragma mark is not really portable, if you're building a portable application and need it to work with a compiler that doesn't just ignore #pragma directives that it doesn't understand, the comment-style mark is a decent alternative.


q:
Anyone knows a good way to resize any window to for example 640x480?

Reason is, of course, screencasting.

Under windows I've used ZoneSize from donationcoder. (Btw: For Firefox it's easy, just use the web developer toolbar.)

[A]
Use the
wmctrl
command:
To list the windows:
```
```
$ wmctrl -l
0x00c00003 -1 rgamble-desktop Bottom Expanded Edge Panel
0x00c00031 -1 rgamble-desktop Top Expanded Edge Panel
0x00e00022 -1 rgamble-desktop Desktop
0x0260007c  0 rgamble-desktop Google - Mozilla Firefox
```
```
To resize a window based on its title:
```
```
wmctrl -r Firefox -e 0,0,0,640,480
```
```
The arguments to the resize option are
```
gravity,X,Y,width,height
```
so this will place the window at the top-left corner of the screen and resize it to 640X480.


q:
Here is what I am trying to do:
Given a date, a day of the week, and an integer n, determine whether the date is the nth day of the month.

For example:

input of 1/1/2009,Monday,2
would be false because 1/1/2009 is not the second Monday

input of
11/13/2008,Thursday,2
would return true because it is the second Thursday

How can I improve this implementation?

private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
    int d = date.Day;
    return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}

[A]
You could change the check of the week so the function would read:
```
```
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
  int d = date.Day;
  return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
```
```
Other than that, it looks pretty good and efficient.


q:
How can I create a Sidebar form in delphi.

I try the ScreenSnap and Align properties but I need that the form stay visible even if the user maximize other forms, without been on top. Just like the windows sidebar do.

Update: From the comments: if a window is maximized, it maximizes next to the window, not in front of or behind.

[A]
You can call a Windows API function to force your application to stay on top:
```
```
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
```
```


q:
I am really stuck with this Parser Error Message telling me "Could not load the assembly 'App_Web_amlohswi'. Make sure that it is compiled before accessing the page."  I have been looking around for a few hours checking different posts here and googling information.  I have found out that I need to set up a new Application Pool that runs .NET 2.x.

(On a side note, my app is being developed in .NET 3.5, is there a way to set it up to use 3.5 instead of 2.x?)

Can someone provide me with a good explaination on how to set this up properly and (optionally) why is it necessary?

I am more used to developing in PHP so I am used to edit src >> upload >> success!

Thanks!

[A]
ASP.NET 3.5 sites run in 2.0 app pools as long as that version of .NET is installed on the system.
You may have to set up web.config properly. Visual Studio should do this for you when you create a new project.
You should also make sure you don't combine 1.1 and 2.0 applications in the same app pool. Try putting it in a separate app pool and see that helps.


q:
I have a web application project (wap) that is successfully being deployed to a development server by our tfsbuild server.

I'd like the build server to run our collection of webtests after deployment.

What is a best practice (or ANY practice) for doing this?

[A]
You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :
```
```
IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());
```
```
The first two bytes do not seem to be used, but in the case of AF_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.
You might also want to make sure that your code will handle IPv6 (AF_INET6) properly, or handle the fact that AF_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.


q: When using regular expressions in Ruby, what is the difference between $1 and \1?

[A]
\1 is a backreference which will only work in the same
```
sub
```
or
```
gsub
```
method call, e.g.:
```
```
"foobar".sub(/foo(.*)/, '\1\1') # => "barbar"
```
```
$1 is a global variable which can be used in later code:
```
```
if "foobar" =~ /foo(.*)/ then
  puts "The matching word was #{$1}"
end
```
```
Output:
```
```
"The matching word was bar"
# => nil
```
```


q: Here's the scenario - a client uploads a Sybase dump file to (gzipped) to our local FTP server. We have an automated process which picks these up and then moves them to different server within the network where the database server resides. Unfortunately, this transfer is over a WAN, which for large files takes a long time, and sometimes our clients forget to FTP in binary mode, which results in 10GB of transfer over our WAN all for nothing as the dump file can't be loaded at the other end. What I'd like to do, is verify the integrity of the dump file on the local server before sending it out over the WAN, but I can't just try and "load" the dump file, as we don't have Sybase installed (and can't install it). Are there any tools or bits of code that I can use to do this?

[A]
There is no way to really verify the integrity of the dump file without loading it in some way by a backup server. The client should know whether the dump is successful or not via the backup log or output during the dump.
But to solve your problem you should use to SFTP or SCP, all transfers are done in binary, alleviating your problem.
Ensure that they are also using compression in the dump a value of 1-3 is more than enough, this should reduce your network traffic also.


q:
I have a form that excepts a file upload in ASP.NET. I need to increase the max upload size to above the 4 MB default.

I have found in certain places referencing the below code at msdn.

[ConfigurationPropertyAttribute("maxRequestLength", DefaultValue = )]

None of the references actually describe how to use it, and I have tried several things with no success. I only want to modify this attribute for certain pages that are asking for file upload.

Is this the correct route to take? And how do I use this?

[A]
If its windows 2003 / IIS 6.0 then check out AspMaxRequestEntityAllowed = "204800" in the file
metabase.xml
located in folder C:\windows\system32\inetsrv\
The default value of "204800" (~205Kb) is in my opinion too low for most users. Just change the value to what you think should be max.
If you cant save the file after editing it you have to either stop the ISS-server or enable the server to allow editing of the file:
(source:
itmaskinen.se
)
Edit: I did not read the question correct (how to set the maxrequest in webconfig). But this informatin may be of interrest for other people, many people who move their sites from win2000-server to win2003 and had a working upload-function and suddenly got the
Request.BinaryRead Failed
error will have use of it. So I leave the answer here.


q: How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?

[A]
You definitely can. Consider a Form class which stores information about the form itself: the
```
method
```
,
```
action
```
,
```
enctype
```
attributes. Also throw in stuff like an optional heading and/or description text at the top. Of course you will also need an array of input elements. These could probably be put into their own class (though subclassing them for InputText, InputCheckbox, InputRadio maybe be a bit over the top). Here's a vague skeleton design:
```
```
class Form {
    var $attributes,    // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]
        $heading,
        $description,
        $inputs        // array of FormInput elements
    ;

    function render() {
        $output = "<form " . /* insert attributes here */ ">"
              . "
" . $this->heading . "
"
              . "
" . $this->description . "
"
        ;
        // wrap your inputs in whatever output style you prefer:
        // ordered list, table, etc.
        foreach ($this->inputs as $input) {
            $output .= $input->render();
        }
        $output .= "</form>";
        return $output;
    }
}
```
```
The FormInput class would just need to store the basics, such as type, name, value, label. If you wanted to get tricky then you could apply validation rules which would then be converted to Javascript when rendering.


q:
Say I have a sql query

SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users

Now say the records are now either in dictionary base or a strongly typed collection.

I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.

Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.

This is a test project as I am getting familiar with the web world wqith VS-2008

[A]
Perhaps LINQ and an anonymous class could do the trick for you.
```
```
from user in UserCollection
select new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn }
```
```


q: What does the quote "Level of Indirection solves every Problem" mean in Computer Science?

[A]
Generally it means that by increasing the level of abstraction one can make the problem easier to understand/resolve.
Be careful with your abstractions though, the full quote at least as I heard it is, "You can solve every problem with another level of indirection, except for the problem of too many levels of indirection".


q:
I am using SQL Server Reporting Services 2008 (though this seems to be an issue for me in 2005 also).  I have a report that has one page per customer (i.e. paged on customerId).  The odd thing I'm seeing is that the first report (i.e. first page of the report) has a bit of extra white space at the top than the other pages.  In general this seems to occur when you have a title for the report and paging (so that the first page has the title, but each successive page does not).  The report I'm dealing with does not have a title like that, but still has this extra white space.

What I'm wondering is how do I prevent that extra white space on this first page of the report.  How do I make each page of the report identical?

I do not have a header or footer applied to the report either.

[A]
There are a couple of different causes for extra space at the top of the HTML render of a page in any version of Reporting Services.  There are a couple of tricks to working around this depending upon the cause of the problem:
Move the title from the Header to the Body of the report.  If the title is a label, this doesn't always help.
If you are using a table, then add a separate row to the header of the table.  This seems to work very well, particularly when you render to Excel.  However, not all report requirements can support this as a solution.
In SSRS 2000/2005, if you are using a container such as a rectangle or group, then the odds that you will having a spacing issue increase.  If you can move the title out of the container, then this can help reduce the likelihood of a problem.  I haven't tried using the Tablix grouping controls in SSRS 2008, so I can't tell if this will work in SSRS 2008.
If you keep the header and footer objects on even you aren't adding any labels to the regions, then these can lead to extra spaces on the first page.
It is difficult to give you better advice without reproducing your exact problem.  If you want to post the code for a sample RDL file temporarily, then I can try to reproduce the problem in SSRS 2008 on my machine and see if I can provide you with a custom solution to your problem.


q:
I need to construct some rather simple SQL, I suppose, but as it's a rare event that I work with DBs these days I can't figure out the details.

I have a table 'posts' with the following columns:

id, caption, text

and a table 'comments' with the following columns:

id, name, text, post_id

What would the (single) SQL statement look like which retrieves the captions of all posts which have one or more comments associated with it through the 'post_id' key? The DBMS is MySQL if it has any relevance for the SQL query.

[A]
You're basically looking at performing a subquery --
```
SELECT p.caption FROM posts p WHERE (SELECT COUNT(*) FROM comments c WHERE c.post_id=p.id) > 1;
```
This has the effect of running the
```
SELECT COUNT(*)
```
subquery for each row in the posts table. Depending on the size of your tables, you might consider adding an additional column,
```
comment_count
```
, into your
```
posts
```
table to store the number of corresponding
```
comments
```
, such that you can simply do
```
SELECT p.caption FROM posts p WHERE comment_count > 1
```


q:
I've written a cheap & cheerful sound board in for my Mac, and I play the various sounds with NSSound like this:

-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
    BOOL wasPlaying = FALSE;

    if([nowPlaying isPlaying])  {
        [nowPlaying stop];
        wasPlaying = TRUE;
    }

    if(soundEffect != nowPlaying)
    {
        [soundEffect play];
        nowPlaying = soundEffect;
    } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
        [nowPlaying play];
    }
}

Rather than just stop it dead, I'd like it to fade out over a couple of seconds or so.

[A]
Something like this perhaps? You probably want a more linear dropoff, but the basic idea is make a loop and sleep the period of time till the next update.
```
```
if([nowPlaying isPlaying])  {
    for(int i = 1; i < 100; ++i)
    {
        [nowPlaying setVolume: (1.0 / i)];
        Sleep(20);
    }
    [nowPlaying stop];
    wasPlaying = TRUE;
}
```
```


q:
I've heard that enabling Link-Time Code Generation (the /LTCG switch) can be a major optimization for large projects with lots of libraries to link together. My team is using it in the Release configuration of our solution, but the long compile-time is a real drag. One change to one file that no other file depends on triggers another 45 seconds of "Generating code...". Release is certainly much faster than Debug, but we might achieve the same speed-up by disabling LTCG and just leaving /O2 on.

Is it worth it to leave /LTCG enabled?

[A]
It is hard to say, because that depends mostly on your project - and of course the quality of the LTCG provided by VS2005 (which I don't have enough experience with to judge). In the end, you'll have to measure.
However, I wonder why you have that much problems with the extra duration of the release build. You should only hand out reproducible, stable, versioned binaries that have reproducible or archived sources. I've rarely seen a reason for frequent, incremental release builds.
The recommended setup for a team is this:
Developers typically create only incremental debug builds on their machines. Building a release should be a complete build from source control to redistributable (binaries or even setup), with a new version number and labeling/archiving the sources. Only these should be given to in-house testers / clients.
Ideally, you would move the complete build to a separate machine, or maybe a virtual machine on a good PC. This gives you a stable environment for your builds (includes, 3rd party libraries, environment variables, etc.).
Ideally, these builds should be automated ("one click from source control to setup"), and should run daily.


q:
Can someone show me how to get the top & left position of a div or span element when one is not specified?

ie:

<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>

In the above, if I do:

document.getElementById('11a').style.top

The value of 55px is returned. However, if I try that for span '12a', then nothing gets returned.

I have a bunch of div/spans on a page that I cannot specify the top/left properties for, but I need to display a div directly under that element.

[A]
This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
```
```
function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}
```
```
However, if you just wanted the x,y position of the element relative to its container, then all you need is:
```
```
var x = el.offsetLeft, y = el.offsetTop;
```
```
To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.
```
```
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
```
```


q: How can I check whether a variable is defined in Ruby?  Is there an isset-type method available?

[A]
```
defined?(your_var)
```
will work. Depending on what you're doing you can also do something like
```
your_var.nil?
```


q:
I need to generate random numbers within a specified interval, [max;min].

Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.

Currenly I am generating as:

for(int i=0; i<6; i++)
{
    DWORD random = rand()%(max-min+1) + min;
}

From my tests, random numbers are generated around one point only.

Example
min = 3604607;
max = 7654607;

Random numbers generated:

3631594
3609293
3630000
3628441
3636376
3621404

From answers below: OK, RAND_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?

[A]
If you want numbers to be uniformly distributed over the range, you should break your range up into a number of equal sections that represent the number of points you need. Then get a random number with a min/max for each section.
As another note, you should probably not use
```
rand()
```
as it's not very good at actually generating random numbers. I don't know what platform you're running on, but there is probably a better function you can call like
```
random()
```
.


q:
We have an internal .NET case management application that automatically creates a new case from an email. I want to be able to identify other emails that are related to the original email so we can prevent duplicate cases from being created.

I have observed that many, but not all, emails have a thread-index header that looks useful.

Does anybody know of a straightforward algorithm or package that we could use?

[A]
As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.
However, you'll get a pretty high hit rate with the following:
Every email message should have a unique "Message-ID" field. Find this, and keep a record of it as a part of the case. (See
RFC-822
)
If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.
Check for the "In-Reply-To" field, if the ID shown matches a known Message-ID then you know the email is related.
The "References" and "Original-Message-ID" headers have similar meanings.
If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.
The internet standards
RFC-822
,
RFC-2076
and
RFC-4021
may be useful further reading.
Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, "Close as Duplicate Case" or "Merge with Duplicate Case", along with tools to make it easier to find duplicates.


q:
I'm writing a website in JSP using Struts and Hibernate. I'm looking for a way to implement a rich UI where you can have more than just buttons. For examples, drag and drops, drop down lists that updates itself in real time as you type more letters out etc. Is there a way to use something like Swing with Struts and Hibernate? Or are there any other options available for making a rich UI?? (I'm open to abandon Struts and/or Hibernate if there are better alternatives)

Fundamental problem: The organization I work for have strict rules about what development tools and open source libraries we can or cannot use, and is pretty slow on updating their approval list. None of the AJAX things (e.g. GWT, dojo) are on the list yet.

Thank you for taking the time to read this post!


q:
Say I have a method that needs to pull 8 values from a map with 100 elements in it. Which do you think would be preferable:

Walk in a for loop from begin to end once, pulling the elements out by switching on the key?

Or using find 8 times to get those values?

[A]
I would use find 8 times.  It will be less (and more obvious) code.
You should try not make performance judgements based on small numbers since (a) it isn't likely to be a performance bottleneck either way at this size and (b) the numbers may change in the future -- choose the algorithm with the best asymptotic performance.
Note: you mention 'switching' on the key ... that may apply in your case, but in general you can't switch on the key value in a map.  Allowing for this would make the code to searching for M items in a map by iteration even more complex.


q:
For instance, does the compiler know to translate

string s = "test " + "this " + "function";

to

string s = "test this function";

and thus avoid the performance hit with the string concatenation?

[A]
Yes. This is guaranteed by the C# specification. It's in section 7.18 (of the C# 3.0 spec):
Whenever an expression fulfills the
  requirements listed above, the
  expression is evaluated at
  compile-time. This is true even if the
  expression is a sub-expression of a
  larger expression that contains
  non-constant constructs.
(The "requirements listed above" include the + operator applied to two constant expressions.)
See also
this question
.


q:
Getting the subdomain from a URL sounds easy at first.

http://www.domain.example

Scan for the first period then return whatever came after the "http://" ...

Then you remember

http://super.duper.domain.example

Oh. So then you think, okay, find the last period, go back a word and get everything before!

Then you remember

http://super.duper.domain.co.uk

And you're back to square one. Anyone have any great ideas besides storing a list of all TLDs?

[A]
Anyone have any great ideas besides
  storing a list of all TLDs?
No, because each TLD differs on what counts as a subdomain, second level domain, etc.
Keep in mind that there are top level domains, second level domains, and subdomains.  Technically speaking, everything except the TLD is a subdomain.
In the domain.com.uk example, "domain" is a subdomain, "com" is a second level domain, and "uk" is the TLD.
So the question remains more complex than at first blush, and it depends on how each TLD is managed.  You'll need a database of all the TLDs that include their particular partitioning, and what counts as a second level domain and a subdomain.  There aren't too many TLDs, though, so the list is reasonably manageable, but collecting all that information isn't trivial.  There may already be such a list available.
Looks like
http://publicsuffix.org/
is one such list—all the common suffixes (.com, .co.uk, etc) in a list suitable for searching.  It still won't be easy to parse it, but at least you don't have to maintain the list.
A "public suffix" is one under which
  Internet users can directly register
  names. Some examples of public
  suffixes are ".com", ".co.uk" and
  "pvt.k12.wy.us". The Public Suffix
  List is a list of all known public
  suffixes.
The Public Suffix List is an
  initiative of the Mozilla Foundation.
  It is available for use in any
  software, but was originally created
  to meet the needs of browser
  manufacturers. It allows browsers to,
  for example:
Avoid privacy-damaging "supercookies" being set for
  high-level domain name suffixes
Highlight the most important part of a domain name in the user
  interface
Accurately sort history entries by site
Looking through the list
, you can see it's not a trivial problem.  I think a list is the only correct way to accomplish this...


q:
I have this code in my aspx page;

<a href="javascript:void(0);" onclick=<% Print(); %> title="Print listings">Print</a>

which presents a link to print a listings to a pdf when the user clicks on it; as you can note the script calls a function from the behind code.

The problem is that when I coded this it happens that when I go this page it prints to pdf when is loading, I thought it would wait for a click but instead it performs the printing.

What is the problem? thanks in advance.

PD. I'm working with VS2005 and for the pdf creation I use iTextSharp.

[A]
Its a bit hard to tell exactly what is happening from your code snippet, but I would assume that you are outputting the pdf file to the response stream as part of the print() function.
This is will display the pdf on load because the code behind is evaluated at render time (just before it sends the code to the browser) instead of being evaluated on the client.
To get the behavior you would like the best method is to create a http handler file (ashx) that will accept any required arguments as request variables on the url and will then output the pdf to the stream.
You can then just create a href to the ashx file with the correct arguments to dispaly the document.


q:
Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:

assertEquals(expectedValue, actualValue);

hit Ctrl + Shift + O and have Eclipse add:

import static org.junit.Assert.assertEquals;

Maybe I'm asking too much.

[A]
Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede),  go to
Window->Preferences->Java->Editor->Content Assist
and check the checkbox for
Use static imports (only 1.5 or higher)
.
This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (
CTRL
+
1
) on the line it will give you the option to add the static import which is good enough.


q:
I need to replace our Ajax Modal Popup controls with a JavaScript equivalent. We use this as a simple context sensitive help type popup. I did a quick browse but didn't see quite what I was looking for. I just need some text and a simple Close button/link, but I would like the page darkened below the popup, as it does with the Ajax modal control.

Can anyone suggest a nice JavaScript popup/help type solution that you've used?

[A]
Maybe you are looking for something like
this
? [ui.jquery.com]
It's the simplest one, and can come bundled with a lot of other eye candy. Of course you could also look around the rest of the
jQuery plug-ins page
, specially the
Windows and Overlays section
.


q:
C#: How would you cycle through items in a listview using next and previous buttons?

Background:

Let's say you have 10 items in a listview.

Next to the listview there are two buttons titled previos and next.

Problem:

How would you cycle through those listview items after clicking the Next and or Previous button?

[A]
Without testing it, I'm guessing this would work:
```
```
for(int i=0;i<listView.Items.Count;i++)
      listView.Items[i]
```
```


q:
Is there a way I can set up callbacks on (or automataically log) method parameters, entries, and exits without making explicit calls within each method? I basically want to log this information to my logger class (which is static) without having to do it manually for each method.

Right now I have to call Logger::logEntry() and Logger::logExit() in every method to accomplish this. I would love to not have to do this:

class TestClass {
    public function tester($arg) {
        Logger::logEntry();
        Logger::info('Parameter $arg => ' . $arg);

        // Do some stuff...

        Logger::logExit();
    }
}

[A]
you could use the magic function
```
__call
```
. It gets called when no functions match that name. Rename your methods to be prefixed with something, (eg: underscore), and optionally set them to private/protected.
```
```
class TestClass {
    public function __call($function, $args) {
        Logger::logEntry();
        Logger::info('Parameters: ' . implode(", ", $args);

        $localFunc = "_" . $function;
        $return = $this->$localFunc($args);

        Logger::logExit();

        return $return;
    }

    private function _tester() {
        // do stuff...
        return "tester called";
    }
}

 $t = new TestClass();
 echo $t->tester();
 // "tester called"
```
```


q: I have a string which holds a decimal value in it and I need to convert that string into a floating point variable. So an example of the string I have is "5.45" and I want a floating point equivalent so I can add .1 to it. I have searched around the internet, but I only see how to convert a string to an integer.

[A]
You don't need to convert it at all:
```
```
% perl -e 'print "5.45" + 0.1;'
5.55
```
```


q:
To send a serial string character to the serial port.  I would need to call WriteFile(handle, "A", strlen("A"), ...)

However, what if I want to specify and send a hex or binary number?  For example, I want to send WriteFile(handle, 0x41, sizeOf(0x41), ...) ?

Is there a function that allow me to do this?

[A]
If you just want to write one byte, it still needs to be in an array.
So you would need:
```
```
int buffer[1024];
buffer[0] = 42;

WriteFile(handle, buffer, 1);
```
```
See this:
http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx


q:
Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the $n values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.

Python does it like so:

>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> match = regex.match('42')
>>> print match.groupdict()
{'count': '42'}

I know the ?P indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?

[A]
AFIK
PCRE
has named group capturing as:
```
```
(?'NAME'pattern)
(?<NAME>pattern)
```
```
You can find info
here
.


q:
I'm looking to calculate the number of months between 2 date time fields.

Is there a better way than getting the Unix timestamp and then dividing by 2 592 000 (seconds) and rounding up within MySQL?

[A]
The
DATEDIFF
function can give you the number of days between two dates.  Which is more accurate, since... how do you define a month?  (28, 29, 30, or 31 days?)


q:
I was trying to follow some instructions today, and it starts with the comment

REM  In SQLPlus I manually copy in each line and execute it.

That's nice, I don't have SQLPlus, I have SQLDeveloper.  The lines that were pasted in were of the type:

@\\server\dir\dir\dir\commandfile1.txt;
COMMIT;

...etc.

It didn't like it when I tried that in a SQL window.  I opened up and pasted in the commands by hand, and it wasn't happy with that either.  (Did I mention that I'm not so good with this application nor Oracle, but that everyone else was out today?)  The files there started with code like:

rem
set echo on
rem
execute procedure_name ('parameter1', 'parameter2');

A co-worker did have SQLPlus, and together we got it resolved.  But, is there a way for me to do this with SQLDeveloper, so I'm not stuck if he's out too?

[A]
This would do it:
```
```
begin
    procedure_name ('parameter1', 'parameter2');
end;
/
```
```


q:
I was wondering if anyone can help me get started with creating a room in Sandy 3D. I know I can generate the planes, but I am unsure as to how to implement simple physics (i.e. the player cannot walk through a wall). Is there a simple way to do this, or should I look into something like WOW (3D physics engine for Flash)?

Thanks,
Cameron


q: I have a MySQL table where an indexed INT column is going to be 0 for 90% of the rows. If I change those rows to use NULL instead of 0, will they be left out of the index, making the index about 90% smaller?

[A]
It looks like it does index the
```
NULL
```
s too.
Be careful when you run this because MySQL will LOCK the table for WRITES during the index creation. Building the index can take a while on large tables even if the column is empty (all nulls).
Reference
.


q:
I have an Asp.Net 1.1 application that uses the following code to write out an image file to a pop up web page.

    Response.ContentType="image/tiff"   'Only for Tif files
    Dim objStream As Object
    objStream = Server.CreateObject("ADODB.Stream")
    objStream.open()
    objStream.type = 1
    objStream.loadfromfile(localfile)
    Response.BinaryWrite(objStream.read)

I'm testing this out with TIF files. The files are being displayed correctly in IE6 and Safari but in IE7 they are not displaying and nothing seems to be returning to the web page. Files with jpg, gif extensions are being displayed properly. What might be the problem here?

[A]
Have you tried setting the
Content-Disposition
to Inline?
```
```
Response.AppendHeader("Content-Disposition", "inline");
```
```


q:
I am trying to write a console app that simply lists the number of lists at the sharepoint root.

I tried doing it by using the following code, but the object SPContext.Current is null.  Any ideas of how to get the web object?

 SPWeb web = SPContext.Current.Site.OpenWeb("http://localhost") ;

[A]
```
```
SPSite spSite = new SPSite("http://myurl");
SPWeb spMySite = spSite.Allwebs["mysite"];
SPWeb spRootsite = spsite.RootWeb;
```
```
The console app will only run on the server as usual.
Also, the url used
http://myurl
can be a url to a page and an SPSite object will be created. E.g.
http://myurl/mysite/pages/default.aspx
will get a valid SPSite object.


q:
It seems like the classical way to handle transactions with JDBC is to set auto-commit to false. This creates a new transaction, and each call to commit marks the beginning the next transactions.
On multithreading app, I understand that it is common practice to open a new connection for each thread.

I am writing a RMI based multi-client server application, so that basically my server is seamlessly spawning one thread for each new connection.
To handle transactions correctly should I go and create a new connection for each of those thread ?
Isn't the cost of such an architecture prohibitive?

[A]
Yes, in general you need to create a new connection for each thread.  You don't have control over how the operating system timeslices execution of threads (notwithstanding defining your own critical sections), so you could inadvertently have multiple threads trying to send data down that one pipe.
Note the same applies to any network communications.  If you had two threads trying to share one socket with an HTTP connection, for instance.
Thread 1 makes a request
Thread 2 makes a request
Thread 1 reads bytes from the socket, unwittingly reading the response from thread 2's request
If you wrapped all your transactions in critical sections, and therefore lock out any other threads for an entire begin/commit cycle, then you might be able to share a database connection between threads.  But I wouldn't do that even then, unless you really have innate knowledge of the JDBC protocol.
If most of your threads have infrequent need for database connections (or no need at all), you might be able to designate one thread to do your database work, and have other threads queue their requests to that one thread.  That would reduce the overhead of so many connections.  But you'll have to figure out how to manage connections per thread in your environment (or ask another specific question about that on StackOverflow).
update:
To answer your question in the comment, most database brands don't support multiple concurrent transactions on a single connection (InterBase/Firebird is the only exception I know of).
It'd be nice to have a separate transaction object, and to be able to start and commit multiple transactions per connection.  But vendors simply don't support it.
Likewise, standard vendor-independent APIs like JDBC and ODBC make the same assumption, that transaction state is merely a property of the connection object.


q:
I am having a Html hyperlink. I need to link this hyperlink to another page.When I place the mouse over the link. It should show the image.
how to do this

[A]
you can do this using javascript..
This will create a square that follows your mouse on div or element hover.
Create a .js file with those contents here:
```
```
var WindowVisible = null;
function WindowShow() {
    this.bind = function(obj,url,height,width) {
        obj.url = url;
        obj.mheight = height;
        obj.mwidth = width;
        obj.onmouseover = function(e) {
            if (WindowVisible == null) {
                if (!e) e = window.event;
                var tmp = document.createElement("div");
                tmp.style.position = 'absolute';
                tmp.style.top = parseInt(e.clientY + 15) + 'px';
                tmp.style.left = parseInt(e.clientX + 15) + 'px';
                    var iframe = document.createElement('iframe');
                    iframe.src = this.url;
                    iframe.style.border = '0px';
                    iframe.style.height = parseInt(this.mheight)+'px';
                    iframe.style.width = parseInt(this.mwidth)+'px';
                    iframe.style.position = 'absolute';
                    iframe.style.top = '0px';
                    iframe.style.left = '0px';
                tmp.appendChild(iframe);
                tmp.style.display = 'none';
                WindowVisible = tmp;
                document.body.appendChild(tmp);
                tmp.style.height = parseInt(this.mheight) + 'px';
                tmp.style.width = parseInt(this.mwidth) + 'px';
                tmp.style.display = 'block';
            }
        }
        obj.onmouseout = function() {
            if (WindowVisible != null) {
                document.body.removeChild(WindowVisible);
                WindowVisible = null;
            }
        }
        obj.onmousemove = function(e) {
            if (!e) e = window.event;
            WindowVisible.style.top = parseInt(e.clientY + 15) + 'px';
            WindowVisible.style.left = parseInt(e.clientX + 15) + 'px';
        }
    }
}
```
```
Then in your html do the following:
Include the .js file
```
<script type="text/javascript" src="myfile.js"></script>
```
Put in your web page:
```
```

```
```
Here is a full implementation in a HTML:
```
```

    <title>test page</title>

```
```
bye bye!


q:
Is there a better free TreeView control that exists for Visual Studio 2008 / .NET 3.5?

I believe I need something a little more powerful than the out-of-the box version. I'm not exactly sure for what yet but I thought I'd ask quickly before I get too far in to my project.

[A]
TreeViewAdv
seems to be pretty nice. It is described with the following features on SourceForge.net:
Extensible advanced TreeView.
100% management C# code.
Features: Model/View architecture.
Multicolumns.
Multiselection.
Different controls for each node: CheckBox, Icon, Label ...
Drag&Drop highlighting.
Load on demand.
Incremental search.
We will most likely use this in one or two occasions in an upcoming project, IIRC.
HTH


q:
Example C API signature:

void Func(unsigned char* bytes);

In C, when I want to pass a pointer to an array, I can do:

unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call

How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?

[A]
You can use unsafe code:
```
```
unsafe
{
     fixed(byte* pByte = byteArray)
     IntPtr intPtr = new IntPtr((void *) pByte);
     Func(intPtr);
}
```
```
If you need to use safe code, you can use a few tricks:
```
```
IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray));
Marshal.Copy(byteArray, 0, intPtr, Marshal.SizeOf(byteArray));

Func(intPtr);

Marshal.FreeHGlobal(intPtr);
```
```
However, the safe code is going to be slow IMHO.


q:
When do you call Microsoft.Security.Application.AntiXss.HtmlEncode?  Do you do it when the user submits the information or do you do when you're displaying the information?

How about for basic stuff like First Name, Last Name, City, State, Zip?

[A]
You should only encode or escape your data at the last possible moment, whether that's directly before you put it in the database, or display it on the screen. If you encode too soon, you run the risk of accidentally double encoding (you'll often see
```
&amp;
```
on newbies' websites - myself included).
If you do want to encode sooner than that, then take measures to avoid the double encoding. Joel wrote an article about good uses for hungarian notation, where he advocated use of prefixes to determine what is stored in the variable. eg: "us" for unsafe string, "ss" for safe string.
```
```
usFirstName = getUserInput('firstName')

ssFirstName = cleanString(usFirstName);
```
```
Also note that it doesn't matter what the type of information is (city, zip code, etc) - leaving any of these unchecked is asking for trouble.


q:
Given the following class, what is your opinion on the best way to handle create/edit where Attributes.Count  can be any number.

public class Product {
  public int Id {get;set;}
  public string Name {get;set;}
  public IList<Attribute> Attributes {get;set;}
}

public class Attribute {
  public string Name {get;set;}
  public string Value {get;set;}
}

The user should be able to edit both the Product details (Name) and Attribute details (Name/Value) in the same view, including adding and deleting new attributes.

Handling changes in the model is easy, what's the best way to handle the UI and ActionMethod side of things?

[A]
Depends on the experience you are looking to create for the user. I have implemented something similar for tagging content. In the model, Tags are represented as IList, but the UI shows a comma delimited list in a single text field. I then handle merging the items in the list into a string to populate the text field, and I split the input to put items back into the IList in the model.
In my DAL, I then deal with converting the List into LINQ entities, handle inserts and deletes, etc.
It isn't the most straight forward code, but it isn't too difficult to manage and it gives the user an expected interface.
I'm sure there are other ways to handle it but I would focus on what would work best for the user and then work out the mapping details based on that.


q:
Given the following domain classes:

class Post {
   SortedSet tags
   static hasMany = [tags: Tag]
}

class Tag {
   static belongsTo = Post
   static hasMany = [posts: Post]
}

From my understanding so far, using a hasMany will result in hibernate Set mapping.
However, in order to maintain uniqueness/order, Hibernate needs to load the entire set from the database and compare their hashes.

This could lead to a significant performance problem with adding and deleting posts/tags
if their sets get large. What is the best way to work around this issue?

[A]
The ordering of the set is guaranteed by the
```
Set
```
implementation, ie, the
```
SortedSet
```
. Unless you use a
```
List
```
, which keeps track of indexes on the db, the ordering is server-side only.
If your domain class is in a
```
SortedSet
```
, you have to implement
```
Comparable
```
in order to enable the proper sorting of the set.
The question of performance is not really a question per se. If you want to access a single
```
Tag
```
, you should get it by its
Id
. If you want the sorted tags, well, the sort only makes sense if you are looking at all
```
Tags
```
, not a particular one, so you end up retrieving all
```
Tags
```
at once. Since the sorting is performed server-side and not db-side, there is really not much difference between a
```
SortedSet
```
and a regular
```
HashSet
```
in regards to Db.


q:
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.

I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.

Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.

[A]
See Simons answer below.  The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the
```
IsMvcAjaxRequest
```
extension method currently works is that it checks
```
Request["__MVCASYNCPOST"] == "true"
```
, and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the
```
__MVCASYNCPOST
```
value into your request and then you could take advantage of the
```
IsMvcAjaxRequest
```
extension method.
Here is a
link to the source of the IsMvcAjaxRequest extension method
for your convenience.
Alternatively, you could create a clone of the
```
IsMvcAjaxRequest
```
extension method called
```
IsjQueryAjaxRequest
```
that checks
```
Request["__JQUERYASYNCPOST"] == "true"
```
and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
```
```
public static class HttpRequestBaseExtensions
{
    public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
    {
        if (request == null)
            throw new ArgumentNullException("request");

        return request["__JQUERYASYNCPOST"] == "true";
    }
}
```
```
Checking from an action if a method is a jQuery $.ajax() request:
```
```
if (Request.IsjQueryAjaxRequest())
    //some code here
```
```
JavaScript
```
```
$('form input[type=submit]').click(function(evt) {
    //intercept submit button and use AJAX instead
    evt.preventDefault();

    $.ajax(
        {
            type: "POST",
            url: "<%= Url.Action("Create") %>",
            dataType: "json",
            data: { "__JQUERYASYNCPOST": "true" },
            success: function(data) {alert(':)');},
            error: function(res, textStatus, errorThrown) {alert(':(');}
        }
    );
});
```
```


q:
Ok, so I have VS 2008 and SVN. When I "rebuild all" a handful of my .dll's disappear from my bin folder.

I have these .dll's in a library folder and that's where I am referencing them from.

When I go to publish the app the publish fails, I think they are related. When I reboot my web.config (change something and save) this error goes away. However, the publish still fails.

When I go to the folder and update svn puts all of them back of course, but then it just happens all over again.

Thank you.

[A]
Sounds like the build procedure removes the contents of your bin directory on build.
I don't understnad where you say you are referencing them from the library folder- and they also exist in the bin directory.
Your publish could be failing for other reasons- it is most helpful to post the errors.
Updating SVN reverts the files to the latest version- so if you have no file, the latest version is the one that exists in your repository.
Things to check:
You are probably receiving errors on your build- it sounds like the DLL's are actually output from other projects in your solution, so you should check if they are building properly or if they are being output to a different directory instead of your bin folder.
Your subversion repository probably shouldn't have any binary or intermediate files such as dll, lib, exe, suo, ncb, and some others but those are the main ones.
Post more details here- from the sound of it, it seems you may be overlooking errors that you didn't post here.


q:
I was really looking at the differences between pass by value and how Java allocates objects and what java does to put objects on the stack.

Is there anyway to access objects allocated on the heap?  What mechanisms does java enforce to guarantee that the right method can access the right data off the heap?

It seems like if you were crafty and maybe even manipulate the java bytecode during runtime, that you might be able to manipulate data off the heap when you aren't supposed to?

[A]
All objects in Java are located on the heap.  I'm not quite sure what you mean by "access objects from the heap".  The only things stored on the stack are the list of functions which called into the current context and their local variables and parameters.  All local variables and parameters are either primitive types or references.
If you allocate an object using
```
new
```
(which is the only way to allocate non-primitive types; yes this includes array types), then the object is allocated on the heap, and a reference to that object is stored on either the stack or the heap, depending on if the reference is stored in a local variable/parameter or as a member of another object.
When passed as parameters to functions, all objects are passed by reference - if the function modifies the parameter, the original object is also modified.  Identically, one could also say that the object references are passed by value - if you change a parameter to refer to a new object, it will continue to refer to that object for the duration of the function, but the original object which was passed in will still refer to whatever it referred to before.  Primitive types are also passed by value.


q:
I have a form with a <textarea> and I want to capture any line breaks in that textarea on the server-side, and replace them with a <br/>.

Is that possible?

I tried setting white-space:pre on the textarea's CSS, but it's still not enough.

[A]
Have a look at the
```
nl2br()
```
function. It should do exactly what you want.


q:
So, following a tutorial I found on MSDN I've created what you might call an "engine" using DirectX and C#. I haven't seen a lot of this sort of thing (Personally, that is) done in C# and the majority seem to favour C/C++ so I'm curious as to whether using C# will come back to bite me, or whether I should just go ahead?

The reason I ask is that the tutorial stopped rather suddenly and so there's a basis of something but it's small enough to be ported without much hassle. I like C# myself, but I don't know whether there's something everyone else knows that I don't.

[A]
I suggest staying with what you are familiar with.  Use of C or C++ should only be considered in your situation if you intend to do some lower level functionality, like implement your own image processing or create custom filters or transforms (depending on what you are using directx for).
Graphic applications can have computationally intensive aspects.  Most of these have been addressed in the DirectX api- which is just as fast if you use it from C++ or from C#.
Where you would consider lower level language: If you are creating some image processing which could perform quicker natively- this only applies if it is not offered by the directx api, such as creating some custom encoders/decoders.  In this case you could create the custom component in another language- and then load it in your C# application separately.  If you are- look into using C++ Intrinsics, which allow you to program for your CPU, and also take a look at GPGPU API's like CUDA.


q: What is the point of an action returning ActionResult?

[A] ActionResult is the base class for many different types of controller results.  By returning the base class, the controller action can return different types of results depending on the outcome of the method -- a ViewResult, a RedirectToActionResult, etc.  ActionResult contains all of the data needed by the View or new Action that is the result of the current controller action.


q:
I have an Excel macro that deletes a sheet, copies another sheet and renames it to the same name of the deleted sheet. This works fine when run from Excel, but when I run it by calling the macro from Python I get the following error message:

Run-time error '1004' - Cannot rename a sheet to the same name as
  another sheet, a referenced object library or a workbook referenced by
  VisualBasic.

The macro has code like the following:

Sheets("CC").Delete
ActiveWindow.View = xlPageBreakPreview
Sheets("FY").Copy After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).Name = "CC"

and the debugger highlights the error on the last line where the sheet is renamed. I've also tried putting these calls directly in python but get the same error message.

Any suggestions are much appreciated!

Thanks.

[A]
I ran the code inside Excel VBA.
I am guessing that the following line is failing.
```
Sheets("CC").Delete
```
And that is the reason, you can't give the new sheet same name as existing (non-deleted) sheet.
Put
```
Application.DisplayAlerts = False
```
before
```
Sheets("CC").Delete
```
and
```
Application.DisplayAlerts = True
```
once you are finished with the code.
I haven't used python but it seems the library is swallowing that error for you and letting you go ahead to the next statement.
Hope that helps.


q:
I've inherited a rather large application that really could use some cleanup. There is data access code littered throughout the application. In code behinds, some in business logic classes, some inline in in classic asp pages.

What I'd like to do is refactor this code, removing all the data access code into a few DAL classes.

All the data access is done through stored procedures (Microsoft SQL 2000). There are 300-400 of them.

It seems like there should be an automated way to analyse the store procedures, and automatically generate c# methods for each of them, mapping the Method parameters to the stored procedure parameters, with a method returning a datatable.

I don't have any experience with ORM products, and I'm not sure if what I'm looking for is a full blown ORM, or just a 3rd party utility that will help generate simple wrappers around the sp calls.

[A]
If you have access to .NET Framework 3.5 and Linq to SQL, you can do it very easily, check this video:
LINQ to SQL: Using Stored Procedures
Using existing stored procedures and
  functions is easy with LINQ. We simply
  drag the stored procedures onto the
  O/R mapping surface and call them from
  the generated Data Context object.


q: Is there any HTML5 support in IE8?  Is it on the IE8 roadmap?

[A]
According to
http://msdn.microsoft.com/en-us/library/cc288472(VS.85).aspx#html
, IE8 will have "strong" HTML 5 support. I haven't seen anything discussing exactly what "strong support" entails, but I can say that yes, some HTML5 stuff is going to make it into IE8.


q:
Forgive me for a potentially silly question here, but in other programming languages (scripting ones like PHP or Perl) it is often easy to dump everything contained within a variable.

For instance, in PHP there are the var_dump() or print_r() functions. Perl has the Data::Dumper CPAN class, etc etc.

Is there something like this for Objective-C? It would be very convenient in a few cases to be able to dump everything like that, instead of using gdb to inspect each variable.

[A]
Use NSLog() to dump contents of objects. For example:
```
```
NSData* myData = //... assume this exists
NSLog(@"Contents of myData: %@", myData);
```
```
NSLog has a printf-style format string (expects an NSString object) followed by a variable list of parameters, just like printf. The replacement character %@ represents an object the description method on an object. This is useful for dumping most Objective-C objects in Cocoa.
If you want to dump the contents of an object using gdb (I see you tagged this with gdb), use the special "po" directive instead of print. For example:
```
```
gdb) po myData
```
```
will cause gdb to dump the myData object. po is a shortcut for print-object.


q:
I have included <zlib.h> in my iphone application and the source code I was mocking up the sample code of Molecules provided by Brad Larson, however, when I build the project, it returns the error as below.  Can anyone point out for me whether this is a library linking problem or am I missing something else?

"_deflate", referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o "_inflateEnd",
referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "inflateInit2",
referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "_inflate",
referenced from: -[NSData(Gzip) initWithGzippedData:] in NSData+Gzip.o "_deflateEnd",
referenced from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o "deflateInit2", referenced
from: -[NSData(Gzip) gzipDeflate] in NSData+Gzip.o ld: symbol(s) not found collect2: ld
returned 1 exit status

[A]
In your Target's
```
Build Settings
```
tab, scroll down to the
```
Other Linker Flags
```
section and make sure
```
-lz
```
is in the field. This will link against the built-in zlib, and your error should go away.
After changing the Linker Flags you must select
```
Clean
```
from the
```
Product
```
menu before building again.


q:
If I have a string "12 23 34 56"

What's the easiest way to change it to "\x12 \x23 \x34 \x56"?

[A]
```
```
string s = "12 23 34 45";
stringstream str(s), out;
int val;
while(str >> val)
    out << "\\x" << val << " "; // note: this puts an extra space at the very end also
                               //       you could hack that away if you want

// here's your new string
string modified = out.str();
```
```


q:
Say I have two lists:

var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};

Is it possible to write a LINQ statement that will generate the following list:

var result = new []{
    new {i = 1, s = "a"},
    new {i = 1, s = "b"},
    new {i = 1, s = "c"},
    new {i = 2, s = "a"},
    new {i = 2, s = "b"},
    new {i = 2, s = "c"},
    new {i = 3, s = "a"},
    new {i = 3, s = "b"},
    new {i = 3, s = "c"}
};

?

Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:

var result = list1.SelectMany(i =>  list2.Select(s => new {i = i, s = s}));

[A]
```
```
var result = from l1 in list1
             from l2 in list2
             select new { i = l1, s = l2};
```
```


q:
I want to output a timestamp with a PST offset (e.g., 2008-11-13T13:23:30-08:00). java.util.SimpleDateFormat does not seem to output timezone offsets in the hour:minute format, it excludes the colon. Is there a simple way to get that timestamp in Java?

// I want 2008-11-13T12:23:30-08:00
String timestamp = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").format(new Date());
System.out.println(timestamp);
// prints "2008-11-13T12:23:30-0800" See the difference?

Also, SimpleDateFormat cannot properly parse the example above. It throws a ParseException.

// Throws a ParseException
new SimpleDateFormat("yyyy-MM-dd'T'h:m:ssZ").parse("2008-11-13T13:23:30-08:00")

[A]
```
```
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'h:m:ss.SZ");
```
```
Is not what exactly you need?


q:
I am getting the following error when trying to install Visual Studio 2005 on my 64bit, Vista computer:

"1305.Error reading from file
  C:\Program Files (x86)\Microsoft
  Visual Studio 8\Microsoft Visual
  Studio 2005 Standard Edition -
  ENU\SITSetup.dll"

I have successfully used the same DVD's to install Visual Studio on my old XP machine, and I can find the file (SITSetup.dll) on the DVD...and copy it off...so I don't think this is a case of having a bad DVD. At the time the error message pops up, I can see the file on my hard-drive, but it has a 0 size.

I've Googled this problem, and found some ideas, but nothing has worked thus far. Any suggestions would be appreciated.

[A]
I just installed it yesterday on my Vista box (32-bit, which may be the problem). It seemed to go through fine so I don't know what to tell you other than than when I first launched the app it notified me of "known compatibility issues" and recommended that I install both the SP1 and Vista SP! updates. No further issues past that.
As such, I would suspect either a problem with the 64 bit OS (though
Microsoft says it's fine...
) or other software on your machine. If you have a virus scanner running, for instance, disable it while installing.


q:
I'm currently using Rcov to get C0 code coverage analysis for a rails project that I'm working on.

However, those results are practically meaningless- I have 100% coverage according to rcov (as it only covers C0 analysis) and I've barely written half the test cases for the functionality that exists thus far.

I'm used to the useful results from the code coverage in Visual Studio 2008 Team, which has C1 coverage.  Are there any tools that provide similar coverage for ruby?

[A]
At the moment, there are no C1 coverage tools for Ruby. In fact, there aren't
any
coverage tools other than RCov.
Until recently, it was only possible to write tools like this by patching or extending the MRI interpreter in C. Since approximately two years ago, it is also possible to extend JRuby in Java, and there is actually since last month a port of RCov for JRuby. However, this requires both a knowledge of Ruby
and
C, and a pretty deep knowledge at that, because fiddling around with the internals of MRI is not for the faint at heart.
But only with Rubinius will it be possible to write dynamic analysis tools such as code coverage tools in Ruby itself, making tool writing accessible to a much larger portion of the Ruby community. My hope is that this, coupled with the substantial financial backing of tool vendors (many major IDE vendors are either working on or have already introduced Ruby IDEs, including CodeGear (ex-Borland), IntelliJ, NetBeans, Eclipse, SapphireSteel (Ruby in Steel for Visual Studio) and even Microsoft) will lead to rapid innovation in the Ruby tooling space in 2009 and we will see things like C1, C2 coverage, NPath complexity, much more fine-grained profiling and so on.
Until then, the only idea I have is to use Java tools. The JRuby guys try to emit the proper magic metadata to make their generated bytecode at least penetrable by the Java tools. So, maybe it is possible to use Java coverage tools with JRuby. However, I have no idea whether that actually works, nor if it is supposed to work.


q:
I was remote debugging a stack overflow from a recursive function. The Visual Studio IDE only showed the first 1,000 frames (all the same function), but I needed to go up further too see what the cause was.

Does anybody know how to get VS to 'move up' in a stack listing?

Thanks.

[A]
I do not believe there is a way to do this via the UI (or even a registry hack).  My guess at the reason is showing all of the frames in a stack overflow situation can have a very negative performance impact.
Most stack frames are the result of bad recursion.  If this is the case, you can likely set a conditional breakpoint on the target function.  Set it to break only when the hit count reaches a certain level.  I'd start with a count of around 1,000.  You may have to experiment a bit to get the right count but it shouldn't take more than a few tries.


q:
Can anyone tell me what is the difference between XSDObjectGen.exe & XSD.exe?

Is there any way to make XSDObjectGen.exe work in dot net 2.0?

[A]
Looks like you can use it with VS2005 at least (according to
this article, anyway
)
Just add it to your External Tools collection of VS2005 under "Tools>>External Tools...".
Set your parameters as the following
For VB: $(ItemPath) /l:vb
/f:$(ItemFileName).vb /c /d /t
For C#: $(ItemPath) /l:cs
/f:$(ItemFileName).vb /c /d /t
It does appear that XSD and XSDObjectGen will yield different classes.  In fact, comments in this Rick Strahl article say "
they yield
very
different classes
" in the
article here
.


q: What is the keyboard short cut in Eclipse to jump to the closing brace of a scope?

[A]
Place the cursor next to an opening
or closing
brace and punch
Ctrl
+
Shift
+
P
to find the matching brace. If Eclipse can't find one you'll get a
"No matching bracket found"
message.
edit:
as
mentioned by Romaintaz below
, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.


q:
I have a string that I would like to tokenize.
But the C strtok() function requires my string to be a char*.
How can I do this simply?

I tried:

token = strtok(str.c_str(), " ");

which fails because it turns it into a const char*, not a char*

[A]
Duplicate the string, tokenize it, then free it.
```
```
char *dup = strdup(str.c_str());
token = strtok(dup, " ");
free(dup);
```
```


q:
I was reading about App Engine on wikipedia and came across some GQL restrictions:

JOIN is not supported

can SELECT from at most one table at a time

can put at most 1 column in the WHERE clause

What are the advantages of these restrictions?

Are these restrictions common in other places where scalability is a priority?

[A]
The datastore that GQL talks to is:
not a relational database like MySQL or PostgreSQL
is a Column-oriented DBMS called BigTable
One reason to have a database like this is to have a very high performance database that you can scale across hundreds of servers.
GQL is not SQL it is SQL-like.
Here are some references:
http://en.wikipedia.org/wiki/Column-oriented_DBMS
http://en.wikipedia.org/wiki/BigTable
http://code.google.com/appengine/docs/datastore/overview.html
http://code.google.com/appengine/docs/datastore/gqlreference.html


q: What is the difference between request, response and server?

[A]
A client (web user) makes a
Request
to a
Server
which processes the
Request
and determines the appropriate
Response


q:
When I'm writing some tight loop that needs to work fast I am often bothered by thoughts about how the processor branch prediction is going to behave. For instance I try my best to avoid having an if statement in the most inner loop, especially one with a result which is not somewhat uniform (say evaluates to true or false randomly).

I tend to do that because of the somewhat common knowledge that the processor pre-fetches instructions and if it turned out that it mis-predicted a branch then the pre-fetch is useless.

My question is - Is this really an issue with modern processors? How good can branch prediction expected to be?

What coding patterns can be used to make it better?

(For the sake of the discussion, assume that I am beyond the "early-optimization is the root of all evil" phase)

[A]
My answer is:
The reason AMD has been as fast or better than Intel at some points is the past is simply that they had better branch prediction.
If your code has no branch prediction, (Meaning it has no branches), then it can be expected to run faster.
So, conclusion: avoid branches if they're not necessary. If they are, try to make it so that one branch is evaluated 95% of the time.


q:
I know about code-behind files, but what is the best real-world way of Designers that are using DreamWeaver or other Design Tools to work with Visual Studio programmers?

For example, say you have a basic website with user interface forms hitting the database... the database work is definitely done by the developer but how to tie the designed forms with the database coding or client-side logic that may involve events on controls, or other GUI related tie-ins.  Are the graphic designers also controlling application flow?  There seems to be a large disconnect that needs addressed - especially when it comes time to tweak the design after it's been implemented.

[A]
The best way is to make sure that your designers have some knowledge of what kind of HTML they will be working with.
Every ASP.NET developer is aware of MS-HTML, that lovely nesting of HTML tables, but designers aren't. Designers have their own requirements to meet and they'll do them in the best manner possible. Sadly it's not often good for us.
I am always frustrated when I receive a design from our UI team which shows radio-buttons nicely layed out in a grid using floating div's. Then I have to shatter their dreams that no, I can't generate you that HTML (ok, I can with the use of ControlAdapters, but every time they are different designs!).
Try and have a 90%/ 10% rule, where 90% of the design is done before the ASP.NET starts and the 10% is done once the ASP.NET is completed, and done against ASP.NET generated HTML.
And make sure you're using source control! Code doesn't exist unless it's in source control! And thanks to the latest TFS PowerTools there's a lovely Windows Shell integration component so you don't need to use VS to check in and out now more :D


q:
Basically, I'm trying to write the following (pseudocode) in an ASP.NET HttpModule:

*pre-code*
try { handler.ProcessRequest(...) }
catch (Exception) { *error-code* }
finally { *post-code* }

I've found that I can hook into HttpModule.PreExecuteHandler for "pre-code" and .Error for "error-code".  But PostExecuteHandler doesn't seem to be running reliably.

BeginRequest and EndRequest run reliably but are too early for the code I need to write, which requires inspection of the handler that was chosen to execute.  The handler isn't chosen until after BeginRequest.

Is there a best practice for writing this kind of wrapper?

Thanks!

[A]
Add this to your Global.asax file:
```
```
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
    //
}

protected void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
    //
}
```
```
That should work 100%.


q: How can I prevent the user from being able to resize an image in designMode?  (disable the handles when image is clicked)

[A]
Say you turn contentEditable on like this:
```
```
document.body.contentEditable = true;
```
```
All you have to do is turn it off for all (or some) images.
```
```
var imgs = document.getElementsByTagName("IMG");
for (var i = 0; i < imgs.length; ++i) {
    imgs[i].contentEditable = false;
}
```
```


q:
I'm making a Java application with an application-logic-thread and a database-access-thread.
Both of them persist for the entire lifetime of the application and both need to be running at the same time (one talks to the server, one talks to the user; when the app is fully started, I need both of them to work).

However, on startup, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method dbthread.isReady()).
I wouldn't mind if app thread blocks until the db thread was ready.

Thread.join() doesn't look like a solution - the db thread only exits at app shutdown.

while (!dbthread.isReady()) {} kind of works, but the empty loop consumes a lot of processor cycles.

Any other ideas? Thanks.

[A]
This applies to all languages:
You want to have an event/listener model.  You create a listener to wait for a particular event.  The event would be created (or signaled) in your worker thread.  This will block the thread until the signal is received instead of constantly polling to see if a condition is met, like the solution you currently have.
Your situation is one of the most common causes for deadlocks- make sure you signal the other thread regardless of errors that may have occurred.  Example- if your application throws an exception- and never calls the method to signal the other that things have completed.  This will make it so the other thread never 'wakes up'.
I suggest that you look into the concepts of using events and event handlers to better understand this paradigm before implementing your case.
Alternatively you can use a blocking function call using a mutex- which will cause the thread to wait for the resource to be free.  To do this you need good thread synchronization- such as:
```
```
Thread-A Locks lock-a
Run thread-B
Thread-B waits for lock-a
Thread-A unlocks lock-a (causing Thread-B to continue)
Thread-A waits for lock-b
Thread-B completes and unlocks lock-b
```
```


q:
Is it possible to set some image as title of Navigation bar?

I think NYTimes application used a Navigation bar and title is look like image file (the reason why it's seems UINavigationBar is because they use right button to search).

[A]
You can use an
```
UIImageView
```
for the
```
UINavigationItem.titleView
```
property, something like:
```
```
self.navigationItem.titleView = myImageView;
```
```


q:
Try as I might, I'm unable to resolve an address to IP. The code snippet is shown below. I keep getting the No such host is known exception, even though I could access google with my browser (The DNS server is almost certainly working). I'm however behind company's firewall.

try
{
   foreach (IPAddress address in Dns.GetHostAddresses("www.google.com"))
   {
      Console.WriteLine(address.ToString());
   }
}
catch (SocketException e)
{
   Console.WriteLine("Source : " + e.Source); // System
   Console.WriteLine("Message : " + e.Message); // No such host is known
}

[A]
There is nothing wrong with your code.  Given that you can access www.google.com from a web browser the next most likely problem is that the web browser is using a proxy server.  The web browser is actually accessing www.google.com through the proxy server which is allowed through the firewall.  The simple application you wrote is not allowed through the firewall and is resulting in an exception.
You can verify this by looking at the proxy settings in Internet Explorer.
Tools -> Options -> Connections -> Lan Settings
There will be a proxy server group of settings.  If there is a value present, this is almost certainly your problem.


q:
I just uploaded my first ASP.NET (as part of my learning of vb.net) and got into awful mess with the connection pooling (funny things happen when there are more than 1 user of your web site) all sorted now by better use of the try catch statements (well the idea was to learn) BUT I was wondering if this is the best / final method, now if the try fails, then a LOT of the detail on the page isn't placed/updated, so if you are doing some database work and the try fails, do you reload the page ... redirect to self and hope it work the next time ... or just inform the user there was a error and they should try again ?

Thanks

[A]
You could create an app that looks for contiguous block of text disregarding formatting tags (if required).  You could do this by using a DOM parser and walking the tree, keeping track of the immediate parent (because that is your output).
Start form parent nodes and traverse the tree for each node that is just formatting, it would continue the 'count' within that sub block.  It would count the characters of the content.
Once you find the most content block, traverse back up the tree to its parent to get your answer.
I think your solution relies on how you traverse the DOM and keep track of the nodes that you are scanning.
What language are you using? Any other details for your project?  There may be language specific or package specific tools you could use as well.