Question:
In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;?

I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.

Answer:
```
```
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
```
```
Return value:
1
:
```
READ_COMMITTED_SNAPSHOT
```
option is
ON
. Read operations under the
```
READ COMMITTED
```
isolation level are based on snapshot scans and do not acquire locks.
0
(default):
```
READ_COMMITTED_SNAPSHOT
```
option is
OFF
. Read operations under the
```
READ COMMITTED
```
isolation level use
Shared (S) locks
.


Question:
Have any well-documented or open source projects targeted iPhone, Blackberry, and Android ? Are there other platforms which are better-suited to such an endeavor ?
Note that I am particularly asking about client-side software, not web apps, though any information about the difficulties of using web apps across multiple mobile platforms is also interesting.

Answer:
The iPhone uses Objective C, the Blackberry Java SE with RIM functionality and Android another custom version of Java. I could possibly see how you could combine the latter two but there is no functionality (without jailbreaking) of running Java applications on an iPhone.
The best bet I've seen so far is something like
Qt
that will run on Windows CE, almost certainly shortly Symbian, some Java platforms and the three major desktop OSs.


Question:
Definition:

A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction

How to check if the given string is a palindrome?

This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.

Looking for solutions in any and all languages possible.

Answer:
```
```
boolean isPalindrome(String str1) {
  //first strip out punctuation and spaces
  String stripped = str1.replaceAll("[^a-zA-Z0-9]", "");
  return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString());
}
```
```
Java version


Question:
I need to design a small project for generating excel reports in .NET, which will be sent to users to use.

The excel reports will contain PivotTables.

I don't have much experience with them, but I can think of three implementation alternatives:

Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.

Generate a small access database and send it along with the excel file, connect to it.

Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.

What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?

Answer:
```
```
boolean isPalindrome(String str1) {
  //first strip out punctuation and spaces
  String stripped = str1.replaceAll("[^a-zA-Z0-9]", "");
  return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString());
}
```
```
Java version


Question:
Is there an existing solution to create a regular expressions dynamically out of a given date-time format pattern? The supported date-time format pattern does not matter (Joda DateTimeFormat, java.text.SimpleDateTimeFormat or others).

As a specific example, for a given date-time format like dd/MM/yyyy hh:mm, it should generate the corresponding regular expression to match the date-times within the specified formats.

Answer:
```
SimpleDateFormat
```
already does this with the
```
parse()
```
method.
If you need to parse multiple dates from a single string, start with a regex (even if it matches too leniently), and use
```
parse()
```
on all the potential matches found by the regex.


Question:
I am trying to code TDD style in PHP and one of my biggest stumbling blocks (other than lack of a decent IDE) is that I have to make my own hacked together IoC container just to inject all my mock objects properly.

Has anyone used an Ioc container in PHP?  All I've been able to find is PHP IOC on the ever-annoying phpclasses.org and it seems to have almost no documentation and not much of a following.

Answer:
I played with some DI Frameworks for PHP, but I haven't used one in production. Have some links:
http://www.stubbles.net/
which
I think is the oldest I tried
http://php.xjconf.net/
FLOW3
- I belive this one will
become a very nice framework (its
beta right now)
You mentioned you would use it for TDD - so maybe have a look at
Dependency Injection for Unit Tests in PHP


Question: How can I build a loop in JavaScript?

Answer:
A loop in JavaScript looks like this:
```
```
for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
```
```


Question:
How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?

i.e. something like:

If Typeof(foobar) = "CommandButton" Then ...

/EDIT: to clarify, I need to check on Dynamically Typed objects. An example:

Dim y As Object

Set y = CreateObject("SomeType")

Debug.Print( <The type name of> y)

Where the output would be "CommandButton"

Answer:
This should prove difficult, since in VB6 all objects are COM (
```
IDispatch
```
) things. Thus they are only an interface.
```
TypeOf(object) is class
```
probably only does a COM get_interface call (I forgot the exact method name, sorry).


Question: Does anyone have any experience with a tool that generates test strings from a BNF grammar that could then be fed into a unit test?

Answer:
I don't have an answer to the tool question, but I will say it is fairly easy in any text processing language (perl/python/etc) to randomly generate sentences from a BNF grammar, and slightly more verbose in a bigger language (Java/C/etc), but it shouldn't be too hard to roll your own.
The problem with this, of course, is that it can only generate strings in the grammar, and unless your grammar is very simple, the test space is infinitely large.


Question:
I've noticed that SQL Server 2005 x64 does not seem to lock pages into memory the same way SQL Server 2000 did.  In 2000 I could easily see from task manager that SQL had locked 8GB of ram with AWE.  I'm fairly certain I've got 2005 setup in an equivalent way.

Is this a normal x64 difference or am I forgetting a crucial setup option?

Answer:
SQL Server 2005 x64 certainly doesn't need, or use, AWE; AWE is only to allow it to use > 4GB on 32 bit systems.
You
can
use the old lock-pages-in-memory trick, but as this KB shows (
http://support.microsoft.com/kb/918483
): "Note For 64-bit editions of SQL Server 2005, only SQL Server 2005 Enterprise Edition can use the Lock pages in memory user right."


Question:
Since Graduating from a very small school in 2006 with a badly shaped & outdated program (I'm a foreigner & didn't know any better school at the time) I've come to realize that I missed a lot of basic concepts from a mathematical & software perspective that are mostly the foundations of other higher concepts.

I.e. I tried to listen/watch the open courseware from MIT on Introduction to Algorithms but quickly realized I was missing several mathematical concepts to better understand the course.

So what are the core mathematical concepts a good software engineer should know? And what are the possible books/sites you will recommend me?

Answer: Start with what we CS folks call "discrete math".  Calculus and linear algebra can come in quite handy too because they get your foot in the door to a lot of application domains.  Once you've mastered those three, go for probability theory.  Those 4 will get you to competency in 95% (I made that up) of application domains.


Question:
Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible?

If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)?

Answer:
```
```
tf diff /shelveset:shelveset /format:unified
```
```
Edit:
This writes to standard output.  You can pipe the output to a file.
For more options, see
Difference Command
.


Question:
How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?

An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.

Answer:
You can use Prototype's
```
addClassName
```
and
```
removeClassName
```
methods.
Create a CSS class "hilight" that you'll apply to the hilighted
```
<tr>
```
's.  Then run this code on page load:
```
```
var rows = $$('tbody tr');
for (var i = 0; i < rows.length; i++) {
    rows[i].onmouseover = function() { $(this).addClassName('hilight'); }
    rows[i].onmouseout = function() { $(this).removeClassName('hilight'); }
}
```
```


Question:
I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the application gets executed).

Is it possible?

Answer:
You could loop the groups like i did in this answer:
Determining members of local groups via C#
After reading some more, the easiest thing would be to use the
```
System.DirectoryServices.AccountManagement
```
namespace. Here is how it can be used:
http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx
Sample:
```
```
public static bool IsUserInGroup(string username, string groupname, ContextType type)
{
    PrincipalContext context = new PrincipalContext(type);

    UserPrincipal user = UserPrincipal.FindByIdentity(
        context,
        IdentityType.SamAccountName,
        username);
    GroupPrincipal group = GroupPrincipal.FindByIdentity(
        context, groupname);

    return user.IsMemberOf(group);
}
```
```


Question:
Wrote the following in PowersHell as a quick iTunes demonstration:

$iTunes = New-Object -ComObject iTunes.Application
$LibrarySource = $iTunes.LibrarySource
foreach ($PList in $LibrarySource.Playlists)
{
  write-host $PList.name
}

This works well and pulls back a list of playlist names.
However on trying to close iTunes a warning appears

One or more applications are using the iTunes scripting interface. Are you sure you want to quit?

Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?

Itunes 7.7.1, Windows XP

Answer:
Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to.  The script uses .Net methods to release the COM objects.  When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET.
```
```
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource)
    [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes)
```
```
I also run my scripts the majority of time from a shortcut, not from the powershell prompt.
Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running.  iTunes seems to keep track of that.  Running the script in a manner that exits it's process after running, eliminated the message.
One method of running your script from powershell, is to prefix your script with powershell.
```
```
powershell .\scriptname.ps1
```
```
The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt.


Question: So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact?

Answer:
I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace.  I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time an exception is thrown... so it's not like you are just jumping from one place in the code to another, there is a lot going on.
I don't think it's a problem as long as you are using exceptions for EXCEPTIONAL behavior (so not your typical, expected path through the program).


Question:
We have some input data that sometimes appears with &nbsp characters on the end.

The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.

Ltrim and Rtrim don't remove the characters, so we're forced to do something like:

UPDATE myTable
SET myColumn = replace(myColumn,char(160),'')
WHERE charindex(char(160),myColumn) > 0

This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?

Answer:
This page
has a sample of how you can remove non-alphanumeric chars:
```
```
-- Put something like this into a user function:
DECLARE @cString    VARCHAR(32)
DECLARE @nPos    INTEGER
SELECT  @cString = '90$%45623 *6%}~:@'
SELECT  @nPos = PATINDEX('%[^0-9]%', @cString)

WHILE @nPos > 0
BEGIN
SELECT @cString = STUFF(@cString, @nPos, 1, '')
SELECT  @nPos = PATINDEX('%[^0-9]%', @cString)
END

SELECT @cString
```
```


Question:
I'm thinking this might be a quick and easy way to lower the form spam on our site just a little bit. The idea being that (I have read) spammers aren't running with javascript enabled. (Or at least they are accessing your website without running javascript. I.e., they aren't browsing up to it in IE or FF.

I can use .asp or .aspx.

Answer:
The simplest way is to set a cookie via javascript and check for it on postback.However, if you're looking to minimize spam you should actually have the browser perform a simple task which requires javascript execution. See Phil Haack's "Invisibile Captcha Validator" control, which has since been included in his Subkismet library:
http://haacked.com/archive/2006/09/26/Lightweight_Invisible_CAPTCHA_Validator_Control.aspx


Question:
I have an application that reads a CSV file with piles of data rows.  I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors.  Each row translates into an object.  Is there an easy way to find out the size of that object programmatically?  Is there a reference that defines how large primitive types and object references are for a VM?

Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory.  Maybe that is a different question, but I'd still like to know.

Answer:
I doubt you want to do it programmatically unless you just want to do it once and store it for future use.  It's a costly thing to do.  There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.
One way you could do it is to serialize the thing to a File and look at the size of the file, like this:
```
```
Serializable myObject;
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser"));
oos.write (myObject);
oos.close ();
```
```
Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else.
Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean & byte = 1 byte, short & char = 2 bytes, etc.), working your way down the membership hierarchy.  But that's tedious and expensive and ends up doing the same thing the serialization strategy would do.


Question:
I've been doing c# for a long time, and have never come across an easy way to just new up a hash.

I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.

{ "whatever" => {i => 1}; "and then something else" => {j => 2}};

Answer:
If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.
This example is based on the
MSDN Example
```
```
var students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}
};
```
```


Question: I don't ever recall coming across anything for C that's as extensive as C++'s Boost library.

Answer: I've never seen anything. Really, C++ templates are the enabling technology for STL and much of boost, and C doesn't have them. I've seen many C-interface libraries for things like image processing, 3D graphics, networking, etc., but never a real general-purpose library like boost. You can find pieces though - threading libraries, string libraries, etc. - that are similar to sections of boost.


Question:
Can I return it as an object if I am doing a

Select OneItem from Table Where OtherItem = "blah"?

Is there a better way to do this?

I am building a constructor to return an object based on its name rather than its ID.

Answer:
```
query.UniqueResult<T>()
```
returns just one
T


Question:
I'm coming from the open source world, and interested in giving ASP.NET a spin. But I'm having a little trouble separating the tools from the platform itself in regards to the licensing. I've downloaded Visual Web Developer 2008 Express, but not sure how different this is from one of the full-featured Visual Studio licenses -- and whether or not my Express license will prevent me from using all the features of ASP.NET.

Is a Visual Studio license just an IDE, or does it include pieces of .NET not available to the Express license?  What about the other tools like IIS and SQL Server?

Thanks.

Answer:
All of .net is available in the .net SDK, so in theory you will not need Visual Studio at all.
Now, there are some things that Express will not do. For example, the Database Designer is not very comprehensive and adding different remote databases is not or only very hardly possible. Still, in code you can connect to everything.
There is also no Remote Debugger, no support for creating Setup Files (well, that does not apply to ASP.net anyway), no real Publish Web Site Feature (although that can be
added manually
as it's just a Frontend for a SDK tool), no integrated Unit testing (and Microsoft
loves to threaten people
who add it), etc.
For a full comparison, see here:
Visual Studio 2008 Editions
But as said: Functionality of .net is all in the SDK, Visual Studio is just making it a bit easier to work with.


Question: What does the , operator do in C?

Answer:
The expression:
```
```
(expression1,  expression2)
```
```
First
```
expression1
```
is evaluated, then
```
expression2
```
is evaluated, and the value of
```
expression2
```
is returned for the whole expression.


Question:
Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops?

(this question is specific, not about optimization in general, thanks)

Answer:
The fun thing about optimization is that speed gains are found in the unlikeliest of places.
It's also the reason you need a profiler, rather than guessing where the speed problems are.
I recommend starting with a profiler (
```
gperf
```
if you're using GCC) and just start poking around the results of running your application through some normal operations.


Question:
What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?

Thanks!

Answer:
Nettuts has a great introduction to web-developement for iPhone. You find it
here
This is the specific code you asked for (taken from that article):
```
```
<!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->

<!--
place iPhone code in here
-->

<!--#else -->

<!--
    place standard code to be used by non iphone browser.
-->
<!--#endif -->
```
```


Question: I'm on a little quest of merging the structure of two MySql databases. Is there a tool for this with the might of Red-Gate's SQL Compare? Are there any free alternatives?

Answer:
although i dont have any experience with it, i hear that navicat would be the tool to use:
https://www.navicat.com/en/products/navicat-for-mysql
also toad for mysql i hear isnt bad:
http://www.quest.com/toad-for-mysql/


Question:
A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:

Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate
    '' 10 words
    args.IsValid = args.Value.Split(" ").Length <= 10
End Sub

Does anyone have a more thorough/accurate method of getting a word count?

Answer:
You can use one of the builtin validators with a regex that counts the words.
I'm a little rusty with regex so go easy on me:
```
```
(\b.*\b){0,10}
```
```


Question:
I'm looking for some "Best Practices" for automating the deployment of Stored Procedures/Views/Functions/Table changes from source control. I'm using StarTeam & ANT so the labeling is taken care of; what I am looking for is how some of you have approached automating the pull of these objects from source - not necessarily StarTeam.

I'd like to end up with one script that can then be executed, checked in, and labeled.

I'm NOT asking for anyone to write that - just some ideas or approaches that have (or haven't) worked in the past.

I'm trying to clean up a mess and want to make sure I get this as close to "right" as I can.

We are storing the tables/views/functions etc. in individual files in StarTeam and our DB is SQL 2K5.

Answer:
I prefer to separate views, procedures, and triggers (objects that can be re-created at will) from tables.  For views, procedures, and triggers, just write a job that will check them out and re-create the latest.
For tables, I prefer to have a database version table with one row.  Use that table to determine what new updates have not been applied.  Then each update is applied and the version number is updated.  If an update fails, you have only that update to check and you can re-run know that the earlier updates will not happen again.


Question: What are the available libraries for creating pretty charts and graphs in a Python application?

Answer:
Have you looked into
ChartDirector for Python
?
I can't speak about this one, but I've used ChartDirector for PHP and it's pretty good.


Question: How are people unit testing code that uses Linq to SQL?

Answer:
Normally, you don't need to test the part of the code that uses LINQ to SQL but if you really want to, you can use the same data sets that you're querying against the server and turn them into in-memory objects and run the LINQ queries against that (which would use the Enumerable methods instead of Queryable).
Another option is to use Matt Warren's
mockable version of the DataContext
.
You can also get the SQL statements that LINQ to SQL uses by getting them via the debugger (from the IQueryable object), check those manually, and then include them in the automated tests.


Question:
There are many ASP.MVC blog post bits and pieces scattered over different web sites, as well as couple of resource questions here - ASP.NET Model-view-controller (MVC) - where do I start from? and MVC Learning Resources

I wonder if there was a one-stop tutorial posted yet on getting started with ASP.NET MVC?

Thank you!

Edit: I probably need to clarify - a one-stop tutorial that'd help to get started within and hour or two and learn more as I go... Reading books is a non starter for me personally - takes more time I can afford and starts with basics...

Answer:
http://www.asp.net/mvc
Whoops, submitted before I was done.  The ASP.NET MVC site has tons of videos/screencast on getting started with ASP.NET MVC.  Definitely watch the Scott Hanselman ones first.
Edit
The Rob Conery screencasts that
@David provided
are provided on the
ASP.NET MVC site
also, under videos.  That would constitute one spot to get those resources and also the ones the ASP.NET MVC team put out.
One note on any resource you use.  You could run into functionality that is no longer available in the framework due to it being in development.  If you use the resources provided that you already found along with the tutorials, you will find the replacements or how to get around it.


Question:
Let's say you have a variable in a makefile fragment like the following:

MY_LIST=a b c d

How do I then reverse the order of that list?  I need:

$(warning MY_LIST=${MY_LIST})

to show

MY_LIST=d c b a

Edit:  the real problem is that

ld -r some_object.o ${MY_LIST}

produces an a.out with undefined symbols because the items in MY_LIST are actually archives, but in the wrong order.  If the order of MY_LIST is reversed, it will link correctly (I think).  If you know a smarter way to get the link order right, clue me in.

Answer:
Doh!  I could have just used a shell script-let:
```
(for d in ${MY_LIST}; do echo $$d; done) | tac
```


Question: I know RIM has their own IDE (BlackBerry JDE) for building BlackBerry apps, but does anyone know how to configure IntelliJ IDEA to build/debug BlackBerry apps?

Answer:
Not really an answer, but more asking for clarification what is different for Blackberry dev versus other J2ME devices...
I see its a
MIDP J2ME
device, and so the standard
Intellij J2ME
support would seem to give most of what is needed.
I guess the emulator side of things might be different... but maybe you can call the jde emulator from IDEA...
Regards,
Chris


Question:
Here is the full error: SqlException: A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 1 - I/O Error detected in read/write operation)

I've started seeing this message intermittently for a few of the unit tests in my application (there are over 1100 unit & system tests).  I'm using the test runner in ReSharper 4.1.

One other thing: my development machine is a VMWare virtual machine.

Answer:
I ran into this many moons ago.  Bottom line is you are running out of available ports.
First make sure your calling application has connection pooling on.
If that does then check the number of available ports for the SQL Server.
What is happening is that if pooling is off then every call takes a port and it takes by default 4 minutes to have the port expire, and you are running out of ports.
If pooling is on then you need to profile all the ports of SQL Server and make sure you have enough and expand them if necessary.
When I came across this error, connection pooling was off and it caused this issue whenever a decent load was put on the website.  We did not see it in development because the load was 2 or 3 people at max, but once the number grew over 10 we kept seeing this error.  We turned pooling on, and it fixed it.


Question:
Is there a good way to see what format an image is, without having to read the entire file into memory?

Obviously this would vary from format to format (I'm particularly interested in TIFF files) but what sort of procedure would be useful to determine what kind of image format a file is without having to read through the entire file?

BONUS: What if the image is a Base64-encoded string? Any reliable way to infer it before decoding it?

Answer:
Most image file formats have unique bytes at the start. The unix
```
file
```
command looks at the start of the file to see what type of data it contains. See the Wikipedia article on
Magic numbers in files
and
magicdb.org
.


Question: What is best practice when creating your exception classes in a .NET solution: To derive from System.Exception or from System.ApplicationException?

Answer:
```
ApplicationException
```
considered useless
is a strong, and critical, argument against
```
ApplicationException
```
.
Upshot: don't use it. Derive from
```
Exception
```
.


Question:
I am using Windows, and I have two monitors.

Some applications will always start on my primary monitor, no matter where they were when I closed them.

Others will always start on the secondary monitor, no matter where they were when I closed them.

Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?

@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS.  But as you said, it doesn't let you control the default monitor a program launches into.

Answer:
I'm fairly sure the primary monitor is the default.  If the app was coded decently, when it's closed, it'll remember where it was last at and will reopen there, but -- as you've noticed -- it isn't a default behavior.
EDIT: The way I usually do it is to have the location stored in the app's settings.  On load, if there is no value for them, it defaults to the center of the screen.  On closing of the form, it records its position.  That way, whenever it opens, it's where it was last.  I don't know of a simple way to tell it to launch onto the second monitor the first time automatically, however.
-- Kevin Fairchild


Question:
Does any one know how the event handler manages the posted events?

In my app i have two threads (guiThread and computationThread). After an exception is thrown I call postEvent(..) to an existing dialog. The Qt-Event-Handler holds this one back until the dialog is closed.

Sorry my question is a bit cloudy. I will write it more exactly, if I have time left. I found a work around. But for me the problem is still interesting.

Answer:
As mentionned in the Qt documentation about
QCoreApplication::postEvent
:
When control returns to the main event loop, all events that are stored in the queue will be sent using the notify() function.
...which explains why the Qt Event Handler holds the event until the dialog is closed.
If I understand correctly what you want to do, I would try using
sendEvent
.


Question:
I think this is specific to IE 6.0 but...

In JavaScript I add a div to the DOM. I assign an id attribute. When I later try to pick up the div by the id all I get is null.

Any suggestions?

Example:

var newDiv = document.createElement("DIV");
newDiv.setAttribute("ID", "obj_1000");
document.appendChild(newDiv);

alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") );

Alert prints "::null"

Seems to work fine in Firefox 2.0+

Answer:
You have to add the div to the dom.
```
```
// Create the Div
var oDiv = document.createElement('div');
document.body.appendChild(oDiv);
```
```


Question:
How do I create a branch in subversion that is deeper' than just the 'branches' directory?

I have the standard trunk, tags and branches structure and I want to create a branch that is several directories deeper than the 'branches' tag.

Using the standard svn move method, it gives me a folder not found error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.

What do I need to do to create this?

For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version_1/project/subproject' (which does not exist yet)?

Answer:
```
```
svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject
```
```
That should create the directory you want to put the subproject in (
```
--parents
```
means "create the intermediate directories for me").


Question:
As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.

An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.

Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (Model->find(), etc.), but I'm not sanguine about this.

Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work...

Answer:
Shouldn't be too bad, you just need a group by (this is off the type of my head, so forgive syntax errors):
```
```
SELECT entry-id, count(id) AS c
FROM comment
WHERE comment.createdate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
GROUP BY entry-id
ORDER BY c DESC
```
```


Question:
var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();

Answer:
Well - I don't know if your initial code block would work, but I'm guessing you have to mark your new e2 as insert on submit. Thus:
```
```
var e1 = new E1();
var e2 = new e2();
e1.e2s.Add(e2); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.insertonsubmit(e1);
context.e2s.insertonsubmit(e2);
context.submitchanges();
```
```


Question: How can you import a foxpro DBF file in SQL Server?

Answer:
Use a linked server or use openrowset, example
```
```
SELECT * into SomeTable
FROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;
SourceDB=\\SomeServer\SomePath\;
SourceType=DBF',
'SELECT * FROM SomeDBF')
```
```


Question:
System.IO.Directory.GetFiles() returns a string[].  What is the default sort order for the returned values?  I'm assuming by name, but if so how much does the current culture effect it?  Can you change it to something like creation date?

Update: MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time.  That information is lost once you have the array (it contains only strings).  I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this.  Seems very inefficient.

Answer:
```
```
Dim Files() As String
Files = System.IO.Directory.GetFiles("C:\")
Array.Sort(Files)
```
```


Question:
I'm looking for a graph algorithm with some unusual properties.

Each edge in the graph is either an "up" edge or a "down" edge.

A valid path can go an indefinite number of "up"'s followed by an indefinite number of "down"'s, or vice versa. However it cannot change direction more than once.

E.g., a valid path might be A "up" B "up" C "down" E "down" F
an invalid path might be A "up" B "down" C "up" D

What is a good algorithm for finding the shortest valid path between two nodes? What about finding all of the equal length shortest paths?

Answer:
Assuming you don't have any heuristics, a variation of
dijkstra's algorithm
should suffice pretty well. Every time you consider a new edge, store information about its "ancestors". Then, check for the invariant (only one direction change), and backtrack if it is violated.
The ancestors here are all the edges that were traversed to get to the current node, along the shortest path. One good way to store the ancestor information would be as a pair of numbers. If U is up, and D is down, a particular edge's ancestors could be
```
UUUDDDD
```
, which would be the pair
```
3, 4
```
. You will not need a third number, because of the invariant.
Since we have used dijkstra's algorithm, finding multiple shortest paths is already taken care of.


Question:
I frequently find myself writing code like this:

List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
    Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();

Better would be something like this:

List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);

I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block?

Answer:
Do this:
```
```
list.ForEach(i => Console.Write("{0}\t", i));
```
```
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)


Question:
I was wondering if anyone could point to an Open Source date utility class that is fairly robust. I find myself rolling my own when I want to do a lot of things I take for granted in C# and Java. For instance I did find a decent example of a DateDiff() function that I tore apart and another DatePart() function. Another examples would be parsing different date/time formats. I'm trying to avoid reinventing something if it's already built.

Another possibility may be a nice set of Javascript files that I can convert to ActionScript 3. So far I've found DateJS but I want to get a good idea of what is out there.

Answer:
as3corelib
has the
DateUtil
class and it should be pretty reliable since it's written by some Adobe employees. I haven't encountered any problems with it.


Question:
I'm not too sure what is going on here, but sometimes a particular file in my repository will change the case of its name. e.g.,:

before: File.h

after: file.h

I don't really care why this is happening, but this causes git to think it is a new file, and then I have to go and change the file name back. Can you just make git ignore case changes?

[edit]
I suspect it is Visual Studio doing something weird with that particular file, because it seems to happen most often when I open and save it after changes. I don't have any way to fix bugs in VS however, but git should be a bit more capable I hope.

Answer:
Since version 1.5.6 there is an
```
ignorecase
```
option available in the
```
[core]
```
section of
```
.git/config
```
e.g. add
```
ignorecase = true
```
To change it for just one repo, from that folder run:
```
```
git config core.ignorecase true
```
```
To change it globally:
```
```
git config --global core.ignorecase true
```
```


Question: So I'm using an IDataReader to hydrate some business objects, but I don't know at runtime exactly what fields will be in the reader.  Any fields that aren't in the reader would be left null on the resulting object.  How do you test if a reader contains a specific field without just wrapping it in a try/catch?

Answer:
You can't just test reader["field"] for null or DBNull because a IndexOutOfRangeException is thrown if the column isn't in the reader.
The code I use in my mapping layer for creating domain objects and the stored procedures that use the mapping layer might have different column names is below; you could modify it to not throw an exception if the column isn't found and return default(t) or null.
I understand this isn't the most elegant or optimal solution (and really, if you can avoid it then you should), however, legacy stored procedures or Sql queries might warrant a work-around.
```
```
/// <summary>
    /// Grabs the value from a specific datareader for a list of column names.
    /// </summary>
    /// <typeparam name="T">Type of the value.</typeparam>
    /// <param name="reader">Reader to grab data off of.</param>
    /// <param name="columnNames">Column names that should be interrogated.</param>
    /// <returns>Value from the first correct column name or an exception if none of the columns exist.</returns>
    public static T GetColumnValue<T>(IDataReader reader, params string[] columnNames)
    {
        bool foundValue = false;
        T value = default(T);
        IndexOutOfRangeException lastException = null;

        foreach (string columnName in columnNames)
        {
            try
            {
                int ordinal = reader.GetOrdinal(columnName);
                value = (T)reader.GetValue(ordinal);
                foundValue = true;
            }
            catch (IndexOutOfRangeException ex)
            {
                lastException = ex;
            }
        }

        if (!foundValue)
        {
            string message = string.Format("Column(s) {0} could not be not found.",
                string.Join(", ", columnNames));

            throw new IndexOutOfRangeException(message, lastException);
        }

        return value;
    }
```
```


Question:
Right now my ant task looks like.

<javadoc sourcepath="${source}" destdir="${doc}">
    <link href="http://java.sun.com/j2se/1.5.0/docs/api/" />
</javadoc>

And I'm getting this warning:

javadoc: warning - Error fetching URL: http://java.sun.com/j2se/1.5.0/docs/api/package-list

How do I get the javadoc to properly link to the API?  I am behind a proxy.

Answer:
You probably need the
http.proxyHost and http.proxyPort system properties
set. For example,
```
ANT_OPTS="-Dhttp.proxyHost=proxy.y.com" ant doc
```
Alternatively, you could set the "offline" flag and provide a package list, but that could be a pain for the Java core.


Question: What is the best way to sort the results of a sql query into a random order within a stored procedure?

Answer:
```
```
select foo from Bar order by newid()
```
```


Question:
I have a team lead who seems to think that business logic is very subjective, to the point that if my stored procedure has a WHERE ID = @ID — he would call this “business logic”

What approach should I take to define “business logic” in a very objective way without offending my team lead?

Answer:
I really think you just need to agree on a clear definition of what you mean when you say "business logic".  If you need to be "politically sensitive", you could even craft the definition around your team lead's understanding, then come up with another term ("domain rules"?) that defines what you want to talk about.
Words and terms are relatively subjective -- of course, once you leave that company you will need to 're-learn' industry standards, so it's always better to stick with them if you can, but the main goal is to communicate clearly and get work done.


Question: How do I setup an Ant task to generate Emma code coverage reports?

Answer:
To answer questions about where the source and instrumented directories are (these can be switched to whatever your standard directory structure is):
```
```
<property file="build.properties" />
<property name="source" location="src/main/java" />
<property name="test.source" location="src/test/java" />
<property name="target.dir" location="target" />
<property name="target" location="${target.dir}/classes" />
<property name="test.target" location="${target.dir}/test-classes" />
<property name="instr.target" location="${target.dir}/instr-classes" />
```
```
Classpaths:
```
```
<path id="compile.classpath">
  <fileset dir="lib/main">
    <include name="*.jar" />
  </fileset>
</path>

<path id="test.compile.classpath">
  <path refid="compile.classpath" />
  <pathelement location="lib/test/junit-4.6.jar" />
  <pathelement location="${target}" />
</path>

<path id="junit.classpath">
  <path refid="test.compile.classpath" />
  <pathelement location="${test.target}" />
</path>
```
```
First you need to setup where Ant can find the Emma libraries:
```
```
<path id="emma.lib" >
    <pathelement location="${emma.dir}/emma.jar" />
    <pathelement location="${emma.dir}/emma_ant.jar" />
</path>
```
```
Then import the task:
```
```
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
```
```
Then instrument the code:
```
```
<target name="coverage.instrumentation">
    <mkdir dir="${instr.target}"/>
    <mkdir dir="${coverage}"/>
    <emma>
        <instr instrpath="${target}" destdir="${instr.target}" metadatafile="${coverage}/metadata.emma" mode="copy">
            <filter excludes="*Test*"/>
        </instr>
    </emma>
    <!-- Update the that will run the instrumented code -->
    <path id="test.classpath">
        <pathelement location="${instr.target}"/>
        <path refid="junit.classpath"/>
        <pathelement location="${emma.dir}/emma.jar"/>
    </path>
</target>
```
```
Then run a target with the proper VM arguments like:
```
```
<jvmarg value="-Demma.coverage.out.file=${coverage}/coverage.emma" />
<jvmarg value="-Demma.coverage.out.merge=true" />
```
```
Finally generate your report:
```
```
<target name="coverage.report" depends="coverage.instrumentation">
    <emma>
        <report sourcepath="${source}" depth="method">
            <fileset dir="${coverage}" >
                <include name="*.emma" />
            </fileset>
            <html outfile="${coverage}/coverage.html" />
        </report>
    </emma>
</target>
```
```


Question:
I have a file that I want to include in Python but the included file is fairly long and it'd be much neater to be able to split them into several files but then I have to use several include statements.

Is there some way to group together several files and include them all at once?

Answer:
Yes, take a look at the "6.4 Packages" section in
http://docs.python.org/tut/node8.html
:
Basically, you can place a bunch of files into a directory and add an __init__.py file to the directory.  If the directory is in your PYTHONPATH or sys.path, you can do "import directoryname" to import everything in the directory or "import directoryname.some_file_in_directory" to import a specific file that is in the directory.
The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as "string", from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.


Question:
Visual Studio Solution files contain two GUID's per project entry. I figure one of them is from the AssemblyInfo.cs

Does anyone know for sure where these come from, and what they are used for?

Answer:
According to MSDN
:
[The
```
Project
```
] statement contains the
  unique project GUID and the project
  type GUID. This information is used by
  the environment to find the project
  file or files belonging to the
  solution, and the VSPackage required
  for each project. The project GUID is
  passed to IVsProjectFactory to load
  the specific VSPackage related to the
  project, then the project is loaded by
  the VSPackage.


Question:
In python, there are some special variables and filenames that are surrounded by double-underscores.  For example, there is the

__file__

variable.  I am only able to get them to show up correctly inside of a code block.  What do I need to enter to get double underscores in regular text without having them interpreted as an emphasis?

Answer:
__file__
Put a backslash before the first underscore.
Like this:
```
```
\__file__
```
```


Question: We are currently looking to adopt some type of "standard" developer framework and have looked into using the Enterprise Library.  Would you recommend using these blocks as the foundation for software development, or should we do something home grown?

Answer:
Like all good answers to architecture and programming questions, the answer is "it depends".
It depends on how unique your data access and object design needs are.  It may also depend on how you plan on supporting your application in the long term.  Finally, it greatly depends on the skill level of your developers.
There isn't a one-size-fits-all answer to this question, but generally, if your main focus is on cranking out software that provides some business value, pick out an existing framework and run with it.  Don't spend your cycles building something that won't immediately drive business profits (i.e. increases revenues and/or decreases costs).
For example, one of my organization's projects is core to the operations of the company, needs to be developed and deployed as soon as possible, and will have a long life.  For these reasons, we picked CSLA with some help from Enterprise Library.  We could have picked other frameworks, but the important thing is that we picked a framework that seemed like it would fit well with our application and our developer skillset and we ran with it.
It gave us a good headstart and a community from which we can get support.  We immediately started with functionality that provided business value and were not banging our heads against the wall trying to build a framework.
We are also in the position where we can hire people in the future who have most likely had exposure to our framework, giving them a really good headstart.  This should reduce long-term support costs.
Are there things we don't use and overhead that we may not need?  Perhaps.  But, I'll trade that all day long for delivering business value in code early and often.


Question: I am writing a DDL script to drop a number of tables but need to identify all dependencies for those tables first. Those dependencies include foreign key constraints, stored procedures, views, etc. Preferably, I want to programmatically script out dropping those dependencies using the system tables/views before dropping the dependent table.

Answer:
You can use the sp_depends stored procedure to do this:
```
USE AdventureWorks
GO
EXEC sp_depends @objname = N'Sales.Customer' ;
```
http://msdn.microsoft.com/en-us/library/ms189487(SQL.90).aspx


Question: Can anyone point me to a good introduction to coding against the paypal API?

Answer:
I would suggest you start by downloading the SDK:
https://www.paypal.com/IntegrationCenter/ic_sdk-resource.html
The SDK includes the following:
Client libraries that call PayPal APIs
API documentation for SDK components
Sample code for Website Payments Pro and various administrative APIs
Testing console that can verify connectivity to PayPal and submit API calls
You may also want to take a look at
Encore Systems .NET* Class Library for PayPal SOAP API


Question: Does filling out HTML meta description/keyword tags matter for SEO?

Answer:
Google will use meta tags, but the description, to better summarize your site.  They won't help to increase your page rank.
See:
http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=79812
EDIT
: @Petr, are you sure that meta tags influence page rank?  I am pretty sure that they don't, but if you have some references, I'd love to learn more about this.  I have seen
this
, from the Official Google Webmaster Central Blog, which is what leads me to believe that they don't:
Even though we sometimes use the
  description meta tag for the snippets
  we show, we still don't use the
  description meta tag in our ranking.


Question:
From the Immediate Window in Visual Studio:

> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"

It seems that they should both be the same.

The old FileSystemObject.BuildPath() didn't work this way...

Answer:
Not knowing the actual details, my guess is that it makes an attempt to join like you might join relative URIs. For example:
```
```
urljoin('/some/abs/path', '../other') = '/some/abs/other'
```
```
This means that when you join a path with a preceding slash, you are actually joining one base to another, in which case the second gets precedence.


Question:
In trying to figure out this problem (which is still unsolved and I still have no clue what is going on), I am wondering if maybe an external reference to the table in question is causing the problem.  For example, a trigger or view or some other such thing.

Is there an easy way to find all references to a given database table?  Including all views, triggers, constraints, or anything at all, preferably from the command line, and also preferably without a 3rd party tool (we are using db2).

Answer:
Wow, I wouldn't have thought it, but there seems to be.. Good ole DB2.
I find the publib db2 docs view very very handy by the way:
http://publib.boulder.ibm.com/infocenter/db2luw/v8//index.jsp
I just found the "SYSCAT.TABDEP" catalog view in it, which seems to contain more or less what you asked for. I suspect for anything not covered there you'll have to trawl through the rest of the syscat tables which are vast. (Unfortunately I can't seem to link you to the exact page on SYSCAT.TABDEP itself, the search facility should lead you to it fairly easily though).
Most databases these days have a set of tables which contain data about the layout of your actual schema tables, quite handy for this sort of thing.


Question: What do you use to capture webpages, diagram/pictures and code snippets for later reference?

Answer:
Evernote
http://www.evernote.com
and delicious
http://www.delicious.com


Question:
what I'm after is something I can feed a number into and it will return the highest order bit.  I'm sure there's a simple way.  Below is an example output (left is the input)

1 -> 1
2 -> 2
3 -> 2
4 -> 4
5 -> 4
6 -> 4
7 -> 4
8 -> 8
9 -> 8
...
63 -> 32

Answer:
Continually remove the low order bit comes to mind...
```
```
int highest_order_bit( int x )
{
    int y = x;
    do {
        x = y;
        y = x & (x-1); //remove low order bit
    }
    while( y != 0 );
    return x;
}
```
```


Question:
Given:

e = 'a' + 'b' + 'c' + 'd'

How do I write the above in two lines?

e = 'a' + 'b' +
    'c' + 'd'

Answer:
Put a
```
\
```
at the end of your line or enclose the statement in parens
```
( .. )
```
. From
IBM
:
```
```
b = ((i1 < 20) and
     (i2 < 30) and
     (i3 < 40))
```
```
or
```
```
b = (i1 < 20) and \
    (i2 < 30) and \
    (i3 < 40)
```
```


Question:
I have two elements:

<input a>
<input b onclick="...">

When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so document.getElementsByName is out. Looking into the event object, I thought event.target.parentNode would have some function like getElementsByName, but this does not seem to be the case with <td>s. Is there any simple way to do this?

Answer:
If
```
a
```
and
```
b
```
are next to each other and have the same parent, you can use the
```
prevSibling
```
property of
```
b
```
to find
```
a
```
.


Question: I'm trying to use the Optiflag package in my Ruby code and whenever I try to do the necessary require optiflag.rb, my program fails with the standard no such file to load -- optiflag message. I added the directory with that library to my $PATH variable, but it's still not working. Any ideas?

Answer:
is it a gem? Are you doing
```
```
require 'rubygems'
require 'optiflag'
```
```
or equivalent?


Question:
I'm trying to use some data from a PlanPlusOnline account.  They only provide a java web services API.  The server for the site where the data will be used does not allow me to install Tomcat (edit: or a JVM for that matter).  I'm not going to lie, I am a Java software engineer, and I do some web work on the side.  I'm not familiar with web services or servlets, but I was willing to give it a shot.  I'd much rather they have JSON access to the data, but as far as I know they don't.  Any ideas?

EDIT: to clarify.   The web service provided by planplusonline is Java based.  I am trying to access the data from this web service without using Java.  I believe this is possible now, but I need to do more research.  Anyone who can help point me in the right direction is appreciated.

Answer:
Are you trying to implement a client to a web service hosted somewhere else?  If so, Java's not necessary.  You can do web service clients in
.NET
,
PHP
,
Ruby
, or pretty much any modern web technology out there.  All you need is a WSDL document to provide metadata about how to invoke the services.


Question: I come from a world that favors building your own rather than rely on libraries and frameworks built by others. After escaping this world I have found the joy, and ease, of using such tools as Typed DataSets within Visual Studio. So besides the loss of flexibility what else do you lose? Are there performance factors (disregarding the procs vs dynamic sql debate)? Limitations?

Answer:
Performance is improved with typed datasets over untyped datasets (though I've never found  performance issues with trivial things like that worth worrying about).
I'd say the biggest pain is just keeping them in sync with your database--I can't speak for VS 2008 but prior versions do not provide good support for this. I literally drag the procs onto the designer everytime the resultset's schema changes. Not fun.
But, you do get compile time type checking which is great and things like Customer.Name instead of Dataset.Tables(0).Rows(0)("Name").
So, if your schema is relatively static, they may be worth it, but otherwise, I wouldn't bother.
You could also look into a real ORM.


Question:
Does anyone have examples of how to use DBMS_APPLICATION_INFO package with JBOSS?

We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the database using DBMS_APPLICATION_INFO so I can more easily track which sections of the application is causing database issues.

I'm not too familiar with session life cycles in JBOSS, but at the end of the day, what needs to happen is at the start and end of a transaction, this package needs to be called.

Has anyone done this before?

Answer:
yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
```
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
```
Change it to:
```
public class LoggingConnectionPool extends ConnectionPool{
    public OracleConnection getConnection(String datasourceName, String module, String action){
        OracleConnection conn=getConnection(datasourceName);
        CallableStatement call=conn.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
        try{
            call.setString(1,module);
            call.setString(2,action);
            call.execute();
        finally{
            call.close();
        }
        return new WrappedOracleConnection(conn);
    }
```
Note the use of WrappedOracleConnection above. You need this because you need to trap the close call
```
public class WrappedOracleConnection extends OracleConnection{
    public void close(){
        CallableStatement call=this.preparedCall("begin dbms_application_info.setModule(module_name => ?, action_name => ?); end;");
        try{
            call.setNull(1,Types.VARCHAR);
            call.setNull(2,Types.VARCHAR);
            call.execute();
        finally{
            call.close();
        }
    }

    // and you need to implement every other method
    //for example
    public CallableStatement prepareCall(String command){
        return super.prepareCall(command);
    }
    ...
}
```
Hope this helps, I do something similar on a development server to catch connections that are not closed (not returned to the pool).


Question: An OleDB provider is a binary implementing COM interfaces provided by Microsoft. From that it seems to be possible to create a provider using C#. Is that correct? Is there a sample demonstrating that? If not, would you discourage me from doing that? I see that there are multiple unmanaged samples but I can't find any managed.

Answer:
I am not sure I really understand your question?! There already
is
a managed OleDBProvider?!
```
```
using System.Data.OleDb;
```
```
I would certainly discourage writing a provider that exists and works absolutely fine! :)
But in answer to your first question, you can of course create your own. The
Data Provider Roadmap
may be a good place to start for an overview and links  to samples etc.


Question:
If starting a new project what would you use for your ORM NHibernate or LINQ and why.  What are the pros and cons of each.

edit: LINQ to SQL not just LINQ (thanks @Jon Limjap)

Answer:
Errr... there's
LINQ for NHibernate
.
Perhaps what you mean is which to use:
LINQ to SQL
NHibernate
I prefer NHibernate.
LINQ to SQL is fairly lightweight, but it's a little bit more tightly coupled to your data structure, as opposed to NHibernate which is pretty flexible in terms of the types of object definitions that can be mapped to your table structures.
Of course that's not to say that LINQ to SQL has no uses: this very website uses it. I believe that it's quite useful to get up and running in small applications where the database schema is not as massive.


Question:
I want to wrap a piece of code that uses the Windows Impersonation API into a neat little helper class, and as usual, I'm looking for a way to go test-first. However, while WindowsIdentity is a managed class, the LogonUser call that is required to actually perform the logging in as another user is an unmanaged function in advapi32.dll.

I think I can work around this by introducing an interface for my helper class to use and hiding the P/Invoke calls in an implementation, but testing that implementation will still be a problem. And you can imagine actually performing the impersonation in the test can be a bit problematic, given that the user would actually need to exist on the system.

Answer:
Guideline: Don't test code that you haven't written.
You shouldn't be concerned with WinAPI implementation not working (most probably it works as expected).
Your concern should be testing the 'Wiring' i.e. if your code makes the right WinAPI call. In which case, all you need is to mock out the interface and let the mock framework tell if you the call was made with the right params. If yes, you're done.
Create IWinAPIFacade (with relevant WinAPI methods) and implementation CWinAPIFacade.
Write a test which plugs in a mock of IWinAPIFacade and verify that the appropriate call is made
Write a test to ensure that CWinAPIFacade is created and plugged in as a default (in normal functioning)
Implement CWinAPIFacade which simply blind-delegates to Platform Invoke calls - no need to auto-test this layer. Just do a manual verification. Hopefully this won't change that often and nothing breaks. If you find that it
does
in the future, barricade it with some tests.


Question:
I have IIS 5.1 installed on Windows XP Pro SP2. Besides I have installed VS 2008 Express with .NET 3.5. So obviously IIS is configured for ASP.NET automatically for .NET 3.5

The problem is whenever I access http://localhost IE & Firefox both presents authentication box. Even if I enter Administrator user and its password, the authentication fails. I have already checked the anonymous user access (with IUSR_ user and password is controlled by IIS) in Directory Security options of default website.

However other deployed web apps work fine (does not ask for any authentication).

In IE this authentication process stops if I add http://localhost in Intranet sites option.

Please note that the file system is FAT32 when IIS is installed.

Regards,
Jatan

Answer:
It could be because of couple of Browser settings. Try with these options checked..
Tools > Internet Options > Advanced > Enable Integrated Windows Authentication (works with Integrated Windows Authentication set on IIS)
Tools > Internet Options> Security > Local Intranet > Custom Level > Automatic Logon
Worst case, try adding localhost to the Trusted sites.
If you are in a network, you can also try debugging by getting a network trace. Could be because of some proxy trying to authenticate.


Question:
I have some Ruby code which takes dates on the command line in the format:

-d 20080101,20080201..20080229,20080301

I want to run for all dates between 20080201 and 20080229 inclusive and the other dates present in the list.

I can get the string 20080201..20080229, so is the best way to convert this to a Range instance? Currently, I am using eval, but it feels like there should be a better way.

@Purfideas I was kind of looking for a more general answer for converting any string of type int..int to a Range I guess.

Answer:
assuming you want the range to iterate properly through months etc, try
```
```
require 'date'

ends = '20080201..20080229'.split('..').map{|d| Date.parse(d)}
(ends[0]..ends[1]).each do |d|
  p d.day
end
```
```


Question:
I am trying to apply styles to HTML tags dynamically by reading in the value of certain HTML attributes and applying a class name based on their values. For instance, if I have:

<p height="30">

I want to apply a class="h30" to that paragraph so that I can style it in my style sheet. I can't find any information on getting the value of an attribute that is not an id or class. Help?

Answer:
Attributes are just properties (usually). So just try:
```
```
for (e in ...) {
    if (e.height == 30) {
        e.className = "h30";
    }
}
```
```
Or use something like jquery to simplify this kind of stuff.


Question: I have long since forgotten the password for the root user on one of my boxes. Is there a way I can change it without having to log in to the instance, or will I have to reinstall?

Answer:
A quick Google resulted in this answer. In the root shell type:
```
```
mysqladmin -u root password <password>
```
```


Question:
How do I enable external access to MySQL Server? I can connect locally but I cannot connect from another box on the network.

I just tried

grant all privileges on *.* to root@'%' identified by '*****' with grant option;

And restarted MySQL Server with no success.

Answer:
You probably have to edit the configuration file (usually my.cnf) to listen in the external interface instead of on localhost only.
Change the
```
bind-address
```
parameter to your machine's IP address.
If this is an old MySQL installation, you should comment out the skip-networking parameter.
Afterwards, restart MySQL and you'll be set


Question: I am developing console application in .Net and I want to change a behavior a little based on information that application was started from cmd.exe or from explorer.exe. Is it possible?

Answer:
The
CreateToolhelp32Snapshot Function
has a Process32First method that will allow you to read a
PROCESSENTRY32 Structure
. The structure has a property that will get you the information you want:
th32ParentProcessID
- The identifier
  of the process that created this
  process (its parent process).
This article will help you get started using the ToolHelpSnapshot function:
http://www.codeproject.com/KB/cs/IsApplicationRunning.aspx


Question: If I use restful_authentication in my ruby on rails app are passwords transfered between the broswer and the server in paintext? And if so how worried should I be about it?

Answer:
Well, you need to be worried if you are not hosting it over HTTPS... because if it is straight HTTP, then yes it is being passed in plaintext.
I don't know Rails specifically, but I'm pretty sure it has nothing to do with whether you host it via HTTP or HTTPS.
Edit: I found
this link
which apparently provides an example Rails app over HTTPS.
Further Edit: Here is
another link
discussing HTTPS with Rails.


Question:
For example, if passed the following:

a = []

How do I check to see if a is empty?

Answer:
```
```
if not a:
    print("List is empty")
```
```
Using the
implicit booleanness
of the empty
```
list
```
is quite Pythonic.


Question: What are some of the ways? What frameworks can you use?

Answer:
Well, I presume you mean unit testing your code that hits the database, in which case, there is
NDbUnit
, which appears to be a DbUnit clone for .NET.  I've never used it, but I have used DbUnit, and it is quite useful.
Edit: I assumed you were using .NET because you mentioned MSSQL.  If however you are actually using Java, there is
DbUnit
.


Question:
I have a bunch of servlets running under the Tomcat servlet container. I would like to separate test code from production code, so I considered using a test framework.
JUnit is nicely integrated into Eclipse, but I failed to make it run servlets using a running Tomcat server. Could you please recommend a unit testing framework that supports testing Tomcat servlets? Eclipse integration is nice but not necessary.

Answer:
Okay.  Ignoring the 'tomcat' bit and coding to the servlet, your best bet is to create mocks for the response and request objects, and then tell it what you expect out of it.
So for a standard empty doPost, and using
EasyMock
, you'll have
```
```
public void testPost() {
   mockRequest = createMock(HttpServletRequest.class);
   mockResponse = createMock(HttpServletResponse.class);
   replay(mockRequest, mockResponse);
   myServlet.doPost(mockRequest, mockResponse);
   verify(mockRequest, mockResponse);
}
```
```
Then start adding code to the doPost.  The mocks will fail because they have no expectations, and then you can set up the expectations from there.
Note that if you want to use EasyMock with classes, you'll have to use the EasyMock class extension library.  But it'll work the same way from then on.


Question:
Is it possible to order results in SQL Server 2005 by the relevance of a freetext match? In MySQL you can use the (roughly equivalent) MATCH function in the ORDER BY section, but I haven't found any equivalence in SQL Server.

From the MySQL docs:

For each row in the table, MATCH() returns a relevance value; that is, a similarity measure between the search string and the text in that row in the columns named in the MATCH() list.

So for example you could order by the number of votes, then this relevance, and finally by a creation date. Is this something that can be done, or am I stuck with just returning the matching values and not having this ordering ability?

Answer:
If you are using
```
FREETEXTTABLE
```
then it returns a column name
```
Rank
```
, so
```
order by Rank
```
should work. I don't know if other freetext search methods are also returning this value or not. You can have a try.


Question: Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation?

Answer:
If you
do
find you need to write unique code for an environment, use pythons
```
```
import mymodule_jython as mymodule

import mymodule_cpython as mymodule
```
```
have this stuff in a simple module (''module_importer''?) and write your code like this:
```
```
from module_importer import mymodule
```
```
This way, all you need to do is alter
```
module_importer.py
```
per platform.


Question: Ulimately I just wanted to extract strings from the .rc file so I could translate them, but anything that goes with .rc files works for me.

Answer:
Maybe this helps? (
http://social.msdn.microsoft.com/forums/en-US/regexp/thread/5e87fce9-ec73-42eb-b2eb-c821e95e0d31/
)
They are using the following regex to find the stringtable in the rc source:
(?<=\bSTRINGTABLE\s+BEGIN\s+).*?(?=\s+END\b)
Edit - And you can read the key values pairs with the following statement with the MultiLine option:
@"\s+(.*?)\s+""(.*)""";


Question:
I've started using Vim to develop Perl scripts and am starting to find it very powerful.

One thing I like is to be able to open multiple files at once with:

vi main.pl maintenance.pl

and then hop between them with:

:n
:prev

and see which file are open with:

:args

And to add a file, I can say:

:n test.pl

which I expect would then be added to my list of files, but instead it wipes out my current file list and when I type :args I only have test.pl open.

So how can I add and remove files in my args list?

Answer:
Vim (but not the original Vi!) has tabs which I find (in many contexts) superior to buffers. You can say
```
:tabe [filename]
```
to open a file in a new tab. Cycling between tabs is done by clicking on the tab or by the key combinations [
n
]
```
gt
```
and
```
gT
```
. Graphical Vim even has graphical tabs.


Question:
When trying to connect to an ORACLE user via TOAD (Quest Software) or any other means (Oracle Enterprise Manager) I get this error:

ORA-011033: ORACLE initialization or shutdown in progress

Answer:
After some googling, I found the advice to do the following, and it worked:
```
```
SQL> startup mount

ORACLE Instance started

SQL> recover database

Media recovery complete

SQL> alter database open;

Database altered
```
```


Question:
I am not concerned about other kinds of attacks. Just want to know whether HTML Encode can prevent all kinds of XSS attacks.

Is there some way to do an XSS attack even if HTML Encode is used?

Answer:
I don't believe so. Html Encode converts all functional characters (characters which could be interpreted by the browser as code) in to entity references which cannot be parsed by the browser and thus, cannot be executed.
```
```
<script/>
```
```
There is no way that the above can be executed by the browser.
**Unless their is a bug in the browser ofcourse.*


Question:
I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well

This:

\#\#

prints:

\#\#

I would like:

##

Answer:
Maybe, the following site helps?
http://velocity.apache.org/tools/1.4/generic/EscapeTool.html


Question:
What was the motivation for having the reintroduce keyword in Delphi?

If you have a child class that contains a function with the same name as a virtual function in the parent class and it is not declared with the override modifier then it is a compile error. Adding the reintroduce modifier in such situations fixes the error, but I have never grasped the reasoning for the compile error.

Answer:
When the ancestor class also has a method with the same name, and it is not necessarily declared virtual, you would see a compiler warning (as you would hide this method).
In other words: You tell the compiler that you know that you hide the ancestor function and replace it with this new function and do so deliberately.
And why would you do this? If the method is virtual in the parent class, the only reason is to prevent polymorphism. Other then that just override and do not call inherited. But if the parent method is not declared virtual (and you cannot change that, because you do not own the code for example), you can inherit from that class and let people inherit from your class without seeing a compiler warning.


Question:
Java has a convenient split method:

String str = "The quick brown fox";
String[] results = str.split(" ");

Is there an easy way to do this in C++?

Answer:
Here is a sample tokenizer class that might do what you want
```
```
//Header file
class Tokenizer
{
    public:
        static const std::string DELIMITERS;
        Tokenizer(const std::string& str);
        Tokenizer(const std::string& str, const std::string& delimiters);
        bool NextToken();
        bool NextToken(const std::string& delimiters);
        const std::string GetToken() const;
        void Reset();
    protected:
        size_t m_offset;
        const std::string m_string;
        std::string m_token;
        std::string m_delimiters;
};

//CPP file
const std::string Tokenizer::DELIMITERS(" \t\n\r");

Tokenizer::Tokenizer(const std::string& s) :
    m_string(s),
    m_offset(0),
    m_delimiters(DELIMITERS) {}

Tokenizer::Tokenizer(const std::string& s, const std::string& delimiters) :
    m_string(s),
    m_offset(0),
    m_delimiters(delimiters) {}

bool Tokenizer::NextToken()
{
    return NextToken(m_delimiters);
}

bool Tokenizer::NextToken(const std::string& delimiters)
{
    size_t i = m_string.find_first_not_of(delimiters, m_offset);
    if (std::string::npos == i)
    {
        m_offset = m_string.length();
        return false;
    }

    size_t j = m_string.find_first_of(delimiters, i);
    if (std::string::npos == j)
    {
        m_token = m_string.substr(i);
        m_offset = m_string.length();
        return true;
    }

    m_token = m_string.substr(i, j - i);
    m_offset = j;
    return true;
}
```
```
Example:
```
```
std::vector <std::string> v;
Tokenizer s("split this string", " ");
while (s.NextToken())
{
    v.push_back(s.GetToken());
}
```
```


Question:
Can a Linq query retrieve BLOBs from a Sql Database?

And how do they come out?

Answer:
If I'm not mistaken LINQ to SQL teats BLOB as System.Byte[]
I recall that there was some problem with SqlMetal, it generated wrong type for BLOB, but MSVS dmbl designer should work.


Question:
Programming in vim I often go search for something, yank it, then go back to where I was, insert it, modify it.

The problem is that after I search and find, I need to MANUALLY find my way back to where I was.

Is there an automatic way to go back to where I was when I initiated my last search?

Answer:
I've always done by it setting a mark.
In command-mode, press
m
[letter]
.  For example,
m
a
sets a mark at the current line using
a
as the mark identifier.
To get back to the mark press
'
[letter]
.  For example,
'
a
takes you back to the line mark set in step 1.  To get back to the column position of the row where you marked the line, use
`
a
(
back-tick
[letter]
).
To see all of the marks that currently set, type
```
:marks
```
.
On a slightly unrelated note, I just discovered another nifty thing about marks.
Let's say you jump to mark
b
by doing
m
b
.  Vim automatically sets the mark
'
(that's a single-quote) to be whichever line you were on before jumping to mark
b
.
That means you can do
'
b
to jump to that mark, then do
''
(2 single-quotes) to jump back to wherever you were before.
I discovered this accidentally using the
```
:marks
```
command, which shows a list of all marks.


Question: I'm trying to produce sheets of photographs with captions arranged in a grid using XSLT and XSL-FO. The photo URLs and captions are produced using a FOR XML query against an SQL Server database, and the number of photos returned varies from sheet to sheet. I want to lay the photos out in four columns, filling the grid from left to right and from top to bottom. In HTML I'd do this by putting each photo and caption into a div and using "float: left" to make them flow into the grid. Is there a similarly elegant method using XSL-FO?

Answer:
To keep life simple I would normally setup a table for this, it's quite simple and will ensure that things get laid out right. If you wanted to do it similarly to how you would do it in HTML then you should layout block-container elements.
However you decide to do it I would always recommend using the
ZVON Reference
site. Nice lookup of elements and available attributes, and while their XSL-FO doesn't include much in the way of explanation every page deep links to the standards document.


Question:
I'm running Visual Studio 2008 with the stuff-of-nightmares awful MS test framework.  Trouble is that it's sending my CPU to 100% (well 25% on a quad-core).

My question is why can't Visual Studio run on more than one core?  Surely M$ must have a sufficient handle on threading to get this to work.

Answer:
I have VS2008 running on all 4 CPUs. Just set this environment variable / project flag.
/MP
(It can be set in C/C++ Settings, Advanced. In project settings)
Edit: The MP flag can also accept a number, e.g. /MP2 which means it will only run on 2 cores. Leaving it as just /MP means it will run on the maximum amount of cores.
Edit2: The MP flag is probably for the compiler only.


Question:
Is there a way to convert a HTML string into a Image .tiff file?

I am using C# .NET 3.5. The requirement is to give the user an option to fact a confirmation. The confirmation is created with XML and a XSLT. Typically it is e-mailed.

Is there a way I can take the HTML string generated by the transformation HTML string and convert that to a .tiff or any image that can be faxed?

3rd party software is allowed, however the cheaper the better.

We are using a 3rd party fax library, that will only accept .tiff images, but if I can get the HTML to be any image I can covert it into a .tiff.

Answer:
A starting point might be the software of
WebSuperGoo
, which provide rich image editing products, cheap or for free.
I know for sure their PDF Writer can do basic HTML (
http://www.websupergoo.com/helppdf6net/source/3-concepts/b-htmlstyles.htm
). This should not be too hard to convert to TIFF.
This does not include the full HTML subset or CSS. That might require using Microsofts IE ActiveX component.


Question:
I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?

I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine?

Answer:
As Google Web Toolkit is a
subset of Java
it works best when you Java at the backend too.  Since Google App Engine is currently
Python only
I think you'd have to do a lot of messing about to get your server and client to talk nicely to each other.
jQuery seems to be the most popular JavaScript library option in the
AJAX Tag at DjangoSnippets.com
.
Edit:
The above is only true of Google App Engine applications written in Python.  As Google App Engine now supports Java, GWT could now be a good choice for writing an AJAX front end.
Google even have a tutorial showing you how to do it.


Question:
Migrating a project from ASP.NET 1.1 to ASP.NET 2.0 and I keep hitting this error.

I don't actually need Global because I am not adding anything to it, but after I remove it I get more errors.

Answer:
There are a few things you can try with this, seems to happen alot and the solution varies for everyone it seems.
If you are still using the IIS virtual directory make sure its pointed to the correct directory and also check the ASP.NET version it is set to, make sure it is set to ASP.NET 2.0.
Clear out your bin/debug/obj all of them. Do a
Clean solution
and then a
Build Solution
.
Check your project file in a text editor and make sure where its looking for the global file is correct, sometimes it doesnt change the directory.
Remove the global from the solution and add it back after saving and closing. make sure all the script tags in the ASPX file point to the correct one after.
You can try running the
Convert to Web Application
tool, that redoes all of the code and project files.
IIS Express is using the wrong root directory (see answer in
VS 2012 launching app based on wrong path
)
Make sure you close VS after you try them.
Those are some things I know to try. Hope one of them works for you.


Question:
how can i create an application to read all my browser (firefox) history?
i noticed that i have in

C:\Users\user.name\AppData\Local\Mozilla\Firefox\Profiles\646vwtnu.default

what looks like  a sqlite database (urlclassifier3.sqlite) but i don't know if its really what is used to store de history information.
i searched for examples on how to do this but didn't find anything.

ps: although the title is similar i believe this question is not the same as "How do you access browser history?"

Answer:
I believe
```
places.sqlite
```
is the one you should be looking into for history (Firefox 3). Below are a couple of Mozilla wiki entries that have some info on the subject.
Mozilla 2: Unified Storage
Browser History
(see especially section "Database Design" here)
In earlier versions of Firefox they stored history in a file called
```
history.dat
```
, which was encoded in a format called "Mork".
This perl script by Jamie Zawinski
can be used to parse Mork files.


Question:
I've been trying to figure out a regex to allow me to search for a particular string while automatically skipping comments.  Anyone have an RE like this or know of one?  It doesn't even need to be sophisticated enough to skip #if 0 blocks; I just want it to skip over // and /* blocks.  The converse, that is only search inside comment blocks, would be very useful too.

Environment: VS 2003

Answer:
This is a harder problem than it might at first appear, since you need to consider comment tokens inside strings, comment tokens that are themselves commented out etc.
I wrote a string and comment parser for C#, let me see if I can dig out something that will help... I'll update if I find anything.
EDIT:
... ok, so I found my old 'codemasker' project.  Turns out that I did this in stages, not with a single regex.  Basically I inch through a source file looking for start tokens, when I find one I then look for an end-token and mask everything in between.  This takes into account the context of the start token... if you find a token for "string start" then you can safely ignore comment tokens until you find the end of the string, and vice versa. Once the code is masked (I used guids as masks, and a hashtable to keep track) then you can safely do your search and replace, then finally restore the masked code.
Hope that helps.


Question:
We have an ASP.NET application that manages it's own User, Roles and Permission database and we have recently added a field to the User table to hold the Windows domain account.

I would like to make it so that the user doesn't have to  physically log in to our application, but rather would be automatically logged in based on the currently logged in Windows domain account DOMAIN\username.  We want to authenticate the Windows domain account against our own User table.

This is a piece of cake to do in Windows Forms, is it possible to do this in Web Forms?

I don't want the user to be prompted with a Windows challenge screen,  I want our system to handle the log in.

Clarification: We are using our own custom Principal object.

Clarification: Not sure if it makes a difference or not, but we are using IIS7.

Answer:
```
```
using System.Security.Principal;
...
WindowsPrincipal wp = (WindowsPrincipal)HttpContext.Current.User;
```
```
to get the current domain user. Of course you have to make sure that the IIS is set up to handle Windows Authentication.


Question:
Are there any free tools available to view the contents of the solution user options file (the .suo file that accompanies solution files)?

I know it's basically formatted as a file system within the file, but I'd like to be able to view the contents so that I can figure out which aspects of my solution and customizations are causing it grow very large over time.

Answer:
I don't know any tool, but you can try to access user settings via
IVsPersistSolutionOpts
interface


Question:
Say I have a linked list of numbers of length N. N is very large and I don’t know in advance the exact value of N.

How can I most efficiently write a function that will return k completely random numbers from the list?

Answer:
I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your random numbers once.
If you somehow don't know the length of your linked list (how?), then you could grab the first k into an array, then for node r, generate a random number in [0, r), and if that is less than k, replace the rth item of the array. (Not entirely convinced that doesn't bias...)
Other than that: "If I were you, I wouldn't be starting from here." Are you sure linked list is right for your problem? Is there not a better data structure, such as a good old flat array list.


Question: I'm looking at a new computer which will probably have vista on it.  But there are so many editions of vista; are there any weird restrictions on what you can run on the various editions?  For instance you couldn't run IIS on Windows ME.  Can you still run IIS on the home editions of vista?

Answer:
I would suggest: First find your k random numbers. Sort them. Then traverse both the linked list and your random numbers once.
If you somehow don't know the length of your linked list (how?), then you could grab the first k into an array, then for node r, generate a random number in [0, r), and if that is less than k, replace the rth item of the array. (Not entirely convinced that doesn't bias...)
Other than that: "If I were you, I wouldn't be starting from here." Are you sure linked list is right for your problem? Is there not a better data structure, such as a good old flat array list.


Question:
Surprisingly as you get good at vim, you can code even faster than standard IDEs such as Eclipse. But one thing I really miss is code completion, especially for long variable names and functions.

Is there any way to enable code completion for Perl in vim?

Answer:
Ctrl
-
P
(Get Previous Match) and
Ctrl
-
N
(Get Next Match) are kind of pseudo code completion.  They basically search the file (Backwards for
Ctrl
-
P
, Forwards for
Ctrl
-
N
) you are editing (and any open buffers, and if you are using TAGS anything in your TAG file) for words that start with what you are typing and add a drop down list.  It works surprisingly well for variables and function names, even if it isn't intellisense.  Generally I use
Ctrl
-
P
as the variable or function I am looking for is usually behind in the code.  Also if you keep the same copy of Vim open, it will search the files you have previously opened.


Question:
Database? Page variables? Enum?

I'm looking for opinions here.

Answer:
IF the menu is dynamic
per-user
then you'll have to hit the database for each user.  From then on I would probably store it in session to avoid future round-trips to the database.
If it's dynamic, but the entire site sees the same items, then put it in the database and cache the results


Question:
How does the comma operator work in C++?

For instance, if I do:

a = b, c;

Does a end up equaling b or c?

(Yes, I know this is easy to test - just documenting on here for someone to find the answer quickly.)

Update:  This question has exposed a nuance when using the comma operator.  Just to document this:

a = b, c;    // a is set to the value of b!

a = (b, c);  // a is set to the value of c!

This question was actually inspired by a typo in code.  What was intended to be

a = b;
c = d;

Turned into

a = b,    //  <-  Note comma typo!
c = d;

Answer:
It would be equal to
```
b
```
.
The comma operator has a lower precedence than assignment.


Question: There is a lot of buzz about Microsoft Silverlight, especially after the Olympics. Also H264 will be supported in a future version. Where do you think Silverlight will be 1 year from now?

Answer:
100% more.
(so about 4 people)


Question:
How to implement Repository pattern withe LinqToEntities
how to implement the interface

Answer:
No, they aren't (or at least you can't assume they are). Having said that, there are some tricks to do this atomically, but they typically aren't portable (see
Compare-and-swap
).


Question:
I am developing a web app which requires a username and password to be stored in the web.Config, it also refers to some URLs which will be requested by the web app itself and never the client.

I know the .Net framework will not allow a web.config file to be served, however I still think its bad practice to leave this sort of information in plain text.

Everything I have read so far requires me to use a command line switch or to store values in the registry of the server.  I have access to neither of these as the host is online and I have only FTP and Control Panel (helm) access.

Can anyone recommend any good, free encryption DLL's or methods which I can use?  I'd rather not develop my own!

Thanks for the feedback so far guys but I am not able to issue commands and and not able to edit the registry.  Its going to have to be an encryption util/helper but just wondering which one!

Answer:
Encrypting and Decrypting Configuration Sections
(ASP.NET) on MSDN
Encrypting Web.Config Values in ASP.NET 2.0
on ScottGu's
blog
Encrypting Custom Configuration Sections
on K. Scott Allen's
blog
EDIT:
If you can't use asp utility, you can encrypt config file using
SectionInformation.ProtectSection
method.
Sample on codeproject:
Encryption of Connection Strings inside the Web.config in ASP.Net 2.0


Question:
I have an asp.net url path which is being generated in a web form, and is coming out something like "/foo/bar/../bar/path.aspx", and is coming out in the generated html like this too. It should be shortened to "/foo/bar/path.aspx".

Path.Combine didn't fix it. Is there a function to clean this path up?

Answer:
You could create a helper class which wrapped the UriBuilder class in System.Net
```
```
public static class UriHelper
{
    public static string NormalizeRelativePath(string path)
    {
        UriBuilder _builder = new UriBuilder("http://localhost");
        builder.Path = path;
        return builder.Uri.AbsolutePath;
    }
}
```
```
which could then be used like this:
```
```
string url = "foo/bar/../bar/path.aspx";
Console.WriteLine(UriHelper.NormalizeRelativePath(url));
```
```
It is a bit hacky but it would work for the specific example you gave.
EDIT: Updated to reflect Andrew's comments.


Question:
Using Vim I often want to replace a block of code with a block that I just yanked.

But when I delete the block of code that is to be replaced, that block itself goes into the register which erases the block I just yanked. So I've got in the habit of yanking, then inserting, then deleting what I didn't want, but with large blocks of code this gets messy trying to keep the inserted block and the block to delete separate.

So what is the slickest and quickest way to replace text in Vim?

is there a way to delete text without putting it into the register?

is there a way to say e.g. "replace next word" or "replace up to next paragraph"

or is the best way to somehow use the multi-register feature?

Answer:
Well, first do this command:
```
```
:h d
```
```
Then you will realize that you can delete into a specific register. That way you won't alter what is in your default register.


Question:
Let's say you work someplace where every change to source code must be associated with a bug-report or feature-request, and there is no way to get that policy reformed.  In such an environment, what is the best way to deal with code refactorings (that is, changes that improve the code but do not fix a bug or add a feature)?

Write up a bug-report and associate the refactoring with it.

Write up a feature-request and associate the refactoring with it.

Sneak in the refactorings while working on code that is associated with a bug-report/feature-request.

Just don't do any refactoring.

Other

Note that all bug reports and feature descriptions will be visible to managers and customers.

Answer: I vote for the "sneak in refactorings" approach, which is, I believe, the way refactoring is meant to be done in the first place.  It's probably a bad idea to refactor just for the sake of "cleaning up the code."  This means that you're making changes for no real reason.  Refactoring is, by definition, modifying the without the intent of fixing bugs or adding features.  If you're following the KISS principle, any new feature is going to need at least some refactoring because you're not really thinking about how to make the most extensible system possible the first time around.


Question: Sure, we can use a simple bulleted list or a mindmap.  But, there must be a better, more interactive way.  What do you use when starting your website architecture?

Answer:
By "architecture", do you mean the initial site map? If not, please post a clarification and I'll edit my response.
Our tech team starts development after our creative department has done their stuff. Part of what we get is output from the information architect. He passes off a graphical sitemap, a detailed sitemap as an Excel sheet, and a set of wireframes in a PDF.


Question:
The following SQL:

SELECT notes + 'SomeText'
FROM NotesTable a

Give the error:

The data types nvarchar and text are incompatible in the add operator.

Answer:
The only way would be to convert your text field into an nvarchar field.
```
```
Select Cast(notes as nvarchar(4000)) + 'SomeText'
From NotesTable a
```
```
Otherwise, I suggest doing the concatenation in your application.


Question: We have an ASP.NET application running at a customer site that uses ActiveDirectory for user login via the ActiveDirectoryMembershipProvider. Their primary domain controller that we were pointing to went down this morning, and in getting everything set back up the client was wondering if we could have a redundant connection to two domain controllers; i.e. specifying a primary and a backup AD server. A Google search proved fruitless - does anyone know if this can be done?

Answer:
It can be done, it will just take some work.
You will need to create a class that inherits off of the ActiveDirectoryMemberhsipProvider and use it has your provider instead.  That way you can maintain most of the functionality.  Then setup a way to specify two connectionStringName properties, one for primary and one for secondary.  You will also need to create the code to read the information from the config since you are changing it.  Then just override the methods where you need to catch when the primary is down and switch to the secondary.  This will be the most reusable way of doing it.
There's probably other ways of doing it, but it will probably be hacky and not very reusable.  Like testing the connection before each request and then setting the connectionstring that way.
Based on the
MSDN documentation
on the class, this will probably be the only way to do it.  They don't provide the functionality internal.


Question:
I have a set of calculation methods sitting in a .Net DLL.  I would like to make those methods available to Excel (2003+) users so they can use them in their spreadsheets.

For example, my .net method:

public double CalculateSomethingReallyComplex(double a, double b) {...}

I would like enable them to call this method just by typing a formula in a random cell:

=CalculateSomethingReallyComplex(A1, B1)

What would be the best way to accomplish this?

Answer:
There are two methods - you can used Visual Studio Tools for Office (VSTO):
http://blogs.msdn.com/pstubbs/archive/2004/12/31/344964.aspx
or you can use COM:
http://blogs.msdn.com/eric_carter/archive/2004/12/01/273127.aspx
I'm not sure if the VSTO method would work in older versions of Excel, but the COM method should work fine.