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

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

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

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


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

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


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

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

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


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

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


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

"Articles (ArticleID, ArticleTitle, ArticleContent)"

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

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

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


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

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

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


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

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

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


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

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


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

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


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

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


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

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

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

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


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

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

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


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

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


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

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


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

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

How to get IntelliSense to reliably work in Visual Studio 2008

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

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


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

Private Sub Command1_Click(Index As Integer)

   Text1(Index).Text = Timer

End Sub

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

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


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

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

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

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

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

Thanks.

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


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

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

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

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

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

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


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

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

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

{apple => 1, banana => 2}

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

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


Question:
I'm looking for a good way to perform multi-row inserts into an Oracle 9 database.  The following works in MySQL but doesn't seem to be supported in Oracle.

INSERT INTO TMP_DIM_EXCH_RT
(EXCH_WH_KEY,
 EXCH_NAT_KEY,
 EXCH_DATE, EXCH_RATE,
 FROM_CURCY_CD,
 TO_CURCY_CD,
 EXCH_EFF_DATE,
 EXCH_EFF_END_DATE,
 EXCH_LAST_UPDATED_DATE)
VALUES
    (1, 1, '28-AUG-2008', 109.49, 'USD', 'JPY', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
    (2, 1, '28-AUG-2008', .54, 'USD', 'GBP', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
    (3, 1, '28-AUG-2008', 1.05, 'USD', 'CAD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
    (4, 1, '28-AUG-2008', .68, 'USD', 'EUR', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
    (5, 1, '28-AUG-2008', 1.16, 'USD', 'AUD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008'),
    (6, 1, '28-AUG-2008', 7.81, 'USD', 'HKD', '28-AUG-2008', '28-AUG-2008', '28-AUG-2008');

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


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

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


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

Display the base name 'f'

Perform an action on 'f.in'

Perform another action on 'f.out'

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

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


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

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

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

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


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

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

Answer:
System.Web.
```
```
HttpContext.Current.Handler
HttpContext.Current.Request.Server.Transfer
```
```


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

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


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

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

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


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

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

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

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


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

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


Question: Is it possible to cache database connections when using PHP like you would in a J2EE container?  If so, how?

Answer:
You cannot instantiate connection pools manually.
But you can use the "built in" connection pooling with the
mysql_pconnect
function.


Question:
From a web developer point of view, what changes are expected in the development arena when Google Chrome is released?

Are the developments powerful enough to make another revolution in the web? Will the way we see web programming change?

Or is it just another web browser?

Answer:
I think this is just another web browser. The most impact I expect to be improved Javascript performance, and the usability perspective. The first will benefit developers, especially when using Google Gears. I think the users will benefit the most from an enhanced user experience, the safety features, and ease of use.
I can only hope other browser vendors (MS) will follow Mozilla and Google to create a faster Javascript implementation, since this is the only thing that can truly impact web development.


Question: Things like $log$ and $version$ which add data upon check-in to the file. I'm interested in seeing the other ones and what information they can provide, but I can't get much info unless I know what they are called.

Answer:
Both Subversion and CVS call them
```
Keywords
```
.
Have a look in the SVN manual here
(scroll down to
svn:keywords
) or
here for CVS
.


Question:
Is a GUID unique 100% of the time?

Will it stay unique over multiple threads?

Answer:
While each generated GUID is not
guaranteed to be unique, the total
number of unique keys (2
128
or
3.4×10
38
) is so large that the probability of the same number being
generated twice is very small. For
example, consider the observable
universe, which contains about 5×10
22
stars; every star could then have
6.8×10
15
universally unique GUIDs.
From
Wikipedia
.
These are some good articles on how a GUID is made (for .NET) and how you could get the same guid in the right situation.
https://ericlippert.com/2012/04/24/guid-guide-part-one/
https://ericlippert.com/2012/04/30/guid-guide-part-two/
https://ericlippert.com/2012/05/07/guid-guide-part-three/


Question: Here's my scenario - I have an SSIS job that depends on another prior SSIS job to run. I need to be able to check the first job's status before I kick off the second one. It's not feasible to add the 2nd job into the workflow of the first one, as it is already way too complex. I want to be able to check the first job's status (Failed, Successful, Currently Executing) from the second one's, and use this as a condition to decide whether the second one should run, or wait for a retry. I know this can be done by querying the MSDB database on the SQL Server running the job. I'm wondering of there is an easier way, such as possibly using the WMI Data Reader Task? Anyone had this experience?

Answer:
You may want to create a third package the runs packageA and then packageB.  The third package would only contain two execute package tasks.
http://msdn.microsoft.com/en-us/library/ms137609.aspx
@Craig
A status table is an option but you will have to keep monitoring it.
Here is an article about events in SSIS for you original question.
http://www.databasejournal.com/features/mssql/article.php/3558006


Question:
I have an SQL query that takes the following form:

UPDATE foo
SET flag=true
WHERE id=?

I also have a PHP array which has a list of IDs. What is the best way to accomplish this other than with parsing, as follows, ...

foreach($list as $item){
    $querycondition = $querycondition . " OR " . $item;
}

... and using the output in the WHERE clause?

Answer:
You should be able to use the IN clause (assuming your database supports it):
```
UPDATE foo
SET flag=true
WHERE id in (1, 2, 3, 5, 6)
```


Question:
I have an actionscript file that defines a class that I would like to use inside a Flex application.

I have defined some custom controls in a actionscript file and then import them via the application tag:

<mx:Application
    xmlns:mx="http://www.adobe.com/2006/mxml"
    xmlns:scorecard="com.apterasoftware.scorecard.controls.*"
...
</mx:Application>

but this code is not a flex component, rather it is a library for performing math routines, how do I import this class?

Answer:
You'd need to import the class inside a script tag.
```
```
<mx:Application
  xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Script>
    import com.apterasoftware.scorecard.controls.*;
    // Other imports go here

    // Functions and other code go here
  </mx:Script>

  <!-- Components and other MXML stuff go here -->
  <mx:VBox>
    <!-- Just a sample -->
  </mx:VBox>
</mx:Application>
```
```
Then you'll be able to reference that class anywhere else in your script tag.  Depending on how the class is written you may not be able to use binding within the MXML, but you could define your own code to handle that.
Namespace declarations are only used to import other MXML components.  AS classes are imported using the import statement either within a Script block or another AS file.


Question: What data structures would you use to represent a chessboard for a computer chess program?

Answer:
The simple approach is to use an 8x8 integer array. Use 0 for empty squares and assign values for the pieces:
```
```
1 white pawns
2 white knights
3 white bishops
4 white rooks
5 white queens
6 white king

Black pieces use negative values
-1 black pawn
-2 black knight
etc

8| -4 -2 -3 -5 -6 -3 -2 -4
7| -1 -1 -1 -1 -1 -1 -1 -1
6|  0  0  0  0  0  0  0  0
5|  0  0  0  0  0  0  0  0
4|  0  0  0  0  0  0  0  0
3|  0  0  0  0  0  0  0  0
2|  1  1  1  1  1  1  1  1
1|  4  2  3  5  6  3  2  4
  -------------------------
   1  2  3  4  5  6  7  8
```
```
Piece moves can be calculated by using the array indexes. For example the white pawns move by increasing the row index by 1, or by 2 if it's the pawn's first move. So the white pawn on [2][1] could move to [3][1] or [4][1].
However this simple 8x8 array representation of has chessboard has several problems. Most notably when you're moving 'sliding' pieces like rooks, bishops and queens you need to constantly be checking the indexes to see if the piece has moved off the board.
Most chessprograms today, especially those that run on a 64 bit CPU, use a bitmapped approach to represent a chessboard and generate moves. x88 is an alternate board model for machines without 64 bit CPUs.


Question:
The IE Developer Toolbar is a plugin that can dock or separate from the browser. I understand its much more difficult to do this in IE than in Firefox.

How does one create an IE plugin?

What languages are available for this task?

How can I make a Hello World plugin?

Answer:
Here are a few resources that might help you in your quest to create browser helper objects (BHO).
http://petesearch.com/wiki/ (archived)
http://www.hackszine.com/blog/archive/2007/06/howto_port_firefox_extensions.html
http://msdn.microsoft.com/en-us/library/ms182554(VS.80).aspx
http://www.codeplex.com/TeamTestPlugins


Question: I want to use the  MultipleLookupField control in a web page that will run in the context of SharePoint. I was wondering if anyone would help me with an example, which shows step by step how to use the control two display two SPField Collections.

Answer:
I'm not entirely sure I understand your question, especially the bit about displaying two SPField collections. Sorry if this turns out to be the answer to a completely different question!
Anyway here's a quick demo walkthrough of using the MultipleLookupField in a web part.
Create a team site. Add a few tasks to the task list. Also put a document in the Shared Documents library. Create a new column in the Shared Documents library; call it "Related", have it be a Lookup into the Title field of the Tasks list, and allow multiple values.
Now create a web part, do all the usual boilerplate and then add this:
```
```
Label l;
MultipleLookupField mlf;

protected override void CreateChildControls()
{
    base.CreateChildControls();
    SPList list = SPContext.Current.Web.Lists["Shared Documents"];
    if (list != null && list.Items.Count > 0)
    {
        LiteralControl lit = new LiteralControl("Associate tasks to " +
                             list.Items[0].Name);
        this.Controls.Add(lit);

        mlf = new MultipleLookupField();
        mlf.ControlMode = SPControlMode.Edit;
        mlf.FieldName = "Related";
        mlf.ItemId = list.Items[0].ID;
        mlf.ListId = list.ID;
        mlf.ID = "Related";
        this.Controls.Add(mlf);

        Button b = new Button();
        b.Text = "Change";
        b.Click += new EventHandler(bClick);
        this.Controls.Add(b);

        l = new Label();
        this.Controls.Add(l);
    }

}

void bClick(object sender, EventArgs e)
{
    l.Text = "";
    foreach (SPFieldLookupValue val in (SPFieldLookupValueCollection)mlf.Value)
    {
        l.Text += val.LookupValue.ToString() + " ";
    }
    SPListItem listitem = mlf.List.Items[0];
    listitem["Related"] = mlf.Value;
    listitem.Update();
    mlf.Value = listitem["Related"];
}

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    EnsureChildControls();
}
```
```
Granted, this is borderline ridiculous -- everything is hard-coded, there is no error-handling at all, and it serves no useful purpose -- but it's only meant as a quick demo. Now build and deploy this web part and add an instance of it to your team site's homepage; it should allow you to get and set the tasks which are associated with the first document in the library.
The strange bit towards the end of the button Click handler, where we read a value from mlf.Value and then write it back again, appears to be required if you want the UI to stay in sync with the actual list values. Try omitting the last line of bClick to see what I mean. This has been driving me nuts for the last hour or so, and I'm hoping another commenter can come up with a better approach...


Question: I was looking at the API documentation for stl vector, and noticed there was no method on the vector class that allowed the removal of an element with a certain value. This seems like a common operation, and it seems odd that there's no built in way to do this.

Answer:
Use the global method std::remove with the begin and end iterator, and then use std::vector.erase to actually remove the elements.
Documentation links
std::remove
http://www.cppreference.com/cppalgorithm/remove.html
std::vector.erase
http://www.cppreference.com/cppvector/erase.html
```
```
std::vector<int> v;
v.push_back(1);
v.push_back(2);

//Vector should contain the elements 1, 2

//Find new end iterator
std::vector<int>::iterator newEnd = std::remove(v.begin(), v.end(), 1);

//Erase the "removed" elements.
v.erase(newEnd, v.end());

//Vector should now only contain 2
```
```
Thanks to Jim Buck for pointing out my error.


Question: Windows has a feature that allows an administrator to perform auto-logon whenever it is started. How can this feature be activated?

Answer:
Based on the advice, moved the answer to the answers section:
There are tools out there that give you a GUI for setting this easily, but you can also do it relatively easily by editing the registry.
Under the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
Add the following values:
DefaultDomainName     String  < domain-name >
DefaultUserName   String  < username >
DefaultPassword   String  < password >
AutoAdminLogon    String  1
Important: Using auto-logon is insecure and should, in general, never be used for standard computer configurations. The problem is not only that your computer is accessible to anyone with physical access to it, but also that the password is saved in plain-text in a well known location in your registry. This is usually used for test environments or for special setups. This is even more important to notice if you intend to perform auto-logon as an administrator.


Question: I'm getting a Connection Busy With Results From Another Command error from a SQLServer Native Client driver when a SSIS package is running. Only when talking to SQLServer 2000. A different part that talks to SQLServer 2005 seems to always run fine. Any thoughts?

Answer:
Microsoft KB article 822668
is relevant here:
FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query
Symptoms
Under stress conditions, you may receive the following error message when you perform linked server activity:
```
```
Server: Msg 7399, Level 16, State 1, Procedure <storedProcedureName>, Line 18 OLE DB provider 'SQLOLEDB' reported an error.
OLE/DB Provider 'SQLOLEDB' ::GetSchemaLock returned 0x80004005:

OLE DB provider SQLOLEDB supported the Schema Lock interface, but returned 0x80004005 for GetSchemaLock .].
OLE/DB provider returned message: Connection is busy with results for another command
OLE DB error trace [OLE/DB Provider 'SQLOLEDB' ::CreateSession returned 0x80004005.
```
```
Note
The OLE DB source of the error may vary. However, all variations of the error message include the text "Connection is busy with results for another command".
Resolution
To resolve this problem, obtain the latest service pack for Microsoft SQL Server 2000.
As noted there, the problem was first corrected in SQL Server 2000 Service Pack 4.
This blog post
by Mark Meyerovich, a Senior Software Engineer at RDA Corp, also provides some insight (now archived, because the original link went dead):
SQL Server service pack upgrade
A quick search on Google turns up the following article (
http://support.microsoft.com/kb/822668
):
  FIX: "Connection is busy with results for another command" error message occurs when you run a linked server query.
It basically implies the issue is a bug and recommends an upgrade to Service Pack 4. We have started out with SQL Server 2000 SP3 and we do have some linked servers in the equation, so we give it a try. After the upgrade to SP4 – same result.


Question:
I'm trying to boil down the concepts of coupling and cohesion to a concise definition. Can someone give me a short and understandable explanation (shorter than the definitions on Wikipedia here and here)? How do they interact?

Thanks.

Anybody have a good, short example?

Answer:
Coupling - A measure of how much a module (package, class, method) relies on other modules. It is desirable to reduce coupling, or reduce the amount that a given module relies on the other modules of a system.
Cohesion - A measure of how closely related the members (classes, methods, functionality within a method) of a module are to the other members of the same module. It is desirable to increase cohesion as that indicates that a module has a very specific task and does only that task.


Question:
In Python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals().  Is there some equivalent way of doing this in Javascript?  For instance, I would like to do something like the following:

var foo = function(){ alert('foo'); };
var bar = function(){ alert('bar'); };

var s = 'foo';
locals()[s](); // alerts 'foo'

Is this at all possible, or should I just be using a local object for the lookup?

Answer:
Well, I don't think that there is something like that in js. You can always use eval instead of locals(). Like this:
```
```
eval(s+"()");
```
```
You just have to know that actually function
foo
exists.
Edit:
Don't use eval:) Use:
```
```
var functionName="myFunctionName";
window[functionName]();
```
```


Question:
I know how to use tags in subversion. I create a tag every time I get to a release milestone.

What I don't quite understand is how they work.

Is a tag just a copy, made from what ever revision I specify? Or is a tag more like a reference, where internally subversion just says GO TO /trunk/project/ Revision 5 or whatever.

The command to create a tag (svn copy) seems to imply that it's a copy, but I've seen other people write that subversion doesn't really copy anything.

Say I dump just the HEAD revision of a repository. I don't care about any history except the tags. Are those tags dumped along with the rest of the Head revision?

Finally, is all this just programming magic that I don't really want to know.

Answer:
Right, a tag is just a copy:
```
```
svn copy trunk tags/BLAH
```
```
When people say SVN doesn't really copy anything, they mean that the repository doesn't need to duplicate the data. It uses something akin to symbolic links to keep track of the copies.


Question: How do I create a new webpage in the Documentum front end Webtop?

Answer:
Why WebTop?  You should use Web Publisher which is built on WebTop with the specific purpose of managing web content. Is this an OOTB installation?  Web Publisher / WebTop requires significant amount of customization in order to start being useful.  Do you have templates defined?  If so, then just go to File New and select your template.
http://www.dmdeveloper.com/
Is a good site with some very good how-to's.


Question: As the title says, is there a way to run the same Adobe AIR app more than once?  I have a little widget I wrote that shows thumbnails from a couple of photo streams, and I'd like to fix it so I can look at more than  one stream at a time.  Thanks!

Answer:
It seems that this is not possible. From the
documentation
:
Only one instance of an AIR application is started. When an already running application is invoked again, AIR dispatches a new invoke event to the running instance.
It also gives a possible workaround:
It is the responsibility of an AIR to respond to an invoke event and take the appropriate action (such as opening a new document window).
There is
already a bug
related to this on the bugtracker, but it is marked closed with no explicit resolution given...


Question:
How can I create a new database from my C# application?

I'm assuming once I create it, I can simply generate a connection string on the fly and connect to it, and the issue all the  CREATE TABLE statements.

Answer:
KB307283
explains how to create a database using ADO.NET.
From the article:
```
```
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");

str = "CREATE DATABASE MyDatabase ON PRIMARY " +
    "(NAME = MyDatabase_Data, " +
    "FILENAME = 'C:\\MyDatabaseData.mdf', " +
    "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
    "LOG ON (NAME = MyDatabase_Log, " +
    "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
    "SIZE = 1MB, " +
    "MAXSIZE = 5MB, " +
    "FILEGROWTH = 10%)";

SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
    MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
    if (myConn.State == ConnectionState.Open)
    {
        myConn.Close();
    }
}
```
```


Question:
Code below does not run correctly and throws InvalidOperationExcepiton.

public void Foo()
{
 DataContext context = new DataContext();
 LinqEntity item = new LinqEntity(){ Id = 1, Name = "John", Surname = "Doe"} ;
 context.LinqEntities.Attach(item, true);
}

Answer:
I'm not sure what you mean by disconnected from the database.
It appears that you are trying to insert a new row into the LinqEntities table -- is that correct?
If that is the case you'll want to do
```
```
context.LinqEntities.InsertOnSubmit(item);
context.Submit();
```
```


Question:
I am writing a few extensions to mimic the map and reduce functions in Lisp.

public delegate R ReduceFunction<T,R>(T t, R previous);
public delegate void TransformFunction<T>(T t, params object[] args);

public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial)
{
     var aggregate = initial;
     foreach(var t in list)
         aggregate = r(t,aggregate);

     return aggregate;
}
public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args)
{
    foreach(var t in list)
         f(t,args);
}

The transform function will cut down on cruft like:

foreach(var t in list)
    if(conditions && moreconditions)
        //do work etc

Does this make sense? Could it be better?

Answer:
I would use the built in Func delegates instead.  This same code would work on any IEnumerable.  Your code would turn into:
```
```
public static R Reduce<T,R>(this IEnumerable<T> list, Func<T,R> r, R initial)
{
     var aggregate = initial;
     foreach(var t in list)
         aggregate = r(t,aggregate);

     return aggregate;
}
public static void Transform<T>(this IEnumerable<T> list, Func<T> f)
{
    foreach(var t in list)
             f(t);
}
```
```


Question:
Is it true that the only way to handle default function arguments is through function overloading?

For example, in PHP I can do this:

function foo($x, $y=0)
{
}

Would the best way to handle it in C# be this?

void foo(int x)
{
  foo(x, 0);
}

void foo(int x, int y)
{
}

Example lifted from here

Edit

Made the C# example into actual C# (Thanks Blair Conrad)

Answer:
Yes, that'd be best
, except you'd omit the
```
$
```
s on the parameter names
, as others have pointed out. For those interested in the rationale behind the lack of default parameter values, see @Giovanni Galbo's explanation.


Question:
I've got an MS-Access app (1/10th MS-Acccess, 9/10ths MS-SQL) that needs to display photographs of some assets along with their specifications. Currently the images are stored in an MS-Access table as an OLE Object (and copy-n-pasted into the field by the users).

For various reasons, I would like to do is store the original .jpgs in a folder on the network drive, and reference them from the application portion. I have considered moving into MS-SQL's image data type (and its replacement varbinary), but I think my user population will more easily grasp the concept of the network folder.

How can I get MS Access to display the contents of a .jpg?

Answer:
The easiest way is probably to plop an Internet Explorer onto one of your forms. Check out this site:
http://www.acky.net/tutorials/vb/wbrowser/
Since you can reference that object in Access, you will only need to point the webbrowser control to the path of the .jpg (NavigateTo() if I remember correctly).
EDIT:
The above link was just googled and picked from the results (first one that opened quickly). I do not think it is a very good tutorial, it just has all the pointers you need... Check out msdn etc. if you need more information!


Question:
How do I get it to work with my project?

http://ajax.asp.net/

http://www.codeplex.com/AjaxControlToolkit/

Answer:
Install the ASP.NET AJAX Control Toolkit
Download the ZIP file
AjaxControlToolkit-Framework3.5SP1-DllOnly.zip
from the
ASP.NET AJAX Control
Toolkit Releases
page of the
CodePlex web site.
Copy the contents of this zip file
directly into the bin directory of
your web site.
Update web.config
Put this in your web.config under the <controls> section:
```
```
<?xml version="1.0"?>
<configuration>
    ...
    <system.web>
        ...
        <pages>
            ...
            <controls>
                ...
                <add tagPrefix="ajaxtoolkit"
                    namespace="AjaxControlToolkit"
                    assembly="AjaxControlToolKit"/>
            </controls>
        </pages>
        ...
    </system.web>
    ...
</configuration>
```
```
Setup Visual Studio
Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"
Inside that tab, right-click on the Toolbox and select "Choose Items..."
When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.
You can now use the controls in your web sites!


Question:
I'm trying to get a Firefox plugin to read data from a HTTP get, parse the results and present them as links in a bookmark-like drop-down menu.

My quesion then is: Does anyone have any sample code that will do this?

Answer:
Having never developed one myself, I'm not certain how this is typically done in Firefox plugins, but since plugin scripting is JavaScript, I can probably help out with the loading part. Assuming a variable named url containing the URL you want to request:
```
```
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);

xmlhttp.onreadystatechange = function() {
    if(this.readyState == 4) { // Done loading?
        if(this.status == 200) { // Everything okay?
            // read content from this.responseXML or this.responseText
        } else { // Error occurred; handle it
            alert("Error " + this.status + ":\n" + this.statusText);
        }
    }
};

xmlhttp.send(null);
```
```
A couple of notes on this code:
You may want more sophisticated status code handling. For example, 200 is not the only non-error status code. Details on status codes can be found
here
.
You probably want to have a timeout to handle the case where, for some reason, you don't get to readyState 4 in a reasonable amount of time.
You may want to do things when earlier readyStates are received.
This page
documents the readyState codes, along with other properties and methods on the XMLHttpRequest object which you may find useful.


Question:
I have a very strange problem. Under some elusive circumstances I fail to apply any jQuery selector on my pages under IE. It's OK under Firefox though. The jQuery function simply returns empty array.

Any suggestions?

Page is too complex to post it here. Practically any selector, except "#id" selectors, returns a zero element array. The jQuery version is 1.2.3

Answer:
What version(s) of IE is it failing under? Is it failing for a specific complex selector? I think we need an example.
Edit: Does the problem go away if you upgrade to 1.2.6? 1.2.6 is primarily a bug-fix release according to
this page
.
Failing that, the best way to find the problem is to create a minimum page that can reproduce the bug. Without that, it's just about impossible to troubleshoot.


Question:
Does C# have built-in support for parsing strings of page numbers?  By page numbers, I mean the format you might enter into a print dialog that's a mixture of comma and dash-delimited.

Something like this:

1,3,5-10,12

What would be really nice is a solution that gave me back some kind of list of all page numbers represented by the string.  In the above example, getting a list back like this would be nice:

1,3,5,6,7,8,9,10,12

I just want to avoid rolling my own if there's an easy way to do it.

Answer:
It doesn't have a built-in way to do this, but it would be trivial to do using String.Split.
Simply split on ',' then you have a series of strings that represent either page numbers or ranges. Iterate over that series and do a String.Split of '-'. If there isn't a result, it's a plain page number, so stick it in your list of pages. If there is a result, take the left and right of the '-' as the bounds and use a simple for loop to add each page number to your final list over that range.
Can't take but 5 minutes to do, then maybe another 10 to add in some sanity checks to throw errors when the user tries to input invalid data (like "1-2-3" or something.)


Question:
I infrequently (monthly/quarterly) generate hundreds of Crystal Reports reports using Microsoft SQL Server 2005 database views.  Are those views wasting CPU cycles and RAM during all the time that I am not reading from them?  Should I instead use stored procedures, temporary tables, or short-lived normal tables since I rarely read from my views?

I'm not a DBA so I don't know what's going on behind the scenes inside the database server.

Is it possible to have too many database views?  What's considered best practice?

Answer:
For the most part, it doesn't matter. Yes, SQL Server will have more choices when it parses SELECT * FROM table (it'll have to look in the system catalogs for 'table') but it's highly optimized for that, and provided you have sufficient RAM (most servers nowadays do), you won't notice a difference between 0 and 1,000 views.
However, from a people-perspective, trying to manage and figure out what "hundreds" of views are doing is probably impossible, so you likely have a lot of duplicated code in there. What happens if some business rules change that are embedded in these redundant views?
The main point of views is to encapsulate business logic into a pseudo table (so you may have a person table, but then a view called "active_persons" which does some magic). Creating a view for each report is kind of silly unless each report is so isolated and unique that there is no ability to re-use.


Question:
The ASP page gets data uses that to draw a graph, I then need to save the image created to JPEG to be displayed on the browser and also used in PDF and other format. What is the best way to compress the image? I am currently porting a JPEG compression library to ASP but I think it will be too slow on this ARM device running Windows CE 6.0.

So, the ASP page, running in Windows CE webservers, gets data, renders it into a bitmap image than then needs to be delivered to the browser accessing that ASP page. The same image is also used in PDF and one other proprietary format that can contain JPEG streams.

Edit:
What I am looking for is to way to create an array representing a bitmap and then compressing it to JPEG with ASP in Windows CE's IIS which has quite limited ASP implementation.

Answer:
I'm confused...
The images from ASP would be compressed on the server side--not client side.
I'm sure your web server is not running on Windows CE, so I don't think your concern is warranted.
EDIT:
Seems as though you can run a web server on Windows CE:
http://www.microsoft.com/windows/embedded/products/windowsce/default.mspx
.  I'll keep my thoughts to myself from now on. :-x


Question:
I've got to get a directory listing that contains about 2 million files, but when I do an ls command on it nothing comes back. I've waited 3 hours. I've tried ls | tee directory.txt, but that seems to hang forever.

I assume the server is doing a lot of inode sorting. Is there any way to speed up the ls command to just get a directory listing of filenames? I don't care about size, dates, permission or the like at this time.

Answer:
How about
```
find ./ -type f
```
(which will find all files in the currently directory)?  Take off the
```
-type f
```
to find everything.


Question:
I have a flag enum below.

[Flags]
public enum FlagTest
{
    None = 0x0,
    Flag1 = 0x1,
    Flag2 = 0x2,
    Flag3 = 0x4
}

I cannot make the if statement evaluate to true.

FlagTest testItem = FlagTest.Flag1 | FlagTest.Flag2;

if (testItem == FlagTest.Flag1)
{
    // Do something,
    // however This is never true.
}

How can I make this true?

Answer:
For bit operations, you need to use bitwise operators.
This should do the trick:
```
```
if ((testItem & FlagTest.Flag1) == FlagTest.Flag1)
{
    // Do something,
    // however This is never true.
}
```
```
Edit:
Fixed my if check - I slipped back into my C/C++ ways (thanks to Ryan Farley for pointing it out)


Question:
Is there an easy way to find the storage card's path on a Windows Mobile device
when there is a storage card and a bluetooth ftp connection?

Answer:
On Windows CE 5 (which is the base for Windows Mobile 6) the storage cards get mounted at the root file system as "Storage Card\", "Storage Card2\", etc.
To find out if it's mounted call GetFileAttributes (or the remote version CeGetFileAttributes I believe) passing in the full path ("\Storage Card\"). If it returns INVALID_FILE_ATTRIBUTES then it's not mounted, otherwise check to make sure it's a directory before returning true.


Question:
A client of mine has asked me to integrate a 3rd party API into their Rails app.  The only problem is that the API uses SOAP.  Ruby has basically dropped SOAP in favor of REST.  They provide a Java adapter that apparently works with the Java-Ruby bridge, but we'd like to keep it all in Ruby, if possible.  I looked into soap4r, but it seems to have a slightly bad reputation.

So what's the best way to integrate SOAP calls into a Rails app?

Answer:
Try
SOAP4R
SOAP4R
Getting Started with SOAP4R
And I just heard about this on the Rails Envy Podcast (ep 31):
WS-Deathstar SOAP walkthrough


Question:
I have an NFS-mounted directory on a Linux machine that has hung. I've tried to force an unmount, but it doesn't seem to work:

$ umount -f /mnt/data
$ umount2: Device or resource busy
$ umount: /mnt/data: device is busy

If I type "mount", it appears that the directory is no longer mounted, but it hangs if I do "ls /mnt/data", and if I try to remove the mountpoint, I get:

$ rmdir /mnt/data
rmdir: /mnt/data: Device or resource busy

Is there anything I can do other than reboot the machine?

Answer:
You might try a lazy unmount:
```
```
umount -l
```
```


Question: I am a member of all the roles (Browser, Content Manager, My Reports, Publisher, Report Builder). If I login with a Local Administrator account, I can see and use it fine. Any ideas?

Answer:
The first thing I would check is to make sure that your normal login is mapped to a role with the correct system-level permissions.  The item-level role definitions don't make a difference for the "Report Builder" button.
From the browser-based report manager interface:
Click "site settings"
In the Security section, click "Configure system-level role definitions"
Click the Role that you want to have this ability (e.g. "System Administrator" and "System User" are the default roles, but I believe that you can create your own if you want to).
Make sure that the "Execute Report Definitions" task is checked/selected.  This is the permission that controls whether or not the "Report Builder" button is displayed.
Click "OK" and then return to the "Site Settings" page.
In the Security section, click "Configure site-wide security"
Click "New Role Assignment" and then map your login (or an AD group to which your login belongs might be even better) to the system-level role you edited in the previous steps.
The forms are pretty straightforward, and I'd guess that your login just isn't mapped to the proper system-level role since you can see the button with the local administrator login.  If that doesn't work, you might check your IIS security settings for the report service to make sure that they're configured to use windows authentication (assuming that's what you're using in the first place).


Question: And why would I use one over the other in my code?

Answer:
Caution: This answer appears to be out of date.
It was posted before .NET 4 became available, which apparently introduced some optimizations regarding
```
Type
```
and thus rendered the information in this answer obsolete. See
this more recent answer
for details.
According to
this blog post (from 2006) by Vance Morrison
,
```
RuntimeTypeHandle
```
is a value type (
```
struct
```
) that wraps an unmanaged pointer, so
```
Type.GetTypeHandle(obj).Equals(anotherHandle)
```
is faster to use for strict "is exactly the same type" comparisons than
```
obj.GetType().Equals(anotherType)
```
— the latter creates
```
System.Type
```
instances which are, apparently, heavier.
However, it's also less obvious, and definitely falls under the category "micro-optimization" so if you're wondering when you need one over the other, you should probably just use System.Type.


Question:
Is it possible to handle POSIX signals within the Java Virtual Machine?

At least SIGINT and SIGKILL should be quite platform independent.

Answer:
Perhaps
Runtime#addShutdownHook
?


Question: I need to empty an LDF file before sending to a colleague.  How do I force SQL Server to truncate the log?

Answer:
In management studio:
Don't do this on a live environment, but to ensure you shrink your dev db as much as you can:
Right-click the database, choose
```
Properties
```
, then
```
Options
```
.
Make sure "Recovery model" is set to "Simple", not "Full"
Click OK
Right-click the database again, choose
```
Tasks
```
->
```
Shrink
```
->
```
Files
```
Change file type to "Log"
Click OK.
Alternatively, the SQL to do it:
```
```
ALTER DATABASE mydatabase SET RECOVERY SIMPLE
 DBCC SHRINKFILE (mydatabase_Log, 1)
```
```
Ref:
http://msdn.microsoft.com/en-us/library/ms189493.aspx


Question:
I have a List of Foo.

Foo has a string property named Bar.

I'd like to use LINQ to get a string[] of distinct values for Foo.Bar in List of Foo.

How can I do this?

Answer:
Try this:
```
```
var distinctFooBars = (from foo in foos
                       select foo.Bar).Distinct().ToArray();
```
```


Question:
I always thought Java uses pass-by-reference.

However, I've seen a blog post that claims that Java uses pass-by-value.

I don't think I understand the distinction they're making.

What is the explanation?

Answer:
Java is always pass by value, with no exceptions,
ever
.
So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java
never
provides direct access to the values of
objects themselves
, in
any
circumstances. The only access to objects is through a
reference
to that object. Because Java objects are
always
accessed through a reference, rather than directly, it is common to talk about fields and variables
and method arguments
as being
objects
, when pedantically they are only
references to objects
.
The confusion stems from this (strictly speaking, incorrect) change in nomenclature.
So, when calling a method
For primitive arguments (
```
int
```
,
```
long
```
, etc.), the pass by value is
the actual value
of the primitive (for example, 3).
For objects, the pass by value is the value of
the reference to the object
.
So if you have
```
doSomething(foo)
```
and
```
public void doSomething(Foo foo) { .. }
```
the two Foos have copied
references
that point to the same objects.
Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.


Question:
As the title already states, I'm trying to declare a nested function and return a pointer to that function. I want this function 'not' to return a new function pointer which will return the negation of whatever the original function was.

Here is what I have:

someType not( someType original ) {
    int isNot( ListEntry* entry ) {
        return !original( entry );
    }

    someType resultFunc = calloc( 1024, 1 );
    memcpy( resultFunc, &isNot, 1024 );

    return resultFunc;
}

someType is defined as:

typedef int(*someType)(ListEntry* entry)

Answer:
I'm using GCC.
You can turn on nested functions by using the flag:
```
```
-fnested-functions
```
```
when you compile.


Question:
I'm trying to call a function after I load some XML into Actionscript, and I'm just wondering how I call that function. Example:

//Function Declarations
function parentFunction()
{
    function callMe()
    {
     textField.text = "lawl";
    }
}

Now, how do I call the "callMe()" function in a different part of the code, like an onRelease function?

on(release)
{
callMe(); //doesn't work
parentFunction().callMe(); //doesn't work
parentFunction.callMe(); //doesn't work
}

ActionScript 2.0 is just so wonky! Any ideas?

Answer:
Are you forced to declare callMe inside of parentFunction?  I assume so because otherwise you would just do
function parent()  { }
function callMe()  { }
To be clear, a function can't own another function unless you provide some scope for that function to live in.
So in JavaScript, you would do this by using the prototype object to declare the callMe function as a method of the object that parentFunction returned.
http://www.howtocreate.co.uk/tutorials/javascript/objects
For ActionScript, read this article on Adobe's website:
http://www.adobe.com/devnet/flex/articles/as_collections_03.html
EDIT: After some more reading it appears the way you did things, you are actually declaring callMe as a
private
function.  See this article which should make the whole
private/public javascript issue
a lot more understandable.


Question:
Extreme Programming, Scrum and Test Driven Development definitely seem to be the most popular Agile methods at the moment. But someone recently suggested that I take a look at Feature Driven Development.

Have you ever used this method with any success? What are the advantages of using it?

Answer:
FDD is an older methodology. It has lot's of the ideas of other agile methodologies and misses some of them. Like Scrum it's a bit management-focussed and I think you need some elements from XP for practical implementations.
FDD is certainly interesting to look into. But just like Scrum and XP I think you have to understand the mechanics and not just implement the practices to be succesful. If you just "do FDD" or "do Scrum" you're not as adaptive as you should be.
The things I would look into if you want to understand agile would be
Scrum or FDD to understand what management can get out of agile.
XP to understand how enable agile from a technology perspective.
Crystal Clear to understand the communications aspects.
Lean Agile to get a completely different perspective on agile methodologies
I wouldn't call TDD an agile methodology by the way. It's an practice from XP but not a complete methodology per se.


Question: I need to determine if I'm on a particular view.  My use case is that I'd like to decorate navigation elements with an "on" class for the current view.  Is there a built in way of doing this?

Answer:
My current solution is with extension methods:
```
```
public static class UrlHelperExtensions
{
    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <typeparam name="TController">The type of the controller.</typeparam>
    /// <param name="helper">Url Helper</param>
    /// <param name="action">The action to check.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
    {
        MethodCallExpression call = action.Body as MethodCallExpression;
        if (call == null)
        {
            throw new ArgumentException("Expression must be a method call", "action");
        }

        return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
                typeof(TController) == helper.ViewContext.Controller.GetType());
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
        return IsAction(helper, actionName, controllerName);
    }

    /// <summary>
    /// Determines if the current view equals the specified action
    /// </summary>
    /// <param name="helper">Url Helper</param>
    /// <param name="actionName">Name of the action.</param>
    /// <param name="controllerName">Name of the controller.</param>
    /// <returns>
    ///     <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
    /// </returns>
    public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
    {
        if (String.IsNullOrEmpty(actionName))
        {
            throw new ArgumentException("Please specify the name of the action", "actionName");
        }
        if (String.IsNullOrEmpty(controllerName))
        {
            throw new ArgumentException("Please specify the name of the controller", "controllerName");
        }

        if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
        {
            controllerName = controllerName + "Controller";
        }

        bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
        return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
    }
}
```
```


Question:
Both the jQuery and Prototpye JavaScript libraries refuse to allow me to use a variable to select an list item element by index number although they accept a hard coded number.

For example, in Prototype this works:

$$('li')[5].addClassName('active');

But this will not work no matter how I try to cast the variable as a number or integer:

$$('li')[currentPage].addClassName('active');

In jQuery I get similar weirdness. This will work:

jQuery('li').eq(5).addClass("active");

But this will not work again even though the value of currentPage is 5 and its type is number:

jQuery('li').eq(currentPage).addClass("active");

I'm trying to create a JavaScript pagination system and I need to set the class on the active page button. The list item elements are created dynamically depending upon the number of pages I need.

Answer:
Are you certain that
```
currentPage
```
is an integer? Try something like:
```
```
var currentPage = 5;
jQuery('li').eq(currentPage);
```
```
as a simple sanity check. If that works, you should try casting to
```
Integer
```
.


Question:
I've been using PHP for too long, but I'm new to JavaScript integration in some places.

I'm trying to find the fastest way to pass database information into a page where it can be modified and displayed dynamically in JavaScript.

Right now, I'm looking at loading a JSON with PHP echo statements because it's fast and effective, but I saw that I could use PHP's JSON library (PHP 5.2).

Has anybody tried the new JSON library, and is it better than my earlier method?

Answer: Use the library. If you try to generate it manually, I predict with 99% certainty that the resulting text will be invalid in some way. Especially with more esoteric features like Unicode strings or exponential notation.


Question:
What are they and what are they good for?

I do not have a CS degree and my background is VB6 -> ASP -> ASP.NET/C#. Can anyone explain it in a clear and concise manner?

Answer:
Imagine if every single line in your program was a separate function. Each accepts, as a parameter, the next line/function to execute.
Using this model, you can "pause" execution at any line and continue it later. You can also do inventive things like temporarily hop up the execution stack to retrieve a value, or save the current execution state to a database to retrieve later.


Question:
I'm building an excel template (*.xlt) for a user here, and one of the things I want to do is have it insert the current date when a new document is created (ie, when they double-click the file in windows explorer).  How do I do this?

Update: I should have added that I would prefer not to use any vba (macro).  If that's the only option, then so be it, but I'd really like to avoid forcing my user to remember to click some 'allow macro content' button.

Answer:
You can edit the default template for excel -
There is a file called
```
Book.xlt
```
in the
```
XLSTART
```
directory, normally located at
```
C:\Program Files\Microsoft Office\Office\XLStart\
```
You should be able to add a macro called Workbook_Open
```
```
Private Sub Workbook_Open()
    If ActiveWorkBook.Sheets(1).Range("A1") = "" Then
        ActiveWorkBook.Sheets(1).Range("A1") = Now
    End If
End Sub
```
```
My VBA is a little rusty, but you might find something like this works.


Question: I've inherited a large VB6 app at my current workplace. I'm kinda learning VB6 on the job and there are a number of problems I'm having. The major issue at the moment is I can't figure out how to check if a key exists in a Collection object. Can anyone help?

Answer:
I've always done it with a function like this:
```
```
public function keyExists(myCollection as collection, sKey as string) as Boolean
  on error goto handleerror:

  dim val as variant

  val = myCollection(sKey)
  keyExists = true
  exit sub
handleerror:
  keyExists = false
end function
```
```


Question:
I'm trying to find a way to validate a large XML file against an XSD. I saw the question ...best way to validate an XML... but the answers all pointed to using the Xerces library for validation. The only problem is, when I use that library to validate a 180 MB file then I get an OutOfMemoryException.

Are there any other tools,libraries, strategies for validating a larger than normal XML file?

EDIT: The SAX solution worked for java validation, but the other two suggestions for the libxml tool were very helpful as well for validation  outside of java.

Answer:
Instead of using a DOMParser, use a SAXParser.  This reads from an input stream or reader so you can keep the XML on disk instead of loading it all into memory.
```
```
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);

SAXParser parser = factory.newSAXParser();

XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(new SimpleErrorHandler());
reader.parse(new InputSource(new FileReader ("document.xml")));
```
```


Question:
I'm maintaining some code that uses a *= operator in a query to a Sybase database and I can't find documentation on it.  Does anyone know what *= does?  I assume that it is some sort of a join.

select * from a, b where a.id *= b.id

I can't figure out how this is different from:

select * from a, b where a.id = b.id

Answer:
It means outer join, a simple = means inner join.
```
```
*= is LEFT JOIN and =* is RIGHT JOIN.
```
```
(or vice versa, I keep forgetting since I'm not using it any more, and Google isn't helpful when searching for *=)


Question: After test driving Google Chrome for 30 minutes or so, I like it, even if it seems bare-bones at the moment.  The obvious way to add a few things I can't live without would be through plugins.  Does anyone have any links to resources on how to get started building a plugin/addon for Chrome?  Thanks.

Answer:
Chrome does support the netscape plugin api, but that is for displaying certain kinds of content.
You seem to be after a extention api, really firefox is the only major browser to encourage and support third party extentions to browsing capability (that aren't simply new toolbars)
Nothing in the developer documentation points to a browser enhancing api - google seem to want to keep a tight reign on the look and feel of the application.
You might find a more conclusive answer on the development site:
dev.chromium.org, and some of the developers might be on irc on #chromium on freenode.


Question:
Is it possible to create a REST web service using ASP.NET 2.0?  The articles and blog entries I am finding all seem to indicate that ASP.NET 3.5 with WCF is required to create REST web services with ASP.NET.

If it is possible to create REST web services in ASP.NET 2.0 can you provide an example.

Thanks!

Answer: I'm only just beginning to use them, but from what I've seen 2.0 pretty assumes SOAP.


Question: It will be important for developers wanting to develop for the chrome browser to be able to review existing bugs (to avoid too much pulling-out of hair), and to add new ones (to improve the thing).  Yet I can't seem to find the bug tracking for this project.  It is open source, right?

Answer:
From the
Google Site
Click the Page menu page menu.
Select Report a bug or broken website.
Choose an issue type from the drop-down menu. The web address of the webpage you're on is recorded automatically.
If possible, add key details in the 'Description' field, including steps to reproduce the issue you're experiencing.
Keep 'Send source of current page' and 'Send screenshot of current page' checkboxes selected.
Click the Send report button to report a Google Chrome bug.
I don't see any reference to public bug tracking...


Question:
Although the general case is undecidable, many people still do solve problems that are equivilent well enough for day to day use.

In cohen's phd thesis on computer viruses, he showed how virus scanning is equivilent to the halting problem, yet we have an entire industry based around this challenge.

I also have seen microsoft's terminator project -  http://research.microsoft.com/Terminator/

Which leads me to ask - is the halting problem overrated - do we need to worry about the general case?

Will types become turing complete over time - dependant types do seem like a good development?

Or, to look the other way, will we begin to use non turing complete languages to gain the benefits of static analysis ?

Answer:
The Halting Problem is really only interesting if you look at it in the general case, since if the Halting problem were decidable, all other undecidable problems would also be decidable via reduction.
So, my opinion on this question is, no, it is not easy in the cases that matter.  That said, in the real world, it may not be such a big deal.
See also:
http://en.wikipedia.org/wiki/Halting_problem#Importance_and_consequences


Question:
How do you give a C# auto-property an initial value?

I either use the constructor, or revert to the old syntax.

 Using the Constructor:

class Person
{
    public Person()
    {
        Name = "Initial Name";
    }
    public string Name { get; set; }
}

Using normal property syntax  (with an initial value)

private string name = "Initial Name";
public string Name
{
    get
    {
        return name;
    }
    set
    {
        name = value;
    }
}

Is there a better way?

Answer:
Have you tried using the
DefaultValueAttribute
or
ShouldSerialize and Reset methods
in conjunction with the constructor?  I feel like one of these two methods is necessary if you're making a class that might show up on the designer surface or in a property grid.


Question:
I am setting the .Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key.

Without changing the underlying string (by replacing all _ with __), is there a way to disable the accelerator for Labels?

Answer:
You could override the RecognizesAccessKey property of the ContentPresenter that is in the default template for the label. For example:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <Grid>
    <Grid.Resources>
      <Style x:Key="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}" TargetType="Label">
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="Label">
              <Border>
                <ContentPresenter
                  HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                  VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                  RecognizesAccessKey="False" />
              </Border>
            </ControlTemplate>
          </Setter.Value>
        </Setter>
      </Style>
    </Grid.Resources>
    <Label>_This is a test</Label>
  </Grid>
</Page>
```
```


Question: In this question someone asked for ways to display disk usage in Linux. I'd like to take this one step further down the cli-path... how about a shell script that takes the output from something like a reasonable answer to the previous question and generates a graph/chart from it (output in a png file or something)? This may be a bit too much code to ask for in a regular question, but my guess is that someone already has a oneliner laying around somewhere...

Answer:
I guess there are a couple of options:
For a pure CLI solution, use something like gnuplot. See
here
for example usage. I haven't used gnuplot since my student days :-)
Not really a pure CLI solution, but download something like
JFreeChart
and write a simple Java app that reads stdin and creates your chart.
Hope this helps.


Question:
Are all of these equal?  Under what circumstances should I choose each over the others?

var.ToString()

CStr(var)

CType(var, String)

DirectCast(var, String)

EDIT: Suggestion from NotMyself…

TryCast(var, String)

Answer:
I prefer the following syntax:
```
```
Dim number As Integer = 1
Dim str As String = String.TryCast(number)

If str IsNot Nothing Then
```
```
Hah you can tell I typically write code in C#. 8)
The reason I prefer TryCast is you do not have to mess with the overhead of casting exceptions. Your cast either succeeds or your variable is initialized to null and you deal with that accordingly.


Question:
How do I determine the (local-) path for the "Program Files" directory on a remote computer? There does not appear to any version of SHGetFolderPath (or related function) that takes the name of a remote computer as a parameter.

I guess I could try to query HKLM\Software\Microsoft\Windows\CurrentVersion\ProgramFilesDir using remote-registry, but I was hoping there would be "documented" way of doing it.

Answer:
I prefer the following syntax:
```
```
Dim number As Integer = 1
Dim str As String = String.TryCast(number)

If str IsNot Nothing Then
```
```
Hah you can tell I typically write code in C#. 8)
The reason I prefer TryCast is you do not have to mess with the overhead of casting exceptions. Your cast either succeeds or your variable is initialized to null and you deal with that accordingly.


Question:
I'd like to keep a "compile-counter" for one of my projects. I figured a quick and dirty way to do this would be to keep a text file with a plain number in it, and then simply call upon a small script to increment this each time I compile.

How would I go about doing this using the regular Windows command line?

I don't really feel like installing some extra shell to do this but if you have any other super simple suggestions that would accomplish just this, they're naturally appreciated as well.

Answer:
It would be an new shell (but I think it is worth it), but from PowerShell it would be
```
```
[int](get-content counter.txt) + 1 | out-file counter.txt
```
```


Question:
If I have an HTML helper like so:

Name:<br />
<%=Html.TextBox("txtName",20) %><br />

How do I apply a CSS class to it? Do I have to wrap it in a span? Or do I need to somehow utilize the HtmlAttributes property of the helper?

Answer:
You can pass it into the TextBox call as a parameter.
```
```
Name:<br/>
<%= Html.TextBox("txtName", "20", new { @class = "hello" }) %>
```
```
This line will create a text box with the value 20 and assign the class attribute with the value hello.  I put the @ character in front of the class, because class is a reserved keyword.  If you want to add other attributes, just separate the key/value pairs with commas.


Question: Is there an IDE that I can load on a Blackberry, E71, or an iPhone?

Answer: Not that I know of, typically you'll develop apps on a desktop machine (PC/MAC whatever) and download/control the application on the phone. Also I don't think Java is available on a standard (non-cracked) iPhone.


Question:
What code do you need to add in PHP to automatically have the browser download a file to the local machine when a link is visited?

I am specifically thinking of functionality similar to that of download sites that prompt the user to save a file to disk once you click on the name of the software?

Answer:
Here is an example of sending back a pdf.
```
```
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
header('Content-Transfer-Encoding: binary');
readfile($filename);
```
```
@Swish
I didn't find application/force-download content type to do anything different (tested in IE and Firefox). Is there a reason for not sending back the actual MIME type?
Also in the PHP manual
Hayley Watson
posted:
If you wish to force a file to be downloaded and saved, instead of being rendered, remember that there is no such MIME type as "application/force-download". The correct type to use in this situation is "application/octet-stream", and using anything else is merely relying on the fact that clients are supposed to ignore unrecognised MIME types and use "application/octet-stream" instead (reference: Sections 4.1.4 and 4.5.1 of RFC 2046).
Also according
IANA
there is no registered application/force-download type.


Question: Do you know if it's possible to build an application for the LinkedIn platform?

Answer:
Yes, Linkedin has an API:
http://www.programmableweb.com/api/linkedin
http://blog.linkedin.com/blog/2007/12/the-intelligent.html
So you could build an application that uses it.
Update:
(
from second link
)
We’ll be phasing all of this in over the coming months and to get involved with the Intelligent Application Platform either for APIs, widgets, or hosted applications, send us an e-mail to
developers@linkedin.com
telling us what you want to build and what you need to build it.
Since there are published Mashups using LinkedIn I would assume that means you can use the API even if the documentation isn't readily available.
As a tip, in the future include links to what you found that didn't work, so we know not to give it to you again.
I poked around a bit more and I found some
more on their widgets
which appears to be the main focus of their API.


Question: Grails makes it very easy to configure datasources for different environments (development, test, production) in its DataSources.groovy file, but there seems to be no facility for configuring multiple datasources in one environment. What to I do if I need to access several databases from the same Grails application?

Answer:
The following post seems to be the best source of information on the subject:
How to get mutli-dataSource in grails
It boils down to:
Define datasource1 in DevelopmentDataSource
Define datasource2 in resources.xml
Write a DAO for CRUD of the domain objects using datasource2
In hibernate.cfg.xml, list all domain objects.
Only the first datasource will have dynamic finder methods.
If its a really simple query you are after and don't mind not having the ORM features you could use Groovy SQL or the native SQL features of Hibernate.


Question:
I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string.  In my situation it would be used as a unique session/key identifier that would "likely" be unique over 500K+ generation (my needs don't really require anything much more sophisticated).

Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like "AEYGF7K0DM1X".

Answer:
Algorithm
To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.
Implementation
Here's some fairly simple and very flexible code for generating random identifiers.
Read the information that follows
for important application notes.
```
```
public class RandomString {

    /**
     * Generate a random string.
     */
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];
    }

    /**
     * Create an alphanumeric string generator.
     */
    public RandomString(int length, Random random) {
        this(length, random, alphanum);
    }

    /**
     * Create an alphanumeric strings from a secure generator.
     */
    public RandomString(int length) {
        this(length, new SecureRandom());
    }

    /**
     * Create session identifiers.
     */
    public RandomString() {
        this(21);
    }

}
```
```
Usage examples
Create an insecure generator for 8-character identifiers:
```
```
RandomString gen = new RandomString(8, ThreadLocalRandom.current());
```
```
Create a secure generator for session identifiers:
```
```
RandomString session = new RandomString();
```
```
Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:
```
```
String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);
```
```
Use as session identifiers
Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.
There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.
The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.
Use as object identifiers
Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.
Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.
Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox."
The probability of a collision,
p
, is approximately n
2
/(2q
x
), where
n
is the number of identifiers actually generated,
q
is the number of distinct symbols in the alphabet, and
x
is the length of the identifiers. This should be a very small number, like 2
‑50
or less.
Working this out shows that the chance of collision among 500k 15-character identifiers is about 2
‑52
, which is probably less likely than undetected errors from cosmic rays, etc.
Comparison with UUIDs
According to their specification,
UUIDs
are not designed to be unpredictable, and
should not
be used as session identifiers.
UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.
UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.


Question:
In the process of developing my first WCF service and when I try to use it I get "Method not Allowed" with no other explanation.

I've got my interface set up with the ServiceContract and OperationContract:

    [OperationContract]
    void FileUpload(UploadedFile file);

Along with the actual method:

    public void FileUpload(UploadedFile file) {};

To access the Service I enter http://localhost/project/myService.svc/FileUpload
but I get the "Method not Allowed" error

Am I missing something?

Answer:
The basic intrinsic types (e.g.
```
byte
```
,
```
int
```
,
```
string
```
, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.
So, a silly question (but I have to ask it...): is UploadedFile marked as a
```
[DataContract]
```
? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].
Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)
A tremendous resource for WCF development is what we know in our shop as "the fish book":
Programming WCF Services
by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.


Question:
Given the following:

List<List<Option>> optionLists;

what would be a quick way to determine the subset of Option objects that appear in all N lists? Equality is determined through some string property such as option1.Value == option2.Value.

So we should end up with List<Option> where each item appears only once.

Answer:
Ok, this will find the list of Option objects that have a Value appearing in
every
list.
```
```
var x = from list in optionLists
        from option in list
        where optionLists.All(l => l.Any(o => o.Value == option.Value))
        orderby option.Value
        select option;
```
```
It doesn't do a "distinct" select so it'll return multiple Option objects, some of them with the same Value.


Question:
Suppose someone worked for a company that put up an HTTP proxy preventing internet access without password authentication (NTLM, I think). Also suppose that this password rotated on a daily basis, which added very little security, but mostly served to annoy the employees. How would one get started writing a Firefox add-on that automatically entered these rotating passwords?

To clarify: This add-on would not just submit the password; the add-on would programmatically generate it with some knowledge of the password rotation scheme.

Answer:
This is built into Firefox. Open up about:config, search for 'ntlm'
The setting you're looking for is called network.automatic-ntlm-auth.trusted-uris and accepts a comma-space delimited list of your proxy server uris.
This will make FireFox automatically send hashed copies of your windows password to the proxy, which is disabled by default for obvious reasons. IE can do this automatically because it can use security zones to figure out whether a proxy server is trusted or not.
Blog post discussing this


Question:
I have a number of users with multi-megabyte files that need to be processed before they can be uploaded. I am trying to find a way to do this without having to install any executable software on their machines.

If every machine shipped with, say, Python it would be easy. I could have a Python script do everything. The only scripting language I can think of that's on every machine is JavaScript. However I know there are security restrictions that prevent reading and writing local files from web browsers.

Is there any way to use this extremely pervasive scripting language for general purpose computing tasks?

EDIT: To clarify the requirements, this needs to be a cross platform, cross browser solution. I believe that HTA is an Internet Explorer only technology (or that the Firefox equivalent is broken).

Answer:
The application that I maintain and develop for work is an
HTML Application
or
HTA
, linked with a SQL Server 2005 backend. This allows various security restrictions to be "avoided". All the client-side components in the application are done with javascript, including writing files to locally mapped network drives and loading data into screens/pages in an AJAXy way.
Perhaps HTA could be helpful for your situation.


Question:
How can I get an image to stretch the height of a DIV class?

Currently it looks like this:

However, I would like the DIV to be stretched so the image fits properly, but I do not want to resize the `image.

Here is the CSS for the DIV (the grey box):

.product1 {
    width: 100%;
    padding: 5px;
    margin: 0px 0px 15px -5px;
    background: #ADA19A;
    color: #000000;
    min-height: 100px;
}

The CSS being applied on the image:

.product{
    display: inline;
    float: left;
}

So, how can I fix this?

Answer:
```
```
display:inline
float:left
```
```
is your problem
Floating makes the parents width not be stretched by the child, try placing the image without the float. If you take the float off, it should give you the desired effect.
Another approach would be to make sure you are clearing your floats at the end of the parent element so that they don't scope creep.
Update:
After viewing your link Your height issue as displayed, is because the floats are not being cleared.