q: If I use assert() and the assertion fails then assert() will call abort(), ending the running program abruptly.  I can't afford that in my production code.  Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?

[A]
Yes, as a matter of fact there is.  You will need to write a custom assert function yourself, as C++'s
```
assert()
```
is exactly C's
```
assert()
```
, with the
```
abort()
```
"feature" bundled in.  Fortunately, this is surprisingly straightforward.
Assert.hh
```
```
template <typename X, typename A>
inline void Assert(A assertion)
{
    if( !assertion ) throw X();
}
```
```
The above function will throw an exception if a predicate doesn't hold.  You will then have the chance to catch the exception.  If you don't catch the exception,
```
terminate()
```
will be called, which will end the program similarly to
```
abort()
```
.
You may wonder what about optimizing away the assertion when we're building for production.  In this case, you can define constants that will signify that you're building for production and then refer to the constant when you
```
Assert()
```
.
debug.hh
```
```
#ifdef NDEBUG
    const bool CHECK_WRONG = false;
#else
    const bool CHECK_WRONG = true;
#endif
```
```
main.cc
```
```
#include<iostream>

struct Wrong { };

int main()
{
    try {
        Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5);
        std::cout << "I can go to sleep now.\n";
    }
    catch( Wrong e ) {
        std::cerr << "Someone is wrong on the internet!\n";
    }

    return 0;
}
```
```
If
```
CHECK_WRONG
```
is a constant then the call to
```
Assert()
```
will be compiled away in production, even if the assertion is not a constant expression.  There is a slight disadvantage in that by referring to
```
CHECK_WRONG
```
we type a little more.  But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit.  So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds.
The
```
Assert()
```
function is equivalent to typing
```
```
if( !assertion ) throw X();
```
```
but it clearly indicates the intent of the programmer:  make an assertion.  Assertions are also easier to grep for with this approach, just like plain
```
assert()
```
s.
For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2.


q: Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.

[A]
How about parsing the HTML data and extracting the data with the help of the parser ?
I'd try something like the author described in
chapter 8.3 in the Dive Into Python book

s: huggingface

c: devops

d: intermediate


q:
I'm trying to get some stats on how many of the visitors to our website have Silverlight enabled browsers.

We currently use Google Analytics for the rest of our stats so ideally we'd like to just add 'Silverlight enabled' tracking in with the rest of our Google Analytics stats.  But if it has to get written out to a DB etc then so be it.

Nikhil has some javascript to Silverlight tracking to Google Analytics.  I have tried this code but Google Analytics doesn't pick it up.

Does anyone have any other ideas/techniques?

[A]
I think you answered it yourself. The page you are linking to does just that: detect which version of Silverlight the user has (not if s/he installs it). From the page:
After a little poking around, I found that Google Analytics has support for reporting a user-defined field.
...
Basically this detects the presence of Silverlight, and if its available, it records the version as the value of the user-defined field. Now your analytics reports will have one of three values: "(not set)", "Silverlight/1.0" or "Silverlight/2.0".


q:
Imagine we have a program trying to write to a particular file, but failing.

On the Windows platform, what are the possible things which might be causing the file to be un-writable, and what steps could be suggested to an end user/administrator to fix it.

Please include steps which might require administrator permissions (obviously users may not be administrators, but for this question, let's assume they are (or can become) administrators.

Also, I'm not really familiar with how permissions are calculated in windows. - Does the user need write access to each directory up the tree, or anything similar to that?

[A]
Some suggestions:
No write permission (get permission through Security tab on file Properties window; you must be the file owner or an Administrator)
File is locked (close any program that may have the file open, then reboot if that doesn't help)
File has the read-only DOS attribute set (unset it from file Properties window, or with
```
attrib -r
```
; you must be the file owner or an Administrator)
Edit 1: Only the second item (file is locked) has a possible solution that all users are likely to be able to do without help.  For the first and third, you'll probably want to provide guidance (and hope the file wasn't made read-only intentionally!).
Edit 2: Technically, the user does need write and execute (chdir) permissions on all directories up to the root.  Windows may skip some of the recursive checks up the tree as a performance optimization, but you should not rely on this because admins can force on these so-called "traverse checks" for certain users.
Edit 3: @RobM: Yes, you should check that there is no obvious reason that the user should not have the permissions she needs but does not have.  I alluded to this in a less direct way in my first edit.  However, in some cases users should have write permission to a file but do not because of filesystem corruption, a misbehaving program, or a mistake on their own part.


q: Does anyone know if you can and how to start off a scheduled Windows task on a Remote Server from within a SQL Server Integration Services (SSIS) package?

[A]
It should be possible as the Task Scheduler has a scriptable
COM API
that can be used for interacting with tasks.
You could therefore either create a custom task that uses COM interop to call the Task Scheduler API, or it'd probably be quicker to use an Active X Script task to do your dirty work.


q:
How do I determine the size of my array in C?

That is, the number of elements the array can hold?

[A]
Executive summary:
```
```
int a[17];
size_t n = sizeof(a)/sizeof(a[0]);
```
```
Full answer:
To determine the size of your array in bytes, you can use the
```
sizeof
```
operator:
```
```
int a[17];
size_t n = sizeof(a);
```
```
On my computer, ints are 4 bytes long, so n is 68.
To determine the number of elements in the array, we can divide
the total size of the array by the size of the array element.
You could do this with the type, like this:
```
```
int a[17];
size_t n = sizeof(a) / sizeof(int);
```
```
and get the proper answer (68 / 4 = 17), but if the type of
```
a
```
changed you would have a nasty bug if you forgot to change
the
```
sizeof(int)
```
as well.
So the preferred divisor is
```
sizeof(a[0])
```
or the equivalent
```
sizeof(*a)
```
, the size of the first element of the array.
```
```
int a[17];
size_t n = sizeof(a) / sizeof(a[0]);
```
```
Another advantage is that you can now easily parameterize
the array name in a macro and get:
```
```
#define NELEMS(x)  (sizeof(x) / sizeof((x)[0]))

int a[17];
size_t n = NELEMS(a);
```
```


q:
I am trying to figure out what exactly is Appdomain recycling?
When a aspx page is requested for the first time from a DotNet application, i understand that an appdomain for that app is created, and required assemblies are loaded into that appdomain, and the request will be served.
Now, if the web.config file or the contents of the bin folder, etc are modified, the appdomain will be "recycled".
My question is, at the end of the recycling process, will the appdomain be loaded with assemblies and ready to serve the next request? or a page has to be requested to trigger the assemblies to load?.

[A]
Take a look at this - that might explain it:
http://weblogs.asp.net/owscott/archive/2006/02/21/ASP.NET-v2.0-
2D00
-AppDomain-recycles_2C00_-more-common-than-before.aspx#440333
In general. What is called "first hit" on an ASP.NET Website is usually taking longer time, due to compilation, and creation of an AppDomain.
Whenever you deploy a site - make sure to use the "Publish Website" function in Visual Studio, to pre-compile your website. Then the "first hit" penalty is reduced. And remember to set the configuration to Release, and not Debug!


q: So I've been using InstantRails to check out Ruby on rails. I've been using Notepad++ for the editing. Now I don't want to install Ruby or Rails on my machine. Is there any walk through/tutorial on how to integrate Radrails or Netbeans with InstantRails?

[A]
Here's a tutorial:
http://ruby.meetup.com/73/boards/view/viewthread?thread=2203432
(I don't know if it's any good.)
And here's one with InstantRails+Netbeans:
https://web.archive.org/web/20100505044104/http://weblogs.java.net/blog/bleonard/archive/2007/03/instant_rails_w.html


q:
What is reflection, and why is it useful?

I'm particularly interested in Java, but I assume the principles are the same in any language.

[A]
The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.
So, to give you a code example of this in Java (imagine the object in question is foo) :
```
```
Method method = foo.getClass().getMethod("doSomething", null);
method.invoke(foo, null);
```
```
One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.
There are some good reflection examples to get you started at
http://docs.oracle.com/javase/tutorial/reflect/index.html
And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.
Update from a comment:
The ability to inspect the code in the system and see object types is
  not reflection, but rather Type Introspection. Reflection is then the
  ability to make modifications at runtime by making use of
  introspection. The distinction is necessary here as some languages
  support introspection, but do not support reflection. One such example
  is C++


q:
What is the best way to implement, from a web page a download action using asp.net 2.0?

Log files for a action are created in a directory called [Application Root]/Logs.  I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.

[A]
Does this help:
http://www.west-wind.com/weblog/posts/76293.aspx
```
```
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");
Response.TransmitFile( Server.MapPath("~/logfile.txt") );
Response.End();
```
```
Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.


q:
I'm writing a Perl script and would like to use a n-ary tree data structure.

Is there a good implementation that is available as source code (rather than part of a Perl library) ?

[A]
I don't really understand why you want it was "source" rather than as a perl library, but you can download the source for any CPAN module.
I haven't used it, but
Tree
looks to fill your requirements.


q:
I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match.

How I can replace all the URL? I guess I should be using the exec command, but I did not really figure how to do it.

function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    return text.replace(exp,"<a href='$1'>$1</a>");
}

[A]
Replacing URLs with links (Answer to the General Problem)
The regular expression in the question misses
a lot
of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like
```
.museum
```
, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post
The Problem With URLs
for an explanation of some of the other issues.
The
best summary of URL matching libraries
is in
Dan Dascalescu's Answer
(as of Feb 2014)
"Make a regular expression replace more than one match" (Answer to the specific problem)
Add a "g" to the end of the regular expression to enable global matching:
```
```
/ig;
```
```
But that only fixes the problem in the question where the regular expression was only replacing the first match.
Do not use that code.


q:
Sorry for this not being a "real" question, but Sometime back i remember seeing a post here about randomizing a randomizer randomly to generate truly random numbers, not just pseudo random. I dont see it if i search for it.

Does anybody know about that article?

[A]
It's not possible to obtain 'true' random numbers, a computer is a logical construct that can't possibly create 'truly' random anything, only pseudo-random. There are better and worse pseudo-random algorithms out there, however.
In order to obtain a 'truly' random number you need a physical random source, some gambling machines actually have these built in - often it's a radioactive source, the radioactive decay (which as far as I know is
truly
random) is used to generate the numbers.


q:
I seem right now to be embroiled in a debate with another programmer on this project who thinks that views have no merits.  He proposes a system that PHP looks something like this:

$draw = new Draw;
$nav = $draw->wideHeaderBox().
$draw->left().
    $draw->image().
        Image::get($image,60,array('id'=>'header_image')).
    $draw->imageEnd().
$draw->leftEnd().
$draw->left(10).
    '<div id="header_text">'.
        self::defaultSectionText().
    '</div>'.
$draw->leftEnd().

and so on (this is in the controller btw).  Now his arguments for this actually make some sense, he claims that if there is a redesign all we need to do is change the HTML in one place and it changes everywhere automatically. For some reason however, this method still rubs me the wrong way, is there any merit to views over this method?  I mean besides not having to retype HTML by hand.

[A]
The argument he uses is the argument you need to
have
views. Both result in only changing it in one place. However, in his version, you are mixing view markup with business code.
I would suggest using more of a templated design. Do all your business logic in the PHP, setup all variables that are needed by your page. Then just have your page markup reference those variables (and deal with no business logic whatsoever).
Have you looked at smarty?
http://smarty.php.net


[A]
http://regexlib.com/REDetails.aspx?regexp_id=610
^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$
This RE validates both dates and/or
  times patterns. Days in Feb. are also
  validated for Leap years. Dates: in
  dd/mm/yyyy or d/m/yy format between
  1/1/1600 - 31/12/9999. Leading zeroes
  are optional. Date separators can be
  either matching dashes(-), slashes(/)
  or periods(.) Times: in the hh:MM:ss
  AM/PM 12 hour format (12:00 AM -
  11:59:59 PM) or hh:MM:ss military time
  format (00:00:00 - 23:59:59). The 12
  hour time format: 1) may have a
  leading zero for the hour. 2) Minutes
  and seconds are optional for the 12
  hour format 3) AM or PM is required
  and case sensitive. Military time 1)
  must have a leading zero for all hours
  less than 10. 2) Minutes are
  manditory. 3) seconds are optional.
  Datetimes: combination of the above
  formats. A date first then a time
  separated by a space. ex) dd/mm/yyyy
  hh:MM:ss
Edit
: Make sure you copy the RegEx from the regexlib.com website as StackOverflow sometimes removes/destroys special chars.


q:
I'd like to find the different ways to solve a real life problem I had: imagine to have a contest, or a game, during which the users collect points. You have to build a query to show the list of users with the best "n" scores.

I'm making an example to clarify. Let's say that this is the Users table, with the points earned:

UserId - Points
1      - 100
2      -  75
3      -  50
4      -  50
5      -  50
6      -  25

If I want the top 3 scores, the result will be:

UserId - Points
1      - 100
2      -  75
3      -  50
4      -  50
5      -  50

This can be realized in a view or a stored procedure, as you want. My target db is Sql Server. Actually I solved this, but I think there are different way to obtain the result... faster or more efficent than mine.

[A]
Untested, but should work:
```
```
select * from users where points in
(select distinct top 3 points from users order by points desc)
```
```


q:
I have the following code in a web.config file of the default IIS site.

<httpModules>
    <add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/>
</httpModules>

Then when I setup and browse to a virtual directory I get this error

Could not load file or assembly 'Charts' or one of its dependencies. The system cannot find the file specified.

The virtual directory is inheriting the modules from the default web.config.

How do you stop this inheritance?

[A]
I've found the answer.  Wrap the HttpModule section in location tags and set the inheritInChildApplications attribute to false.
```
```
<location path="." inheritInChildApplications="false">
  <system.web>
    <httpModules>
      <add type="MDL.BexWebControls.Charts.ChartStreamHandler,Charts" name="ChartStreamHandler"/>
    </httpModules>
  </system.web>
</location>
```
```
Now any virtual directories will not inherit the settings in this location section.
@GateKiller This isn't another website, its a virtual directory so inheritance does occur.
@petrich I've had hit and miss results using
```
<remove />
```
.  I have to remember to add it to every virtual directory which is a pain.


q: I'm customizing a SugarCRM 5, and in my SugarCRM database I have all invoices which were imported from our ERP. Now, I would like to know if it is possible to create a new sub-panel in the Accounts Panel without editing the original SugarCRM files, so that my client invoices index are visible in that interface.

[A]
Last time I checked, you could use the
module builder
to extend the interface. From 5.0 (or maybe 4.x) on, Sugar added all those APIs, which should enable you to extend SugarCRM without hacking it in and losing it with the next upgrade.
Hope that helps!


q:
I am creating an application for a Windows Mobile computer. The catch is that the device (Motorola MC17) does not have a touch screen or universal keys - there are only six programmable hardware keys. Fitt's law is not applicable here, most Microsoft guidelines are also moot. For now I'm mimicking Nokia's S60 keyboard layout as close as possible, since it's the most popular phone platform among my target audience.

Are there any guidelines for creating a simple, discoverable user interface on such a constrained device? What fonts and colours should I use to make my UI readable? How do I measure if the items on-screen are big enough? What conventions should I follow?


q:
Is it possible to have a fixture change between test methods? If so, how can I do this?

My syntax for this problem :

In the cakephp framework i am building tests for a behavior that is configured by adding fields to the table. This is intended to work in the same way that adding the "created"
and "modified" fields will auto-populate these fields on save.

To test this I could create dozens of fixtures/model combos to test the different setups, but it would be a hundred times better, faster and easier to just have the fixture change "shape" between test methods.

If you are not familiar with the CakePHP framework, you can maybe still help me as it uses SimpleTest

Edit: rephrased question to be more general


q:
Is it possible to use gcov for coverage testing of multi-threaded applications?

I've set some trivial tests of our code-base up, but it would be nice to have some idea of the coverage we're achieving. If gcov isn't appropriate can anyone recommend an alternative tool (possible oprofile), ideally with some good documentation on getting started.

[A]
We've certainly used gcov to get coverage information on our multi-threaded application.
You want to compile with gcc 4.3 which can do coverage on dynamic code.
You compile with the
```
-fprofile-arcs -ftest-coverage
```
options, and the code will generate .gcda files which gcov can then process.
We do a separate build of our product, and collect coverage on that, running unit tests and regression tests.
Finally we use lcov to generate HTML results pages.


q:
I have a List<int> and a List<customObject>. The customObject class has an ID property. How can I get a List<customObject> containing only the objects where the ID property is in the List<int> using LINQ?

Edit: I accepted Konrads answer because it is easier/more intuitive to read.

[A]
Untested, but it'll be something like this:
```
```
var matches = from o in objList
                  join i in intList on o.ID equals i
                  select o;
```
```
@Konrad just tested it, and it does work - I just had a typo where I'd written "i.ID" rather than "i".


q: Are you working on a (probably commercial) product which uses RDF/OWL/SPARQL technologies? If so, can you please describe your product?

[A]
O'Reilly's Practical RDF has a chatper titled
Commercial Uses of RDF/XML
. The table at the left lists the subsections:
Chandler
,
RDF Gateway
,
Seamark
, and Adobe's
XMP
stuff.


q:
How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?

For example how can I convert:

How do I generate a Friendly URL in C#?

Into

how-do-i-generate-a-friendly-url-in-C

[A]
Here's how we do it. Note that there are probably more edge conditions than you realize at first glance..
```
```
if (String.IsNullOrEmpty(title)) return "";

// remove entities
title = Regex.Replace(title, @"&\w+;", "");
// remove anything that is not letters, numbers, dash, or space
title = Regex.Replace(title, @"[^A-Za-z0-9\-\s]", "");
// remove any leading or trailing spaces left over
title = title.Trim();
// replace spaces with single dash
title = Regex.Replace(title, @"\s+", "-");
// if we end up with multiple dashes, collapse to single dash
title = Regex.Replace(title, @"\-{2,}", "-");
// make it all lower case
title = title.ToLower();
// if it's too long, clip it
if (title.Length > 80)
    title = title.Substring(0, 79);
// remove trailing dash, if there is one
if (title.EndsWith("-"))
    title = title.Substring(0, title.Length - 1);
return title;
```
```


q: I'd like to be able to view the event log for a series of asp.net websites running on IIS. Can I do this externally, for example, through a web interface?

[A]
Do you want to know if you can home-roll something or are you looking for an app you can get off the shelf?
I'm not a Windows guy, but I think Microsoft's MOM/SCOM solution will probably let you view the event log over a web UI - probably really heavy and expensive if that's all you need though.
A quick google found
http://www.codeproject.com/KB/XML/Event_Logger.aspx
which shows that you can get in if you want to roll your own... also an MS tool on
msdn
Sorry I can't be more help


q:
I want to show a chromeless modal window with a close button in the upper right corner.
Is this possible?

[A]
You'll pretty much have to roll your own Close button, but you can hide the window chrome completely using the WindowStyle attribute, like this:
```
```
<Window WindowStyle="None">
```
```
That will still have a resize border. If you want to make the window non-resizable then add ResizeMode="NoResize" to the declaration.


q:
So I know that unit testing is a must. I get the idea that TDD is the way to go when adding new modules. Even if, in practice, I don't actually do it. A bit like commenting code, really.

The real thing is, I'm struggling to get my head around how to unit-test the UI and more generally objects that generate events: user controls, asynchronous database operations, etc.

So much of my code relates to UI events that I can't quite see how to even start the unit testing.

There must be some primers and starter docs out there? Some hints and tips?

I'm generally working in C# (2.0 and 3.5) but I'm not sure that this is strictly relevant to the question.

[A]
You should separate logic and presentation. Using MVP(Model-View-Presenter)/MVC (Model-View-Controller) patterns you can unit test you logic without relying on UI events.
Also you can use
White framework
to simulate user input.
I would highly recommend you to visit Microsoft's
Patterns&Practices developer center
, especially take a look at composite application block and Prism - you can get a lot of information on test driven design.


q:
How do you use the the org.springframework.ws.transport.jms.WebServiceMessageDrivenBean class from the Java Spring Framework - Spring-WS project?

There is very little documentation or examples available on the web.

[A]
From what I gather from reading the
javadocs
it looks like this allows a Spring
WebServiceMessageReceiver
to be invoked using a JMS client instead of a web services client.  Hopefully that's right, because the rest of this is based on that assumption.
The basics of is should match with how you create a regular Spring message driven bean.  There is a little bit of documentation on how to do that in the
Spring Reference Manual
.  Also see the
AbstractEnterpriseBean Javadoc
for some additional information about how the Spring context is retrieved.
The extra configuration required for a WebServiceMessageDrivenBean appear to be a
ConnectionFactory
, a
WebServiceMessageFactory
, and your
WebServiceMessageReceiver
.  These need to use the bean names specified in the Javadoc for the WebServiceMessageDrivenBean.  The bean names are "connectionFactory", "messageFactory", and "messageReceiver" respectively.


q:
I had a discussion with some colleagues mentioning that there are not too many projects that we do which make use of WPF for creating UI for a windows application (we almost always use Windows Forms instead).

Are your experiences the same - i.e. there is not too much adoption of this technology?

Why do you think that is? And will we have a time when we see much more of WPF?

[A]
Though WPF was introduced few years ago it was too raw to use it in the real world apps.  Major problem that stops WPF from wide adoption is a lack of RAD tools and out-of-box components.  Currently we have Blend, more or less working Cider, but usable versions of these tools came not so long ago. Another reason is a completely different architecture which  leads to longer development time as compared with WinForms due to prolonged learning\adoption period for developers.
I think we will see rising of WPF in the next few years.


q: By default IntelliJ IDEA 7.0.4 seems to use 4 spaces for indentation in XML files.  The project I'm working on uses 2 spaces as indentation in all it's XML.  Is there a way to configure the indentation in IntelliJ's editor?

[A]
Sure there is. This is all you need to do:
Go to
```
File -> Settings -> Global Code Style -> General
```
Disable the checkbox next to 'Use same settings for all file types'
The 'XML' tab should become enabled. Click it and set the 'tab' (and probably 'indent') size to 2.


q: Does anyone have any recommendations for implementations of ActiveRecord in PHP? I've been using CBL ActiveRecord, but I was wondering if there were any viable alternatives.

[A]
Depends! ;)
For example there is
ADODB's Active Record implementation
, then there is Zend_Db_DataTable and
Doctrine
. Those are the ones I know of, I am sure there are more implementations.
Out of those three I'd recommend Doctrine. Last time I checked Adodb carried a lot of extra weight for PHP4 and Zend_Db_* is generally not known to be the best in terms of completeness and performance (most likely due to its young age).
Doctrine aside from Active Table and the general database abstraction thing (aka DBAL) has so many things (e.g. migrations) which make it worth checking out, so if you haven't set your mind on a DBAL yet, you need to check it out.


q:
I currently have an MS Access application that connects to a PostgreSQL database via ODBC. This successfully runs on a LAN with 20 users (each running their own version of Access). Now I am thinking through some disaster recovery scenarios, and it seems that a quick and easy method of protecting the data is to use log shipping to create a warm-standby.

This lead me to think about putting this warm-standby at a remote location, but then I have the question:

Is Access connecting to a remote database via ODBC usable?
I.e. the remote database is maybe in the same country with ok ping times and I have a 1mbit SDSL line.

[A]
Yes.
I don't have any experience using Access to hit PostgreSQL from a remote location but I have successfully used Access as a front-end to SQL Server & DB2 from a remote location with success.
Ironically, what you don't want to do is use Access to front-end an Access database (mdb) from a remote location over a high-latency link.  Since hitting the MDB uses file-based operations it's pretty easy to end up with a corrupt database if you have anything more than a trivial db.


q:
We are using SourceForge Enterprise Edition 4.4 in one of our project.

My question is, in CollabNet SFEE (SourceForge Enterprise Edition 4.4), how will we get attachments associated with an Artifacts Using SFEE SOAP API?

We have made our own .net 2.0 client. We are not using .net SDK provided by Collabnet,

[A]
If you commit with a message you can add "[artf1000]" (where artf1000 is your artifact number) to the beginning or end of your commit message. Then it will associate to that artifact you can also do this with documents using doc1000, to get the id of the item you can use the URL it is what is after the
http://sfeeserver/sf/go/
.
Documents and artifacts are the only item I have used this for so I am not sure about other types of links, but I would imagine anything that has a /go/ID could be referenced by the ID.
ie:
http://sfeeserver/sf/go/artf1000
http://sfeeserver/sf/go/doc1000
Edited to add:
I have seemingly successfully tried this with releases, tasks, and discussions as well.


q:
I'm trying to make the case for click-once and smart client development but my network support team wants to keep with web development for everything.

What is the best way to convince them that click-once and smart client development have a place in the business?

[A]
They have a place in the Windows environment but not in any other environment and so if you intend on writing applications for external clients, then your probably best sticking with Web based development.
I heard this "Write Once, Run Many" before from Microsoft when Asp.net 1.1 was released, it never happened in practice.


q: How can I find the origins of conflicting DNS records?

[A]
An easy way is to use an online domain tool. My favorite is
Domain Tools
(formerly whois.sc). I'm not sure if they can resolve conflicting DNS records though. As an example, the DNS servers for stackoverflow.com are
```
```
NS51.DOMAINCONTROL.COM
  NS52.DOMAINCONTROL.COM
```
```


q: I work for a .NET/MSSQL shop that has trouble supporting customers running Novell, partially because we don't have Novell (or the money for it) and partially because we have no one with Novell experience. This question could easily be expanded to "How can we improve our support of technology X when we don't have technology X?" Obviously, I expect someone to say "it is easy to acquire the technology or someone with that kind of experience," but keep in mind I'm just a developer, not the development manager or someone with power over the purse strings. I looked for a Novell server virtual appliance (though I'm not sure "Novell server" is what I should be looking for) but didn't find much on VMware's website.

[A]
There is a
60 day evaluation trial of Open Enterprise Server 2
available (requires free registration). If you install it in a VM, there's nothing stopping you from reinstalling it after 60 days (well except licence).
But you will need someone good with Linux to handle this (and preferably good with this precise technology). In a MS shop this might be a problem.
The easiest solution would be to outsource this - have some external techs test your software for compatibility. If you find out you are paying too much - hire someone who knows this software stack.
You can't support something if you don't test against it. And you can't test against something you don't know.


q:
How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?

Something like:

DateTime.Now.StartWeek(Monday);

[A]
This would give you the preceding Sunday (I think):
```
```
DateTime t = DateTime.Now;
t -= new TimeSpan ((int) t.DayOfWeek, 0, 0, 0);
```
```


q:
Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:

Typedef myGenDef = < Object1, Object2 >;

HashMap< myGenDef > hm = new HashMap< myGenDef >();

for (Entry< myGenDef > ent : hm..entrySet())
{
.
.
.
}

[A]
No. Though, groovy, a JVM language, is dynamically typed and would let you write:
```
```
def map = new HashMap<complicated generic expression>();
```
```


q: I am considering log-shipping of Write Ahead Logs (WAL) in PostgreSQL to create a warm-standby database. However I have one table in the database that receives a huge amount of INSERT/DELETEs each day, but which I don't care about protecting the data in it. To reduce the amount of WALs produced I was wondering, is there a way to prevent any activity on one table from being recorded in the WALs?

[A]
Unfortunately, I don't believe there is. The WAL logging operates on the page level, which is much lower than the table level and doesn't even know which page holds data from which table. In fact, the WAL files don't even know which pages belong to which
database
.
You might consider moving your high activity table to a completely different instance of PostgreSQL. This seems drastic, but I can't think of another way off the top of my head to avoid having that activity show up in your WAL files.


q:
Lets say I have a loop in Bash:

for foo in `some-command`
do
   do-something $foo
done

do-something is cpu bound and I have a nice shiny 4 core processor. I'd like to be able to run up to 4 do-something's at once.

The naive approach seems to be:

for foo in `some-command`
do
   do-something $foo &
done

This will run all do-somethings at once, but there are a couple downsides, mainly that do-something may also have some significant I/O which performing all at once might slow down a bit. The other problem is that this code block returns immediately, so no way to do other work when all the do-somethings are finished.

How would you write this loop so there are always X do-somethings running at once?

[A]
Instead of a plain bash, use a Makefile, then specify number of simultaneous jobs with
```
make -jX
```
where X is the number of jobs to run at once.
Or you can use
```
wait
```
("
```
man wait
```
"): launch several child processes, call
```
wait
```
- it will exit when the child processes finish.
```
```
maxjobs = 10

foreach line in `cat file.txt` {
 jobsrunning = 0
 while jobsrunning < maxjobs {
  do job &
  jobsrunning += 1
 }
wait
}

job ( ){
...
}
```
```
If you need to store the job's result, then assign their result to a variable. After
```
wait
```
you just check what the variable contains.


q: I have a basic understanding of mock and fake objects, but I'm not sure I have a feeling about when/where to use mocking - especially as it would apply to this scenario here.

[A]
You should mock an object when you have a dependency in a unit of code you are trying to test that needs to be "just so".
For example, when you are trying to test some logic in your unit of code but you need to get something from another object and what is returned from this dependency might affect what you are trying to test - mock that object.
A great podcast on the topic can be found
here


q: The primary class in the subprocess module is name Popen, and represents a subprocess. Popen sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is.  Does anyone know why it was chosen over something simple like, say, Subprocess?

[A]
I suppose the name was chosen because the functionality
```
subprocess
```
is replacing was formerly in the
```
os
```
module as the
```
os.popen
```
function. There could be even ways to automate migration between the two.


q:
While I know IronRuby isn't quite ready for the world to use it, I was wondering if anyone here tried it and tested how well it faired against the other Rubies out there in terms of raw performance?

If so, what are the results, and how did you go about measuring the performance (which benchmarks etc)?

Edit: The IronRuby team maintains a site on how they compare to Ruby MRI 1.8 at http://ironruby.info/. Below the spec pass rate table, they also have some information on how IronRuby performs on these specs. This table is not continuously updated, but I assume they update it often enough (you can see the last update at the top of the page).

[A]
I have used it and it has worked great for what I have done.  However my measuring of performance isn't really scientific, because it was all visual.  However I did notice that IronRuby seemed a little more snappier when I compared the two program on equal tasks.  I really think this had to do more with the strong and tight binding with IIS that .NET has more than the speed of the framework.
But I could totally be wrong, because I didn't really stress my applications to the levels that Twitter might see.  But from my .NET experience I know it would hold up just as well if not better than current production Ruby applications.
By the way I tested Ruby using FastCGI under IIS.


q:
How does one convert an image from one color profile to another (screen to printer, or scanner to screen).  In Visual C++ you would use the function in ICM.h, is there a managed way to do this with GDI+?

I need to use GDI+, not WPF.  I'd prefer to have a managed solution, but if it is not available, I guess PInkvoke will have to suffice.

[A]
There are a number of solutions.
For GDI+,
check out this article at MSDN
(HOW TO: Use GDI+ and Image Color Management to Adjust Image Colors).
For WPF (.NET 3.0), see the
System.Windows.Media
namespace. There are a number of different classes, such as the
BitmapEncoder
, that have the concept of a
ColorContext
, which "Represents the International Color Consortium (ICC) or Image Color Management (ICM) color profile that is associated with a bitmap image."
Both of these seem pretty complex, so there's always the option of buying somebody else's code.  Atalasoft's
DotImage Photo Pro
has ICC profile setting capabilities built in.  The code is expensive; a dev license is almost 2k.  But based on their participation in the dotnet community, I'd give them a whirl.


q:
I recently "needed" a zip function in Perl 5 (while I was thinking about How do I calculate relative time?), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements.

(Pseudo)example:

@a=(1, 2, 3);
@b=('apple', 'orange', 'grape');
zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape');

Haskell has zip in the Prelude and Perl 6 has a zip operator built in, but how do you do it in an elegant way in Perl 5?

[A]
The
List::MoreUtils
module has a zip/mesh function that should do the trick:
```
```
use List::MoreUtils qw(zip);

my @numbers = (1, 2, 3);
my @fruit = ('apple', 'orange', 'grape');

my @zipped = zip @numbers, @fruit;
```
```
Here is the source of the mesh function:
```
```
sub mesh (\@\@;\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@\@) {
    my $max = -1;
    $max < $#$_  &&  ($max = $#$_)  for @_;

    map { my $ix = $_; map $_->[$ix], @_; } 0..$max;
}
```
```


q: If I get an error code result from a Cocoa function, is there any easy way to figure out what it means (other than by grepping through all the .h files in the framework bundles)?

[A]
You should look at the
```
<Framework/FrameworkErrors.h>
```
header for whatever framework the method you're using that's returning an error comes from.
For example, an
```
NSError
```
in the Cocoa domain that you get from a method in the Foundation framework will have its
```
code
```
property described in the
```
<Foundation/FoundationErrors.h>
```
header.  Similarly with AppKit and
```
<AppKit/AppKitErrors.h>
```
and Core Data and
```
<CoreData/CoreDataErrors.h>
```
.
Also, if you print the description of the
```
NSError
```
in the debugger, it should include not only the error domain and code, but also the name of the actual error code constant so you can look it up in the API reference.


q:
I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content:

<html>
<head>
<title>www.mysmallwebsite.com</title>
</head>

<frameset>
   <frame src="http://www.myIsv.com/myWebSite/" name="redir">
      <noframes>
        <p>Original location:
          <a href="www.myIsv.com/myWebSite/">http://www.myIsv.com/myWebSite/</a>
        </p>
      </noframes>
 </frameset>
</html>

It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that?

Edit:
This doesn't work both on IE and on Firefox (no plugins)

Thanks

[A]
What do you mean?
Are you saying that when you go from www.mysmallwebsite.com to www.myIsv.com/myWebSite/ then the PHP session is lost?
PHP recognizes the session with an ID (alpha-numeric hash generated on the server). The ID is passed from request to request using a cookie called PHPSESSID or something like that (you can view the cookies a websites sets with the help of your browser ... on Firefox you have Firebug + FireCookie and the wonderful Web Developer Toolbar ... with which you can view the list of cookies without a sweat).
So ... PHP is passing the session ID through the PHPSESSID cookie. But you can pass the session ID as a plain GET request parameters.
So when you place the html link to the ugly domain name, assuming that it is the same PHP server (with the same sessions initialized), you can put it like this ...
```
```
www.myIsv.com/myWebSite/?PHPSESSID=<?=session_id()?>
```
```
I haven't worked with PHP for a while, but I think this will work.


q:
I'm using Flash to play an .flv movieclip on my site, but I want to have the .swf send trigger an event in my javascript when it start loading, starts playing and ends playing.

What is the best way to do that in Flash CS3 using Actionscript 3.0 ?

[A]
A common way to do this is with the
ExternalInterface
class, which you can use to call JavaScript methods.
First define your JavaScript methods, for example:
```
```
<script language="JavaScript">
    function startsPlaying()
    {
        // do something when the FLV starts playing
    }
</script>
```
```
Then modify your ActionScript to call the JavaScript method at the appropriate time:
```
```
// inform JavaScript that the FLV has started playing
ExternalInterface.call("startsPlaying");
```
```
For more information, see the related Flash CS3
documentation
.


q:
I would like to convert the following string into an array/nested array:

str = "[[this, is],[a, nested],[array]]"

newarray = # this is what I need help with!

newarray.inspect  # => [['this','is'],['a','nested'],['array']]

[A]
Looks like a basic parsing task. Generally the approach you are going to want to take is to create a recursive function with the following general algorithm
```
```
base case (input doesn't begin with '[') return the input
recursive case:
    split the input on ',' (you will need to find commas only at this level)
    for each sub string call this method again with the sub string
    return array containing the results from this recursive method
```
```
The only slighlty tricky part here is splitting the input on a single ','. You could write a separate function for this that would scan through the string and keep a count of the openbrackets - closedbrakets seen so far. Then only split on commas when the count is equal to zero.


q:
I'm currently working on a quite large library (5M lines of code, in C++ under VS2005, 1 solution and close to 100 projects). Even though we distribute compilation, and use incremental linking, recompilation and relinking after small source modifications takes between a few minutes (usually at least 3) and close to one hour.

This means that our modify code/build/debug cycles tend to be really long (to my taste!), and it's quite easy to lose the 'flow' during a build: there's typically not much time to do anything useful (maybe do a bit of email, otherwise read some article online or a few pages of a book).

When writing new code or doing major refactoring, I try to compile one file at a time only. However, during debugging for example, it really gets on my nerves!

I'm wondering how I could optimize my time? I guess I'm not the only one in that situation: what do/would you do?

[A]
I don't know much about development at that level, but... it seems like it would be a good idea to separate into multiple solutions. You could have a final "pre-ship" step that consolidates them all into a single .dll if you/your customers really insist.
Compare, e.g., to the .NET Framework where we have lots of different assemblies (System, System.Drawing, System.Windows.Forms, System.Xml...). Presumably all of these could be in different solutions, referencing each other's build results (as opposed to all in a single solution, referencing each other as projects).


q:
Given an Oracle table created using the following:

CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE);

Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following:

import dbi, odbc

connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")

cursor = connection.cursor()
cursor.execute("SELECT WhenAdded FROM Log")

results = cursor.fetchall()

When I run this, I get the following:

Traceback (most recent call last):
...
    results = cursor.fetchall()
dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s
in FETCH

The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?

[A]
My solution to this, that I hope can be bettered, is to use Oracle to explicitly convert the TIMESTAMP into a string:
```
```
cursor.execute("SELECT TO_CHAR(WhenAdded, 'YYYY-MM-DD HH:MI:SSAM') FROM Log")
```
```
This works, but isn't portable. I'd like to use the same Python script against a SQL Server database, so an Oracle-specific solution (such as TO_CHAR) won't work.


q:
What is the best way to track changes in a database table?

Imagine you got an application in which users (in the context of the application not DB users ) are able to change data which are store in some database table. What's the best way to track a history of all changes, so that you can show which user at what time change which data how?

[A]
You've got a few issues here that don't relate well to each other.
At the basic database level you can track changes by having a separate table that gets an entry added to it via triggers on INSERT/UPDATE/DELETE statements. Thats the general way of tracking changes to a database table.
The other thing you want is to know which
user
made the change. Generally your triggers wouldn't know this. I'm assuming that if you want to know which user changed a piece of data then its possible that multiple users could change the same data.
There is no right way to do this, you'll probably want to have a separate table that your application code will insert a record into whenever a user updates some data in the other table, including user, timestamp and id of the changed record.
Make sure to use a transaction so you don't end up with cases where update gets done without the insert, or if you do the opposite order you don't end up with insert without the update.


q:
Do any asynchronous connectors exist for Mysql that can be used within a C or C++ application? I'm looking for something that can be plugged into a reactor pattern written in Boost.Asio.

[Edit:] Running a synchronous connector in threads is not an option.

[A]
I think the only solution will be to create an asynchronous service that wraps a
standard connector
. You'll need to understand the ODBC APIs though.


q: Also, how do LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN fit in?

[A]
A inner join only shows rows if there is a matching record on the other (right) side of the join.
A (left) outer join shows rows for each record on the left hand side, even if there are no matching rows on the other (right) side of the join. If there is no matching row, the columns for the other (right) side would show NULLs.


q: The printf function takes an argument type, such as %d or %i for a signed int. However, I don't see anything for a long value.

[A]
```
%ld
```
see
```
printf
```
reference on cplusplus.com


q:
I find myself doing this sort of thing all the time.  I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel.

Is there an existing function that will let me accomplish this same sort of thing more succinctly?

(defun remove-low-words (word-list)
  "Return a list with words of insufficient score removed."
  (let ((result nil))
    (dolist (word word-list)
      (when (good-enough-score-p word) (push word result)))
    result))

[A]
There are a couple ways you can do this.  First, and probably most easily, you can do it recursively.
```
```
(defun remove-low-words (word-list)
  (if (good-enough-score-p (car word-list))
      (list word (remove-low-words (cdr word-list)))
      (remove-low-words (cdr word-list))))
```
```
You could also do it with
```
mapcar
```
and
```
reduce
```
, where the former can construct you a list with failing elements replaced by
```
nil
```
and the latter can be used to filter out the
```
nil
```
.
Either would be a good candidate for a "filter" macro or function that takes a list and returns the list filtered by some predicate.


q:
Did Installing OneCare cause a "Generating user instances in SQL Server is disabled" error?

The only change that I've made to my computer is uninstalling AVG and installing the trial for Microsoft OneCare. Did OneCare change the SQLServer installation somehow?

This is a very "odd" question but is something I would post on EE in hopes of someone having had the same issue and giving their solution.

[A]
I would look more at the uninstalling of AVG as the culprit.  OneCare does not care or even notice SQL Server instances as far as I can tell where as AVG does.
I would look into your SQL Server instance and check the jobs.  One or more may have been added by AVG.  You should remove them.  You might also want to drop the AVG database.  Just to be sure.
Note: I have never
uninstalled
AVG.  I just have notice some of what it did to my Database when my SysAdmin installed it.  Being an Accidental DBA I haven't had the time to properly evaluate it's actions.


q: I'd like to be able to write a ruby program that can restart without dropping it's socket connections.

[A]
You're talking about network sockets, not UNIX sockets I assume?
I'm not sure this suits your needs, but the way I would do it is by seperating the networking and logic part, and only restart the logic part, then reconnect the logic part to the networking part.


q:
I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00.
In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00

What would be the best way to do this?
My code is below:

this.txtPayment.Text = dr["Payment"].ToString();

[A]
```
```
this.txtPayment.Text = string.Format("{0:c}", dr[Payment"].ToString());
```
```


q:
What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light of day.

Along these same lines (this is primarily my interest for static analysis), tools for testing code for multithreading issues (deadlocks, race conditions, etc.) also seem a bit scarce. Typemock Racer just popped up so I'll be looking at that. Anything beyond this?

Real-life opinions about tools you've used are appreciated.

[A]
Gendarme
is an open source rules based static analyzer (similar to FXCop, but finds a lot of different problems).
Clone Detective
is a nice plug-in for Visual Studio that finds duplicate code.
Also speaking of Mono, I find the act of compiling with the Mono compiler (if your code is platform independent enough to do that, a goal you might want to strive for anyway) finds tons of unreferenced variables and other Warnings that Visual Studio completely misses (even with the warning level set to 4).


q:
I want to combine two structures with differing fields names.

For example, starting with:

A.field1 = 1;
A.field2 = 'a';

B.field3 = 2;
B.field4 = 'b';

I would like to have:

C.field1 = 1;
C.field2 = 'a';
C.field3 = 2;
C.field4 = 'b';

Is there a more efficient way than using "fieldnames" and a for loop?

EDIT: Let's assume that in the case of field name conflicts we give preference to A.

[A]
In C, a struct can have another struct as one of it's members.  While this isn't exactly the same as what you're asking, you could end up either with a situation where one struct contains another, or one struct contains two structs, both of which hold parts of the info that you wanted.
psuedocode: i don't remember the actual syntax.
```
```
A.field1 = 1;
A.field2 = 'a';
A.field3 = struct B;
```
```
to access:
    A.field3.field4;
or something of the sort.
Or you could have struct C hold both an A and a B:
```
```
C.A = struct A;
C.B = struct B;
```
```
with access then something like
```
```
C.A.field1;
C.A.field2;
C.B.field3;
C.B.field4;
```
```
hope this helps!
EDIT: both of these solutions avoid naming collisions.
Also, I didn't see your
```
matlab
```
tag.  By convention, you should want to edit the question to include that piece of info.


q:
When using the Entity Framework, does ESQL perform better than Linq to Entities?

I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.

[A]
The more code you can cover with compile time checking for me is something that I'd place a higher premium on than performance. Having said that at this stage I'd probably lean towards ESQL not just because of the performance, but it's also (at present) a lot more flexible in what it can do. There's nothing worse than using a technology stack that doesn't have a feature you really really need.
The entity framework doesn't support things like custom properties, custom queries (for when you need to really tune performance) and does not function the same as linq-to-sql (i.e. there are features that simply don't work in the entity framework).
My personal impression of the Entity Framework is that there is a lot of potential, but it's probably a bit to "rigid" in it's implementation to use in a production environment in its current state.


q: Which databases does Adobe Flash support, if any?

[A]
None.
Instead, you would need to create some middleware (say, a webservice) that you talked to that did the database CRUD for you.


q:
Hey so what I want to do is snag the content for the first paragraph. The string $blog_post contains a lot of paragraphs in the following format:

<p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p>

The problem I'm running into is that I am writing a regex to grab everything between the first <p> tag and the first closing </p> tag. However, it is grabbing the first <p> tag and the last closing </p> tag which results in me grabbing everything.

Here is my current code:

if (preg_match("/[\\s]*<p>[\\s]*(?<firstparagraph>[\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph))
   echo "<p>" . $blog_paragraph["firstparagraph"] . "</p>";
else
  echo $blog_post;

[A]
It would probably be easier and faster to use
strpos()
to find the position of the first
```
```

```
```
and first
```
```

```
```
then use
substr()
to extract the paragraph.
```
```
$paragraph_start = strpos($blog_post, '
');
 $paragraph_end = strpos($blog_post, '
', $paragraph_start);
 $paragraph = substr($blog_post, $paragraph_start + strlen('
'), $paragraph_end - $paragraph_start - strlen('
'));
```
```
Edit:
Actually the regex in others' answers will be easier and faster... your big complex regex in the question confused me...


q:
Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead.

However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?

[A]
You could use something like this as your pre-commit script:
```
#! /usr/bin/perl

while (<>) {
    $last = $_;
}

if (! ($last =~ m/\n$/)) {
    print STDERR "File doesn't end with \\n!\n";
    exit 1;
}
```


q:
I'm looking for a way of getting a concurrent collection in C# or at least a collection which supports a concurrent enumerator.  Right now I'm getting an InvalidOperationException when the collection over which I'm iterating changes.

I could just deep copy the collection and work with a private copy but I'm wondering  if there is perhaps a better way

Code snippet:

foreach (String s in (List<String>) callingForm.Invoke(callingForm.delegateGetKillStrings))
{
    //do some jazz
}

--edit--

I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well.

private void addKillString(String s)
{
    lock (killStrings)
    {
        killStrings.Add(s);
    }
}

[A]
Other than doing a deep-copy your best bet might be to lock the collection:
```
```
List<string> theList = (List<String> )callingForm.Invoke(callingForm.delegateGetKillStrings);
    lock(theList.SyncRoot) {
        foreach(string s in theList) {
               // Do some Jazz
        }
    }
```
```


q: What are the ways that you use to model and retrieve hierarchical info in a database?

[A]
What's the best way to represent a hierachy in a SQL database?  A generic, portable technique?
Let's assume the hierachy is mostly read, but isn't completely static.  Let's say it's a family tree.
Here's how not to do it:
```
```
create table person (
person_id integer autoincrement primary key,
name      varchar(255) not null,
dob       date,
mother    integer,
father    integer
);
```
```
And inserting data like this:
```
```
person_id   name      dob       mother father
1           Pops      1900/1/1   null   null
2           Grandma   1903/2/4   null   null
3           Dad       1925/4/2   2      1
4           Uncle Kev 1927/3/3   2      1
5           Cuz Dave  1953/7/8   null   4
6           Billy     1954/8/1   null   3
```
```
Instead, split your nodes and your relationships into two tables.
```
```
create table person (
person_id integer autoincrement primary key,
name      varchar(255) not null,
dob       date
);

create table ancestor (
ancestor_id   integer,
descendant_id integer,
distance      integer
);
```
```
Data is created like this:
```
```
person_id   name      dob
1           Pops      1900/1/1
2           Grandma   1903/2/4
3           Dad       1925/4/2
4           Uncle Kev 1927/3/3
5           Cuz Dave  1953/7/8
6           Billy     1954/8/1

ancestor_id  descendant_id  distance
1            1              0
2            2              0
3            3              0
4            4              0
5            5              0
6            6              0
1            3              1
2            3              1
1            4              1
2            4              1
1            5              2
2            5              2
4            5              1
1            6              2
2            6              2
3            6              1
```
```
you can now run arbitary queries that don't involve joining the table back on itself, which would happen if you have the heirachy relationship in the same row as the node.
Who has grandparents?
```
```
select * from person where person_id in
    (select descendant_id from ancestor where distance=2);
```
```
All your descendants:
```
```
select * from person where person_id in
    (select descendant_id from ancestor
    where ancestor_id=1 and distance>0);
```
```
Who are uncles?
```
```
select decendant_id uncle from ancestor
    where distance=1 and ancestor_id in
    (select ancestor_id from ancestor
        where distance=2 and not exists
        (select ancestor_id from ancestor
        where distance=1 and ancestor_id=uncle)
    )
```
```
You avoid all the problems of joining a table to itself via subqueries, a common limitation is 16 subsuqeries.
Trouble is, maintaining the ancestor table is kind of hard - best done with a stored procedure.


q: I'm thinking of starting a wiki, probably on a low cost LAMP hosting account. I'd like the option of exporting my content later in case I want to run it on IIS/ASP.NET down the line. I know in the weblog world, there's an open standard called BlogML which will let you export your blog content to an XML based format on one site and import it into another. Is there something similar with wikis?

[A]
I haven't heard of WikiML.
I think your biggest obstacle is gonna be converting one wiki markup to another. For example, some wikis use markdown (which is what Stack Overflow uses), others use another markup syntax (e.g. BBCode, ...), etc.. The bottom line is - assuming the contents are databased it's not impossible to export and parse it to make it "fit" in another system. It might just be a pain in the ass.
And if the contents are not databased, it's gonna be a royal pain in the ass. :D
Another solution would be to stay with the same system. I am not sure what the reason is for changing the technology later on. It's not like a growing project requires IIS/ASP.NET all of the sudden. (It might just be the other way around.) But for example, if you could stick with PHP for a while, you could also run that on IIS.


q: I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?

[A]
You should take a look at
Apache OpenOffice API
. A project for creating an API for Open Office. A few languages they said to support are: C++, Java, Python, CLI, StarBasic, JavaScript and OLE.
Java Example of a mailmerge in OpenOffice
.


q:
My website was recently attacked by, what seemed to me as, an innocent code:

<?php
  if ( isset( $ _GET['page'] ) ) {
    include( $ _GET['page'] . ".php" );
  } else {
    include("home.php");
  }
?>

There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection.

This website has an explanation and a few examples of avoiding code injection: http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html

How would you protect this code from code injection?

[A]
I'm assuming you deal with files in the same directory:
```
```
<?php
if (isset($_GET['page']) && !empty($_GET['page'])) {
  $page = urldecode($_GET['page']);
  $page = basename($page);
  $file = dirname(__FILE__) . "/{$page}.php";
  if (!file_exists($file)) {
    $file = dirname(__FILE__) . '/home.php';
  }
} else {
  $file = dirname(__FILE__) . '/home.php';
}
include $file;
?>
```
```
This is not too pretty, but should fix your issue.


q:
I'm using the RESTful authentication Rails plugin for an app I'm developing.
I'm having a strange issue I can't get to the bottom of.
Essentially, the first time I log into the app after a period of inactivity (the app is deployed in production, but only being used by me), I will be brought to a 404 page, but if I go back to the home page and log in again, everything works according to plan.
Any ideas?

[A]
Please check your routes.
Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the config/routes.rb file. The priority goes from top to bottom. The last route in that file is at the lowest priority and will be applied last. If no route matches,
404
is returned.
More info:
http://api.rubyonrails.org/classes/ActionController/Routing.html


q:
I'm developing an Eclipse plug-in, based on a bunch of core Eclipse plug-ins like SWT, JDT, GEF and others.

I need my plug-in to be compatible with Eclipse 3.3, since many potential customers are still using it. However, personally I like the new features in Eclipse 3.4 and would like to use it for my development. This means I need PDE to reference 3.3 code and, when debug, execute a 3.3 instance.

Any tips on how this can be achieved?

Thanks.

[A]
You can change the 'Target platform' setting to point to the location of an existing set of eclipse 3.3 plugins. This will compile your code against the 3.3 plugins, making sure that they stay compatible no matter which version of eclipse you are using to develop the application.
The setting is under Window->Preferences->Plug-in development->Target Platform


q:
I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user.

What is the easiest way to do this?

Maybe the db migration is not the best for this type of thing. Thanks!

It would be nice if it could be a completely automated process. The following process would be ideal.

A user signs up on our site to use this web app

Migrations are run to create this users database and get tables setup correctly

Is there a way of calling a rake task from a ruby application?

[A]
We use seperate configuration files for each user. So in the config/ dir we would have roo.database.yml which would connect to my personal database, and I would  copy that over the database.yml file that is used by rails.
We were thinking of expanding the rails Rakefile so we could specify the developer as a environment variable, which would then select a specfic datbase configuration, allowing us to only have one database.yml file. We haven't done this though as the above method works well enough.


q: How to take screenshot programmically of desktop area in Mac OS X ?

[A]
Qt includes an example screenshot app in examples\desktop\screenshot. Qt works on a range of platforms, including MacOSX.
http://trolltech.com/products/qt/


q:
If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be:

SELECT Field1, Field2 FROM Table

And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal:

SELECT Field1, Field2, Field3 = 'Value' FROM Table

Is this possible at all?

[A]
```
```
SELECT Field1, Field2, 'Value' Field3 FROM Table
```
```
or for clarity
```
```
SELECT Field1, Field2, 'Value' AS Field3 FROM Table
```
```


q: Ok, here's a very short and to the point question. When trying to import a virtual PC 2004 Windows 2003 Server VM in VM Workstation 6.0.2 I'm getting an error 'unable to determine guest operating system'. Soo how to fix?

[A]
From
here
:
Make sure that that the VM is not currently running in VMware Server.
Make sure that VMware Server does not have a lock on the VM’s files. You have have to stop all VMware Server Services and/or reboot the (VMWare) server.
Make sure you have appropriate permissions to the VM’s files.


q: I would like to test a string containing a path to a file for existence of that file (something like the -e test in Perl or the os.path.exists() in Python) in C#.

[A]
Use:
```
```
File.Exists(path)
```
```
MSDN:
http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
Edit: In System.IO


q:
I want to merge two dictionaries into a new dictionary.

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = merge(x, y)

>>> z
{'a': 1, 'b': 3, 'c': 4}

Whenever a key k is present in both dictionaries, only the value y[k] should be kept.

[A]
```
```
x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = dict(x.items() + y.items())
print z
```
```
For items with keys in both dictionaries ('b'), you can control which one ends up in the output by putting that one last.


q: Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either .sty or .cls, how would I do that?


q:
I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again.  And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by .NET for form elements.

I can understand the code-behind reasoning for .NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction.  What can I do to work around this?

I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of .NET effectively changing rendered source on the fly.  It also means that CSS is less useful now and less efficient to create and maintain.

Any tips or advice greatly appreciated--anything for a few less sleepless nights...

[A]
You can extend .net controls and make them return actual id's when related properties are called.
ClientID is the id attribute and UniqueID is the name attribute of html elements. So when you create a textbox like the following and using this instead of the textbox in framework, you make id and name attributes render as the same as the server-side id.
```
```
public class MyTextBox : TextBox
{
    public override string ClientID { get { return ID; } }
    public override string UniqueID { get { return ID; } }
}
```
```
To use this new user control, basically register this control as you would do for a custom user control (you can do is in web.config so you won't have to do it in all your pages):
```
```
<%@ Register Assembly="MyLibrary" NameSpace="MyLibrary.WebControls" TagPrefix="MyPrefix" %>
```
```
And use it like you would use a text box:
```
```
<MyPrefix:MyTextBox ID="sampleTextBox" runat="server" />
```
```


q:
Large pages are available in Windows Server 2003 and Windows Vista.

But how do I enable large pages for my application?

[A]
You will have to assign the
```
Lock pages in memory
```
privilege to any user that runs your application.  This includes administrators.
Select Control
Panel -> Administrative Tools -> Local Security
Policy
Select Local
Policies -> User Rights Assignment
Double click "Lock pages in memory", add users and/or groups
Reboot the machine


q:
What would be the best way to draw a simple animation just before showing a modal JDialog? (i.e. expanding borders from the mouse click point to the dialog location). I thought it would be possible to draw on the glasspane of the parent frame on the setVisible method of the dialog.

However, since the JDialog is modal to the parent, I couldn't find a way to pump drawing events into EDT before the JDialog becomes visible, since the current event on the EDT has not been completed yet.

[A]
Are you trying to show the JDialog indepentently of the annimation? In order to get the order set properly, you may need to bundle those actions in a runnable that is passed to the EDT at once.
eg:
```
```
SwingUtilities.invokeLater(new Runnable(){
   public void run(){
      doAnnimation();
      showDialog();
   }
}
```
```
It may be best to subclass JDialog so that you can just add the doAnnimation() logic to the setVisible(..) or show() method before calling the superclass implementation.
Finally, I imagine you'll need to set the dimensions of the dalog manually --  I don't remember if Java will know the actual size of the dialog before it is shown, so you may get some useless information for your annimation if you query the size before showing it.


q:
I have a .Net desktop application with a TreeView as one of the UI elements.

I want to be able to multi-select that TreeView, only that isn't supported at all.

So I'm adding check-boxes to the tree, My problem is that only some items are selectable, and those that aren't can't consistently cascade selections.

Is there any way to disable or hide some check-boxes while displaying others?

[A]
The default behavior of TreeView is that when the
Checkboxes
property is set to true, that checkboxes will be shown for all TreeNodes.
The behavior that you are looking for - to disable or hide some checkboxes - is a custom modification of the normal behavior. You can create a custom implementation of TreeView or TreeNode that overrides the default behavior. One other thing to try would be to use the TreeView.
StateImageList
property. Some sites to check out for more info:
See
this post
to the MSDN forums that goes through an implementation similar to what you are attempting.
CodeProject:
Tri-State TreeView
CodeProject:
How to handle custom node state images in a TreeView (e.g. tristate checkboxes)


q: How can a .net class library project and resulting dll be protected so it cant be referenced by other applications (.net projects) except those projects in my own solution?

[A]
Forgive my ignorance, but if they're all class libraries, what does the code do?  Isn't the purpose of having a dll so that the code can be referenced.
In any case if you mark everything
```
internal
```
it won't be able to be accessed outside its own library


q:
I've had a FTP server (Mac OS X, but not the server version) set up for a while where the users are virtual, i.e. they are not actual user accounts in the server's OS, but accounts handled by the FTP server software -- to the OS they all look like the ftp user account. I'd like to retire the FTP server software and go SFTP instead.

Is there a way to set up SFTP/SSH so that I can create virtual users and at the same time sandbox them?

The reason I want virtual users is because I add and remove accounts from time to time, and doing that with proper user accounts tend to get messy, and I don't know of a good way to sandbox them. There's always some files left and each user has their own user directory (with a lot of files only relevant if they would actually log on to the machine when sitting in front of it), which is quarantined when the account is removed, so you have to remove it by hand yourself, and so on.

[A]
The usual generic Unix answer to this is 'PAM'. If you want plain old OpenSSH SSHD to handle your SFTP, you need something plugged in to SSHD's PAM stack (/etc/pam.d/sshd) that does what you need and leaves out what you don't need. This might be a general-purpose directory server (probably LDAP) that maps all your virtual users to one home directory and gives them a restricted or scponly kind of shell.
If you want to look at FTP servers that can also do FTP-ssl (which is not the same as SFTP),  good ftp servers like Pure-ftpd or vsftp will do that.  FTP-ssl servers have simpler virtual user support.
http://www.bsdguides.org/guides/freebsd/networking/pure-ftpd_virtual_users.php


q: I prefer dark backgrounds for coding, and I've downloaded a jar file containing an IntelliJ IDEA color theme that has a dark background. How do I tell IntelliJ about it?

[A]
Take a look here:
Third Party Add-ons
You
may
have to extract the jar using a zip application. Hopefully inside you'll find a collection of XML files.
IntelliJ IDEA Plugins


q:
I want to create a Java application bundle for Mac without using Mac.

According to Java Deployment Options for Mac OS X, I can do this by using Xcode, Jar Bundler, or from the command line. Once the files and folders are set up, all I need for the command line method is to call /Developer/Tools/SetFile. Is there a SetFile clone on Linux or Windows? If not, do I have to get a Mac?

[A]
A Java application bundle on OS X is nothing more than a directory containing your .jars and a number of configuration files.  The SetFile tool sets a custom HFS filesystem property on the directory to tell finder that it is an app, but giving it a ".app" extension serves the same purpose.  I don't think there's anything stopping you from building one on, say, Windows, though of course you have no way of testing that it works, but if you are able to test it at least once on a real Mac, you could then conceivably update the .jars within it on Windows to reflect code changes without too much difficulty.
Have a look at the
Bundle Programming Guide
for more info.


q: What are the options? How popular are they? Do these IDEs give similar/better functionality compared to visual studio?

[A]
Yes - you can try using SharpDevelop:
http://www.icsharpcode.net/OpenSource/SD/
Or you can just use notepad, or notepad++
http://notepad-plus.sourceforge.net/
Then compile on the command line.
Edit
: If you're looking for a free solution - try Visual Studio C# Express Edition:
http://www.microsoft.com/express/vcsharp/


q:
I have lots of article store in MS SQL server 2005 database in a table called Articles-

"Articles (ArticleID, ArticleTitle, ArticleContent)"

Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy.

Is it possible to do this in MS SQL Server 2005?

[A]
First of all you need to define what article similarity means.
For example you can associate some meta information with articles, like tags.
To be able to find similar articles you need to extract some features from them, for example you can build full text index.
You can take advantage of full text search capability of MSSQL 2005
```
```
-- Assuming @Title contains title of current articles you can find related articles runnig this query
SELECT * FROM Acticles WHERE CONTAINS(ArticleTitle, @Title)
```
```


q:
Is there any query which can return me the number of revisions made to the structure of a database table?

Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?

[A]
I think you need to create a
```
trigger
```
and store all changes to the table in a separate table. You can then use this table to get the revision history.


q:
I have heard umpteen times that we 'should not mix business logic with other code' or statements like that. I think every single code I write (processing steps I mean) consists of logic that is related to the business requirements..

Can anyone tell me what exactly consists of business logic? How can it be distinguished from other code? Is there some simple test to determine what is business logic and what is not?

[A]
Simply define what you are doing in plain English. When you are saying things businesswise, like "make those suffer", "steal that money", "destroy this portion of earth" you are talking about business layer. To make it clear, things that get you excited go here.
When you are saying "show this here", "do not show that", "make it more beautiful" you are talking about the presentation layer. These are the things that get your designers excited.
When you are saying things like "save this", "get this from database", "update", "delete", etc. you are talking about the data layer. These are the things that tell you what to keep forever at all costs.


q: How do you write code that is easily read by other people and who have had no hand in writing any part of it?

[A]
Keep code nice, clear and simple. Don't comment what you're doing when it's obvious (for instance I know what a foreach or if does, I don't normally need an explanation).
Code tricks (such as auto properties) that make simple things take up fewer lines are good too.


q: I need to add a web part zone to a wiki page. I'm opening the page using SharePoint Designer, but there doesn't seem to be an obvious way (such as a menu) to add a Web Part Zone.

[A]
from:
http://office.microsoft.com/en-us/sharepointdesigner/HA101513941033.aspx
Insert a Web Part zone
In Office SharePoint Designer 2007, open the page where you want to
  insert the Web Part zone.
If the Web Parts task pane is not already open, open it by clicking
  Web Parts on the Task Panes menu.
In Design view, click the location on the page where you want to
  insert the Web Part zone.
At the bottom of the Web Parts task pane, click New Web Part Zone.
The new Web Part zone is inserted on the page.
  ...


q: If I create an HTTP java.net.URL and then call openConnection() on it, does it necessarily imply that an HTTP post is going to happen?  I know that openStream() implies a GET.  If so, how do you perform one of the other HTTP verbs without having to work with the raw socket layer?

[A]
No it does not. But if the protocol of the URL is HTTP, you'll get a
```
HttpURLConnection
```
as a return object. This class has a
```
setRequestMethod
```
method to specify which HTTP method you want to use.
If you want to do more sophisticated stuff you're probably better off using a library like
Jakarta HttpClient
.


q:
How can I calculate the value of PI using C#?

I was thinking it would be through a recursive function, if so, what would it look like and are there any math equations to back it up?

I'm not too fussy about performance, mainly how to go about it from a learning point of view.

[A]
Calculate like this:
```
```
x = 1 - 1/3 + 1/5 - 1/7 + 1/9  (... etc as far as possible.)
PI = x * 4
```
```
You have got Pi !!!
This is the simplest method I know of.
The value of PI slowly converges to the actual value of Pi (3.141592165......). If you iterate more times, the better.


q:
We are bringing a new project in house and whereas previously all our work was on SQL Server the new product uses an oracle back end.

Can anyone advise any crib sheets or such like that gives an SQL Server person like me a rundown of what the major differences are - Would like to be able to get up and running as soon as possible.

[A]
Watch out for the difference in the way the empty string is treated.
```
INSERT INTO atable (a_varchar_column) VALUES ('');
```
is the same as
```
```
INSERT INTO atable (a_varchar_column) VALUES (NULL);
```
```
I have no
```
sqlserver
```
experience, but I understand that it differentiates between the two


q: Does anyone have a regular expression for matching function calls in C programs ?

[A]
Since C isn't a
regular language
and C function calls can contain arbitrary argument expressions, I fear the answer to your question is “no.”


q: I'm currently implementing a raytracer. Since raytracing is extremely computation heavy and since I am going to be looking into CUDA programming anyway, I was wondering if anyone has any experience with combining the two. I can't really tell if the computational models match and I would like to know what to expect. I get the impression that it's not exactly a match made in heaven, but a decent speed increasy would be better than nothing.

[A]
It can certainly be done, has been done, and is a hot topic currently among the raytracing and Cuda gurus.  I'd start by perusing
http://www.nvidia.com/object/cuda_home.html
But it's basically a research problem.  People who are doing it well are getting peer-reviewed research papers out of it.  But
well
at this point still means that the best GPU/Cuda results are approximately competitive with best-of-class solutions on CPU/multi-core/SSE.  So I think that it's a little early to assume that using Cuda is going to accelerate a ray tracer.  The problem is that although ray tracing is "embarrassingly parallel" (as they say), it is not the kind of "fixed input and output size" problem that maps straightforwardly to GPUs -- you want trees, stacks, dynamic data structures, etc.  It can be done with Cuda/GPU, but it's tricky.
Your question wasn't clear about your experience level or the goals of your project.  If this is your first ray tracer and you're just trying to learn, I'd avoid Cuda -- it'll take you 10x longer to develop and you probably won't get good speed.  If you're a moderately experienced Cuda programmer and are looking for a challenging project and ray tracing is just a fun thing to learn, by all means, try to do it in Cuda.  If you're making a commercial app and you're looking to get a competitive speed edge -- well, it's probably a crap shoot at this point... you might get a performance edge, but at the expense of more difficult development and dependence on particular hardware.
Check back in a year, the answer may be different after another generation or two of GPU speed, Cuda compiler development, and research community experience.


q:
Does anyone know how to get IntelliSense to work reliably when working in C/C++ projects? It seems to work for about 1 in 10 files. Visual Studio 2005 seems to be a lot better than 2008.

Edit: Whilst not necessarily a solution, the work-around provided here:

How to get IntelliSense to reliably work in Visual Studio 2008

Is probably the best bet if I want a decent IntelliSense system.

[A]
Native C++ intellisense does not work reliably in any version of Visual Studio. I find there are two common problems:
1) Header file paths are not set-up correctly. When you find a type where intellisense is not working, use the IDE to click through each header file to find the one containing the type. (Right click on #include and select Open Document...). If this fails before you get to the file which declares the type then this is your problem. Make sure header file search paths are set-up correctly.
And,
2) The intellisense database is corrupt. This happens ALL The time. You need to close the solution, delete the .ncb file, and then reopen the solution. I posted the macro I use for this in answer to another question
here
.
The preprocessor can also confuse intellisense - so make sure any #defines during build are also available to intellisense. Other than that, I don't know what else can break it. I've not seen any particular issues with forward declarations.


q:
Maybe I just don't know .NET well enough yet, but I have yet to see a satisfactory way to implement this simple VB6 code easily in .NET (assume this code is on a form with N CommandButtons in array Command1() and N TextBoxes in array Text1()):

Private Sub Command1_Click(Index As Integer)

   Text1(Index).Text = Timer

End Sub

I know it's not very useful code, but it demonstrates the ease with which control arrays can be used in VB6.  What is the simplest equivalent in C# or VB.NET?

[A]
Make an array of controls.
```
```
TextBox[] textboxes = new TextBox[] {
    textBox1,
    textBox2,
    textBox3
};
```
```


q:
A friend of mine is now building a web application with J2EE and Struts, and it's going to be prepared to display pages in several languages.

I was told that the best way to support a multi-language site is to use a properties file where you store all the strings of your pages, something like:

welcome.english = "Welcome!"
welcome.spanish = "¡Bienvenido!"
...

This solution is ok, but what happens if your site displays news or something like that (a blog)? I mean, content that is not static, that is updated often... The people that keep the site have to write every new entry in each supported language, and store each version of the entry in the database. The application loads only the entries in the user's chosen language.

How do you design the database to support this kind of implementation?

Thanks.

[A]
They way I have designed the database before is to have an News-table containing basic info like NewsID (int), NewsPubDate (datetime), NewsAuthor (varchar/int) and then have a linked table NewsText that has these columns: NewsID(int), NewsText(text), NewsLanguageID(int). And at last you have a Language-table that has LanguageID(int) and LanguageName(varchar).
Then, when you want to show your users the news-page you do:
```
```
SELECT NewsText FROM News INNER JOIN NewsText ON News.NewsID = NewsText.NewsID
WHERE NewsText.NewsLanguageID = <<Session["UserLanguageID"]>>
```
```
That Session-bit is a local variable where you store the users language when they log in or enters the site for the first time.


q:
In my host, I currently have installed 2 wordpress applications, 1 phpBB forum and one MediaWiki.

Is there a way to merge the login so that all applications share the same credentials?

For instance, I want to register only in my phpBB and then I want to access all other applications with the given username and password.

Even if you don't know a unified way, what other login integration do you know of? Pros and cons of each?

[A]
I don't know how to share the session cookies, but you can easily share the same login.
i.e. People will need to log separately into both sites, but will be able to use the same username and password.
In the mediawiki file "LocalSettings.PHP", you can tell it to use a different (wordpress) database for authentication:
e.g.
```
```
require_once('includes/AuthPlugin.php');
require_once('extensions/AuthPress.php');

$wgAuth = new AuthPress();
$wgAuth->setAuthPressTablePrefix('evo_');
# Only include the following if you aren't using the same db as  MediaWiki
$wgAuth->setAuthPressDBServer ('localhost');
$wgAuth->setAuthPressDBName('yourWordPressDB');
$wgAuth->setAuthPressUser('mySQL user for same');
$wgAuth->setAuthPressPassword('The password');
```
```
See
http://bbpress.org/forums/topic/mediawiki-bbpress-and-wordpress-integration


q:
In Ruby, given an array in one of the following forms...

[apple, 1, banana, 2]
[[apple, 1], [banana, 2]]

...what is the best way to convert this into a hash in the form of...

{apple => 1, banana => 2}

[A]
Simply use
```
Hash[*array_variable.flatten]
```
For example:
```
```
a1 = ['apple', 1, 'banana', 2]
h1 = Hash[*a1.flatten(1)]
puts "h1: #{h1.inspect}"

a2 = [['apple', 1], ['banana', 2]]
h2 = Hash[*a2.flatten(1)]
puts "h2: #{h2.inspect}"
```
```
Using
```
Array#flatten(1)
```
limits the recursion so
```
Array
```
keys and values work as expected.


[A]
This works in Oracle:
```
```
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
          select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
```
```
The thing to remember here is to use the
```
from dual
```
statement.


q: When coding web services, how do you structure your return values?  How do you handle error conditions (expected ones and unexpected ones)?  If you are returning something simple like an int, do you just return it, or embed it in a more complex object?  Do all of the web methods within one service return an instance of a single class, or do you create a custom return value class for each method?

[A]
I like the Request/Response object pattern, where you encapsulate your arguments into a single [Operation]Request class, which has simple public properties on it.
Something like AddCustomerRequest, which would return AddCustomerResponse.
The response can include information on the success/failure of the operation, any messages that might be used by the UI, possibly the ID of the customer that was added, for example.
Another good pattern is to make these all derive from a simple IMessage interface, where your general end-point is something like Process(params IMessage[] messages)...  this way you can pass in multiple operations in the same web request.


q:
I have a set of base filenames, for each name 'f' there are exactly two files, 'f.in' and 'f.out'.  I want to write a batch file (in Windows XP) which goes through all the filenames, for each one it should:

Display the base name 'f'

Perform an action on 'f.in'

Perform another action on 'f.out'

I don't have any way to list the set of base filenames, other than to search for *.in (or *.out) for example.

[A]
Easiest way, as I see it, is to use a for loop that calls a second batch file for processing, passing that second file the base name.
According to the for /? help, basename can be extracted using the nifty ~n option. So, the base script would read:
```
```
for %%f in (*.in) do call process.cmd %%~nf
```
```
Then, in process.cmd, assume that %0 contains the base name and act accordingly. For example:
```
```
echo The file is %0
copy %0.in %0.out
ren %0.out monkeys_are_cool.txt
```
```
There might be a better  way to do this in one script, but I've always been a bit hazy on how to pull of multiple commands in a single for loop in a batch file.
EDIT: That's fantastic! I had somehow missed the page in the docs that showed that you could do multi-line blocks in a FOR loop. I am going to go have to go back and rewrite some batch files now...


q:
Is there a good way to debug errors in the Visual Studio Designer?

In our project we have tons of UserControls and many complex forms. For the complex ones, the Designer often throws various exceptions which doesn't help much, and I was wondering if there's some nice way to figure out what has gone wrong.

The language is C#, and we're using Visual Studio 2005.

[A]
Each one is different and they can sometimes be obscure. As a first step, I would do the following:
Use source control and save often. When a designer error occurs, get a list of all changes to the affected controls that have occurred recently and test each one until you find the culprit
Be sure to check out the initialization routines of the controls involved. Very often these errors will occur because of some error or bad dependency that is called through the default constructor for a control (an error that may only manifest itself in VS)


q:
What .NET namespace or class includes both Context.Handler and Server.Transfer?

I think one may include both and my hunt on MSDN returned null.

[A]
System.Web.
```
```
HttpContext.Current.Handler
HttpContext.Current.Request.Server.Transfer
```
```


q: What is the best way to go about upgrading TFS 2005 to 2008? Also, what about the Team Build scripts ("Build Types"), are those compatible with Team Build 2008 or do they need converted/migrated somehow?

[A]
On this post on
Upgrading TFS 2005 to 2008
I mentioned that the SharePoint upgrade to 3.0 was the main difficulty. I thought it was performed as part of the upgrade, but it in fact is a separate upgrade process. You should also install Team Explorer 2008 before installing Visual Studio 2008 Service Pack 1 on developer's machines. If you don't, you have to go back and reinstall the service pack. Also be sure to get the SP1 RTM version, which MS just release in the past week or so. If you have already installed the SP1Beta, then you have to download a special removal tool, run that, then install SP1 RTM. We did not have any custom build types, but we did use a custom build guidance package from Conchango - and it upgraded OK.


q:
I can create a menu item in the Windows Explorer context menu by adding keys in the registry to HKEY_CLASSES_ROOT\Folder\shell.

How can I create submenu items to the just created menu item?


q:
So, I've read that it is not a good idea to install VS2008 on my test server machine as it changes the run time environment too much.  I've never attempted remote debugging with Visual Studio before, so what is the "best" way to get line by line remote debugging of server side web app code.  I'd like to be able to set a breakpoint, attach, and start stepping line by line to verify code flow and, you know, debug and stuff :).

I'm sure most of the answers will pertain to ASP.NET code, and I'm interested in that, but my current code base is actually Classic ASP and ISAPI Extensions, so I care about that a little more.

Also, my test server is running in VMWare, I've noticed in the latest VMWare install it mentioning something about debugging support, but I'm unfamiliar with what that means...anyone using it, what does it do for you?

[A]
Visual Studio comes with a
remote debugger
that you can run as an exe on your server. It works best if you can run it as the same domain user as your copy of visual studio. You can then do an attach to process from the debugger on your machine to the IIS process on the server and debug as if it was running on your machine. You get more options for .Net debugging, but there's support for older platforms too.


q:
I installed TortoiseHg (Mercurial) in my Vista 64-bit and the context menu is not showing up when I right click a file or folder.
Is there any workaround for this problem?

[A]
According to the
TortoiseHg FAQ
the context menus will work in 64-bit Vista
if you start a 32-bit instance of explorer by creating a shortcut
with the following settings (as suggested in the answer above):
```
```
Target: %windir%\syswow64\explorer.exe /separate
Start In: %windir%\syswow64\
```
```