q:
I have integrated SRM 5.0 into Portal. Most of the iviews are IAC i.e., all are ITS based services.

The issue is that the Portal Theme does not get reflected on these services after integration.

When a BSP or Webdynpro is integrated then the application reflects the Portal Theme when executed from Portal but the ITS services are not getting this.

I tried using SE80 and editing EBPApplication.css. In BBPGLOBAL i changed all color attributes to custom colour but no effect.

Whch property should i change to remove the blue colour.

[A]
The key value pair table, but with everything is stored as a string and with another column (if necessary) saying which type should the value be casted to.
```
```
CREATE TABLE configKVP(clientId int, key varchar, value varchar, type varchar)
```
```
If the value cannot be casted to the type, then you know it's a misconfiguration and there's no ambiguity.


q:
I want to be able to access custom URLs with apache httpclient. Something like this:

HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("media:///squishy.jpg");
int statusCode = client.executeMethod(method);

Can I somehow register a custom URL handler? Or should I just register one with Java, using

URL.setURLStreamHandlerFactory(...)

Regards.

[A]
I don't think there's a way to do this in commons httpclient. It doesn't make a whole lot of sense either, after all it is a HTTP client and "media:///squishy.jpg" is not HTTP, so all the code to implement the HTTP protocol probably couldn't be used anyways.
```
```
URL.setURLStreamHandlerFactory(...)
```
```
could be the way to go, but you'll probably have to do a lot of protocol coding by hand, depending on your "media"-protocol.

s: huggingface

c: devops

d: intermediate


q: I have a interest in a reported bug which Microsoft have made available a hotfix for. When looking on the site, I'm not able to figure out if this fix is included in a service pack or not. Do anyone know where I can find this out?

[A]
You didn't mention your product but:
List of fixes in Service Pack 1 for XP:
http://support.microsoft.com/kb/324720
List of fixes in Service Pack 2 for XP:
http://support.microsoft.com/kb/811113
List of fixes in Service Pack 3 for XP:
http://support.microsoft.com/kb/946480
List of fixes in Service Pack 1 for Vista:
http://technet.microsoft.com/en-us/library/cc749061.aspx


q:
I wrote a sample program at http://codepad.org/ko8vVCDF that uses a template function.

How do I retrict the template function to only use numbers? (int, double etc.)

#include <vector>
#include <iostream>

using namespace std;

    template <typename T>
T sum(vector<T>& a)
{
    T result = 0;
    int size = a.size();
    for(int i = 0; i < size; i++)
    {
        result += a[i];
    }

    return result;
}

int main()
{
    vector<int> int_values;
    int_values.push_back(2);
    int_values.push_back(3);
    cout << "Integer: " << sum(int_values) << endl;

    vector<double> double_values;
    double_values.push_back(1.5);
    double_values.push_back(2.1);
    cout << "Double: " << sum(double_values);

    return 0;
}

[A]
Why would you want to restrict the types in this case? Templates allow "static duck typing", so anything allowed by what your
```
sum
```
function in this case should be allowed. Specifically, the only operation required of
```
T
```
is add-assignment and initialisation by 0, so any type that supports those two operations would work. That's the beauty of templates.
(If you changed your initialiser to
```
T result = T();
```
or the like, then it would work for both numbers and strings, too.)


q: Is it possible to convert UTF8 string in a std::string to std::wstring and vice versa in a platform independent manner? In a Windows application I would use MultiByteToWideChar and WideCharToMultiByte. However, the code is compiled for multiple OSes and I'm limited to standard C++ library.

[A]
You can use the
```
codecvt
```
locale facet
. There's a specific specialisation defined,
```
codecvt<wchar_t, char, mbstate_t>
```
that may be of use to you, although, the behaviour of that is system-specific, and does not guarantee conversion to UTF-8 in any way.


q:
I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash script with sed to re-write the file.

How do I get sed to replace just the first occurrence of a string in a file rather than replacing every occurrence?

If I use

sed s/#include/#include "newfile.h"\n#include/

it replaces all #includes.

Alternative suggestions to achieve the same thing are also welcome.

[A]
```
```
# sed script to change "foo" to "bar" only on the first occurrence
 1{x;s/^/first/;x;}
 1,/foo/{x;/first/s///;x;s/foo/bar/;}
 #---end of script---
```
```
or, if you prefer:
Editor's note: works with
GNU
```
sed
```
only.
```
```
sed '0,/foo/s//bar/' file
```
```
Source


q:
It seems the .NET Regex.Replace method automatically replaces all matching occurrences.  I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.

What is the most efficient way to stop after the first replacement?

[A]
From
MSDN
:
```
```
Replace(String, String, Int32)
```
```
Within a specified input string, replaces a specified maximum number of strings that
  match a regular expression pattern with a specified replacement string.
Isn't this what you want?


q:
I'm trying to learn C++ so forgive me if this question demonstrates a lack of basic knowledge, you see, the fact is, I have a lack of basic knowledge.

I want some help working out how to create an iterator for a class I have created.

I have a class 'Shape' which has a container of Points.
I have a class 'Piece' which references a Shape and defines a position for the Shape.
Piece does not have a Shape it just references a Shape.

I want it to seem like Piece is a container of Points which are the same as those of the Shape it references but with the offset of the Piece's position added.

I want to be able to iterate through the Piece's Points just as if Piece was a container itself. I've done a little reading around and haven't found anything which has helped me. I would be very grateful for any pointers.

[A]
/EDIT: I see, an own iterator is actually necessary here (I misread the question first). Still, I'm letting the code below stand because it can be useful in similar circumstances.
Is an own iterator actually necessary here? Perhaps it's sufficient to forward all required definitions to the container holding the actual Points:
```
```
// Your class `Piece`
class Piece {
private:
    Shape m_shape;

public:

    typedef std::vector<Point>::iterator iterator;
    typedef std::vector<Point>::const_iterator const_iterator;

    iterator begin() { return m_shape.container.begin(); }

    const_iterator begin() const { return m_shape.container.begin(); }

    iterator end() { return m_shape.container.end(); }

    const_iterator end() const { return m_shape.const_container.end(); }
}
```
```
This is assuming you're using a
```
vector
```
internally but the type can easily be adapted.


q: I have seen a few (old) posts on the 'net about hacking together some support for pre-compiled headers in CMake. They all seem a bit all-over the place and everyone has their own way of doing it. What is the best way of doing it currently?

[A]
Don't even go there. Precompiled headers mean that whenever one of the headers changes, you have to rebuild
everything
. You're lucky if you have a build system that realizes this. More often than never, your build will just fail until you realize that you changed something that is being precompiled, and therefore you need to do a full rebuild. You can avoid this mostly by precompiling the headers that you are absolutely positive won't change, but then you're giving up a large part of the speed gain as well.
The other problem is that your namespace gets polluted with all kinds of symbols that you don't know or care about in many places where you'd be using the precompiled headers.


q: I am currently getting exceptions when modifying an IBindingList on multiple threads. Does anyone have a threadsafe version before I write my own?

[A]
I think you'll find this an incredibly difficult task. The easier path would be to prevent multiple-thread access with a
```
lock
```
:
```
```
void AddItemToList(object o)
{
    lock(myBindingList)
    {
        myBindingList.Add(o);
    }
}
```
```
Look at the
lock statement docs
for more info.


q:
Is it possible to access a constant value (i.e. a public static final variable defined in a Java class) from a Velocity template?

I would like to be able to write something like this:

#if ($a lt Long.MAX_VALUE)

but this is apparently not the right syntax.

[A]
Velocity can only use anything it finds in its context, after e.g.
```
```
context.put("MaxLong", Long.MAX_VALUE);
```
```
You cannot use statics, or access static members of things in Velocity's context due to the way its lookup works (see Velocity's
Property lookup rules
). The best thing to do is add the value you want to check against explicitly in your context.
Edit October 6
on second sight, it seems to be possible to access static members. See the velocity
Developer guide - Support for "Static Classes"
for more information. I have not tried this out, though.


q: Had anybody found a way to migrate MediaWiki pages over to WSS Wikis? We just put up Sharepoint 2007 and while it appears to meet our needs, it doesn't appear to be any tool provided by Microsoft to migrate MediaWiki pages over to WSS wikis.

[A]
There is no such tool provided by Microsoft at this time.
There is one being developed though in the
SharePoint Community Kit
.
Wiki Import/Export Tool
The EWE team is at a very early stage of designing an import/export tool for the SharePoint wiki. The goal is for this tool to be able to import from other wiki products such as FlexWiki, MediaWiki, and TWiki, and Confluence and also from Word and OneNote as well as to export to Word via HTML (per page) and MHTML (entire wiki) formats.
For this CKS 2.0 pre-release, the EWE team is making available a fairly stable build of the FlexWiki Import Tool, for which the source code was graciously donated by Michael Cheng, a developer in the SharePoint product group. This is a one-off tool that will ultimately be converted to a plug-in for the Wiki Import/Export Tool, so if you’re currently using FlexWiki, please test the tool and provide feedback.


q:
i work with sql server, but i must migrate to an application with Oracle DB.
for trace my application queries, in Sql Server i use wonderful Profiler tool. is there something of equivalent for Oracle?

[A]
Oracle, along with other databases, analyzes a given query to create an execution plan.  This plan is the most efficient way of retrieving the data.
Oracle provides the '
```
explain plan
```
' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).
The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:
```
```
explain plan for <sql query>
```
```
The analysis of that data is left for another question, or your further research.


q:
This is clearly not appears like it wouldn't be a best practice. Can someone explain why it would not be a best practice or how this works? Any books or articles  providing an explanation would be appreciated.

//The constructor
public Page_Index() {

    //create a local value
    string currentValue = "This is the FIRST value";

    //use the local variable in a delegate that fires later
    this.Load += delegate(object sender, EventArgs e) {
        Response.Write(currentValue);
    };

    //change it again
    currentValue = "This is the MODIFIED value";

}

The value that is output is the second value "Modified". What part of the compiler magic is making this work? Is this as simple as keeping track of the value on the heap and retrieving it again later?

[Edit]: Given some of the comments, changing the original sentence some...

[A]
currentValue is no longer a local variable: it is a
captured
variable. This compiles to something like:
```
```
class Foo {
  public string currentValue; // yes, it is a field

  public void SomeMethod(object sender, EventArgs e) {
    Response.Write(currentValue);
  }
}
...
public Page_Index() {
  Foo foo = new Foo();
  foo.currentValue = "This is the FIRST value";
  this.Load += foo.SomeMethod;

  foo.currentValue = "This is the MODIFIED value";
}
```
```
Jon Skeet has a really good write up of this in
C# in Depth
, and a separate (not as detailed) discussion
here
.
Note that the variable currentValue is now on the heap, not the stack - this has lots of implications, not least that it can now be used by various callers.
This is different to java: in java the
value
of a variable is captured. In C#, the
variable itself
is captured.


q:
I don't see what all this fuss is about Microsoft's decision to support JQuery within ASP.NET MVC.

There were signs that open-minded people are starting to have some say in the matters of marketing for a while now. And even the way MS does business has started to change. But at it's core it's still acting in response to customers' requests.

I for one don't know what to make of it, except that it brings back to Microsoft's sphere of influence a very visible product.

[A]
Its the first time MS is shipping an open source component
they didn't write
with one of their products.  This doesn't seem like a big deal, but its almost nuclear in its implications.
Think about it... They are saying "we support this."  In an OSS product, MS has no control over the code.  So, they are putting their livelihood (in some small way) into the hands of people who don't work for MS.
I think jQuery's popularity, the fact that it's not mission critical code, and that the codebase is so small all came together to make for favorable circumstances for MS to dip their toe in the water.


q:
.NET developers out there! Need your opinion here!

I am now using Visual Assist X, a decent piece of software, indeed. But the .NET bloggers seem to prefer Resharper more. I might want to consider a switch over, but before that I want your guys opinion first.

[A]
Resharper is much better for C# code (and supposedly VB.Net, but I haven't tried that).
Unfortunately there is no support for C/C++, so if you need that, you might want to keep Visual Assist around.
They don't coexist very well, unfortunately, so you may need to unload one, then load the other, when switching between C/C++ and C#.
To see the magic of Resharper, I would recommend watching the
"Resharper Jedi" video
.


q:
Is there an iSeries command to export the data in a table to CSV format?

I know about the Windows utilities, but since this needs to be run automatically I need to run this from a CL program.

[A]
If you want the data to be downloaded directly to a PC, you can use the "Data Transfer from iSeries" function of IBM iSeries Client Access to create a .CSV file. In the file output details dialog, set the file type to
```
Comma Separated Variable (CSV)
```
.
You can save the transfer description to be reused later.


q:
I'd like to add scrolling capability to a javax.swing.JDesktopPane. But wrapping in a javax.swing.JScrollPane does not produce the desired behavior.

Searching the web shows that this has been an issue for quite some time. There are some solutions out there, but they seem to be pretty old, and I'm not not completely satisfied with them.

What actively maintained solutions do you know?

[A]
I've used
JavaWorld's solution
by creating my own
```
JScrollableDesktopPane.
```


q:
I want to be able to intercept the shutdown event in C# for Windows Vista.  Due to the advanced security features with Vista, any applications that are running after the shutdown command is called are halted and displayed in a list, prompting the user to do something with them.

Does anybody know how to overcome this and what events I need to be using in Vista.

Thanks.

[A]
```
```
System.Environment.HasShutdownStarted
```
```


q: In C# how do you detect is a specific drive is a Hard Drive, Network Drive, CDRom, or floppy?

[A]
DriveInfo.DriveType
should work for you.
```
```
DriveInfo[] allDrives = DriveInfo.GetDrives();

foreach (DriveInfo d in allDrives)
{
    Console.WriteLine("Drive {0}", d.Name);
    Console.WriteLine("  File type: {0}", d.DriveType);
}
```
```


q:
What is the difference between a framework and a library?

I always thought of a library as a set of objects and functions that focuses on solving a particular problem or a specific area of application development (i.e. database access); and a framework on the other hand as a collection of libraries centered on a particular methodology (i.e. MVC) and which covers all areas of application development.

[A]
A
library
performs specific, well-defined operations.
A
framework
is a skeleton where the application defines the "meat" of the operation by filling out the skeleton.  The skeleton still has code to link up the parts but the most important work is done by the application.
Examples of libraries:
Network protocols, compression, image manipulation, string utilities, regular expression evaluation, math.  Operations are self-contained.
Examples of frameworks:
Web application system, Plug-in manager, GUI system.  The framework defines the concept but the application defines the fundamental functionality that end-users care about.


q:
Selecting the union:

select * from table1
union
select * from table1_backup

What is the query to select the intersection?

[A]
In SQL Server
intersect
```
```
select * from table1
intersect
select * from table1_backup
```
```


q:
Is there a way to identify unused attributes/methods in Visual C++ 2008 Professional? If it's not possible by default, recommendations of 3rd-party tools are also much appreciated.

Thanks,

Florian

Edit: nDepend only works for .NET assemblies. I'm looking for something that can be used with native C++ applications.

[A]
nDepend
will do it, along with cleaning your house and taking the dog for a walk. There's a nagware version available for free.
The following code query language statement will get you a list of unused methods
```
```
WARN IF Count > 0 IN SELECT TOP 10 METHODS WHERE MethodCa == 0 AND
   !IsPublic AND !IsEntryPoint AND !IsExplicitInterfaceImpl AND
   !IsClassConstructor AND !IsFinalizer
```
```


q:
Is there a component available list FileUpload which shows files on the server, not the client?

I am basically looking for a clean dialog box to select server side files, like the one used in FileUpload.

[A]
Nope. There's not.  That said, you can use a listbox, and load the files into it.
```
```
public sub file_DatabindListbox(directoryPath as string)
   for each fName as string in io.directory(directorypath).getfilenames()
     dim li as new listitem
     li.text = io.path.getfilename(fName)
     li.value = fName
     myFileListbox.Items.Add(li)
   next
end sub
```
```


q: There are situations, where it is practical to have a type-cast return a null value instead of throwing a ClassCastException. C# has the as operator to do this. Is there something equivalent available in Java so you don't have to explicitly check for the ClassCastException?

[A]
You can use the
```
instanceof
```
keyword in place of C#'s
```
is
```
, but there is nothing like
```
as
```
.
Example:
```
```
if(myThing instanceof Foo) {
   Foo myFoo = (Foo)myThing; //Never throws ClassCastException
   ...
}
```
```


q:
Will .Net 4.0 use a new version of the CLR (v2.1, 3.0) or will it stick with the existing v2.0?

Supplementary: Is it possibly going to keep with CLR v2.0 and add DLR v1.0?

Update: Whilst this might look like a speculative question which cannot be answered, the VS team appear to be releasing more and more info on VS10 and .Net 4.0 so this may very soon not be the case. (Info available here -> http://msdn.microsoft.com/en-us/vstudio/products/cc948977.aspx)

[A]
4.0 is going to be another side by side release from what I have read.
http://blogs.msdn.com/wenlong/archive/2008/09/07/net-4-0-wf-wcf-and-oslo.aspx


q:
I'm trying to get started writing some Ruby on Rails apps and have been successful with Mongrel but, I'd like to deploy my apps to my Apache 2.2 instance on Windows?  All the tutorials I've found seem out of date and are for older versions of Apache/Rails.

Does anyone know of a good, current tutorial for configuring Apache 2.2 for Ruby on Rails apps?

[A]
EDIT:
At least until there's a Phusion Passenger for Win, Apache + Mongrel is the way to go. You can use Apache + FastCGI without Mongrel, but under real loads you will get (more) zombie processes and (more) memory leaks.
You could also look at proxying to
Thin
in the same way as detailed below. However, I've had some instabilities with Thin on Win, even though it's appreciably quicker. AB (Apache Benchmark) is your friend here!
Configuring Apache + Mongrel on Windows is not significantly different from *nix.
Essentially, you need to proxy requests coming into Apache to Mongrel. What this boils down to is something like this:
```
```
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so
<VirtualHost localhost:80>
    ServerName www.myapp.comm
    DocumentRoot "C:/web/myapp/public"
    ProxyPass / http://www.myapp.com:3000/
    ProxyPassReverse / http://www.myapp.com:3000/
    ProxyPreserveHost On
</VirtualHost>
```
```
Stick this in your
```
httpd.conf
```
(or
```
httpd-vhost.conf
```
if you're including it).
It assumes you're going to run mongrel on port 3000, your Rails root is in
```
C:\web\myapp
```
, and you'll access the app at www.myapp.com.
To run the rails app in production mode:
```
```
mongrel_rails start -p 3000 -e production
```
```
And away you go (actually mongrel defaults to port 3000 so you could skip
```
-p 3000
```
if you want).
The main difference is that you cannot daemonize mongrel on Windows (i.e. make it run in the background). Instead you can install it as a service using the
```
mongrel_service
```
gem.
Also, running a cluster is more complicated and you won't be able to use Capistrano. Let me know if you want more info.


q:
I need to call an external dll from c#. This is the header definition:

enum WatchMode {
   WATCH_MODE_SYSTEM = 0,
   WATCH_MODE_APPLICATION  = 1 };

LONG ADS_API WDT_GetMode ( LONG i_hHandle, WatchMode * o_pWatchMode );

I've added the enum and the call in C#:

public enum WatchMode
{
    WATCH_MODE_SYSTEM = 0,
    WATCH_MODE_APPLICATION = 1
}
[DllImport("AdsWatchdog.dll")]
internal static extern long WDT_GetMode(long hHandle, ref WatchMode watchmode);

This generates an AccessViolationException. I know the dll is 'working' because I've also added a call to GetHandle which returns the hHandle mentioned above. I've tried to change the param to an int (ref int watchmode) but get the same error. Doesn anyone know how I can PInvoke the above call?

[A]
You're running into a parameter size problem difference between C# and C++.  In the C++/windows world LONG is a 4 byte signed integer.  In the C# world long is a 8 byte signed integer.  You should change your C# signature to take an int.
ffpf is wrong in saying that you should use an IntPtr here.  It will fix this particular problem on a 32 bit machine since an IntPtr will marshal as a int.  If you run this on a 64 bit machine it will marshal as a 8 byte signed integer again and will crash.


q:
I have been googling for a good time on how to move a file with c# using the TFS API. The idea is to have a folder on which the developers drop database upgrade scripts and the build process get's to the folder creates a build script and moves all the files on the folder to a new folder with the database build version that we just created.

I cannot seriously find any reference about moving files programatically in TFS... (aside of the cmd command line)

does anybody know of a good guide / msdn starting point for learning TFS source control files manipulation via c#?

[A]
Its pretty simple :).
```
```
Microsoft.TeamFoundation.VersionControl.Client.Workspace workspace = GetMyTfsWorkspace();
workspace.PendRename( oldPath, newPath );
```
```
Then you need CheckIn it of course. Use a "workspace.GetPendingChanges()" and "workspace.CheckIn()" methods to do it.


q:
In an OLAP database I work with there is a 'Location' hierarchy consisting of the levels Company -> Region -> Area -> Site -> Room. I am using the following MDX to get all the descendants of a particular member at company level.

DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)

I now have a requirement to exclude a particular Region, named "Redundant", from the report. How can I change the above MDX to exclude this particular Region (and all its descendants)? I know this Region will be called "Redundant" but I do not want to hard-code any of the other Region names, as these may change.

[A]
The EXCEPT function will take a set, and remove the members you dont want. In your case you need to say:
```
```
EXCEPT(
{DESCENDANTS([Location].[Test Company],[Location].[Site], SELF_AND_BEFORE)},
{DESCENDANTS([Location].[Whatever].[Redundant],[Location].[Site], SELF_AND_BEFORE)}
)
```
```
This gives you everything in the first set except what you've mentioned in the second. It's easier to understand like this:
```
```
EXCEPT({the set i want}, {a set of members i dont want})
```
```
You shouldnt need to worry about the third (optional) argument:
http://msdn.microsoft.com/en-us/library/ms144900.aspx


q:
I've always handled optional parameters in JavaScript like this:

function myFunc(requiredArg, optionalArg){
  optionalArg = optionalArg || 'defaultValue';

  // Do stuff
}

Is there a better way to do it?

Are there any cases where using || like that is going to fail?

[A]
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative
```
```
if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
```
```
Or an alternative idiom:
```
```
optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
```
```
Use whichever idiom communicates the intent best to you!


q:
I have some commits that I've decided, after the fact, are going to be more branch work then trunk work. How do I create the branch and revert the trunk while still ensuring merging isn't painful later?

Is it as simple as copying the current trunk to a branch and reverting the trunk? Or will this create headaches later?

[A]
There's nothing wrong with following Philip's method, other than it leaves some "cruft" in the revision history. If you wanted to removed them for tidiness sake, and the revisions are at HEAD you could remove them from the repository by following
these instructions
.
Update:
Philip's method is better than the one suggested in the question for the reasons he stated. Mine and Philip's methods would be similar, except that insead of reverting the trunk I propose removing the revisions from the revision history. (as I said, this can only be done if all the revisions you want to remove are at the HEAD of the repository.)


q:
We let users create ad-hoc queries in our website.  We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel.  I have the application populating a DataTable, then using the datatable to create a tab delimited string.  The problem is getting that to excel.

What is the best way to stream data to Excel?  Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.

[A]
Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from
here
```
```
//for demo purpose, lets create a small datatable & populate it with dummy data
System.Data.DataTable workTable = new System.Data.DataTable();

//The tablename specified here will be set as the worksheet name of the generated Excel file.
workTable.TableName = "Customers";
workTable.Columns.Add("Id");
workTable.Columns.Add("Name");
System.Data.DataRow workRow;

for (int i = 0; i <= 9; i++)
{
workRow = workTable.NewRow();
workRow[0] = i;
workRow[1] = "CustName" + i.ToString();
workTable.Rows.Add(workRow);
}

//...and lets put DataTable2ExcelString to work
string strBody = DataTable2ExcelString(workTable);

Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls");
Response.Write(strBody);
```
```


q: As I understand it, .bat is the old 16-bit naming convention, and .cmd is for 32-bit Windows, i.e., starting with NT. But I continue to see .bat files everywhere, and they seem to work exactly the same using either suffix. Assuming that my code will never need to run on anything older than NT, does it really matter which way I name my batch files, or is there some gotcha awaiting me by using the wrong suffix?

[A]
No - it doesn't matter in the slightest.  On NT the .bat and .cmd extension both cause the cmd.exe processor to process the file in exactly the same way.
Additional interesting information about command.com vs. cmd.exe on WinNT-class systems from MS TechNet (
http://technet.microsoft.com/en-us/library/cc723564.aspx
):
This behavior reveals a quite subtle
  feature of Windows NT that is very
  important. The 16-bit MS-DOS shell
  (COMMAND.COM) that ships with Windows
  NT is specially designed for Windows
  NT. When a command is entered for
  execution by this shell, it does not
  actually execute it. Instead, it
  packages the command text and sends it
  to a 32-bit CMD.EXE command shell for
  execution. Because all commands are
  actually executed by CMD.EXE (the
  Windows NT command shell), the 16-bit
  shell inherits all the features and
  facilities of the full Windows NT
  shell.


q:
I have a function that passes an array to another function as an argument, there will be multiple data types in this array but I want to know how to pass a function or a reference to a function so the other function can call it at any time.

ex.

function A:

add(new Array("hello", some function));

function B:

public function b(args:Array) {
    var myString = args[0];
    var myFunc = args[1];
}

[A]
This is very easy in ActionScript:
```
```
function someFunction(foo, bar) {
   ...
}

function a() {
    b(["hello", someFunction]);
}

function b(args:Array) {
    var myFunc:Function = args[1];
    myFunc(123, "helloworld");
}
```
```


q:
I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.

XML example:

<?xml version="1.0" encoding="utf-8"?>
<node>
  <attribute/>
  <node>
    <attribute/>
    <node/>
  </node>
</node>

Which is the best way to validate it?  Recursion?

[A]
XSD does indeed allow for recursion of elements. Here
is a sample for you
```
```
<xsd:element name="section">
  <xsd:complexType>
    <xsd:sequence>
      <xsd:element ref="title"/>
      <xsd:element ref="para" maxOccurs="unbounded"/>
      <xsd:element ref="section" minOccurs="0" maxOccurs="unbounded"/>
    </xsd:sequence>
  </xsd:complexType>
</xsd:element>
```
```
As you can see the section element contains a child element that is of type section.


q:
I have an object that I'm testing that raises an event.  What is the best way of using Rhino Mocks to check that it was raised?

Best I could come up with (I am certain it gets better than this):

public void MyCallback(object sender, EventArgs e) { _flag = true;}

[Test]
public void DoSomethingRaisesEvent() {
  _flag = false;
  using(_mocks.Record()) {
    Expect.Call(delegeate { _obj.DoSomething();});
  }
  using(_mocks.Playback()) {
    _obj = new SomethingDoer();
    _obj.SomethingWasDoneEvent += new EventHandler(MyHandler);
    Assert.IsTrue(_flag);
  }
}

[A]
I'm not sure how your test actually calls the DoSomething() Method. Maybe you're missing something to fire the event. Other than that, I think you have are on the right track for testing events with Rhino Mocks
In any case, here is another way I like to deal with events:
```
```
[Test]
public void MyEventTest()
{

    IEventRaiser eventRaiser;

    mockView = _mocks.CreateMock<IView>();
    using (_mocks.Record())
    {
      mockView.DoSomethingEvent += null;
      eventRaiser = LastCall.IgnoreArguments();
    }
    using (_mocks.Playback())
    {
       new Controller(mockView, mockModel);
       eventRaiser.Raise(mockView, EventArgs.Empty);
    }
}
```
```


q: What does the POP3 CAPA UIDL command do?

[A]
Gives the unique identifier for a message on the POP3 server.
Possible responses: +OK or -ERR


q:
My questions is simple!

Would you start learning Smalltalk if you had the time? Why? Why not?

Do you already know Smalltalk? Why would you recommend Smalltalk? Why not?

Personally I'm a Ruby on Rails programmer and I really like it. However, I'm thinking about Smalltalk because I read various blogs and some people are calling Ruby something like "Smalltalk Light". The second reason why I'm interested in Smalltalk is Seaside.

Maybe someone has made the same transition before?

EDIT: Actually, what got me most excited about Smalltalk/Seaside is the following Episode of WebDevRadio: Episode 52: Randal Schwartz on Seaside (among other things)

[A]
I was taught Smalltalk in one of the first graduate college level Object-Orient Programming courses (circa 1988).  The teacher thought it best to start was a "pure" OO langauge,before moving on to a more trendy one (we did a bit of C++ at the end of the semester).
By that measure, it's still best to start with pure OO, although these days we have Java & C#, both of which are "nearly-pure" OO -- close enough that you can get by ignoring the non-OO features of them, and limiting yourself to the Pure-OO subset of the langauges.


q:
I would like to format a price in JavaScript. I'd like a function which takes a float as an argument and returns a string formatted like this:

"$ 2,500.00"

How can I do this?

[A]
The main part is inserting the thousand-separators, and that could be done like this:
```
```
<script type="text/javascript">
  function ins1000Sep(val) {
    val = val.split(".");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].replace(/(\d{3})/g, "$1,");
    val[0] = val[0].split("").reverse().join("");
    val[0] = val[0].indexOf(",") == 0 ? val[0].substring(1) : val[0];
    return val.join(".");
  }

  function rem1000Sep(val) {
    return val.replace(/,/g, "");
  }

  function formatNum(val) {
    val = Math.round(val*100)/100;
    val = ("" + val).indexOf(".") > -1 ? val + "00" : val + ".00";
    var dec = val.indexOf(".");
    return dec == val.length-3 || dec == 0 ? val : val.substring(0, dec+3);
  }
</script>

<button onclick="alert(ins1000Sep(formatNum(12313231)));">
```
```


q:
I want to see the stack trace in any function of my code, so i made somthing like this to call it and print the stack trace:

public function PrintStackTrace() {
    try {
        throw new Error('StackTrace');
    } catch (e:Error) {
        trace(e.getStackTrace());
    }
}

I like to know if there are other way to do this. In some place, the Error class creates the stack trace, but maybe it didn't do it with ActionScript 3.0 so maybe it's not posible, but i want to know.

Thanks!

[A]
As far as I know, the only way to make the stack trace available to your own code is via the
getStackTrace()
method in the Error class, just like you're already doing. In response to the example in your question, though, I would mention that you don't actually have to throw the Error -- you can just create it and call the method on it:
```
```
var tempError:Error = new Error();
var stackTrace:String = tempError.getStackTrace();
```
```
Also, like the documentation says, this only works in the debug version of Flash Player, so you can wrap this functionality in an if-block that checks the value of
Capabilities.isDebugger
if you want.


q:
We have been designing our reports around Crystal Reports in VS2008 for our web application and I just discovered the Microsoft provided ReportViewer control.  I've searched around a bit but cannot find a good breakdown of the pros and cons of each method of producing reports.

I'm looking for pros and cons regarding:

Ease of development

Ease of deployment

Ability to export data

Ease of support and finding help on the web

[A]
Well, I can answer for one side. I have used
ReportViewer
aka Client Side Reporting. I can tell you its easy to use, easy to deploy and easy to develop. If you can create SQL Reporting Services reports, you can create these. They can take any kind of datasource so you have full control.
Here is an excellent book on Client Side reporting
.
There are built in PDF and Excel exports available but you can add your own export handling also. You can use in winforms, Asp.Net in your own services. You can do really anything you can imagine with them.
For Crystal Reports, I do not know much about them.


q:
I'm getting warnings about CSS3.0 properties like text-overflow.  Is there a way to validate against 3.0?

HTML5 and CSS3 support is coming to VS2010 in SP1.

Link

And now its here.

http://visualstudiogallery.msdn.microsoft.com/7211bcac-091b-4a32-be2d-e797be0db210/view/Reviews/0?showReviewForm=True

[A]
Apparently, you can define your own Visual Studio Intellisense schema for CSS. I’m not sure if VS will then validate against that, or only use it for code completion.
Might be worth making a minimal one and seeing if it gets used for validation.
Custom CSS Intellisense Schema in Visual Studio 2005 and 2008
I don’t know of an easy way to validate against CSS 3 yet though. CSS 3 is a large, modular spec, and most of it is very much still in flux, despite some decent browser support for some properties.
http://www.w3.org/Style/CSS/current-work


q:
I'm not sure if this is something I should do in T-SQL or not, and I'm pretty sure using the word 'iterate' was wrong in this context, since you should never iterate anything in sql. It should be a set based operation, correct? Anyway, here's the scenario:

I have a stored proc that returns many uniqueidentifiers (single column results). These ids are the primary keys of records in a another table. I need to set a flag on all the corresponding records in that table.

How do I do this without the use of cursors? Should be an easy one for you sql gurus!

[A]
This may not be the most efficient, but I would create a temp table to hold the results of the stored proc and then use that in a join against the target table.  For example:
```
```
CREATE TABLE #t (uniqueid int)
INSERT INTO #t EXEC p_YourStoredProc

UPDATE TargetTable
SET a.FlagColumn = 1
FROM TargetTable a JOIN #t b
    ON a.uniqueid = b.uniqueid

DROP TABLE #t
```
```


q:
Are there any templates/patterns/guides I can follow for designing a multithreaded server?  I can't find anything terribly useful online through my google searches.

My program will start a thread to listen for connections using TcpListener.
Every client connection will be handled by it's own IClientHandler thread.  The server will wrap the clientHandler.HandleClient in a delegate, call BeginInvoke, and then quit caring about it.

I also need to be able to cleanly shutdown the listening thread, which is something I'm not finding a lot of exampes of online.

I'm assuming some mix of lock/AutoResetEvents/threading magic combined with the async BeginAceptTcpClient and EndAcceptTcpClient will get me there, but when it comes to networking code, to me it's all been done. So I have to believe there's just some pattern out there I can follow and not get totally confused by the myriad multithreaded corner cases I can never seem to get perfect.

Thanks.

[A]
Oddly enough you may find something on a Computer Science Assignment,
CSC 512 Programming Assignment 4: Multi-Threaded Server With Patterns
. Altough it's C++ voodoo but the theory is quite understandable for someone who can do C#.
Acceptor/ Connector
Monitor Object
Thread Safe Interface
Wrapper Facade
Scoped Locking
Strategized Locking
Reactor
Half Sync/Half-Async
Leaders/Followers
Altough you can get the whole list of nice readings on the
main page
.


q:
I'm looking for a way to limit the maximum number of running processes in Windows Server 2003.

Is there a registry key somewhere that controls it?
If so, which one is it?

[A]
if you are talking about processes as in the items listed in task manager, then there is no way to do it natively, and you can do it with a program,
but there should be no real valid reason to do so.
If you are talking about making your application only ever launch one EXE no matter how many times it is called, then you are looking for singleton-ing. Example for .NET at:
http://www.thescarms.com/dotnet/SingleInstance.aspx
--EDIT For another language, google for "singleton" and your language.
If you are asking about something else, please elaborate.


q:
I'm doing a webapp and need a backup plan. Here's what I've got so far:

nightly encrypted backup of the SQL database to Amazon S3 and my external drive (incremental if possible, not overly familiar with PostgreSQL yet, but that's another thread)

nightly backup of my Mercurial repo (which includes Apache configs, deploy scripts, etc) to S3 (w/ local backups via Time Machine)

Should I add anything else, or will this cover it? For a gauge of how critical the data is/would be, it's a project management app along the lines of Basecamp.

[A]
Weekly full backup of your database as well as nightly incremental ones as well perhaps?
It means that if one of your old incremental backups gets corrupted then you have lost less than a week of data.
Also, ensure you have a backup test plan to ensure your backups work. There are a lot of horror stories going around about this, from companies that have been doing backups for years, never testing them and then finding out none of them are any good once they need them. (I've also been at a company like this. Thankfully I spotted the backups weren't working before they were required and fixed the problems).


q:
I use Tortoise SVN usuallly, but I have been looking into Mercurial since it is a distributed revision control system.

What I am looking for, in both systems, is a tool that let me pick only parts of a file and commit them. If I want to do this now, I have to copy to a temp version of the file and keep only the changes I want to commit in the current version, and then copy the temp version to the current version again after committing. It's just such a hassle and the program should be able to do this for me.

I heard Git supports this, please let me know if this is correct.

[A]
Mercurial can do this with the
record
extension.
It'll prompt you for each file and each diff hunk.  For example:
```
```
% hg record
diff --git a/prelim.tex b/prelim.tex
2 hunks, 4 lines changed
examine changes to 'prelim.tex'? [Ynsfdaq?]
@@ -12,7 +12,7 @@
 \setmonofont[Scale=0.88]{Consolas}
 % missing from xunicode.sty
 \DeclareUTFcomposite[\UTFencname]{x00ED}{\'}{\i}
-\else
+\else foo
 \usepackage[pdftex]{graphicx}
 \fi

record this change to 'prelim.tex'? [Ynsfdaq?]
@@ -1281,3 +1281,5 @@
 %% Local variables:
 %% mode: latex
 %% End:
+
+foo
\ No newline at end of file
record this change to 'prelim.tex'? [Ynsfdaq?]  n
Waiting for Emacs...
```
```
After the commit, the remaining diff will be left behind:
```
```
% hg di
diff --git a/prelim.tex b/prelim.tex
--- a/prelim.tex
+++ b/prelim.tex
@@ -1281,3 +1281,5 @@
 %% Local variables:
 %% mode: latex
 %% End:
+
+foo
\ No newline at end of file
```
```
Alternatively, you may find it easier to use MQ (Mercurial Queues) to separate the individual changes in your repository into patches. There is a MQ variant of record (qrecord), too.
Update:
Also try the
crecord
extension, which provides a curses interface to hunk/line selection.


q: I have an application that uses Forms Authentication to authenticate one type of user. There is a section in this application that needs to be authenticated for another type of user using a different table in the database. The problem happens if the second type of user's session times out, she is taken to the login page defined in the Forms Authentication section of the main Web.Config instead of the login page for the second type of user. I am looking for solutions to this problem. One idea is to create an application in IIS for the section and create a Web.Config for the folder and add another Forms Authentication section. In my experiments, it seems this doesn't work. Am I missing something obvious? Any insights?

[A]
IIRC, the authentication works per folder.  So you should be able to do it if all of the pages that require the 2nd type of authentication live in a specific sub-folder with it's own config.
Not 100% sure on this, though, so if someone more knowledgeable can contradict me I'll just delete the response.


q:
I have a XML response from an HTTPService call with the e4x result format.

<?xml version="1.0" encoding="utf-8"?>
<Validation Error="Invalid Username/Password Combination" />

I have tried:

private function callback(event:ResultEvent):void {
    if(event.result..@Error) {
        // error attr present
    }
    else {
        // error attr not present
    }
}

This does not seem to work (it always thinks that the error attribute exits) what is the best way to do this? thanks.

EDIT: I have also tried to compare the attribute to null and an empty string without such success...

[A]
I have figured out a solution, I'm still interested if there is a better way to do this...
This will work:
```
```
private function callback(event:ResultEvent):void {
    if(event.result.attribute("Error").length()) {
        // error attr present
    }
    else {
        // error attr not present
    }
}
```
```


q: Does anybody know what hypothetical indexes are used for in sql server 2000?  I have a table with 15+ such indexes, but have no idea what they were created for.  Can they slow down deletes/inserts?

[A]
Not sure about 2000, but in 2005 hypothetical indexes and database objects in general are objects created by
DTA (Database Tuning Advisor)
You can check if an index is hypothetical by running this query:
```
```
SELECT  *
FROM    sys.indexes
WHERE   is_hypothetical = 1
```
```
If you have given the tuning advisor good information on which to base it's indexing strategy, then I would say to generally trust its results, but if you should of course examine how it has allocated these before you trust it blindly. Every situation will be different.


q:
I have 7-8 xml files. Each one is approximately 50 MB in size. What is the best way to merge files programmatically in C# without getting System.OutOfMemory Exception?  So far I have tried reading each file in a StringBuilder and than putting it in an array of string builder but I still get system.outofmemoery exception. Any help??
Thank you,
-Nimesh

[A]
The thing about stringbuilder is you're still trying to keep the entire contents in memory.  You want to only keep a small portion in memory at a time, and that means using filestreams.  Don't read an entire file into memory, open a stream on it and keep reading from the stream.
The problem with xml is that you can't just append them to each other:  you'll break the tag nesting.  So you need to know something about the structure of your xml files so that you can have an idea of what to do at each file boundry.
If you have something that works in theory with StringBuilder, but only fails in practice because of memory constraints, you should be able to translate the StringBuilder's .Append() and .AppendLine() method calls into .Write() and .WriteLine() calls for a filestream.


q:
I'm slowly getting back into PHP, and now I run into a problem, I want to install some web software on our host and I need to have either the latest Zend (which they don't have) or IonCube on the server and IonCube requires enable_dl to be on in the php.ini. Now a colleague of mine thinks I can update this via an .htaccess file on the server. So I created a s.htaccess on my machine as Windows doesn't like emptiness before the file extension. So I added the line php_flag enable_dl On to the file uploaded it and renamed the file to just .htaccess on the server. When I refresh the file is gone, when I keep it as s.htaccess it's fine but my php info still shows it as Off.

What n00b mistake am I making?


q: What delphi function asserts that an object is not nil?

[A]
Not sure what you mean but
```
Assert(Assigned(MyObject));
```
is pretty short and easy to use.


q: How can I run background tasks on App Engine?

[A]
GAE is very useful tool to build scalable web applications. Few of the limitations pointed out by many are no support for background tasks, lack of periodic tasks and strict limit on how much time each HTTP request takes, if a request exceeds that time limit the operation is terminated, which makes running time consuming tasks impossible.
How to run background task ?
In GAE the code is executed only when there is a HTTP request. There is a strict time limit (i think 10secs) on how long the code can take. So if there are no requests then code is not executed. One of the suggested work around was use an external box to send requests continuously, so kind of creating a background task. But for this we need an external box and now we dependent on one more element. The other alternative was sending 302 redirect response so that client re-sends the request, this also makes us dependent on external element which is client. What if that external box is GAE itself ? Everyone who has used functional language which does not support looping construct in the language is aware of the alternative ie recursion is the replacement to loop. So what if we complete part of the computation and do a HTTP GET on the same url with very short time out say 1 second ? This creates a loop(recursion) on php code running on apache.
```
<?php
$i = 0;
if(isset($_REQUEST["i"])){
        $i= $_REQUEST["i"];
    sleep(1);
}
$ch = curl_init("http://localhost".$_SERVER["PHP_SELF"]."?i=".($i+1));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
curl_exec($ch);
print "hello world\n";
?>
```
Some how this does not work on GAE. So what if we do HTTP GET on some other url say url2 which does HTTP GET on the first url ? This seem to work in GAE. Code for this looks like this.
```
class FirstUrl(webapp.RequestHandler):
    def get(self):
        self.response.out.write("ok")
        time.sleep(2)
        urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url2')

class SecondUrl(webapp.RequestHandler):
    def get(self):
        self.response.out.write("ok")
        time.sleep(2)
        urlfetch.fetch("http://"+self.request.headers["HOST"]+'/url1')

application = webapp.WSGIApplication([('/url1', FirstUrl), ('/url2', SecondUrl)])
def main():
    run_wsgi_app(application)
if __name__ == "__main__":
    main()
```
Since we found out a way to run background task, lets build abstractions for periodic task (timer) and a looping construct which spans across many HTTP requests (foreach).
Timer
Now building timer is straight forward. Basic idea is to have list of timers and the interval at which each should be called. Once we reach that interval call the callback function. We will use memcache to maintain the timer list. To find out when to call callback, we will store a key in memcache with interval as expiration time. We periodically (say 5secs) check if that key is present, if not present then call the callback and again set that key with interval.
```
def timer(func, interval):
    timerlist = memcache.get('timer')
    if(None == timerlist):
        timerlist = []
    timerlist.append({'func':func, 'interval':interval})
    memcache.set('timer-'+func, '1', interval)
    memcache.set('timer', timerlist)

def checktimers():
    timerlist = memcache.get('timer')
    if(None == timerlist):
        return False
    for current in timerlist:
        if(None == memcache.get('timer-'+current['func'])):
            #reset interval
            memcache.set('timer-'+current['func'], '1', current['interval'])
            #invoke callback function
            try:
                eval(current['func']+'()')
            except:
                pass
            return True
    return False
```
Foreach
This is needed when we want to do long taking computation say doing some operation on 1000 database rows or fetch 1000 urls etc. Basic idea is to maintain list of callbacks and arguments in memcache and each time invoke callback with the argument.
```
def foreach(func, args):
    looplist = memcache.get('foreach')
    if(None == looplist):
        looplist = []
    looplist.append({'func':func, 'args':args})
    memcache.set('foreach', looplist)

def checkloops():
    looplist = memcache.get('foreach')
    if(None == looplist):
        return False
    if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)):
        arg = looplist[0]['args'].pop(0)
        func = looplist[0]['func']
        if(len(looplist[0]['args']) == 0):
            looplist.pop(0)
        if((len(looplist) > 0) and (len(looplist[0]['args']) > 0)):
            memcache.set('foreach', looplist)
        else:
            memcache.delete('foreach')
        try:
            eval(func+'('+repr(arg)+')')
        except:
            pass
        return True
    else:
        return False

# instead of
# foreach index in range(0, 1000):
#   someoperaton(index)
# we will say
# foreach('someoperaton', range(0, 1000))
```
Now building a program which fetches list of urls every one hour is straight forward. Here is the code.
```
def getone(url):
    try:
        result = urlfetch.fetch(url)
        if(result.status_code == 200):
            memcache.set(url, '1', 60*60)
            #process result.content
    except :
        pass

def getallurl():
    #list of urls to be fetched
    urllist = ['http://www.google.com/', 'http://www.cnn.com/', 'http://www.yahoo.com', 'http://news.google.com']
    fetchlist = []
    for url in urllist:
        if (memcache.get(url) is None):
            fetchlist.append(url)
    #this is equivalent to
    #for url in fetchlist: getone(url)
    if(len(fetchlist) > 0):
        foreach('getone', fetchlist)

#register the timer callback
timer('getallurl', 3*60)
```
complete code is here
http://groups.google.com/group/httpmr-discuss/t/1648611a54c01aa
I have been running this code on appengine for few days without much problem.
Warning: We make heavy use of urlfetch. The limit on no of urlfetch per day is 160000. So be careful not to reach that limit.


q:
When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work.  As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.

Edit
When I access the value like so

TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;

the text box is found, but the .Text is not the user input.

[A]
You should be able to use the GridViewUpdateEventArgs to retrieve the inputted value, for example:
```
```
TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox;
```
```
I have used that syntax before and it works like a charm.


q:
Is there a way set flags on a per-file basis with automake?

In particular, if I have a c++ project and want to compile with -WAll all the files except one for which I want to disable a particular warning, what could I do?

I tried something like:

CXXFLAGS = -WAll ...
bin_PROGRAMS = test
test_SOURCES = main.cpp utility.cpp
utility_o_CXXFLAGS = $(CXXFLAGS) -Wno-unused-value

but it didn't work.

EDITED: removed reference to automake manual, which was actually misleading (thanks to Douglas Leeder).

[A]
You've got confused - that section is referring to options to automake itself.
It's a way of setting the automake command-line options:
-W CATEGORY
  --warnings=category
      Output warnings falling in category. category can be one of:
```
```
gnu
    warnings related to the GNU Coding Standards (see Top).
obsolete
    obsolete features or constructions
override
    user redefinitions of Automake rules or variables
portability
    portability issues (e.g., use of make features that are known to be not portable)
syntax
    weird syntax, unused variables, typos
unsupported
    unsupported or incomplete features
all
    all the warnings
none
    turn off all the warnings
error
    treat warnings as errors
```
```
A category can be turned off by prefixing its name with ‘no-’.
  For instance, -Wno-syntax will hide the
  warnings about unused variables.
The categories output by default are ‘syntax’ and ‘unsupported’.
  Additionally, ‘gnu’ and ‘portability’
  are enabled in --gnu and --gnits
  strictness.
The environment variable WARNINGS can contain a comma separated list of
  categories to enable. It will be taken
  into account before the command-line
  switches, this way -Wnone will also
  ignore any warning category enabled by
  WARNINGS. This variable is also used
  by other tools like autoconf; unknown
  categories are ignored for this
  reason.
The per-file listed in section 17 refers to per-Makefile not source file.
I'm not aware of any per-source file flag setting, but you can set the option for each result binary with:
```
```
binaryname_CXXFLAGS
```
```


q: Is there any way to do this in the Powerbuilder properties window for a datawindow's textbox?

[A]
That kind of depends on how you define "textbox", but in general the only way to mix normal and superscript text is with a richtext control. In PB 11.5, you can even use richtext as a column style.
Good luck,
Terry.


q:
How does Stackoverflow implement the resizable textarea?

Is that something they rolled themselves or is it a publicly available component that I can easily attach to textareas on my sites?

I found this question and it doesn't quite do what I want.

autosizing-textarea

That talks more about automatically resizing textareas whereas I want the little grab-area that you can drag up and down.

[A]
At first I believed it was a built-in feature of the
Wysiwym Markdown editor
, but Shog9 is correct: it's not baked-in at all, but is courtesy of the jQuery plugin TextAreaResizer (I was lead astray by the browser was using to check on the
editor demo
because Google Chrome itself adds the expandable functionality on textareas—much like the Safari browser does).


q:
How can you avoid circular dependencies when you're designing two classes with a producer/consumer relationship? Here ListenerImpl needs a reference to Broadcaster in order to register/unregister itself, and Broadcaster needs a reference back to the Listeners in order to send messages. This example is in Java but it can apply to any OO language.

public interface Listener {
  void callBack(Object arg);
}
public class ListenerImpl implements Listener {
  public ListenerImpl(Broadcaster b) { b.register(this); }
  public void callBack(Object arg) { ... }
  public void shutDown() { b.unregister(this); }
}
public class Broadcaster {
  private final List listeners = new ArrayList();
  public void register(Listener lis) { listeners.add(lis); }
  public void unregister(Listener lis) {listeners.remove(lis); }
  public void broadcast(Object arg) { for (Listener lis : listeners) { lis.callBack(arg); } }
}

[A]
I don't see that being a circular dependency.
Listener depends on nothing.
ListenerImpl depends on Listener and Broadcaster
Broadcaster depends on Listener.
```
```
Listener
       ^        ^
      /          \
     /            \
Broadcaster <--  ListenerImpl
```
```
All arrows end at Listener.  There's no cycle.  So, I think you're OK.


q:
Well, it seems simple enough, but I can't find a way to add a caption to an equation.
The caption is needed to explain the variables used in the equation, so some kind of table-like structure to keep it all aligned and pretty would be great.

[A]
You may want to look at
http://tug.ctan.org/tex-archive/macros/latex/contrib/float/
which allows you to define new floats using
```
\newfloat
```
I say this because captions are usually applied to floats.
Straight ahead equations (those written with
```
$ ... $
```
,
```
$$ ... $$
```
,
```
begin{equation}...
```
) are in-line objects that do not support
```
\caption
```
.
This can be done using the following
snippet
just before
```
\begin{document}
```
```
```
\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}
```
```
and when adding an equation use something like
```
```
\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}
```
```


q:
I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container).  If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething).  I cannot figure out the syntax of the if statement.  I want to write something like:

Public Function Build(Of T) as T
    If T Is IDoSomething then
        Return New DoSomething()
    ElseIf T Is IAndSoOn Then
        Return New AndSoOn()
    Else
        Throw New WhatWereYouThinkingException("Bad")
    End If
End Sub

But this code does not compile.

[A]
```
```
Public Function Build(Of T) As T
  Dim foo As Type = GetType(T)

  If foo Is GetType(IDoSomething) Then
    Return New DoSomething()
  ...
  End If
End Function
```
```


q:
What does the following code do in C/C++?

if (blah(), 5) {
    //do something
}

[A]
Comma operator is applied and the value 5 is used to determine the conditional's true/false.
It will execute blah() and get something back (presumably), then the comma operator is employed and 5 will be the only thing that is used to determine the true/false value for the expression.
Note that the , operator could be overloaded for the return type of the blah() function (which wasn't specified), making the result non-obvious.


q: Has anyone ever done work to get Ruby to do continuations (like Seaside on Smalltalk)?

[A]
Yes, in most cases. MRI (1.8) have supported them as far as my memory reaches, Ruby 1.9 (YARV)
does it, too
, so does Rubinius. JRuby and IronRuby don't have continuations, and it's quite unlikely they will get them (JVM and CLR use stack-instrospection for security)
Ruby as a language supports continuations via
```
callcc
```
keyword. They're used, for example, to implement
```
Generator
```
class from standard library.
continuations on ruby-doc
Continuation-based web frameworks (like seaside, or one from Arc's std. library) seem less popular. I've found
wee
that claim to let you do optional continuations, but I've never used it.


q:
Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.

(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)

[A]
Look at the
selectedIndex
of the
```
select
```
element. BTW, that's a plain ol' DOM thing, not JQuery-specific.


q:
Does BeautifulSoup work with Python 3?

If not, how soon will there be a port? Will there be a port at all?

Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)

[A]
I'm guessing the answer is "No".  According to
Python.org
:
Python 3000 (a.k.a. "Py3k", and
  released as Python 3.0) is a new
  version of the language that is
  incompatible with the 2.x line of
  releases. The language is mostly the
  same, but many details, especially how
  built-in objects like dictionaries and
  strings work, have changed
  considerably, and a lot of deprecated
  features have finally been removed.
  Also, the standard library has been
  reorganized in a few prominent places.
A better place for this particular question might be the
BeautifulSoup forum
.


q: I was currently developing a desktop application in C# using mono and testing in SuSE and Windows. The concept doesn't matter much, but it is a "web lint" program that will scan a web site and return possible issues with security and/or cross browser compatibility.  However, I want to be able to offer binaries for multiple platforms.  Should I stay with Mono, or is there another platform that would give me a better availablility of platforms, such as on Macs, Windows, Linux, and others (possibly mobile platforms), and make it easier to port?

[A]
Java will run on Windows, Linux and Macs. Should be easy to transition from C# - use Apache HTTPClient for grabbing the web content you are scanning, and the scanning code should be more or less the same. However the downside is requiring the user to have the Java runtime installed.
Python is another option - you can build stand-alone executables for Windows, and it comes with most Linux distributions by default, and also Mac OS X (citation needed ;) ). This is a lot less hassle for Windows users (language is compiled into the executable, no other downloads required).
If mono runs on Mac OS X then surely that is a good platform as well?


q: Is there a clean way of cloning a record in SQL that has an index(auto increment).  I want to clone all the fields except the index.  I currently have to enumerate every field, and use that in an insert select, and I would rather not explicitly list all of the fields, as they may change over time.

[A]
Not unless you want to get into dynamic SQL.  Since you wrote "clean", I'll assume not.
Edit:
Since he asked for a dynamic SQL example, I'll take a stab at it.  I'm not connected to any databases at the moment, so this is off the top of my head and will almost certainly need revision.  But hopefully it captures the spirit of things:
```
```
-- Get list of columns in table
SELECT INTO #t
EXEC sp_columns @table_name = N'TargetTable'

-- Create a comma-delimited string excluding the identity column
DECLARE @cols varchar(MAX)
SELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id'

-- Construct dynamic SQL statement
DECLARE @sql varchar(MAX)
SET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' +
    'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition'

PRINT @sql -- for debugging
EXEC(@sql)
```
```


q:
I am trying to extract a certain part of a column that is between delimiters.

e.g. find foo in the following

test 'esf :foo: bar

So in the above I'd want to return foo, but all the regexp functions only return true|false,
is there a way to do this in MySQL

[A]
A combination of
LOCATE
and
MID
would probably do the trick.
If the value
"test 'esf :foo: bar"
was in the field
fooField
:
```
```
MID( fooField, LOCATE('foo', fooField), 3);
```
```


q:
I have several .NET Windows Forms applications that I'm preparing to convert into a ClickOnce/smart-client deployment scenario. I've read the isn't-this-great tutorials, but are there pitfalls or "gotchas" that I should be aware of?

There are several minor applications used off and on, but the main application is in C#, runs 24/7, is quite large, but only changes every few weeks. It also writes to a log file locallly and talks to local hardware devices.

[A]
Here are a few that I am aware of.
Can't put an icon on the desktop.
You can now.
I can't install for all users.
I need to jump through hoops to move the deployment to a different server. It is not a problem if you are developing internally, and the users can see the server that you are publishing to or if you are deploying to the public web, but it is not great if you need to roll out to multiple customer sites independently.
Since
.NET
3.5 SP1 you do not need to sign the deployment manifest anymore which makes it much easier to move deployments to new servers.
I can't install assemblies in the
GAC
. You can get around this by creating regular install packages that are pre-requisites of the ClickOnce application.


q:
I'm benchmarking a WPF application on various platforms and I need an easy way to determine if WPF is using hardware or software rendering.

I seem to recall a call to determine this, but can't lay my hands on it right now.

Also, is there an easy, code based way to force one rendering pipeline over the other?

[A]
Check RenderCapability.Tier
Graphics Rendering Tiers
RenderCapability Class
[
UPDATE
]
RenderCapability.IsPixelShaderVersionSupported
- Gets a value that indicates whether the specified pixel shader version is supported.
RenderCapability.IsShaderEffectSoftwareRenderingSupported
- Gets a value that indicates whether the system can render bitmap effects in software.
RenderCapability.Tier
- Gets a value that indicates the rendering tier for the current thread.
RenderCapability.TierChanged
- Occurs when the rendering tier has changed for the Dispatcher object of the current thread.
RenderCapability.Tier >> 16
Rendering Tier 0
- No graphics hardware acceleration. The DirectX version level is less than version 7.0.
Rendering Tier 1
- Partial graphics hardware acceleration. The DirectX version level is greater than or equal to version 7.0, and lesser than version 9.0.
Rendering Tier 2
- Most graphics features use graphics hardware acceleration. The DirectX version level is greater than or equal to version 9.0.


q:
Basically the question is how to get from this:

foo_id   foo_name
1        A
1        B
2        C

to this:

foo_id   foo_name
1        A B
2        C

[A]
```
```
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
```
```
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_group-concat
From the link above,
```
GROUP_CONCAT
```
: This function returns a string result with the concatenated non-NULL values from a group. It returns NULL if there are no non-NULL values.


q:
This question comes close to what I need, but my scenario is slightly different. The source table and destination table are the same and the primary key is a uniqueidentifier (guid). When I try this:

insert into MyTable
    select * from MyTable where uniqueId = @Id;

I obviously get a primary key constraint violation, since I'm attempting to copy over the primary key. Actually, I don't want to copy over the primary key at all. Rather, I want to create a new one. Additionally, I would like to selectively copy over certain fields, and leave the others null. To make matters more complex, I need to take the primary key of the original record, and insert it into another field in the copy (PreviousId field).

I'm sure there is an easy solution to this, I just don't know enough TSQL to know what it is.

[A]
Try this:
```
```
insert into MyTable(field1, field2, id_backup)
    select field1, field2, uniqueId from MyTable where uniqueId = @Id;
```
```
Any fields not specified should receive their default value (which is usually NULL when not defined).


q:
When I dynamically create a Datagrid and add in a new buttoncolumn how do I access the buttoncolumn_click event?

Thanks.

[A]
This article on the MSDN site clearly explains how to go about
adding a button into a datagrid
. Instead of using the click event of the button you'll use the command event of the DataGrid. Each button will be passing specific commandarguments that you will set.
This article shows
how to use the command event with buttons
. In it you use CommandArguments and CommandNames.


q:
I ran across the following code in Ely Greenfield's SuperImage from his Book component - I understand loader.load() but what does the rest of do?

loader.load((newSource is URLRequest)? newSource:new URLRequest(newSource));

It looks like some kind of crazy inline if statement but still, I'm a little preplexed.  And if it is an if statement - is this way better than a regular if statement?

[A]
this is using the
ternary ?: operator
.  the first part is the condition, between the ? and : is what to return if the condition is true.  after the : is what to return if the condition is false.
a simpler example
```
```
String str = null;
int x = (str != null) ? str.length() : 0;
```
```
would be the same as
```
```
String str = null;
int x;
if (str != null)
  x = str.length()
else
  x = 0;
```
```


q:
What is a strong way to protect against sql injection for a classic asp app?

FYI I am using it with an access DB.  (I didnt write the app)

[A]
Stored Procedures and/or prepared statements:
https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes?
Catching SQL Injection and other Malicious Web Requests
With Access DB, you can still do it, but if you're already worried about SQL Injection, I think you need to get off Access anyway.
Here's a link to the technique in Access:
http://www.asp101.com/samples/storedqueries.asp
Note that what typically protects from injection is not the stored procedure itself, but that fact that it is parameterized and not dynamic.  Remember that even SPs which build dynamic code can be vulnerable to injection if they use parameters in certain ways to build the dynamic code.  Overall, I prefer SPs because they form an interface layer which the applications get to the database, so the apps aren't even allowed to execute arbitrary code in the first place.
In addition, the execution point of the stored procedure can be vulnerable if you don't use command and parameters, e.g. this is still vulnerable because it's dynamically built and can be an injection target:
```
```
Conn.Execute("EXEC usp_ImOnlySafeIfYouCallMeRight '" + param1 + "', '" + param2 + "'") ;
```
```
Remember that your database needs to defend its own perimeter, and if various logins have rights to
```
INSERT/UPDATE/DELETE
```
in tables, any code in those applications (or compromised applications) can be a potential problem.  If the logins only have rights to execute stored procedures, this forms a funnel through which you can much more easily ensure correct behavior.  (Similar to OO concepts where objects are responsible for their interfaces and don't expose all their inner workings.)


q:
I would like to specify a constraint which is another type with a generic argument.

class KeyFrame<T>
{
    public float Time;
    public T Value;
}

// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}

But this cannot be done in c# as of yet, (and I really doubt it will ever be). Is there any elegant solution to this rather than having to specify the type of the keyframe argument?:

class Timeline<TKeyframe, TKeyframeValue>
     where TKeyframe : Keyframe<TKeyframeValue>,
{
}

[A]
As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like:
```
```
class TimeLine<T>
{
private IList<KeyFrame<T>> keyFrameList;
...
}
```
```
fulfill your requirements nicely?


q:
I would like to do something like
     <test:di id="someService"/`>

    <%
       someService.methodCall();
    %>

where <test:di

 gets and instantiates a service bean and creates a scripting variable for use. similar to how jsp:usebean works for example
    <jsp:useBean id="someDate" class="java.util.Date"/>

    <%

       someDate.getYear();

%>

how do i make my own objects available as a scritping variable?

[A]
I think you're trying to write your own tag library.
Check out the tutorial at:
http://www.ironflare.com/docs/tutorials/taglibs/
Edit:
As Garth pointed out, you want to use the TagExtraInfo class after you've defined your tag lib.
http://www.stardeveloper.com/articles/display.html?article=2001081601&page=2


q:
Does anyone know of a method to determine when a file copy completes in VBScript?  I'm using the following to copy:

set sa = CreateObject("Shell.Application")
set zip = sa.NameSpace(saveFile)
set Fol = sa.NameSpace(folderToZip)
zip.copyHere (Fol.items)

[A]
You may have better luck using the Copy method on a
```
FileSystemObject
```
.  I've used it for copying, and it's a blocking call.


q: On the .Net WebBrowser control the only way I can see to load a page to it is to set the URL property.  But I would like to instead give it some HTML code that I already have in memory without writing it out to a file first.  Is there any way to do this?  Or are there any controls that will do this?

[A]
You want the DocumentText Property:
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.documenttext.aspx
?
from
http://www.codeguru.com/forum/showpost.php?p=1691329&postcount=9
:
Also you should provide a couple things:
Don't set DocumentText in the constructor. Use Form_Load or your own method.
If you set DocumentText in the constructor, you will not be able to set it again anywhere in the application. Be sure to check that the Form Designer hasn't set it either.
You can only set DocumentText once per method call. This is odd and most likely a bug, but it's true.
For example: setting DocumentText in a for-loop will only set properly on the first iteration of the loop.
You can however, create a small method to set DocumentText to the passed in string, then call this method in a for-loop.


q:
Does anyone have a good technique (or tutorial) to implement rulers within a C# Windows Forms application? I want to display an image while showing rulers that indicate your mouse position to allow a more accurate positioning of the cursor. Just like the image below:

I tried using splitter controls to hold the tick marks but I don't know how to make the top-left the gray blank area. Any advice? Thanks.

[A]
I would build a custom control to do this in both X and Y location and use two controls.
The control would have to override
```
Paint()
```
and use GDI methods to display the tick marks, it would then capture mouse events and update locations appropriately.


q:
We have a Cash flow report which is basically in this structure:

Date |Credit|Debit|balance|
09/29| 20   | 10  | 10    |
09/30| 0    | 10  | 0     |

The main problem is the balance, and as we are using a DataSet for the Data, it's kinda hard to calculate the balance on the DataSet, because we always need the balance from the previous day.

Also this data comes from several tables and it's been hard to maintain this procedure, because the database metadata is changing frequently.

Anyone could give me some possible different solutions? for the problem?

This report is being displayed on a DataGrid.

[A]
On the code side of things, you've got two relatively easy options, but they both involve iterating through the dataset.
option 1: For loop prior to databinding.
For each row in the datatable, add/subtract the credit/debits to the previous row's balance and assign it to the appropriate cell of your datatable.
Option 2: calculate during databinding.
First you'd have a global variable that you could hold your value in. Set it to zero right before the databind. For each item or altitem, add/subtract the credit/debits to the global variable and assign it to the appropriate cell of your datagrid.


q:
I have tried this...

Dim myMatches As String() =
System.Text.RegularExpressions.Regex.Split(postRow.Item("Post"), "\b\#\b")

But it is splitting all words, I want an array of words that start with#

Thanks!

[A]
Since you want to include the words in the split you should use something like
```
```
"\b#\w+\b"
```
```
This includes the actual word there in the expression. However I'm not sure that's what you want. Could you provide an example of input and the desired output?


q: I'm new to ASP.NET and want to have an asp:content control for the page title, but I want that value to be used for the  tag and for a page header. When I tried to do this with two  tags with the same id, it complained that I couldn't have two tags with the same id. Is there a way to achieve this with contentplaceholders, and if not what would be the easiest way to use a single parameter to the masterpage twice in one page?

[A]
Title is actually an attribute on content pages, so you do something like:
```
```
<%@ Page Language="C#" MasterPageFile="~/default.master" Title="My Content Title" %>
```
```
on the content page. To get that into a header, on the master page just render the page title:
```
```

<%= this.Page.Title %>

```
```


q:
Does anyone know how to get the name of the TARGET (/t) called from the MSBuild command line? There are a few types of targets that can be called and I want to use that property in a notification to users.

Example:

msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV

I want access to the target words ApplicationDeployment in my .Proj file.

Is there a property I can access? Any clue how to do this?

EDIT: I do not want to have to also pass in a property to get this.

UPDATE: This is based on deployment scripts using MSBuild scripts. My build server is not used for deploying code, only for building. The build server itself has build notifications that can be opted into.

[A]
I'm not sure how to do exactly what you ask, but could you pass that string using the /p option?
```
```
msbuild Project.proj /t:ApplicationDeployment /p:Environment=DEV;MyValue=ApplicationDeployment
```
```
The only other way I can see to do it is to use a conditional property in each target, and thus establish the first target to be invoked.
```
```
<Target Name="ApplicationDeployment">
<PropertyGroup>
  <InvokedTarget Condition="'${InvokedTarget}'==''">ApplicationDeployment</InvokedTarget>
</PropertyGroup>

...
</Target>
```
```


q:
How can I limit my post-build events to running only for one type of build?

I'm using the events to copy DLL files to a local IIS virtual directory, but I don't want this happening on the build server in release mode.

[A]
You can pass the configuration name to the post-build script and check it in there to see if it should run.
Pass the configuration name with
```
$(ConfigurationName)
```
.
Checking it is based on how you are implementing the post-build step -- it will be a command-line argument.


q:
mysql5.0 with a pair of databases "A" and "B", both with large innodb tables. "drop database A;" freezes database "B" for a couple minutes. Nothing is using "A" at that point, so why is this such an intensive operation?

Bonus points: Given that we use "A", upload data into "B", and then switch to using "B", how can we do this faster? Dropping databases isn't the sort of thing one typically has to do all the time, so this is a bit off the charts.

[A]
By default, all innodb databases in a given mysql server installation use the same physical pool of data files, so conceivably "drop database A"  could affect database B.  Since "drop database" is likely to involve heavy reorgainsing of the innodb data files, it's conceivable that it's a blocking operation, either because of the intensity of the operation, or by design.
However, I think you can make each database use different physical files, although I haven't tried that myself, so you'll have to figure out the specifics for yourself. Failing that, then you may need to use two different mysql installs side-by-side on the same machine, which is perfectly doable.


q:
I created a Rails application normally. Then created the scaffold for an event class. Then tried the following code. When run it complains about a InvalidAuthenticityToken when the destroy method is executed. How do I authenticate to avoid this response?

require 'rubygems'
require 'activeresource'

class Event < ActiveResource::Base
  self.site = "http://localhost:3000"
end

e = Event.create(
  :name => "Shortest Event Ever!",
  :starts_at => 1.second.ago,
  :capacity => 25,
  :price => 10.00)

e.destroy


q:
I need to substitute the value of a string into my regular expression in Ruby. Is there an easy way to do this? For example:

foo = "0.0.0.0"
goo = "here is some other stuff 0.0.0.0"
if goo =~ /value of foo here dynamically/
  puts "success!"
end

[A]
Use Regexp.new:
```
```
if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/
```
```


q:
I know plenty about the different ways of handling parsing text for information. For parsing integers for example, what kind of performance can be expected. I am wondering if anyone knows of any good stats on this. I am looking for some real numbers from someone who has tested this.

Which of these offers the best performance in which situations?

Parse(...)  // Crash if the case is extremely rare .0001%

If (SomethingIsValid) // Check the value before parsing
    Parse(...)

TryParse(...) // Using TryParse

try
{
    Parse(...)
}
catch
{
    // Catch any thrown exceptions
}

[A]
Always use
T.TryParse(string str, out T value)
. Throwing exceptions is expensive and should be avoided if you can handle the situation
a priori
. Using a try-catch block to "save" on performance (because your invalid data rate is low) is an abuse of exception handling at the expense of maintainability and good coding practices. Follow sound software engineering development practices, write your test cases, run your application, THEN benchmark and optimize.
"We should forget about small efficiencies, say about 97% of the time:
premature optimization is the root of all evil
. Yet we should not pass up our opportunities in that critical 3%" -Donald Knuth
Therefore you assign, arbitrarily like in carbon credits, that the performance of try-catch is
worse
and that the performance of TryParse is
better
. Only after we've run our application and determined that we have some sort of slowdown w.r.t. string parsing would we even consider using anything other than TryParse.
(edit: since it appears the questioner wanted timing data to go with good advice, here is the timing data requested)
Times for various failure rates on 10,000 inputs from the user (for the unbelievers):
```
```
Failure Rate      Try-Catch          TryParse        Slowdown
  0%           00:00:00.0131758   00:00:00.0120421      0.1
 10%           00:00:00.1540251   00:00:00.0087699     16.6
 20%           00:00:00.2833266   00:00:00.0105229     25.9
 30%           00:00:00.4462866   00:00:00.0091487     47.8
 40%           00:00:00.6951060   00:00:00.0108980     62.8
 50%           00:00:00.7567745   00:00:00.0087065     85.9
 60%           00:00:00.7090449   00:00:00.0083365     84.1
 70%           00:00:00.8179365   00:00:00.0088809     91.1
 80%           00:00:00.9468898   00:00:00.0088562    105.9
 90%           00:00:01.0411393   00:00:00.0081040    127.5
100%           00:00:01.1488157   00:00:00.0078877    144.6

/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryCatch(double errorRate, int seed, int count)
{
    Stopwatch stopwatch = new Stopwatch();
    Random random = new Random(seed);
    string bad_prefix = @"X";

    stopwatch.Start();
    for(int ii = 0; ii < count; ++ii)
    {
        string input = random.Next().ToString();
        if (random.NextDouble() < errorRate)
        {
           input = bad_prefix + input;
        }

        int value = 0;
        try
        {
            value = Int32.Parse(input);
        }
        catch(FormatException)
        {
            value = -1; // we would do something here with a logger perhaps
        }
    }
    stopwatch.Stop();

    return stopwatch.Elapsed;
}

/// <param name="errorRate">Rate of errors in user input</param>
/// <returns>Total time taken</returns>
public static TimeSpan TimeTryParse(double errorRate, int seed, int count)
{
    Stopwatch stopwatch = new Stopwatch();
    Random random = new Random(seed);
    string bad_prefix = @"X";

    stopwatch.Start();
    for(int ii = 0; ii < count; ++ii)
    {
        string input = random.Next().ToString();
        if (random.NextDouble() < errorRate)
        {
           input = bad_prefix + input;
        }

        int value = 0;
        if (!Int32.TryParse(input, out value))
        {
            value = -1; // we would do something here with a logger perhaps
        }
    }
    stopwatch.Stop();

    return stopwatch.Elapsed;
}

public static void TimeStringParse()
{
    double errorRate = 0.1; // 10% of the time our users mess up
    int count = 10000; // 10000 entries by a user

    TimeSpan trycatch = TimeTryCatch(errorRate, 1, count);
    TimeSpan tryparse = TimeTryParse(errorRate, 1, count);

    Console.WriteLine("trycatch: {0}", trycatch);
    Console.WriteLine("tryparse: {0}", tryparse);
}
```
```


q:
The project I'm working on needs to render an ESRI shape file, which can have a large number of polygons/shapes.  When I add all these polygons, lines, points, etc to the canvas I'm using, it gets really slow.

To draw the shapes on the map, I'm creating a Path object, and setting it's Data property to a StreamGeometry.  I originally used a Polygon, but according to MSDN a StreamGeometry is much lighter weight.

How can I improve the performance?  Would converting the finished product to a Bitmap, or VisualBrush help?  Is there a more efficient way of to render all these shapes onto the canvas?

EDIT:  I forgot to mention that this needs to be able to work in a Partial-Trust XBAP.

[A]
You are about to discover the motivation behind GPUs and insanely overclocked and cooled-down graphics cards. And double-buffering.
And: converting the thing to a bitmap: what's the difference to rendering it?
After all you have n objects that /somehow/ have to get rendered (unless you can figure out which objects are hidden behind other objects but that doesn't help you much since you'd have to look at n! object relations).
Besides: maybe it pays off to leave the orthodox OOP approach and go procedural instead.


q:
I have searched but apparently my google foo is weak. What I need is a way to prompt for user input in the console and have the request time out after a period of time and continue executing the script if no input comes in. As near as I can tell, Read-Host does not provide this functionality. Neither does $host.UI.PromptForChoice() nor does $host.UI.RawUI.ReadKey(). Thanks in advance for any pointers.

EDIT: Much thanks to Lars Truijens for finding the answer. I have taken the code that he pointed out and encapsulated it into a function. Note that the way that I have implemented it means there could be up to one second of delay between when the user hits a key and when script execution continues.

function Pause-Host
{
    param(
            $Delay = 1
         )
    $counter = 0;
    While(!$host.UI.RawUI.KeyAvailable -and ($counter++ -lt $Delay))
    {
        [Threading.Thread]::Sleep(1000)
    }
}

[A]
Found something
here
:
```
```
$counter = 0
while(!$Host.UI.RawUI.KeyAvailable -and ($counter++ -lt 600))
{
      [Threading.Thread]::Sleep( 1000 )
}
```
```


q: How do I list and export a private key from a keystore?

[A]
A portion of code originally from Example Depot for listing all of the aliases in a key store:
```
```
// Load input stream into keystore
    keystore.load(is, password.toCharArray());

    // List the aliases
    Enumeration aliases = keystore.aliases();
    for (; aliases.hasMoreElements(); ) {
        String alias = (String)aliases.nextElement();

        // Does alias refer to a private key?
        boolean b = keystore.isKeyEntry(alias);

        // Does alias refer to a trusted certificate?
        b = keystore.isCertificateEntry(alias);
    }
```
```
The exporting of private keys came up on the
Sun forums
a couple of months ago, and
u:turingcompleter
came up with a DumpPrivateKey class to stitch into your app.
```
```
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import sun.misc.BASE64Encoder;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args

     *
 [0] Keystore filename.
     *
 [1] Keystore password.
     *
 [2] alias
     *

     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        String b64 = new BASE64Encoder().encode(key.getEncoded());
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}
```
```
Note: this use Sun package,
which is a "bad thing"
.
If you can download
apache commons code
, here is a version which will compile without warning:
```
```
javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java
```
```
and will give the same result:
```
```
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;

public class DumpPrivateKey {
     /**
     * Provides the missing functionality of keytool
     * that Apache needs for SSLCertificateKeyFile.
     *
     * @param args

     *
 [0] Keystore filename.
     *
 [1] Keystore password.
     *
 [2] alias
     *

     */
    static public void main(String[] args)
    throws Exception {
        if(args.length < 3) {
          throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
        }
        final String keystoreName = args[0];
        final String keystorePassword = args[1];
        final String alias = args[2];
        final String keyPassword = getKeyPassword(args,keystorePassword);
        KeyStore ks = KeyStore.getInstance("jks");
        ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
        Key key = ks.getKey(alias, keyPassword.toCharArray());
        //String b64 = new BASE64Encoder().encode(key.getEncoded());
        String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));
        System.out.println("-----BEGIN PRIVATE KEY-----");
        System.out.println(b64);
        System.out.println("-----END PRIVATE KEY-----");
    }
    private static String getKeyPassword(final String[] args, final String keystorePassword)
    {
       String keyPassword = keystorePassword; // default case
       if(args.length == 4) {
         keyPassword = args[3];
       }
       return keyPassword;
    }
}
```
```
You can use it like so:
```
```
java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat
```
```


q: I understand that these methods are for pickling/unpickling and have no relation to the reduce built-in function, but what's the difference between the 2 and why do we need both?

[A]
The docs
say that
If provided, at pickling time
```
__reduce__()
```
will be called with no
arguments, and it must return either a
string or a tuple.
On the other hand,
It is sometimes useful to know the
protocol version when implementing
```
__reduce__
```
. This can be done by
implementing a method named
```
__reduce_ex__
```
instead of
```
__reduce__
```
.
```
__reduce_ex__
```
, when it
exists, is called in preference over
```
__reduce__
```
(you may still provide
```
__reduce__
```
for backwards
compatibility). The
```
__reduce_ex__
```
method will be called with a single
integer argument, the protocol
version.
On the gripping hand,
Guido says
that this is an area that could be cleaned up.


q:
I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem.

How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:

request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.

But that didn't work.

Any Ideas?

The site is on IIS 6.0.
We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.

[A]
Update, you actually want to pick up:
VB.NET:
```
```
Request.QueryString("aspxerrorpath")
```
```
C#:
```
```
Request.QueryString["aspxerrorpath"];
```
```


q: If I have variable of type IEnumerable<List<string>> is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an IEnumerable<string>?

[A]
SelectMany - i.e.
```
```
IEnumerable<List<string>> someList = ...;
        IEnumerable<string> all = someList.SelectMany(x => x);
```
```
For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>.
These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):
```
```
static IEnumerable<TResult> SelectMany<TSource, TResult>(
    this IEnumerable<TSource> source,
    Func<TSource, IEnumerable<TResult>> selector) {

    foreach(TSource item in source) {
      foreach(TResult result in selector(item)) {
        yield return result;
      }
    }
}
```
```
Although that is simplified somewhat.


q:
What is the best way to dynamically create RDLC xml as input to VS2005 Report Viewer?

I would like to autosize columns based on the data sizes.  I would also like to programmatically control what columns are displayed.

[A]
Lisa Nicholls
gives a complete answer
in this thread
about dynamically defining a report. You'll want to scroll down some before you get to a useful answer. This thread most directly answers your question about controlling which columns are displayed.
These same techniques can be used to size the columns programmatically, but your code will have to figure out the appropriate column widths.