q:
Inversion of Control (IoC) can be quite confusing when it is first encountered.

What is it?

Which problem does it solve?

When is it appropriate to use and when not?

[A]
Wikipedia Article
. To me, inversion of control is turning your sequentially written code and turning it into an delegation structure. Instead of your program explicitly controlling everything, your program sets up a class or library with certain functions to be called when certain things happen.
It solves code duplication. For example, in the old days you would manually write your own event loop, polling the system libraries for new events. Nowadays, most modern APIs you simply tell the system libraries what events you're interested in, and it will let you know when they happen.
Inversion of control is a practical way to reduce code duplication, and if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control. Inversion of control is made easy in many languages through the concept of delegates, interfaces, or even raw function pointers.
It is not appropriate to use in all cases, because the flow of a program can be harder to follow when written this way. It's a useful way to design methods when writing a library that will be reused, but it should be used sparingly in the core of your own program unless it really solves a code duplication problem.


q:
How do I call a function, using a string with the function's name? For example:

import foo
func_name = "bar"
call(foo, func_name)  # calls foo.bar()

[A]
Given a module
```
foo
```
with method
```
bar
```
:
```
```
import foo
bar = getattr(foo, 'bar')
result = bar()
```
```
```
getattr
```
can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on.

s: huggingface

c: devops

d: intermediate


q:
I have a simple page with my ScriptManager and my UpdatePanel, and my ContentTemplate has one ListBox and one Label.  I am just trying to catch its OnSelectionChanged so I can update the text in the Label.  No matter what settings I try to tweak, I always get a full-page postback.

Is this really not going to work, or am I just screwing this up?

[A]
You need to have Sharepoint 2007 service pack 1 -- or else there's no chance.
(Sharepoint 2007 predates ajax 1.0 -- they built some support into service pack 1)
Next, from a trouble shooting point of view, test that the
exact
same code functions as expected when hosted in a regular asp.net page. (Literally copy and paste your code across into a fresh page, to rule out any typographical errors). Ruling sharepoint in or out of the problem area will help narrow down the solution space.


q:
I have a perl variable $results that gets returned from a service.  The value is supposed to be an array, and $results should be an array reference.  However, when the array has only one item in it, $results will be set to that value, and not a referenced array that contains that one item.

I want to do a foreach loop on the expected array.  Without checking ref($results) eq 'ARRAY', is there any way to have something equivalent to the following:

foreach my $result (@$results) {
    # Process $result
}

That particular code sample will work for the reference, but will complain for the simple scalar.

EDIT: I should clarify that there is no way for me to change what is returned from the service.  The problem is that the value will be a scalar when there is only one value and it will be an array reference when there is more than one value.

[A]
I've just tested this with:
```
```
#!/usr/bin/perl -w
use strict;

sub testit {

 my @ret = ();
 if (shift){
   push @ret,1;
   push @ret,2;
   push @ret,3;
}else{
  push @ret,"oneonly";
}

return \@ret;
}

foreach my $r (@{testit(1)}){
  print $r." test1\n";
}
foreach my $r (@{testit()}){
   print $r." test2\n";
}
```
```
And it seems to work ok, so I'm thinking it has something to do with the result getting returned from the service?
If you have no control over the returning service this might be hard one to crack


q:
How can I set up my crontab to execute X script at 11:59PM every day without emailing me or creating any logs?

Right now my crontab looks something like this

@daily /path/to/script.sh

[A]
When you do crontab -e, try this:
```
```
59 23 * * * /usr/sbin/myscript > /dev/null
```
```
That means: At 59 Minutes and 23 Hours on every day (*) on every month on every weekday, execute myscript.
See
man crontab
for some more info and examples.


q:
I'm compiling a NAnt project on linux with TeamCity Continuous Integration server. I have been able to generate a test report by running NAnt on mono thru a Command Line Runner but don't have the options of using the report like a NAnt Runner. I'm also using MBUnit for the testing framework.

How can I merge in the test report and display "Tests failed: 1 (1 new), passed: 3049" for the build?

Update: take a look at MBUnitTask its a NAnt task that uses sends messages that TeamCity expects from NUnit so it lets you use all of TeamCity's features for tests.

MBUnitTask

Update: Galio has better support so you just have to reference the Galio MBUnit 3.5 dlls instead of the MBUnit 3.5 dlls and switch to the galio runner to make it work.

[A]
TeamCity watches the command line output from the build.  You can let it know how your tests are going by inserting certain markers into that output See
http://www.jetbrains.net/confluence/display/TCD3/Build+Script+Interaction+with+TeamCity
.  For example
```
```
##teamcity[testSuiteStarted name='Test1']
```
```
will let TeamCity know that a set of tests started.  With MbUnit you can't output these markers while the tests are running, but you can transform the XML file that it outputs.  Here is the XSL that I am using:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text"/>
    <xsl:template match="/">

        <xsl:apply-templates/>

    </xsl:template>

    <xsl:template match="assemblies/assembly">
##teamcity[testSuiteStarted name='<xsl:value-of select="@name" />']

        <xsl:apply-templates select="//run" />

##teamcity[testSuiteFinished name='<xsl:value-of select="@name" />']
    </xsl:template>

    <xsl:template match="run">

        <xsl:choose>
            <xsl:when test="@result='ignore' or @result='skip'">
        ##teamcity[testIgnored name='<xsl:value-of select="@name" />' message='Test Ignored']
            </xsl:when>
            <xsl:otherwise>
        ##teamcity[testStarted name='<xsl:value-of select="@name" />']
            </xsl:otherwise>
        </xsl:choose>

        <xsl:if test="@result='failure'">
            ##teamcity[testFailed name='<xsl:value-of select="@name" />' message='<xsl:value-of select="child::node()/message"/>' details='<xsl:value-of select="normalize-space(child::node()/stack-trace)"/>']
        </xsl:if>

        <xsl:if test="@result!='ignore' and @result!='skip'">
        ##teamcity[testFinished name='<xsl:value-of select="@name" />']
        </xsl:if>

    </xsl:template>

</xsl:stylesheet>
```
```


q:
I have seen these being used every which way, and have been accused of using them the wrong way (though in that case, I was using them that way to demonstrate a point).

So, what do you think are the best practices for employing Extension Methods?

Should development teams create a library of extension methods and deploy them across various projects?

Should there be a collection of common extension methods in the form of an open source project?

Update: have decided to create an organization wide extension methods library

[A]
I think that it depends on what purpose the Extension methods serve.
Extension methods that relate to specific business needs of a project (whether they are connected to basic data types or custom objects) should not be included in a library that would be distributed across multiple projects.
Extension methods that relate to basic data types (int, string, etc) or generics that have a wider application could be packaged and distributed across projects.
Take care not to globally include Extension methods that have little application, as they just clog up intellisense and can lead to confusion and/or misuse.


q:
Is there anyone working solo and using fogbugz out there? I'm interested in personal experience/overhead versus paper.

I am involved in several projects and get pretty hammered with lots of details to keep track of... Any experience welcome.

(Yes I know Mr. Joel is on the stackoverflow team... I still want good answers :)

[A]
I use it, especially since the hosted Version of FugBugz
is free for up to 2 people
. I found it a lot nicer than paper as I'm working on multiple projects, and my paper tends to get rather messy once you start making annotations or if you want to re-organize and shuffle tasks around, mark them as complete only to see that they are not complete after all...
Plus, the Visual Studio integration is really neat, something paper just cannot compete with. Also, if you lay the project to rest for 6 months and come back, all your tasks and notes are still there, whereas with paper you may need to search all the old documents and notes again, if you did not discard it.
But that is just the point of view from someone who is not really good at staying organized :-) If you are a really tidy and organized person, paper may work better for you than it does for me.
Bonus suggestion: Run Fogbugz on a second PC (or a small Laptop like the eeePC) so that you always have it at your fingertips. The main problem with Task tracking programs - be it FogBugz, Outlook, Excel or just notepad - is that they take up screen space, and my two monitors are usually full with Visual Studio, e-Mail, Web Browsers, some Notepads etc.


q:
If I have data like this:

Key
Name

1
Dan

2
Tom

3
Jon

4
Tom

5
Sam

6
Dan

What is the SQL query to bring back the records where Name is repeated 2 or more times?

So the result I would want is

Tom

Dan

[A]
Couldn't be simpler...
```
```
Select Name, Count(Name) As Count
    From Table
    Group By Name
    Having Count(Name) > 1
    Order By Count(Name) Desc
```
```
This could also be extended to delete duplicates:
```
```
Delete From Table
Where Key In (
    Select Max(Key)
        From Table
        Group By Name
        Having Count(Name) > 1
    )
```
```


q:
Is there an efficient method of converting an integer into the written numbers, for example:

string Written = IntegerToWritten(21);

would return "Twenty One".

Is there any way of doing this that doesn't involve a massive look-up table?

[A]
why massive lookup table?
```
```
string GetWrittenInteger(int n)
{
  string[] a = new string[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" }
  string[] b = new string[] { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" }
  string[] c = new string[] {"Twenty", "Thirty", "Forty", "Sixty", "Seventy", "Eighty", "Ninety"};
  string[] d = new string[] {"Hundred", "Thousand", "Million"}
  string s = n.ToString();

  for (int i = 0; i < s.Length; i++)
  {
    // logic (too lazy but you get the idea)
  }
}
```
```


q:
How would one display any add content from a "dynamic" aspx page? Currently I am working on using the System.Web.HttpResponse "Page.Response" to write a file that is stored on a web server to a web request.

This would allow people to hit a url to the type http://www.foo.com?Image=test.jpg and have the image display in their browser. So as you may know this revolves around the use of Response.ContentType.

By using

Response.ContentType = "application/octet-stream";

I am able to display images of type gif/jpeg/png (all i have tested so far), bit trying to display .swf or .ico files gives me a nice little error.

using

Response.ContentType = "application/x-shockwave-flash";

I can get flash files to play, but then the images are messed.

So how do i easily choose the contenttype?

[A]
This is part of a solution I use on a local intranet. Some of the variables you will have to collect yourself as I pull them from a database but you may pull them from somewhere else.
The only extra but I've got in there is a function called
getMimeType
which connects to the database and pulls back the correct mine type based on file extension. This defaults to application/octet-stream if none is found.
```
```
// Clear the response buffer incase there is anything already in it.
Response.Clear();
Response.Buffer = true;

// Read the original file from disk
FileStream myFileStream = new FileStream(sPath, FileMode.Open);
long FileSize = myFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
myFileStream.Read(Buffer, 0, (int)FileSize);
myFileStream.Close();

// Tell the browse stuff about the file
Response.AddHeader("Content-Length", FileSize.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=" + sFilename.Replace(" ","_"));
Response.ContentType = getMimeType(sExtention, oConnection);

// Send the data to the browser
Response.BinaryWrite(Buffer);
Response.End();
```
```


q:
Most people with a degree in CS will certainly know what Big O stands for.
It helps us to measure how well an algorithm scales.

But I'm curious, how do you calculate or approximate the complexity of your algorithms?

[A]
Familiarity with the algorithms/data structures I use and/or quick glance analysis of iteration nesting.  The difficulty is when you call a library function, possibly multiple times - you can often be unsure of whether you are calling the function unnecessarily at times or what implementation they are using.  Maybe library functions should have a complexity/efficiency measure, whether that be Big O or some other metric, that is available in documentation or even
IntelliSense
.


q:
I'm wondering if there's a way to do what I can do below with Python, in Ruby:

sum = reduce(lambda x, y: x + y, map(lambda x, y: x * y, weights, data))

I have two arrays of equal sizes with the weights and data but I can't seem to find a function similar to map in Ruby, reduce I have working.

[A]
The Array.zip function does an elementwise combination of arrays. It's not quite as clean as the Python syntax, but here's one approach you could use:
```
```
weights = [1, 2, 3]
data = [4, 5, 6]
result = Array.new
a.zip(b) { |x, y| result << x * y } # For just the one operation

sum = 0
a.zip(b) { |x, y| sum += x * y } # For both operations
```
```


q: I've been working with providers a fair bit lately, and I came across an interesting situation where I wanted to have an abstract class that had an abstract static method. I read a few posts on the topic, and it sort of made sense, but is there a nice clear explanation?

[A]
Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.
Assume you could, for a moment, inherit static methods. Imagine this scenario:
```
```
public static class Base
{
    public static virtual int GetNumber() { return 5; }
}

public static class Child1 : Base
{
    public static override int GetNumber() { return 1; }
}

public static class Child2 : Base
{
    public static override int GetNumber() { return 2; }
}
```
```
If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.


q: How can I set the background color of an HTML element using css in JavaScript?

[A]
```
```
var element = document.getElementById('element');
element.style.background = '#FF00AA';
```
```


q:
I would like to be able to use the Tab key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.

Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?

I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like Shift+Tab, or Ctrl+Q?

[A]
The previous answer is fine, but I'm one of those guys that's firmly against mixing behavior with presentation (putting JavaScript in my HTML) so I prefer to put my event handling logic in my JavaScript files. Additionally, not all browsers implement event (or e) the same way. You may want to do a check prior to running any logic:
```
```
document.onkeydown = TabExample;

function TabExample(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var tabKey = 9;
  if(evt.keyCode == tabKey) {
    // do work
  }
}
```
```


q:
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL?

Edit:
For example I have the following

Name   id  Col1  Col2
Row1   1    6     1
Row2   2    2     3
Row3   3    9     5
Row4   4    16    8

I want to combine all the following Updates into one query

UPDATE table SET Col1 = 1 WHERE id = 1;
UPDATE table SET Col1 = 2 WHERE id = 2;
UPDATE table SET Col2 = 3 WHERE id = 3;
UPDATE table SET Col1 = 10 WHERE id = 4;
UPDATE table SET Col2 = 12 WHERE id = 4;

[A]
```
```
UPDATE table1, table2 SET table1.col1='value', table2.col1='value' WHERE table1.col3='567' AND table2.col6='567'
```
```
This should work for ya.
There is a reference in
the MySQL manual
for multiple tables.


q:
I've noticed a lot of sites, SO included, use XHTML as their mark-up language and then fail to adhere to the spec. Just browsing the source for SO there are missing closing tags for paragraphs, invalid elements, etc.

So should tools (and developers) use the XHTML doctype if they are going to produce invalid mark up? And should browsers be more firm in their acceptance of poor mark-up?

And before anyone shouts hypocrite, my blog has one piece of invalid mark-up involving the captha (or it did the last time I checked) which involves styling the noscript tag.

[A]
It depends. I had that
issue with my blog
where a YouTube video caused invalid XHTML, but it rendered fine. On the other hand, I have a "Valid XHTML" link, and a combination of a "Valid XHTML" claim and invalid XHTML is not professional.
As SO does not claim to be valid, I think it's acceptable, but personally if I were Jeff i would be bothered and try to fix it even if it looks good in modern browsers, but some people rather just move on and actually get things done instead of fixing non-existent bugs.


q:
How can I connect to a remote SQL server using Mac OS X? I don't really need a GUI, but it would be nice to have for the color coding and resultset grid. I'd rather not have to use a VM.

Is there a SQL client for Mac OS X that works with MS SQL Server?

[A]
This doesn't specifically answer your question, because I'm not sure in any clients exist in Mac OS X, but I generally just
Remote Desktop
into the server and work through that. Another option is
VMware Fusion
(which is much better than
Parallels
in my opinion) + Windows XP +
SQL Server Management Studio
.


q:
I have a very simple problem which requires a very quick and simple solution in SQL Server 2005.

I have a table with x Columns. I want to be able to select one row from the table and then transform the columns into rows.

TableA
Column1, Column2, Column3

SQL Statement to ruturn

ResultA
Value of Column1
Value of Column2
Value of Column3

@Kevin: I've had a google search on the topic but alot of the example where overly complex for my example, are you able to help further?

@Mario: The solution I am creating has 10 columns which stores the values 0 to 6 and I must work out how many columns have the value 3 or more. So I thought about creating a query to turn that into rows and then using the generated table in a subquery to say count the number of rows with Column >= 3

[A]
You should take a look at the UNPIVOT clause.
Update1
: GateKiller, strangely enough I read an article (about something unrelated) about it this morning and I'm trying to jog my memory where I saw it again, had some decent looking examples too. It'll come back to me I'm sure.
Update2
: Found it:
http://weblogs.sqlteam.com/jeffs/archive/2008/04/23/unpivot.aspx


q: What is BODMAS and why is it useful in programming?

[A]
http://www.easymaths.com/What_on_earth_is_Bodmas.htm
:
What do you think the answer to 2 + 3 x 5 is?
Is it (2 + 3) x 5 = 5 x 5 = 25 ?
or 2 + (3 x 5) = 2 + 15 = 17 ?
BODMAS can come to the rescue and give us rules to follow so that we always get the right answer:
(B)rackets (O)rder (D)ivision (M)ultiplication (A)ddition (S)ubtraction
According to BODMAS, multiplication should always be done before addition, therefore 17 is actually the correct answer according to BODMAS and will also be the answer which your calculator will give if you type in 2 + 3 x 5 .
Why it is useful in programming? No idea, but i assume it's because you can get rid of some brackets? I am a quite defensive programmer, so my lines can look like this:
```
```
result = (((i + 4) - (a + b)) * MAGIC_NUMBER) - ANOTHER_MAGIC_NUMBER;
```
```
with BODMAS you can make this a bit clearer:
```
```
result = (i + 4 - (a + b)) * MAGIC_NUMBER - ANOTHER_MAGIC_NUMBER;
```
```
I think i'd still use the first variant - more brackets, but that way i do not have to learn yet another rule and i run into less risk of forgetting it and causing those weird hard to debug errors?
Just guessing at that part though.
Mike Stone EDIT: Fixed math as Gaius points out


q:
I'm using MSVE, and I have my own tiles I'm displaying in layers on top. Problem is, there's a ton of them, and they're on a network server. In certain directories, there are something on the order of 30,000+ files. Initially I called Directory.GetFiles, but once I started testing in a pseudo-real environment, it timed out.

What's the best way to programatically list, and iterate through, this many files?

Edit: My coworker suggested using the MS indexing service. Has anyone tried this approach, and (how) has it worked?

[A]
I've worked on a SAN system in the past with telephony audio recordings which had issues with numbers of files in a single folder - that system became unusable somewhere near 5,000 (on Windows 2000 Advanced Server with an application in C#.Net 1.1)- the only sensible solution that we came up with was to change the folder structure so that there were a more reasonable number of files. Interestingly Explorer would also time out!
The convention we came up with was a structure that broke the structure up in years, months and days - but that will depend upon your system and whether you can control the directory structure...


q:
I have a Rakefile with a Rake task that I would normally call from the command line:

rake blog:post Title

I'd like to write a Ruby script that calls that Rake task multiple times, but the only solution I see is shelling out using `` (backticks) or system.

What's the right way to do this?

[A]
from
timocracy.com
:
```
```
require 'rake'

def capture_stdout
  s = StringIO.new
  oldstdout = $stdout
  $stdout = s
  yield
  s.string
ensure
  $stdout = oldstdout
end

Rake.application.rake_require 'metric_fetcher', ['../../lib/tasks']
results = capture_stdout {Rake.application['metric_fetcher'].invoke}
```
```


q: In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?

[A]
```
```
SELECT Table_Name
FROM Information_Schema.Columns
WHERE Column_Name = 'YourFieldName'
```
```


q: I want to create my Rails application with MySQL, because I like it so much. How can I do that in the latest version of Rails instead of the default SQLite?

[A]
Normally, you would create a new Rails app using
```
```
rails ProjectName
```
```
To use MySQL, use
```
```
rails new ProjectName -d mysql
```
```


q:
I've got TotroiseSVN installed and have a majority of my repositories checking in and out from C:\subversion\ and a couple checking in and out from a network share (I forgot about this when I originally posted this question).

This means that I don't have a "subversion" server per-se.

How do I integrate TortoiseSVN and Fogbugz?

Edit: inserted italics

[A]
This answer is incomplete and flawed! It only works from TortoisSVN to Fogbugz, but not the other way around. I still need to know how to get it to work backwards from Fogbugz (like it's designed to) so that I can see the Revision number a bug is addressed in from Fogbugz while looking at a bug.
Helpful URLS
http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-propertypage.html
http://tortoisesvn.net/issuetracker_integration
Set the "Hooks"
Go into your fogbugz account and click Extras > Configure Source Control Integration
Download "post-commit.bat" and the VBScript file for Subversion
Create a "hooks" directory in a common easily accessed location (preferably with no spaces in the file path)
Place a copy of the files in the hooks directories
Rename the files without the ".safe" extension
Right click on any directory.
Select "TortoiseSVN > Settings" (in the right click menu from the last step)
Select "Hook Scripts"
Click "Add"
Set the properties thus:
Hook Type: Post-Commit Hook
Working Copy Path: C:\\Projects (or whatever your root directory for all of your projects is. If you have multiple you will need to do this step for each one.)
Command Line To Execute: C:\\subversion\\hooks\\post-commit.bat (this needs to point to wherever you put your hooks directory from step 3)
I also selected the checkbox to Wait for the script to finish...
WARNING: Don't forget the double back-slash! "\\"
Click OK...
Note: the screenshot is different, follow the text for the file paths, NOT the screenshot...
At this point it would seem you could click "Issue Tracker Integration" and select Fogbugz. nope. It just returns "There are no issue-tracker providers available".
Click "OK" to close the whole
settings dialogue window
Configure the Properties
Once again, Right click on the root directory of the checked out
project you want to work with (you need to do this "configure the properties" step for each project -- See "Migrating Properties Between Projects" below)
Select "TortoiseSVN > Properties" (in the right click menu
from the last step)
Add five property value pairs by clicking "New..." and inserting the
following in "Property Name" and
"Property Value" respectively:
bugtraq:label BugzID:
bugtraq:message   BugzID: %%BUGID%%
bugtraq:number    true
bugtraq:url
http://[your
fogbugz URL
  here]/default.asp?%BUGID%
bugtraq:warnifnoissue false
Click "OK"
Commiting Changes and Viewing the Logs
Now when you are commiting, you can specify one bug that the commit addresses. This kind of forces you to commit after fixing each bug...
When you view the log (Right click root of project, TortoiseSVN > show log) you can see the bug id that each checking corresponds to (1), and you can click the bug id number to be taken to fogbugz to view that bug automatically if you are looking at the actual log message. Pretty nifty!
Migrating Properties Between Projects
Right click on a project that already has the proper Properties configuration
Select "TortoiseSVN > Properties" (from the right-click menu from step 1)
Highlight all of the desired properties
Click "Export"
Name the file after the property, and place in an easily accessible directory (I placed mine with the hooks files)
Right click on the root directory of the checked out project needing properties set for.
Click "Import"
Select the file you exported in step 4 above
Click Open


q:
When developing a new web based application which version of html should you aim for?

EDIT:

cool I was just attempting to get a feel from others I tend to use XHTML 1.0 Strict in my own work and Transitional when others are involved in the content creation.

I marked the first XHTML 1.0 Transitional post as the 'correct answer' but believe strongly that all the answers given at that point where equally valid.

[A] I'd shoot for XHTML Transitional 1.0. There are still a few nuances out there that don't like XHTML strict, and most editors I've seen now will give you the proper nudges to make sure that things are done right.


q:
(y/N)

Edit: Read-only access is fine.

[A]
If your willing to force the user to also install another application, you could write a small C# or C++ windows service that simply opens a Socket that provides some kind of protocol for accessing the registry. Then in AIR you can use the Socket class to send messages to/from the C# service that would return results to the AIR app.
When the app loads you can try to connect to the Socket, and if the connection is rejected you could prompt the user to download/install the service.
As for direct access to the registry I am pretty sure Adobe wouldn't allow that from AIR.


q:
I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order.

I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough.

I could do this:

select timefield from entries where uid = ? order by timefield;

and look at every 150th row.

Or I could do 20 separate queries and use limit 1 and offset.

But there must be a more efficient solution...

[A]
Something like this came to my mind
```
```
select @rownum:=@rownum+1 rownum, entries.*
from (select @rownum:=0) r, entries
where uid = ? and rownum % 150 = 0
```
```
I don't have MySQL at my hand but maybe this will help ...


q:
I'm writing a web page in ASP.NET. I have some JavaScript code, and I have a submit button with a click event.

Is it possible to call a method I created in ASP with JavaScript's click event?

[A]
You can do it asynchronously using .NET Ajax PageMethods. See
here
or
here
.


q:
So I'm using an app that stores images heavily in the DB. What's your outlook on this? I'm more of a type to store the location in the filesystem, than store it directly in the DB.

What do you think are the pros/cons?

[A]
I'm in charge of some applications that manage many TB of images.  We've found that storing
file paths
in the database to be best.
There are a couple of issues:
database storage is usually more expensive than file system storage
you can super-accelerate file system access with standard off the shelf products
for example, many web servers use the operating system's
sendfile()
system call to asynchronously send a file directly from the file system to the network interface. Images stored in a database don't benefit from this optimization.
things like web servers, etc, need no special coding or processing to access images in the file system
databases win out where transactional integrity between the image and metadata are important.
it is more complex to manage integrity between db metadata and file system data
it is difficult (within the context of a web application) to guarantee data has been flushed to disk on the filesystem


q:
When prototyping initial GUI functionality with a customer is it better to use a pen/paper drawing or to mock something up using a tool and show them that ?

The argument against a tool generated design being that the customer can sometimes focus on the low-level specifics of the mock-up rather than taking a higher level functional view of the GUI overall.

[A]
Always start with paper or paper-like mock-ups first.  You do not want to fall into a trap of giving the impression of completeness when the back-end is completely hollow.
A polished prototype or pixel-perfect example puts too much emphasis on the design.  With an obvious sketch, you have a better shot of discussing desired functionality and content rather than colors, photos, and other stylistic matters.  There will be time for that discussion later in the project.
Jeff discusses paper prototyping in his Coding Horror article
UI-First Software Development
Click the "Watch a video!" link at
twitter.com
to see an interesting take on the idea from
Common Craft
.


q:
I'm trying out the following query:

SELECT A,B,C FROM table WHERE field LIKE 'query%'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query'
UNION
SELECT A,B,C FROM table WHERE field LIKE '%query%'
GROUP BY B ORDER BY B ASC LIMIT 5

That's three queries stuck together, kinda sorta. However, the result set that comes back reflects results from query #3 before the results from query #1 which is undesired.

Is there any way to prioritize these so that results come as all for query #1, then all for query #2 then all for query #3? I don't want to do this in PHP just yet (not to mention having to control for results that showed up in the first query not to show in the second and so forth).

[A]
Can you do it as a subselect, something like
```
```
SELECT * FROM (
    SELECT A,B,C FROM table WHERE field LIKE 'query%'
    UNION
    SELECT A,B,C FROM table WHERE field LIKE '%query'
    UNION
    SELECT A,B,C FROM table WHERE field LIKE '%query%'
) ORDER BY B ASC LIMIT 5
```
```


q: I wrote a component that displays a filename, a thumbnail and has a button to load/play the file. The component is databound to a repeater. How can I make it so that the button event fires to the main application and tells it which file to play?


q: I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem appropriate. Is there some kind of an understood standard?  Or is this just one of those things that you should do whatever you prefer and both are really correct?

[A]
It seems like an
```
IllegalArgumentException
```
is called for if you don't want
```
null
```
to be an allowed value, and the
```
NullPointerException
```
would be thrown if you were trying to
use
a variable that turns out to be
```
null
```
.


q: What is the best way to support multiple languages for the interface in an ASP.NET MVC application? I've seen people use resource files for other applications. Is this still the best way?

[A]
Yes resources are still the best way to support multiple languages in the .NET environment.  Because they are easy to reference and even easier to add new languages.
```
```
Site.resx
Site.en.resx
Site.en-US.resx
Site.fr.resx
etc...
```
```
So you are right still use the resource files.


q:
I'm trying to convince my providers to use ANT instead of Rational Application Development so anyone can recompile, recheck, redeploy the solution anyplace, anytime, anyhow. :P

I started a build.xml for a project that generates a JAR file but stopped there and I need real examples to compare notes. My good friends! I don't have anyone close to chat about this!

This is my build.xml so far.

(*) I edited my question based in the suggestion of to use pastebin.ca

[A]
My Environment: Fedora 8; WAS 6.1 (as installed with Rational Application Developer 7)
The documentation is very poor in this area and there is a dearth of practical examples.
Using the WebSphere Application Server (WAS) Ant tasks
To run as described here, you need to run them from your server
profile
bin directory using the
ws_ant.sh
or
ws_ant.bat
commands.
```
```
<?xml version="1.0"?>
<project name="project" default="wasListApps" basedir=".">
    <description>
        Script for listing installed apps.
        Example run from:
        /opt/IBM/SDP70/runtimes/base_v61/profiles/AppSrv01/bin
    </description>

    <property name="was_home"
        value="/opt/IBM/SDP70/runtimes/base_v61/">
    </property>
    <path id="was.runtime">
        <fileset dir="${was_home}/lib">
            <include name="**/*.jar" />
        </fileset>
        <fileset dir="${was_home}/plugins">
            <include name="**/*.jar" />
        </fileset>
    </path>
    <property name="was_cp" value="${toString:was.runtime}"></property>
    <property environment="env"></property>

    <target name="wasListApps">
        <taskdef name="wsListApp"
            classname="com.ibm.websphere.ant.tasks.ListApplications"
            classpath="${was_cp}">
        </taskdef>
        <wsListApp wasHome="${was_home}" />
    </target>

</project>
```
```
Command:
```
```
./ws_ant.sh -buildfile ~/IBM/rationalsdp7.0/workspace/mywebappDeploy/applist.xml
```
```
A Deployment Script
```
```
<?xml version="1.0"?>
<project name="project" default="default" basedir=".">
<description>
Build/Deploy an EAR to WebSphere Application Server 6.1
</description>

    <property name="was_home" value="/opt/IBM/SDP70/runtimes/base_v61/" />
    <path id="was.runtime">
        <fileset dir="${was_home}/lib">
            <include name="**/*.jar" />
        </fileset>
        <fileset dir="${was_home}/plugins">
            <include name="**/*.jar" />
        </fileset>
    </path>
    <property name="was_cp" value="${toString:was.runtime}" />
    <property environment="env" />
    <property name="ear" value="${env.HOME}/IBM/rationalsdp7.0/workspace/mywebappDeploy/mywebappEAR.ear" />

    <target name="default" depends="deployEar">
    </target>

    <target name="generateWar" depends="compileWarClasses">
        <jar destfile="mywebapp.war">
            <fileset dir="../mywebapp/WebContent">
            </fileset>
        </jar>
    </target>

    <target name="compileWarClasses">
        <echo message="was_cp=${was_cp}" />
        <javac srcdir="../mywebapp/src" destdir="../mywebapp/WebContent/WEB-INF/classes" classpath="${was_cp}">
        </javac>
    </target>

    <target name="generateEar" depends="generateWar">
        <mkdir dir="./earbin/META-INF"/>
        <move file="mywebapp.war" todir="./earbin" />
        <copy file="../mywebappEAR/META-INF/application.xml" todir="./earbin/META-INF" />
        <jar destfile="${ear}">
            <fileset dir="./earbin" />
        </jar>
    </target>

    <!-- http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/api/com/ibm/websphere/ant/tasks/package-summary.html -->
    <target name="deployEar" depends="generateEar">
        <taskdef name="wsInstallApp" classname="com.ibm.websphere.ant.tasks.InstallApplication" classpath="${was_cp}"/>
        <wsInstallApp ear="${ear}"
            failonerror="true"
            debug="true"
            taskname=""
            washome="${was_home}" />
    </target>

</project>
```
```
Notes:
You can only run this once! You cannot install if the app name is in use - see other tasks like
wsUninstallApp
It probably won't start the app either
You need to run this on the server and the script is quite fragile
Alternatives
I would probably use Java Management Extensions (JMX). You could write a file-upload servlet that accepts an EAR and uses the deployment MBeans to deploy the EAR on the server. You would just POST the file over HTTP. This would avoid any WAS API dependencies on your dev/build machine and could be independent of any one project.


q:
In C can I pass a multidimensional array to a function as a single argument when I don't know what the dimensions of the array are going to be?

Besides, my multidimensional array may contain types other than strings.

[A]
You can do this with any data type. Simply make it a pointer-to-pointer:
```
```
typedef struct {
  int myint;
  char* mystring;
} data;

data** array;
```
```
But don't forget you still have to malloc the variable, and it does get a bit complex:
```
```
//initialize
int x,y,w,h;
w = 10; //width of array
h = 20; //height of array

//malloc the 'y' dimension
array = malloc(sizeof(data*) * h);

//iterate over 'y' dimension
for(y=0;y<h;y++){
  //malloc the 'x' dimension
  array[y] = malloc(sizeof(data) * w);

  //iterate over the 'x' dimension
  for(x=0;x<w;x++){
    //malloc the string in the data structure
    array[y][x].mystring = malloc(50); //50 chars

    //initialize
    array[y][x].myint = 6;
    strcpy(array[y][x].mystring, "w00t");
  }
}
```
```
The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should
check the return of malloc()
.)
Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures:
```
```
int whatsMyInt(data** arrayPtr, int x, int y){
  return arrayPtr[y][x].myint;
}
```
```
Call this function with:
```
```
printf("My int is %d.\n", whatsMyInt(array, 2, 4));
```
```
Output:
```
```
My int is 6.
```
```


q: What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution?

[A]
this is what I use for C# w/resharper, should work just the same with vb.net:
```
```
build deploy */bin  */bin/* obj *.dll *.pdb *.user *.suo _ReSharper*  *.resharper* bin
```
```


q:
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.

I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then?

My intuition is currently pushing me towards BufferedStreams. Is this the way to go?

[A]
Not Java per-se, but you may run into issues where you have written something to a file, but it hasn't been actually written yet - it might be in a cache somewhere, and reading from the same file may not actually give you the new information.
Short version - use flush() or whatever the relevant system call is to ensure that your data is actually written to the file.
Note I am not talking about the OS level disk cache - if your data gets into here, it should appear in a read() after this point.  It may be that the language itself caches writes, waiting until a buffer fills up or file is flushed/closed.


q:
I need to learn ADO.NET to build applications based on MS Office. I have read a good deal about ADO.NET in the MSDN Library, but everything seems rather messy to me.

What are the basics one must figure out when using ADO.NET? I think a few key words will suffice to let me organize my learning.

[A]
There are three key components (assuming ur using SQL server):
```
SQLConnection
```
```
SqlCommand
```
```
SqlDataReader
```
(if you're using something else, replace
```
Sql
```
with "Something", like
```
MySqlConnection
```
,
```
OracleCommand
```
)
Everything else is just built on top of that.
Example 1:
```
```
using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
  command.commandText = "SELECT Name FROM Users WHERE Status = @OnlineStatus";
  command.Connection = connection;
  command.Parameters.Add("@OnlineStatus", SqlDbType.Int).Value = 1; //replace with enum
  connection.Open();

  using (SqlDataReader dr = command.ExecuteReader))
  {
      List<string> onlineUsers = new List<string>();

      while (dr.Read())
      {
         onlineUsers.Add(dr.GetString(0));
      }
  }
}
```
```
Example 2:
```
```
using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
  command.commandText = "DELETE FROM Users where Email = @Email";
  command.Connection = connection;
  command.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = "user@host.com";
  connection.Open();
  command.ExecuteNonQuery();
}
```
```


q:
A few months back my team switched our source control over to Apache Subversion from Visual SourceSafe, and we haven't been happier.

Recently I've been looking at Team Foundation Server, and at least on the surface, it seems very impressive.  There is some great integration with Visual Studio, and lots of great tools for DBAs, testers, project managers, etc.

The most obvious difference between these two products is price.  It's hard to beat Apache Subversion (free).  Team Foundation Server is quite expensive, so the extra features would really have to kick Subversion in the pants.

Does anyone have practical experience with both?

How do they compare?

Is Team Foundation Server actually worth the expense?

[A]
I joined an Open Source project over at CodePlex, recently. They use TFS for their source control and I have to say that it's absolutely magnificent. I'm incredibly impressed with it, so far. I'm a huge fan of the IDE integration and how easy it is to branch and tag your code. Adding a solution to source control is something like two clicks, if you've already got everything configured properly.
Now. Is it worth the hefty price tag? I don't think so. The benefit to working on projects at CodePlex is it lets me get the experience with TFS that I need, in the event that I have to use it somewhere later. If you want good IDE integration for your Source Control, go grab
VisualSVN
integration package. It's a much, much cheaper investment to get a lot of the same features (free on non-domain computers BTW).


q:
I'd like to use a LinqDataSource control on a page and limit the amount of records returned.  I know if I use code behind I could do something like this:

IEnumerable<int> values = Enumerable.Range(0, 10);
IEnumerable<int> take3 = values.Take(3);

Does anyone know if something like this is possible with a LinqDataSource control?

[Update]

I'm going to use the LinqDataSource with the ListView control, not a GridView or Repeater.  The LinqDataSource wizard does not provide the ability to limit the number of records return.  The Advanced options only allow you to enabled deletes, inserts, and updates.

[A]
I know that if you use a paging repeater or gridview with the linqdatasource it will automatically optimize the number of results returned, but I'm also pretty sure in the datasource wizard you can go to advanced options and limit it to
```
```
SELECT TOP 3 FROM
```
```
which should allow you to do what you need


q:
I'm using a Dictionary<string, int> where the int is a count of the key.

Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:

int LastCount = mydict[mydict.keys[mydict.keys.Count]];

does not work, because Dictionary.Keys does not implement a []-indexer.

I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a Stack<MyStruct>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?

[A]
You could always do this:
```
```
string[] temp = new string[mydict.count];
mydict.Keys.CopyTo(temp, 0)
int LastCount = mydict[temp[mydict.count - 1]]
```
```
But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys
on MSDN
is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.


q:
I've been doing ASP.NET development for a little while now, and I've used both the GridView and the DataGrid controls before for various things, but I never could find a really good reason to use one or the other. I'd like to know:

What is the difference between these 2 ASP.NET controls? What are the advantages or disadvantages of both? Is one any faster? Newer? Easier to maintain?

The intellisense summary for the controls doesn't seem to describe any difference between the two. They both can view, edit, and sort data and automatically generate columns at runtime.

Edit: Visual Studio 2008 no longer lists DataGrid as an available control in the toolbox. It is still available (for legacy support I assume) if you type it in by hand though.

[A] The DataGrid was originally in .NET 1.0.  The GridView was introduced (and replaced the DataGrid) in .NET 2.0.  They provide nearly identical functionality.


q:
I want to convert a primitive to a string, and I tried:

myInt.toString();

This fails with the error:

int cannot be dereferenced

Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods.  However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point).  So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that.

Furthermore, I believe C# allows such a call, unless I remember incorrectly.  Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?

[A]
Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows
```
myInt
```
as a primitive.  There's a paper about this issue at
jcp.org
.
Autoboxing is mainly useful during assignment or parameter passing -- allowing you to pass a primitive as an object (or vice versa), or assign a primitive to an object (or vice versa).
So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way)
```
```
Integer.toString(myInt);
```
```


q: I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished.  How do I figure out the PID of the process that spawned it?

[A]
You should pass self() to the child as one of the arguments to the entry function.
```
```
spawn_link(?MODULE, child, [self()]).
```
```


q:
I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation.

In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array).

A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value.  Since it is not physically possibly to store all values in memory, I need to store only the few non-zero elements. This could be several million entries.

Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime.

I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?

[A]
For C++, a map works well.  Several million objects won't be a problem.  10 million items took about 4.4 seconds and about 57 meg on my computer.
My test application is as follows:
```
```
#include <stdio.h>
#include <stdlib.h>
#include <map>

class triple {
public:
    int x;
    int y;
    int z;
    bool operator<(const triple &other) const {
        if (x < other.x) return true;
        if (other.x < x) return false;
        if (y < other.y) return true;
        if (other.y < y) return false;
        return z < other.z;
    }
};

int main(int, char**)
{
    std::map<triple,int> data;
    triple point;
    int i;

    for (i = 0; i < 10000000; ++i) {
        point.x = rand();
        point.y = rand();
        point.z = rand();
        //printf("%d %d %d %d\n", i, point.x, point.y, point.z);
        data[point] = i;
    }
    return 0;
}
```
```
Now to dynamically choose the number of variables, the easiest solution is to represent
index as a string
, and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index  will look like "34,45,56". A simple implementation of this technique is as follows:
```
```
std::map data<string,int> data;
char ix[100];

sprintf(ix, "%d,%d", x, y); // 2 vars
data[ix] = i;

sprintf(ix, "%d,%d,%d", x, y, z); // 3 vars
data[ix] = i;
```
```


q:
Is it "acceptable" to have an ASP.Net 2.0 application without the BLL (Business Logic Layer) as the following?

SQL Server Data Storage & Stored Procedures

Data Link Layer (Strongly Typed Table Adapters) connecting to Stored Procs

Presentation Layer ASPX Pages with Code behind and ObjectDataSource for connection straight to the DLL

Is a BLL always preferable, even if business logic is entirely validatable in the presentation's code behind?  What are the potential drawbacks for not using a BLL?

[A]
Like everything else it is environmental and depends on the use of the system.  The question you need to ask your self is:
Will this be actively developed
Is this going to be used over the course of many years and expanded on
Is the expansion of the application unknown and thus infinite
Really it comes down to laziness.  How much time to do you want to spend reworking the system from the UI?  Because having no business layer means duplication of rules in your UI across possibility many many pages.
Then again if this is a proof of concept or short demo or class project.  Take the easy way out.


q:
Any suggestions?  Using visual studio in C#.

Are there any specific tools to use or methods to approach this?

Update:

Sorry, I should have been a little more specific. I am using ASP.Net 2.0 and was looking more for a tool like jUnit for Java. I took a look at NUnit and NUnitAsp and that looks very promising. And I didn't even know that Visual Studio Pro has a testing suite, so I'll look at all of these options (I've just started using Visual Studio/Asp.net/C# this summer).

[A]
Boy, that's a pretty general question.  I'll do my best, but be prepared to see me miss by a mile.
Assumptions
You are using ASP.NET, not plain ASP
You don't really want to test your web pages, but the
logic
behind them. Unit testing the actual .ASPX pages is rather painful, but there are frameworks out there to do it.
NUnitAsp
is one.
The first thing to do is to organize (or plan) your code so that it can be tested.  The two most popular design patterns for this at the time seem to be MVP and MVC.  Both separate the
logic
of the application away from the
view
so that you can test the logic without the view (web pages) getting in your way.
Either MVP or MVC will be effective.  MVC has the advantage of having a Microsoft framework
almost ready to go
.
Once you've selected a framework pattern that encourages testability, you need to use a unit testing tool.
NUnit
is a good starting point.  Visual Studio Professional has a
testing suite built it
, but NUnit +
TestDrive.NET
also works in the IDE.
That's sort of a shotgun blast of information.  I hope some if it hits.  The Pragmatic Bookshelf has a
good book covering the topic
.


q: I lost my MySQL username and password. How do I retrieve it?

[A]
Stop the MySQL process.
Start the MySQL process with the --skip-grant-tables option.
Start the MySQL console client with the -u root option.
List all the users;
```
```
SELECT * FROM mysql.user;
```
```
Reset password;
```
```
UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';
```
```
But
DO NOT FORGET
to
Stop the MySQL process
Start the MySQL Process normally (i.e. without the --skip-grant-tables option)
when you are finished.  Otherwise, your database's security could be compromised.


q:
How can I drop all tables whose names begin with a given string?

I think this can be done with some dynamic SQL and the INFORMATION_SCHEMA tables.

[A]
```
```
SELECT 'DROP TABLE "' + TABLE_NAME + '"'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
```
```
This will generate a script.
Adding clause to check existence of table before deleting:
```
```
SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;'
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME LIKE '[prefix]%'
```
```


q: I am walking through the MS Press Windows Workflow Step-by-Step book and in chapter 8 it mentions a tool with the filename "wca.exe".  This is supposed to be able to generate workflow communication helper classes based on an interface you provide it.  I can't find that file.  I thought it would be in the latest .NET 3.5 SDK, but I just downloaded and fully installed, and it's not there.  Also, some MSDN forum posts had links posted that just go to 404s.  So, where can I find wca.exe?


q:
The firewall I'm behind is running Microsoft ISA server in NTLM-only mode. Hash anyone have success getting their Ruby gems to install/update via Ruby SSPI gem or other method?

... or am I just being lazy?

Note: rubysspi-1.2.4 does not work.

This also works for "igem", part of the IronRuby project

[A]
A workaround is to install
http://web.archive.org/web/20060913093359/http://apserver.sourceforge.net:80/
on your local machine, configure it and run gems through this proxy.
Install: Just download apserver 097 (and not the experimental 098!) and unpack.
Configure: Edit the server.cfg file and put the values for your MS proxy in
```
PARENT_PROXY
```
and
```
PARENT_PROXY_PORT
```
. Enter the values for DOMAIN and USER. Leave PASSWORD blank (nothing after the colon) – you will be prompted when launching it.
Run apserver:
```
cd aps097; python main.py
```
Run Gems:
```
gem install—http-proxy http://localhost:5865/ library
```


q:
Let's say that there is a solution that contains two projects (Project1 and Project2).

Project1 is set as a StartUp Project (its name is displayed in a bold font). I double-click some file in Project2 to open it. The file opens, but something else happens too - Project2 gets set as a StartUp Project.

I tried to find an option in configuration to change it, but I found none.

Can this feature (though it's more like a bug to me) be disabled?

[A]
The way to select a startup project is described in
Sara Ford's blog "Visual Studio Tip of the Day
" (highly recommended). She has a post there about
setting up StartUp projects
. Essentially there are 2 ways, the easiest one being right-clicking on the desired project, and choosing "Set As StartUp Project". That prevents other projects from becoming the StartUp project, even if you click on one their files.


q:
I'm writing a resource handling method where I control access to various files, and I'd like to be able to make use of the browser's cache.  My question is two-fold:

Which are the definitive HTTP headers that I need to check in order to know for sure whether I should send a 304 response, and what am I looking for when I do check them?

Additionally, are there any headers that I need to send when I initially send the file (like 'Last-Modified') as a 200 response?

Some psuedo-code would probably be the most useful answer.

What about the cache-control header?  Can the various possible values of that affect what you send to the client (namely max-age) or should only if-modified-since be obeyed?

[A]
You should send a 304 if the client has explicitly stated that it may already have the page in its cache. This is called a conditional GET, which should include the
if-modified-since
header in the request.
Basically, this request header contains a date from which the client claims to have a cached copy. You should check if content has changed after this date and send a 304 if it hasn't.
See
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25
for the related section in the RFC.


q: How do I generate an ETag HTTP header for a resource file?

[A]
An etag is an arbitrary string that the server sends to the client that the client will send back to the server the next time the file is requested.
The etag should be computable on the server based on the file.  Sort of like a checksum, but you might not want to checksum every file sending it out.
```
```
server                client

        <------------- request file foo

 file foo etag: "xyz"  -------->

        <------------- request file foo
                       etag: "xyz" (what the server just sent)

 (the etag is the same, so the server can send a 304)
```
```
I built up a string in the format "datestamp-file size-file inode number".  So, if a file is changed on the server after it has been served out to the client, the newly regenerated etag won't match if the client re-requests it.
```
```
char *mketag(char *s, struct stat *sb)
{
    sprintf(s, "%d-%d-%d", sb->st_mtime, sb->st_size, sb->st_ino);
    return s;
}
```
```


q:
Does anyone remember the XMP tag?

What was it used for and why was it deprecated?

[A]
A quick Google search on W3C reveals that
```
XMP
```
was introduced for displaying
preformatted text
in HTML 3.2 and earlier. When W3C deprecated the
```
XMP
```
tag, it suggested using the
```
PRE
```
tag as a preferred alternative.
Update:
http://www.w3.org/TR/REC-html32#xmp
,
http://www.w3.org/MarkUp/html-spec/html-spec_5.html#SEC5.5.2.1


q:
I'm talking about http://en.wikipedia.org/wiki/Quality_of_service. With streaming stackoverflow podcasts and downloading the lastest updates to ubuntu, I would like to have QoS working so I can use stackoverflow without my http connections timing out or taking forever.

I'm using an iConnect 624 ADSL modem which has QoS built-in but I can't seem to get it to work. Is it even possible to control the downstream (ie. from ISP to your modem)?

[A]
I don't know if this will help you, but I've never been a fan of using the ISP provided box directly. Personally I use a
Linksys wrt54gl
, with
DD-wrt
, behind(DMZ) my ISP provided box.
DD-wrt has excellent QoS management.
Sorry I can't be more help with your existing hardware.


q:
How is it possible to make prototype methods in C#.Net?

In JavaScript, I can do the following to create a trim method for the string object:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

How can I go about doing this in C#.Net?

[A]
You need to create an extension method, which requires .NET 3.5. The method needs to be static, in a static class. The first parameter of the method needs to be prefixed with "this" in the signature.
```
```
public static string MyMethod(this string input)
{
    // do things
}
```
```
You can then call it like
```
```
"asdfas".MyMethod();
```
```


q:
Is CompileAssemblyFromDom faster than CompileAssemblyFromSource?

It should be as it presumably bypasses the compiler front-end.

[A]
I've tried finding the ultimate compiler call earlier and I gave up. There's quite a number of layers of interfaces and virtual classes for my patience.
I don't think the source reader part of the compiler ends up with a DOM tree, but intuitively I would agree with you. The work necessary to transform the DOM to IL should be much less than reading C# source code.


q: What is the complete and correct syntax for the SQL Case expression?

[A]
The
complete
syntax depends on the database engine you're working with:
For SQL Server:
```
```
CASE case-expression
    WHEN when-expression-1 THEN value-1
  [ WHEN when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END
```
```
or:
```
```
CASE
    WHEN boolean-when-expression-1 THEN value-1
  [ WHEN boolean-when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END
```
```
expressions, etc:
```
```
case-expression    - something that produces a value
when-expression-x  - something that is compared against the case-expression
value-1            - the result of the CASE statement if:
                         the when-expression == case-expression
                      OR the boolean-when-expression == TRUE
boolean-when-exp.. - something that produces a TRUE/FALSE answer
```
```
Link:
CASE (Transact-SQL)
Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and
the first one that matches is used
.
Note
: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be
NULL
.


q:
I am currently aware that ASP.NET 2.0 is out and about and that there are 3.x versions of the .Net Framework.

Is it possible to upgrade my ASP.NET web server to version 3.x of the .Net Framework?

I have tried this, however, when selecting which version of the .Net framwork to use in IIS (the ASP.NET Tab), only version 1.1 and 2.0 show.

Is there a work around?

[A]
Sure, download the 3.5 redistributable, install it on the servre, and you're good to go. .NET versions can be installed side-by-side, so it won't disrupt any "legacy" apps.
http://www.microsoft.com/downloads/details.aspx?FamilyId=333325FD-AE52-4E35-B531-508D977D32A6&displaylang=en


q:
I can do an eval("something()"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I am trying to do is: I have an integer variable (say i) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc.
Now, I want to perform some operations on the " Propertyi " property depending on the value of i.

This is really simple with Javascript. Is there any way to do this with C#?

[A]
You can use reflection to get the property and invoke it. Something like this:
```
```
object result = theObject.GetType().GetProperty("Property" + i).GetValue(theObject, null);
```
```
That is, assuming the object that has the property is called "theObject" :)


q:
Example: I have two shared objects (same should apply to .dlls). The first shared object is from a third-party library, we'll call it libA.so. I have wrapped some of this with JNI and created my own library, libB.so. Now libB depends on libA.

When webstarting, both libraries are places in some webstart working area. My java code attempts to load libB. At this point the system loader will attempt to load libA which is not in the system library path (java.library.path won't help this). The end result is that libB has an unsatisfied link and cannot be used.

I have tried loading libA before libB, but that still does not work. Seems the OS wants to do that loading for me. Is there any way I can make this work other than statically  compiling?

[A]
I'm not sure if this would be handled exactly the same way for webstart, but we ran into this situation in a desktop application when dealing with a set of native libraries (dlls in our case).
Loading libA before libB should work, unless one of those libraries has a dependency that is unaccounted for and not in the path. My understanding is that once it gets to a system loadLibrary call (i.e. Java has found the library in its java.library.path and is now telling the OS to load it) - it is completely dependent on the operating system to find any dependent libraries, because at that point it is the operating system that is loading the library for the process, and the OS only knows how to look in the system path. That seems hard to set in the case of a Webstart app, but there is a way around this that does not involve static compiling. You may be able to shuffle where your libraries are - I am unsure
If you use a custom classloader, you can override loadLibrary and findLibrary so that it can locate your libraries from within a jar in your classpath, and if you also make it aware of your native library dependencies (i.e. libB depends on libA depends on libX, then when loading libB you can catch yourself and ensure you load libA first, and in checking that notice and load libX first. Then the OS doesn't try to find a library that isn't in your path. It's klunky and a bit painful, but ensuring Java finds them and loads them all in the correct order can work.


q:
How do you create your own custom moniker (or URL Protocol) on Windows systems?

Examples:

http:

mailto:

service:

[A]
Take a look at
Creating and Using URL Monikers
,
About Asynchronous Pluggable Protocols
and
Registering an Application to a URL Protocol
from MSDN


q: I have more than one OpenID as I have tried out numerous.  As people take up OpenID different suppliers are going to emerge I may want to switch provinders.  As all IDs are me, and all are authenticated against the same email address, shouldn't I be able to log into stack overflow with any of them and be able to hit the same account?

[A]
I think each site that implements OpenID would have to build their software to allow multiple entries for your OpenID credentials.  However, just because a site doesn't allow you to create multiple entries doesn't mean you can't swap out OpenID suppliers.
How to turn your blog into an OpenID
STEP 1: Get an OpenID. There a lots of servers and services out there you can use. I use
http://www.myopenid.com
STEP 2: Add these two lines to your blog's main template in-between the
```
<HEAD></HEAD>
```
tags at the top of your template. Most all blog engines support editing your template so this should be an easy and very possible thing to do.
Example:
```
<link rel="openid.server" href="http://www.myopenid.com/server" />
<link rel="openid.delegate" href=http://YOURUSERNAME.myopenid.com/ />
```
This will let you use your domain/blog  as your OpenID.
Credits to
Scott Hanselman
and
Simon Willison
for these simple instructions.
Switch Your Supplier
Now that your OpenID points to your blog, you can update your link rel href's to point to a new supplier and all the places that you've tied your blog's OpenID will use the new supplier.


q: The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?

[A]
Use the singleton module:
```
```
class Clazz
  include Singleton
end
```
```
See
http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html
for more info.


q:
I'm currently experimenting with build script, and since I have an ASP.net Web Part under source control, my build script should do that at the end:

Grab the "naked" Windows 2003 IIS VMWare or Virtual PC Image from the Network

Boot it up

Copy the Files from the Build Folder to the Server

Install it

Do whatever else is needed

I have never tried automating a Virtual Machine, but I saw that both VMWare and Virtual Server offer automation facilities. While I cannot use Virtual Server (Windows XP Home :-(), Virtual PC works.

Does anyone here have experience with either VMWare Server or Virtual PC 2007 SP1 in terms of automation?

Which one is better suited (I run windows, so the Platform-independence of VMWare does not count) and easier to automate?

[A]
With VMWare, there is the
Virtual Machine Automation APIs (VIX API)
.  You can find the reference guide
here
.  It works with VMWare Server and WorkStation, but AFAIK it's not available for ESX Server.
From the main page for VIX:
The VIX API allows you to write
  scripts and programs that automate
  virtual machine operations. The API is
  high-level, easy to use, and practical
  for both script writers and
  application programmers. It runs on
  VMware Server and Workstation
  products, both Windows and Linux.
  Bindings are provided for C, Perl, and
  COM (Visual Basic, VBscript, C#).


q:
I really feel that I should learn Lisp and there are plenty of good resources out there to help me do it.

I'm not put off by the complicated syntax, but where in "traditional commercial programming" would I find places it would make sense to use it instead of a procedural language.

Is there a commercial killer-app out there that's been written in Lisp ?

[A]
complicated syntax
??
The syntax for lisp is
incredibly simple
.
Killer app written in lisp:
emacs
.  Lisp will allow you to extend emacs at will to do almost anything you can think of that an editor might do.
But
, you should only learn lisp if you
want
to, and you may never get to use at work ever, but it is still awesome.
Also, I want to add: even if you find places where lisp will make sense, you will probably not convince anyone else that it should be used over java, c++, c#, python, ruby, etc.


q:
I'm developing a data access component that will be used in a website that contains a mix of classic ASP and ASP.NET pages, and need a good way to manage its configuration settings.

I'd like to use a custom ConfigurationSection, and for the ASP.NET pages this works great.  But when the component is called via COM interop from a classic ASP page, the component isn't running in the context of an ASP.NET request and therefore has no knowledge of web.config.

Is there a way to tell the ConfigurationManager to just load the configuration from an arbitrary path (e.g. ..\web.config if my assembly is in the /bin folder)?  If there is then I'm thinking my component can fall back to that if the default ConfigurationManager.GetSection returns null for my custom section.

Any other approaches to this would be welcome!

[A]
Try this:
```
```
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
```
```


q:
How much database performance overhead is involved with using C# and LINQ compared to custom optimized queries loaded with mostly low-level C, both with a SQL Server 2008 backend?

I'm specifically thinking here of a case where you have a fairly data-intensive program and will be doing a data refresh or update at least once per screen and will have 50-100 simultaneous users.

[A]
Have you tried removing the SSP using the command line? I found this worked once when we had a broken an SSP and just wanted to get rid of it.
The command is:
```
```
stsadm.exe -o deletessp -title <sspname> [-deletedatabases]
```
```
The
```
deletedatbases
```
switch is optional.
Also, check in Central Administration under Job Definitions and Job Schedules to ensure no SSP related jobs are still running


q:
In a installation of WebSphere Application Server with Network Deployment, a node is:

a physical machine

an instance of operative system

a logical set of WAS instances that is independent of physical machine or OS instance

[A]
@ggasp Here is what I got off IBM's Information Center
A node is a logical grouping of managed servers.
A node usually corresponds to a logical or physical computer system with a distinct IP host address. Nodes cannot span multiple computers.
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/cagt_node.html


q:
I've written (most of) an application in Flex and I am concerned with protecting the source code. I fired up a demo of Trillix swf decompiler and opened up the swf file that was installed to my Program Files directory. I saw that all of the actionscript packages I wrote were there. I'm not too concerned with the packages, even though there is a substantial amount of code, because it still seems pretty unusable without the mxml files. I think they are converted to actionscript, or atleast I hope. However, I would still like to explore obfuscation.

Does anyone have any experience with Flash / Actionscript 3 / Flex obfuscators? Can you recommend a good product?

[A]
Here's what I would do.
Compile your application to a SWF file. Then encrypt the SWF using AES.
Make a "wrapper" application that loads the encrypted SWF into a ByteArray using URLLoader
Use the
as3crypto
library to decrypt the swf at runtime.
Once decrypted, use Loader.loadBytes to load the decrypted swf into the wrapper application.
This will make it a lot harder to get your code. Not impossible, but harder.
For AIR applications you could leave the SWF encrypted when delivering the application to the end-user. Then you could provide a registration key that contains the key used to decrypt the SWF.
Also, here is a link to an AS3 obfuscator. I am not sure how well it works though.
http://www.ambiera.com/irrfuscator/index.html


q: How do you resolve a domain name to an IP address with .NET/C#?

[A]
```
```
using System.Net;

foreach (IPAddress address in Dns.GetHostAddresses("www.google.com"))
{
   Console.WriteLine(address.ToString());
}
```
```


q:
I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys.

Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers(ALT+CTRL+SHIFT). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to.

Does anyone have any ideas or suggestions on where I should go with this?

[A]
Within your overridden ProcessCmdKey how are you determining which key has been pressed?
The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181.
You can extract the modifiers and the key pressed by ANDing with appropriate enum values:
```
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    bool shiftPressed = (keyData & Keys.Shift) != 0;
    Keys unmodifiedKey = (keyData & Keys.KeyCode);

    // rest of code goes here
}
```
```


q:
We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff.  We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed.  Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details.

Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?


q: When developing whether its Web or Desktop at which point should a developer switch from SQLite, MySQL, MS SQL, etc

[A]
It depends on what you are doing. You might switch if:
You need more scalability or better performance - say from SQLite to SQL Server or Oracle.
You need access to more specific datatypes.
You need to support a customer that only runs a particular database.
You need better DBA tools.
Your application is using a different platform where your database no longer runs, or it's libraries do not run.
You have the ability/time/budget to actually make the change. Depending on the situation, the migration could be a bigger project than everything in the project up to that point. Migrations like these are great places to introduce inconsistencies, or to lose data, so a lot of care is required.
There are many more reasons for switching and it all depends on your requirements and the attributes of the databases.


q:
I'm using ColdFusion to populate a template that includes HTML unordered lists (<ul>s).

Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns.

Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily?  It's not worth some over-complicated heavyweight solution to save some scrolling.

[A]
There is no pure CSS/HTML way to achieve this, as far as I know.  Your best bet would be to do it in pre-processing (
```
if list length > 150, split into 3 columns, else if > 70, split into  2 columns, else 1
```
).
The other option, using JavaScript (I'm not familiar with the
jQuery
library specifically) would be to iterate through lists, probably based on them being a certain class, count the number of children, and if it is a high  enough number, dynamically create a new list after the first, transferring some number of list items to the new list.  As far as implementing the columns, you could probably float them left, followed by an element that had the style
```
clear: left
```
or
```
clear: both
```
.
```
```
.column {
  float: left;
  width: 50%;
}
.clear {
  clear: both;
}
```
```
```
```

Item 1

Item 2

Item 49

Item 50

Item 51

Item 52

Item 99

Item 100

```
```


q:
I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something.

For what do you use regular expressions?

P.S. sorry for my bad english

[A]
A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as
```
*.txt
```
to find all text files in a file manager. The regex equivalent is
```
.*\.txt$
```
.
A great resource for regular expressions:
http://www.regular-expressions.info


q:
I am currently creating a master ddl for our database.  Historically we have used backup/restore to version our database, and not maintained any ddl scripts.  The schema is quite large.

My current thinking:

Break script into parts (possibly in separate scripts):

table creation

add indexes

add triggers

add constraints

Each script would get called by the master script.

I might need a script to drop constraints temporarily for testing

There may be orphaned tables in the schema, I plan to identify suspect tables.

Any other advice?

Edit: Also if anyone knows good tools to automate part of the process, we're using MS SQL 2000 (old, I know).

[A]
What you have there seems to be pretty good. My company has on occasion, for large enough databases, broken it down even further, perhaps to the individual object level. In this way each table/index/... has its own file. Can be useful, can be overkill. Really depends on how you are using it.
@Justin
By domain is mostly always sufficient. I agree that there are some complexities to deal with when doing it this way, but that should be easy enough to handle.
I think this method provides a little more seperation (which in a large database you will come to appreciate) while still making itself pretty manageable. We also write Perl scripts that do a lot of the processing of these DDL files, so that might be an option of a good way to handle that.


q:
I have written an AIR Application that downloads videos and documents from a server. The videos play inside of the application, but I would like the user to be able to open the documents in their native applications.

I am looking for a way to prompt the user to Open / Save As on a local file stored in the Application Storage Directory. I have tried using the FileReference + URLRequest classes but this throws an exception that it needs a remote url.

My last resort is just copying the file to their desktop : \

[A]
Only way I could figure out how to do it without just moving the file and telling the user was to pass it off to the browser.
```
```
navigateToURL(new URLRequest(File.applicationStorageDirectory.nativePath + "/courses/" + fileName));
```
```


q:
I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto?

My dev box is OS X, production - Centos.

[A]
There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons.
Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (
http://httpd.apache.org/docs/2.0/howto/cgi.html
). At that point all you need to do is place your Python scripts in the cgi-bin directory and the standard output will become the HTTP response. Refer to Python's documentation for further info (
https://docs.python.org/library/cgi.html
).
If you want to use a web framework you'll need to setup mod_python or FastCGI. These steps are dependent on which framework you want to use. Django provides clear instructions on how to setup mod_python and Django with Apache (
http://www.djangoproject.com/documentation/modpython/
)


q:
I created a view on a machine using the substring function from Firebird, and it worked.  When I copied the database to a different machine, the view was broken.  This is the way I used it:

SELECT SUBSTRING(field FROM 5 FOR 15) FROM table;

And this is the output on the machine that does not accept the function:

token unknown:  FROM

Both computers have this configuration:

IB Expert version 2.5.0.42 to run the queries and deal with the database.

Firebird version 1.5 as server to database.

BDE Administration version 5.01 installed, with Interbase 4.0 drivers.

Any ideas about why it's behaving differently on these machines?

[A]
Different engine versions?
Have you tried naming that expression in the result?
```
```
SELECT SUBSTRING(field FROM 5 FOR 15) AS x FROM table;
```
```


q:
ASP.NET server-side controls postback to their own page.  This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain.

An HttpWebRequest works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post.

So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?

[A]
If you're using ASP.NET 2.0, you can do this with
cross-page posting
.
Edit: I missed the fact that you're asking about an
external
page.  For that I think you'd need to have your ASP.NET page gen up an HTML form whose action is set to the remote URL and method is set to POST.  (Using cross-page posting, this could even be a different page with no UI, only hidden form elements.)  Then add a bit of javascript to submit the form as soon as the postback result was received on the client.


q: What is the Java equivalent of PHP's $_POST? After searching the web for an hour, I'm still nowhere closer.

[A]
Your
```
HttpServletRequest
```
object has a
```
getParameter(String paramName)
```
method that can be used to get parameter values.
http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)


q:
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?

const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

[A]
I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't have a length method:
```
```
var element_count = 0;
for (e in myArray) {  if (myArray.hasOwnProperty(e)) element_count++; }
```
```
@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as "associative arrays".


q:
I am currently in the process of creating my own blog and I have got to marking up the comments, but what is the best way to mark it up?

The information I need to present is:

Persons Name

Gravatar Icon

Comment Date

The Comment

PS: I'm only interested in semantic HTML markup.

[A]
Here's one way you could do it with the following CSS to float the picture to the left of the contents:
```
```
.comment {
  width: 400px;
}

.comment_img {
  float: left;
}

.comment_text,
.comment_meta {
  margin-left: 40px;
}

.comment_meta {
  clear: both;
}
```
```
```
```

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed mauris. Morbi quis tellus sit amet eros ullamcorper ultrices. Proin a tortor. Praesent et odio. Duis mi odio, consequat ut, euismod sed, commodo vitae, nulla. Suspendisse potenti. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Etiam pede.

Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas rhoncus accumsan velit. Donec varius magna a est.

    By Name on 2008-08-21 11:32 AM

```
```


q:
Although I'm specifically interested in web application information, I would also be somewhat curious about desktop application development as well. This question is driven by my work on my personal website as well as my job, where I have developed a few features, but left it to others to integrate into the look and feel of the site.

Are there any guides or rules of thumb for things like color schemes, layouts, formatting, etc? I want to ensure readability and clarity for visitors, but not be bland and dull at the same time.

As for my knowledge in this area - If you hand me a picture, I have enough knowledge to reproduce it on the screen, but if you ask me to design a new interface or redesign an existing one, I wouldn't know where to begin.

[A]
Usually, each operating System has user Interface Guidelines. For Windows, have a
look here
. (Edit: The links in that post are broken. But a Search for "
User Interface Guidelines
" on MSDN has articles about everything)
Apple has it's own as well. Also, you may want to keep
accessibility
in mind.


q:
I have a self-referential Role table that represents a tree structure

ID [INT] AUTO INCREMENT
Name [VARCHAR]
ParentID [INT]

I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set:

dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID")))

And when I make new child rows in the DataTable I call the SetParentRow method

newRow.SetParentRow(parentRow)

Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter?

[A]
Does it make any difference if you go
```
```
newRow.SetParentRow(parentRow, RoleTable.Relations("RoleToRole"))
```
```


q:
It seems like every time I try to create a pure CSS layout it takes me much longer than if I'd use a table or two. Getting three columns to be equal lengths with different amounts of data seems to require particular fancy hacks, especially when dealing with cross-browser issues.

My Question:

Who are these few tables going to hurt?

Tables seem to work particularly well on tabular data — why are they so reviled in this day and age?

Google.com has a table in its source code, so do many other sites (stackoverflow.com does not by the way).

[A]
I'm of the thought that CSS layout with as few tables as possible is cleaner and better, but I agree that sometimes you just gotta use a table.
Business-wise, it's generally "what's going to get it done the fastest and most reliable way." In my experience, using a few tables generally falls into that category.
I have found that a very effective way to mitigate cross-browser differences in CSS rendering is to use the "strict" doctype at the top of your page:
```
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
```
```
Also, for the dreaded IE6 CSS issues, you can use this hack:
```
```
.someClass {
    background-color:black; /*this is for most browsers*/
    _background-color:white; /*this is for IE6 only - all others will ignore it*/
}
```
```


q:
I would have thought this would be an easy one to Google, but I've been unsucessful.

I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute.

Example:

<xsl:variable name="myId" select="@id" />
<xsl value-of select="//Root/Some/Other/Path/Where[@id='{@myId}']/@Name />

That does not work.  If I replace the {@myId} with the value that is in the variable then it does find the right node, but doign it this way produces nothing.  I'm sure I'm missing something, or perhaps there is a different way to do it.

The context is that there is related data under different top-level nodes that share the same id value so I need to get the related nodes in my template.

[A]
Ok, I finally figured it out.  Silly problem really, I simply needed to leave out the quotes and the braces.  One of those times when I
thought
that I'd already tried that.  :D  Oh, and I mistyped @myId in the first example, the code was actually $myId.
```
```
<xsl:variable name="myId" select="@id" />
<xsl value-of select="//Root/Some/Other/Path/Where[@id=$myId]/@Name" />
```
```


q: I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?


q:
When I try to print a Unicode string in a Windows console, I get an error .

UnicodeEncodeError: 'charmap' codec can't encode character ....

I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?
Is there any way I can make Python automatically print a ? instead of failing in this situation?

Edit:  I'm using Python 2.5.

Note: @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!

@JFSebastian answer is more relevant as of today (6 Jan 2016).

[A]
Note:
This answer is sort of outdated (from 2008). Please use the solution below with care!!
Here is a page that details the problem and a solution (search the page for the text
Wrapping sys.stdout into an instance
):
PrintFails - Python Wiki
Here's a code excerpt from that page:
```
```
$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
    line = u"\u0411\n"; print type(line), len(line); \
    sys.stdout.write(line); print line'
  UTF-8
  <type 'unicode'> 2
  Б
  Б

  $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \
    sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \
    line = u"\u0411\n"; print type(line), len(line); \
    sys.stdout.write(line); print line' | cat
  None
  <type 'unicode'> 2
  Б
  Б
```
```
There's some more information on that page, well worth a read.


q: Is it worth learning the convention or is it a bane to readability and maintainability?

[A]
Considering that most people that use
Hungarian Notation
is following the misunderstood version of it, I'd say it's pretty pointless.
If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar.
If you read the
Wikipedia article
on the subject, you'll find two conflicting notations,
Systems Hungarian Notation
and
Apps Hungarian Notation
.
The original, good, definition is the
Apps Hungarian Notation
, but most people use the
Systems Hungarian Notation
.
As an example of the two, consider prefixing variables with l for length, a for area and v for volume.
With such notation, the following expression makes sense:
```
```
int vBox = aBottom * lVerticalSide;
```
```
but this doesn't:
```
```
int aBottom = lSide1;
```
```
If you're mixing the prefixes, they're to be considered part of the equation, and volume = area * length is fine for a box, but copying a length value into an area variable should raise some red flags.
Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this:
```
```
int iLength;
int iVolume;
int iArea;
```
```
some people use n for number, or i for integer, f for float, s for string etc.
The original prefix was meant to be used to spot problems in equations, but has somehow devolved into making the code slightly easier to read since you don't have to go look for the variable declaration. With todays smart editors where you can simply hover over any variable to find the full type, and not just an abbreviation for it, this type of hungarian notation has lost a lot of its meaning.
But, you should make up your own mind. All I can say is that I don't use either.
Edit
Just to add a short notice, while I don't use
Hungarian Notation
, I do use a prefix, and it's the underscore. I prefix all private fields of classes with a _ and otherwise spell their names as I would a property, titlecase with the first letter uppercase.


q:
This is how I wanted to do it which would work in PHP 5.3.0+

<?php
    class MyClass
    {
        const CONSTANT = 'Const var';
    }

    $classname = 'MyClass';
    echo $classname::CONSTANT; // As of PHP 5.3.0
?>

But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?

[A]
If you absolutly need to access a constant like that, you can do this:
```
```
<?php
class MyClass
{
        const CONSTANT = 'Const var';
}

$classname = 'MyClass';
echo eval( 'return '.$classname.'::CONSTANT;' );
?>
```
```
But, if i were you, I'd try not to use eval.


q:
I'm using IIS in Windows 2003 Server for a SharePoint intranet.
External incoming requests will be using the host header portal.mycompany.com and be forced to use SSL.

I was wondering if there's a way to set up an alternate host header such as
http://internalportal/
which only accepts requests from the internal network, but doesn't force the users to use SSL.

Any recommendations for how to set this up?

[A]
Assuming that
http://internalportal/
wasn't accessible from outside the company, you could set up two websites in IIS. The first site, configured to use a host header value of 'portal.mycompany.com', would require SSL. The second site, configured to use a host header value of 'internalportal', would not require SSL. The host header value is configured under 'Web Site' -> 'Advanced'.
Having a hardware load balancer makes things much easier. The site on the load balancer is set up to require SSL, and your websites in IIS are setup not to require SSL.