q:
I am trying to iterate over all the elements of a static array of strings in the best possible way. I want to be able to declare it on one line and easily add/remove elements from it without having to keep track of the number. Sounds really simple, doesn't it?

Possible non-solutions:

vector<string> v;
v.push_back("abc");
b.push_back("xyz");

for(int i = 0; i < v.size(); i++)
    cout << v[i] << endl;

Problems - no way to create the vector on one line with a list of strings

Possible non-solution 2:

string list[] = {"abc", "xyz"};

Problems - no way to get the number of strings automatically (that I know of).

There must be an easy way of doing this.

[A]
Problems - no way to get the number of strings automatically (that i know of).
There is a bog-standard way of doing this, which lots of people (including MS) define macros like
```
arraysize
```
for:
```
```
#define arraysize(ar)  (sizeof(ar) / sizeof(ar[0]))
```
```


q:
We have some really old code that calls WebServices using behaviours (webservice.htc), and we are having some strange problems... since they've been deprecated a long time ago, I want to change the call.

What's the correct way of doing it? It's ASP.NET 1.1

[A]
While I'm not 100% sure what the Web Service behavior does, I recall it allows client-side script to call Web Services, which would make AJAX it's contemporary replacement.
Since you're using .NET 1.1 how about using
Ajax.NET Professional
to connect to the web services?

s: huggingface

c: devops

d: intermediate


q: I've got a whole directory of dll's I need to register to the GAC. I'd like to avoid registering each file explicitly- but it appears that gacutil has no "register directory" option. Anyone have a fast/simple solution?

[A]
GACUTIL doesn't register DLLs -- not in the "COM" sense. Unlike in COM, GACUTIL copies the file to an opaque directory under %SYSTEMROOT%\assembly and that's where they run from. It wouldn't make sense to ask GACUTIL "register a folder" (not that you can do that with RegSvr32 either).
You can use a batch FOR command such as:
```
```
FOR %a IN (C:\MyFolderWithAssemblies\*.dll) DO GACUTIL /i %a
```
```
If you place that in a batch file, you must replace %a with %%a


q: How can I call a custom action dll written in managed code (.net) from an installer without using an unmanaged intermediary?

[A]
There is support for exactly this in .NET/Windows Installer
Create an assembly using VS.NET.
Add an installer class to the project - select 'Add - New Item'. Select intaller class.
This class derives from System.Configuration.Install.Installer. It has a number of virtual methods such as Install(). This will be called when by the windows installer engine at install time.
This assembly can then be added to your Windows Installer project as a custom action. The method used to declare the custom action as a .NET installer class depends on the tool you are using to create the installation.
Sorry this is a little brief.


q:
After the suggestion to use a library for my ajax needs I am going to use one, the problem is that there are so many and I've no idea how to even begin telling them apart.

Thus, can anybody

A) Give a rundown of the differences or

B) Point me (and others like me) somewhere that has such a list.

Failing that plan C is to go with whichever gets mentioned the most here.

[A]
To answer B:
Comparison of JavaScript frameworks
EDIT:
Although everyone and their mom is apparently riding the
jQuery
bandwagon (I use
MochiKit
), there are many libraries which provide the same functionality - the problem set which most libraries solve (async client-server communication, DOM manipulation, etc.) is the same, and there are few that don't have what you will need to get the job done.
The important thing to determine for yourself is whether or not a library will fit your particular style and sensibilities. Wide-spread ignorance about how
JavaScript
, the language, actually works, coupled with the negative press resulting thereby, coupled with the now-immense popularity of jQuery leads most people down that road. Thankfully, it isn't a bad road to be on as there are a lot of travellers to keep you company when the abstractions leak and you need help. You probably can't go wrong choosing jQuery.


q:
What's the best way to programmatically merge a .reg file into the registry? This is for unit testing; the .reg file is a test artifact which will be added then removed at the start and end of testing.

Or, if there's a better way to unit test against the registry...

[A]
I looked into it by checking out my file associations.
It seems that a .reg file is just called as the first parameter to the
```
regedit.exe
```
executable on Windows.
So you can just say
```
regedit.exe "mytest.reg"
```
. What I'm not sure of is how to get rid of the dialog box that pops up that asks for your confirmation.


q:
I've found ScriptingJsonSerializationSection but I'm not sure how to use it. I could write a function to convert the object to a JSON string manually, but since .Net can do it on the fly with the <System.Web.Services.WebMethod()> and <System.Web.Script.Services.ScriptMethod()> attributes so there must be a built-in way that I'm missing.

PS: using Asp.Net 2.0 and VB.Net - I put this in the tags but I think people missed it.

[A]
This should do the trick
```
```
Dim jsonSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
Dim jsonString as String = jsonSerialiser.Serialize(yourObject)
```
```


q:
I know that the following is true

int i = 17; //binary 10001
int j = i << 1; //decimal 34, binary 100010

But, if you shift too far, the bits fall off the end.  Where this happens is a matter of the size of integer you are working with.

Is there a way to perform a shift so that the bits rotate around to the other side?  I'm looking for a single operation, not a for loop.

[A]
If you know the size of type, you could do something like:
```
```
uint i = 17;
uint j = i << 1 | i >> 31;
```
```
... which would perform a circular shift of a 32 bit value.
As a generalization to circular shift left n bits, on a b bit variable:
```
```
/*some unsigned numeric type*/ input = 17;
var result = input  << n | input  >> (b - n);
```
```
@The comment, it appears that C# does treat the high bit of signed values differently.  I found some info on this
here
.  I also changed the example to use a uint.


q: I'm getting a NoSuchMethodError error when running my Java program.  What's wrong and how do I fix it?

[A]
This is usually caused when using a build system like
Apache Ant
that only compiles java files when the java file is newer than the class file.  If a method signature changes and classes were using the old version things may not be compiled correctly.  The usual fix is to do a full rebuild (usually "ant clean" then "ant").
Sometimes this can also be caused when compiling against one version of a library but running against a different version.


q:
Have you guys had any experiences (positive or negative) by placing your source code/solution on a network drive for Visual Studio 2005 or 2008?  Please note I am not referring to placing your actual source control system on that drive, but rather your working folder.

Thanks


q:
The compiler usually chokes when an event doesn't appear beside a += or a -=, so I'm not sure if this is possible.

I want to be able to identify an event by using an Expression tree, so I can create an event watcher for a test. The syntax would look something like this:

using(var foo = new EventWatcher(target, x => x.MyEventToWatch) {
    // act here
}   // throws on Dispose() if MyEventToWatch hasn't fired

My questions are twofold:

Will the compiler choke? And if so, any suggestions on how to prevent this?

How can I parse the Expression object from the constructor in order to attach to the MyEventToWatch event of target?

[A]
A .NET event isn't actually an object, it's an endpoint represented by two functions -- one for adding and one for removing a handler.  That's why the compiler won't let you do anything other than += (which represents the add) or -= (which represents the remove).
The only way to refer to an event for metaprogramming purposes is as a System.Reflection.EventInfo, and reflection is probably the best way (if not the only way) to get ahold of one.
EDIT: Emperor XLII has written some beautiful code which should work for your own events, provided you've declared them from C# simply as
```
```
public event DelegateType EventName;
```
```
That's because C# creates two things for you from that declaration:
A private delegate field to serve as the backing
storage for the event
The actual event along with
implementation code that makes use
of the delegate.
Conveniently, both of these have the same name.  That's why the sample code will work for your own events.
However, you can't rely on this to be the case when using events implemented by other libraries.  In particular, the events in Windows Forms and in WPF don't have their own backing storage, so the sample code will not work for them.


q:
I have a Flex ComboBox that gets populated by a dataprovider all is well...

I would now like to add a default " -- select a item --" option at the 0 index, how can I do this and still use a dataprovider? I have not seen any examples of such, but I can't imagine this being hard...

[A]
The way I've dealt with this in the past is to create a new collection to serve as the data provider for the combobox, and then I listen for changes to the original source (using an
```
mx.BindingUtils.ChangeWatcher
```
).  When I get such a notification, I recreate my custom data provider.
I wish I knew a better way to approach this; I'll monitor this question just in case.


q:
I used the jQuery Form plugin for asynchronous form submission. For forms that contain files, it copies the form to a hidden iframe, submits it, and copies back the iframe's contents. The problem is that I can't figure out how to find what HTTP status code was returned by the server. For example, if the server returns 404, the data from the iframe will be copied as normal and treated as a regular response.

I've tried poking around in the iframe objects looking for some sort of status_code attribute, but haven't been able to find anything like that.

The $.ajax() function can't be used, because it does not support uploading files. The only way to asynchronously upload files that I know of is using the hidden iframe method.

[A]
You can't get page headers by JS, but you can distinguish error from success:
Try something like this:
```
```
<script type="text/javascript">

    var uploadStarted = false;
    function OnUploadStart(){
        uploadStarted = true;
    }

    function OnUploadComplete(state,message){

       if(state == 1)
        alert("Success: "+message);
       else
         if(state == 0 && uploadStarted)
            alert("Error:"+( message ? message : "unknow" ));
    }

</script>

<iframe id="uploader" name="uploader" onload="OnUploadComplete(0)" style="width:0px;height:0px;border:none;"></iframe>

<form id="sender" action="/upload.php" method="post" target="uploader" enctype="multipart/form-data" onsubmit="OnUploadStart()">
<input type="file" name="files[upload]"/>
<input type="submit" value="Upload"/>
</form>
```
```
On server side:
```
```
/*
  file: upload.php
*/
<?php

   // do some stuff with file

  print '<script type="text/javascript">';
  if(success)
     print 'window.parent.OnUploadComplete(1,"File uploaded!");';
  else
     print 'window.parent.OnUploadComplete(0, "File too large!");';
  print  '</script>';
?>
```
```


q:
I want to escape a DOS filename so I can use it with sed. I have a DOS batch file something like this:

set FILENAME=%~f1

sed 's/Some Pattern/%FILENAME%/' inputfile

(Note: %~f1 - expands %1 to a Fully qualified path name - C:\utils\MyFile.txt)

I found that the backslashes in %FILENAME% are just escaping the next letter.

How can I double them up so that they are escaped?

(I have cygwin installed so feel free to use any other *nix commands)

Solution

Combining Jeremy and Alexandru Nedelcu's suggestions, and using | for the delimiter in the sed command I have

set FILENAME=%~f1
cygpath "s|Some Pattern|%FILENAME%|" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp

[A]
This will work.  It's messy because in BAT files you can't use set var=`cmd` like you can in unix.
The fact that echo doesn't understand quotes is also messy, and could lead to trouble if
```
Some Pattern
```
contains shell meta characters.
```
```
set FILENAME=%~f1
echo s/Some Pattern/%FILENAME%/ | sed -e "s/\\/\\\\/g" >sedcmd.tmp
sed -f sedcmd.tmp inputfile
del /q sedcmd.tmp
```
```
[Edited]: I am suprised that it didn't work for you.  I just tested it, and it worked on my machine.  I am using sed from
http://sourceforge.net/projects/unxutils
and using cmd.exe to run those commands in a bat file.


q:
I do a lot of work in the grid and HPC space and one of the biggest challenges we have with a system distributed across hundreds (or in some case thousands) of servers is analysing the log files.

Currently log files are written locally to the disk on each blade but we could also consider publishing logging information using for example a UDP Appender and collect it centally.

Given that the objective is to be able to identify problems in as close to real time as possible, what should we do?

[A]
First, synchronize all clocks in the system using NTP.
Second, if you are collecting the logs in a single location (like the UDP appender you mention) make sure the logs have enough information to actually help.  I would include at least the server that generated the log, the time it happened, and the message.  If there is any sort of transaction id, or job id type concept, include that also.
Since you mentioned a UDP Appender I am guessing you are using log4j (or one of it's siblings).  Log4j has an MDC class that allows extra information to be passed along through a processing thread.  it can help collect some of the extra information and pass it along.


q:
I'm compiling a simple .c in visual c++ with Compile as C Code (/TC)
and i get this compiler error

error C2143: syntax error : missing ';' before 'type'

on a line that calls for a simple struct

 struct foo test;

same goes for using the typedef of the struct.

error C2275: 'FOO' : illegal use of this type as an expression

[A]
Did you accidentally omit a semicolon on a previous line? If the previous line is an
```
#include
```
, you might have to look elsewhere for the missing semicolon.
Edit: If the rest of your code is valid C++, then there probably isn't enough information to determine what the problem is. Perhaps you could post your code to a
pastebin
so we can see the whole thing.
Ideally, in the process of making it smaller to post, it will suddenly start working and you'll then have discovered the problem!


q: Let X be the set of all sets that do not contain themselves. Is X a member of X?

[A]
The question is ill-posed in the standard
ZFC
(Zermelo-Fraenkel + axiom of Choice) set theory because the object thus defined is not a set.
Since (again, assuming standard ZFC) your
class
{x : x\not\in x} is not a set, the answer becomes no, it's not an element of itself (even as a class) since only sets can be elements of classes or sets.
By the way, as soon as you agree to the
axiom of foundation
, no set can be an element of itself.
Of course the nice thing about math is you can choose whichever axioms you want :) but believing in paradoxes is just weird.


q:
I am learning to write a debug visualizer in vs2008 C#. But keep getting the error saying that MyDebugVisualizer dll can't be loaded when I am in debug mode and click the magnifying glass icon.

My app project is referencing the visualizer project. Before the type definition I have:

[DebuggerVisualizer(typeof(MyVisualizer))]
[Serializable]

I tried putting the visualizer dll in:
C:\Program Files\Microsoft Visual Studio 9.0\Common7\Packages\Debugger\Visualizers
or
C:\Documents and Settings\zlee\My Documents\Visual Studio 2008\Visualizers

Is there something else missing?


q:
I am a developer.  An architect on good days.  Somehow I find myself also being the DBA for my small company.  My background is fair in the DB arts but I have never been a full fledged DBA.  My question is what do I have to do to ensure a realiable and reasonably functional database environment with as little actual effort as possible?

I am sure that I need to make sure that backups are being performed and that is being done.  That is an easy one.  What else should I be doing on a consistant basis?

[A]
I would suggest:
A script to quickly restore the latest backup of a database, in case it gets corrupted
What kind of backups are you doing?  Full backups each day, or incremental every hour, etc?
Some scripts to create new users and grant them basic access.
However, the number one suggestion is to limit as much as possible the power other users have, this will greatly reduce the chance of stuff getting badly messed up.  Servers that have everyone as an sa tend to get screwed up quicker than servers that are locked down.


q:
I have a solution consisting of five projects, each of which compile to separate assemblies. Right now I'm code-signing them, but I'm pretty sure I'm doing it wrong. What's the best practice here?

Sign each with a different key; make sure the passwords are different

Sign each with a different key; use the same password if you want

Sign each with the same key

Something else entirely

Basically I'm not quite sure what "signing" does to them, or what the best practices are here, so a more generally discussion would be good. All I really know is that FxCop yelled at me, and it was easy to fix by clicking the "Sign this assembly" checkbox and generating a .pfx file using Visual Studio (2008).

[A]
If your only objective is to stop FxCop from yelling at you, then you have found the best practice.
The best practice for signing your assemblies is something that is completely dependent on your objectives and needs.  We would need more information like your intended deployment:
For personal use
For use on corporate network PC's as a client application
Running on a web server
Running in SQL Server
Downloaded over the internet
Sold on a CD in shrink wrap
Uploaded straight into a cybernetic brain
Etc.
Generally you use code signing to verify that the Assemblies came from a specific trusted source and have not been modified.
So each with the same key is fine.
Now how that trust and identity is determined is another story.
UPDATE:
How this benefits your end users when you are deploying over the web is if you have obtained a
software signing certificate from a certificate authority
.  Then when they download your assemblies they can verify they came from
Domenic's Software Emporium
, and they haven't been modified or corrupted along the way.  You will also want to sign the installer when it is downloaded.  This prevents the warning that some browsers display that it has been obtained from an unknown source.
Note, you will pay for a software signing certificate.  What you get is the certificate authority become the trusted 3rd party who verifies you are who you say you are.  This works because of a web of trust that traces its way back to a root certificate that is installed in their operating system.  There are a few certificate authorities to choose from, but you will want to make sure they are supported by the root certificates on the target operating system.


q:
I want to be able to get an estimate of how much code & static data is used by my C++ program?

Is there a way to find this out by looking at the executable or object files?  Or perhaps something I can do at runtime?

Will objdump & readelf help?

[A]
```
readelf
```
will indeed help. You can use the
```
-S
```
option; that will show the sizes of all sections.
```
.text
```
is (the bulk of) your executable code.
```
.data
```
and
```
.rodata
```
is your static data. There are other sections too, some of which are used at runtime, others only at link time.


q:
I want to be able to get an estimate of how much code & static data is used by my C++ program?

Is there a way to find this out by looking at the executable or object files?  Or perhaps something I can do at runtime?

Will otool help?

[A]
I think otool can help. Specifically, "otool -s {segment} {section}" should print out the details. I'm not sure if you can get information about __DATA or __TEXT without specifying a section. Maybe those sizes are reported in the mach header: "otool -h"?
```
```
otool -s  __DATA __data MyApp.bundle/Contents/MacOS/MyApp
otool -s __TEXT __text MyApp.bundle/Contents/MacOS/MyApp
```
```
Anyway, Apple documents what gets copied into each section per-segment here:
Apple's mach-o format documentation


q: Graphics and audio editing and processing software often contain functions called "High-Pass Filter" and "Low-Pass Filter".  Exactly what do these do, and what are the algorithms for implementing them?

[A]
Wikipedia:
High-pass filter
Low-pass filter
Band-pass filter
These "high", "low", and "band" terms refer to
frequencies
. In high-pass, you try to remove low frequencies. In low-pass, you try to remove high. In band pass, you only allow a continuous frequency range to remain.
Choosing the cut-off frequency depends upon your application. Coding these filters can either be done by simulating RC circuits or by playing around with Fourier transforms of your time-based data. See the wikipedia articles for code examples.


q: Is there an easy way to set the zoom level for a windows form in C#?  In VBA there was a zoom property of the form.

[A]
There is no way (that I know of) to do what you ask with typical WinForms.
If you're doing custom painting/drawing, you can zoom that by using a zoom transform, but so far as I know there is no "Zoom" property for the form in the entire world of .NET and native Windows/C++ APIs combined.
You could probably rig something yourself such that you scale controls by a constant factor. And you can probably find 3rd-party controls/surfaces which support this. And who knows what is possible with WPF. But in a typical WinForms world, no.


q: What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.

[A]
XHTML is easy, use
lxml
.
```
```
from lxml import etree
from StringIO import StringIO
etree.parse(StringIO(html), etree.HTMLParser(recover=False))
```
```
HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as
nsgmls
or
OpenJade
, and then parse their output.


q: Doug McCune had created something that was exactly what I needed (http://dougmccune.com/blog/2007/05/10/analyze-your-actionscript-code-with-this-apollo-app/) but alas - it was for AIR beta 2.  I just would like some tool that I can run that would provide some decent metrics...any idea's?

[A]
To get a rough estimate, you could always run
```
find . -type f -exec cat {} \; | wc -l
```
in the project directory if you're using Mac OS X.


q: I use this tool called Lazy C++ which breaks a single C++ .lzz file into a .h and .cpp file. I want Makepp to expect both of these files to exist after my rule for building .lzz files, but I'm not sure how to put two targets into a single build line.

[A]
I've never used Makepp personally, but since it's a drop-in replacement for GNU Make, you should be able to do something like:
```
```
build: foo.h foo.cpp
   g++ $(CFLAGS) foo.cpp -o $(LFLAGS) foo

foo.h foo.cpp: foo.lzz
   lzz foo.lzz
```
```
Also not sure about the lzz invocation there, but that should help.  You can read more about this at
http://theory.uwinnipeg.ca/gnu/make/make_37.html
.


q: Wikipedia says SQL Server Express Edition is limited to "one processor, 1 GB memory and 4 GB database files".  Does anyone have practical experience with how well this scales?

[A] We have used SQL Server Express Edition in some of our smaller applications, maybe 5+ users, and smaller databases.  The 4GB is very limiting in a high transaction environments, and in some cases we have had to migrate our customer to SQL Server Standard Edition.


q:
I'm looking to push my domain model into a WCF Service API and wanted to get some thoughts on lazy loading techniques with this type of setup.

Any suggestions when taking this approach?

when I implemented this technique and step into my app, just before the server returns my list it hits the get of each property that is supposed to be lazy loaded ... Thus eager loading. Could you explain this issue or suggest a resolution?

Edit:  It appears you can use the XMLIgnore attribute so it doesn’t get looked at during serialization .. still reading up on this though

[A]
As for any remoting architecture, you'll want to avoid loading a full object graph "down the wire" in an uncontrolled way (unless you have a trivially small number of objects).
The
Wikipedia article
has the standard techniques pretty much summarised (and in C#. too!). I've used both ghosts and value holders and they work pretty well.
To implement this kind of technique, make sure that you separate concerns strictly. On the server, your service contract implementation classes should be the only bits of the code that work with data contracts. On the client, the service access layer should be the only code that works with the proxies.
Layering like this lets you adjust the way that the service is implemented relatively independently of the UI layers calling the service and the business tier that's being called. It also gives you half a chance of unit testing!


q: Is there a Ruby equivalent for Python's "is"? It tests whether two objects are identical (i.e. have the same memory location).

[A]
Use
```
a.equal? b
```
http://www.ruby-doc.org/core/classes/Object.html
Unlike ==, the equal? method should never be overridden by subclasses: it is used to determine object identity (that is, a.equal?(b) iff a is the same object as b).


q:
I'm interested in using Office 2007 to convert between the pre-2007 binary formats (.doc, .xls, .ppt) and the new Office Open XML formats (.docx, .xlsx, .pptx)

How would I do this? I'd like to write a simple command line app that takes in two filenames (input and output) and perhaps the source and/or destination types, and performs the conversion.

[A]
Microsoft has a page which gives several examples of writing scripts to "drive" MS Word.
One such example
shows how to convert from a Word document to HTML.  By changing the last parameter to any values listed
here
, you can get the output in different formats.


q: I've been using Window Home Server for my backups here at home for most of a year now, and I'm really pleased with it.  It's far better than the software I was using previously (Acronis).  I'm thinking about a backup strategy for my work machine and I'd like to know how WHS compares with Vista's built-in backup and restore features.  The plan is to do a full backup to a local external hard drive and backup the documents folder to a network drive on the server.  Anyone have experience using the Vista backup feature like this?

[A]
Chris,
They're different beasts. WHS backup is pretty much automatic and uses deltas - Vista's is manual and I don't believe offers incremental updates.
While your solution (Vista + network copy) would preserve your data it has two problems I an see;
Your documents will only have the latest revision. If you find something was corrupted a month ago it could be very awkward to recover it. Vista's shadow copies may help though.
As soon as you install a program/patch/config your Vista backup is out of date and needs remade, or these repeated if you reinstall.
These might not be dealbreakers and indeed Vista's backup is pretty decent, it's just nowhere near as good as WHS. In my opinion WHS leaves almost everything else standing, you can be sure this tech will be in the "big brother" server versions shortly.


q:
I am ready to start using SVN, but I have NO (as in the money required for free beer) experience with source control.  I have installed subversion on my server (that was easy, 'apt-get install subversion') but now I don't know what to do, how to configure it, or how to use it.

What suggestions do you have, and where can I find good resources to learn to start using it?

Update:

O.K. So the feedback has been great and I have read through a bit of it but I want to clarify my question by saying that I am looking for more information on how to actually go about setting my up my repositories, clients, server, etc.  I know that I could do a quick Google search and find dozens (or more) resources but I'm hoping that someone whom has experience with subversion and a client(I have installed tortoise) could suggest a good reference that will be reliable, and have quality content.

[A]
Eric Sink has an
excellent series
on source code control aimed at beginners. For Subversion specifics, including setting up and administering a server, the
Subversion book
is a great resource, and includes a section with examples of a typical session with Subversion (checkout, commit, merging and updating basics).
Update:
I forgot to mention that for beginners, I'd also recommend messing around in a graphical client, which removes the command-line hassle from the learning experience.
RapidSVN
is a reasonable cross-platform client. You'll also find that common IDEs either come with Subversion support, or have plugins which can be installed, which allow most version control operations to be performed within that environment.
@John Millikin:
While setting up a Subversion server can be complicated, depending on one's general admin experience, don't forget that you don't need to do that just to mess about with a repository and get to grips with the basics - the client can interact with a repository in the local filesystem.


q:
If I have a separate system with its own concept of users and presence, what is the most appropriate architecture for creating a bridge to an XMPP server network?  As far as I can tell there are three primary ways:

Act as a server.  This creates one touchpoint, but I fear it has implications for compatibility, and potentially creates complexity in my system for emulating a server.

Act as a clients.  This seems to imply that I need one connection per user in my system, which just isn't going to scale well.

I've heard of an XMPP gateway protocol, but it's unclear if this is any better than the client solution.  I also can't tell if this is standard or not.

Any suggestions or tradeoffs would be appreciated.  For example, would any of these solutions require running code inside the target XMPP server (not likely something I can do).

[A]
The XMPP gateway protocol you've heard of is most likely to do with transports.  A transport is a server that connects to both a XMPP server and a non-XMPP server.  By running a transport, I can use my Jabber client to talk to someone using, say, MSN Messenger.
A transport typically connects once to the remote network for each JID that it sees as online.  That is, it's your option 2 in reverse.  This is because there is no special relationship between the transport and the non-XMPP network; the transport is simply acting as a bunch of regular clients.  For this to work, XMPP clients must first register with the transport, giving login credentials for the remote network, and allowing the transport to view their presence.
The only reason this has a chance of scaling better is that there can be many transports for the same remote network.  For example, my Jabber server could run a transport to MSN, another Jabber server could run another one, and so on, each one providing connections for a different subset of XMPP users.  While this spreads out the load on the Jabber side, and load balancing on your system may spread out the load as well, it still requires many connections between the two systems.
In your case, because (I assume) the non-XMPP side of things is cooperating, putting a XMPP server interface on the non-XMPP server is likely your best bet.  That server interface is best suited for managing the mapping between XMPP JIDs and how that JID will appear on its own network, rather than forcing XMPP users to register and so on.
In case you haven't seen these, you might find them useful:
http://www.jabber.org/jabber-for-geeks/technology-overview
http://www.xmpp.org/protocols/
http://www.xmpp.org/extensions/
Hope that helps.


q:
I've encountered the term "multi-agent computing" as of late, and I don't quite get what it is. I've read a book about it, but that didn't answer the fundamental question of what an agent was.

Does someone out there have a pointer to some reference which is clear and concise and answers the question without a load of bullshit/marketing speak? I want to know if this is something I should familiarise myself, or whether it's some crap I can probably ignore, because I honestly can't tell.

[A] A multi-agent system is a concept borrowed from AI. It's almost like a virtual world where you have agents that are able to observe, communicate, and react. To give an example, you might have a memory allocation agent that you have to ask for memory and it decides whether or not to give it to you. Or you might have an agent that monitors a web server and restarts it if it hangs. The main goal behind multiagent systems is to have a more Smalltalk-like communication system between different parts of the system in order to get everything to work together, as opposed to more top-down directives that come from a central program.


q:
I'm trying to make a two-column page using a div-based layout (no tables please!). Problem is, I can't grow the left div to match the height of the right one.  My right div typically has a lot of content.

Here's a paired down example of my template to illustrate the problem.

<div style="float:left; width: 150px; border: 1px solid;">
  <ul>
    <li>nav1</li>
    <li>nav2</li>
    <li>nav3</li>
    <li>nav4</li>
  </ul>
</div>
<div style="float:left; width: 250px">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
....
</div>

[A]
Your simplest answer lies in the next version of css (3), which currently no browser supports.
For now you are relegated to calculating heights in javascript and setting them on the left side.
If the navigation is so important to be positioned in such a way, run it along the top.
you could also do a visual trick by moving the borders to the container and the bigger inner, and make it appear to be the same size.
this makes it look the same, but it isn't.
```
```

nav1

nav2

nav3

nav4

  Lorem ipsum dolor sit amet, consectetur adipisicing elit,
  sed do eiusmod tempor incididunt ut labore et dolore magna
  Lorem ipsum dolor sit amet, consectetur adipisicing elit,
  ...

```
```


q:
According to Microsoft the FileUpload control is not compatible with an AJAX UpdatePanel.

I am aware that a PostBackTrigger can be added to the submit button of the form like this:

<Triggers>
  <asp:PostBackTrigger ControlID="Button1" />
</Triggers>

The problem is that this forces the form to perform a full post-back which voids out the whole point of using the UpdatePanel in the first place. Is there a workaround to this issue that does not cause the whole page to refresh?

[A]
I know of a third party component that can do that. It's called
"
swfupload
"
and is free to use and open source, and uses javascript and flash to do the magic.
here is a list of the features they offer:
(from their site)
Upload multiple files at once by ctrl/shift-selecting in dialog
Javascript callbacks on all events
Get file information before upload starts
Style upload elements with XHTML and css
Display information while files are uploading using HTML
No page reloads necessary
Works on all platforms/browsers that has Flash support.
Degrades gracefully to normal HTML upload form if Flash or javascript is
  unavailable
Control filesize before upload starts
Only display chosen filetypes in dialog
Queue uploads, remove/add files before starting upload
They also have a
demo area
where you can play around with their control. That way you can make sure it is exactly what you want.
We used it in one of our projects and it has never failed us so far, so I think this is a safe bet.
oh and here is the download page:
http://code.google.com/p/swfupload/


q:
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity).

Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it is proper for production use in the development of stand-alone complex applications (think for example to a word processor or a graphic tool)?

What IDE would you suggest? The IDLE provided with Python is not enough even for small projects in my opinion.

[A]
In my opinion python is more than ready for developing complex applications. I see pythons strength more on the server side than writing graphical clients. But have a look at
http://www.resolversystems.com/
. They develop a whole spreadsheet in python using the .net ironpython port.
If you are familiar with eclipse have a look at
pydev
which provides auto-completion and debugging support for python with all the other eclipse goodies like svn support. The guy developing it has just been bought by
aptana
, so this will be solid choice for the future.
@Marcin
Cons: as a dynamic language, has way
  worse IDE support (proper syntax
  completion requires static typing,
  whether explicit in Java or inferred
  in SML),
You are right, that static analysis may not provide full syntax completion for dynamic languages, but I thing pydev gets the job done very well. Further more I have a different development style when programming python. I have always an ipython session open and with one F5 I do not only get the perfect completion from ipython, but object introspection and manipulation as well.
But if you want to write second Google
  or Yahoo, you will be much better with
  C# or Java.
Google just rewrote jaiku
to work on top of App Engine, all in python. And as far as I know they use a lot of python inside google too.


q: What is the Java analogue of .NET's XML serialization?

[A]
If you're talking about automatic XML serialization of objects, check out
Castor
:
Castor is an Open Source data binding framework for Java[tm]. It's the shortest path between Java objects, XML documents and relational tables. Castor provides Java-to-XML binding, Java-to-SQL persistence, and more.


q:
If I create a class A as follows:

class A:
    def __init__(self):
        self.name = 'A'

Inspecting the __dict__ member looks like {'name': 'A'}

If however I create a class B:

class B:
    name = 'B'

__dict__ is empty.

What is the difference between the two, and why doesn't name show up in B's __dict__?

[A]
```
B.name
```
is a class attribute, not an instance attribute.  It shows up in
```
B.__dict__
```
, but not in
```
b = B(); b.__dict__
```
.
The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback.  So in the above example,
```
b.name
```
will give you the value of
```
B.name
```
.


q:
So we've discussed logging in passing at my place of work and I was wondering if some of you guys here could give me some ideas of your approaches?

Typically our scenario is, no logging really at all, and mostly .NET apps, winforms/WPF clients talking through web services or direct to a db.

So, the real question is, where or what would you log?  At the moment we have users reporting error messages - so I would assume log startups/shutdowns, exceptions...

Do you take it to calls to the web services or db?  Page loads?

How do you get a good idea of what the user was trying to do at the time?

Is it better to go all the way and log everything across multiple attempts/days, or log only what you need to (given hdd is cheap).

I guess that's a few questions, but I wanted to get more of an idea of what the actual practice is out there in larger shops!

[A]
As a quick answer I would say to come up with a series of categories and have switchable logging levels, e.g. info, warning, error, critical, etc.
Then make it easy to set the logging level to tune the level of detail that you need. Typically, set the logging level in a config file and stop and restart the app.
I would also publicize to the developers what the meaning is for each of the levels.
edit: I would also set up a system to rotate out, compress and archive log files on a regular basis, maybe nightly.


q:
Do you know any grid control compatible with .NET and Mono?

DataGridView seems to be quite buggy on Mono, and GTK# controls depends on GTK+ so you need to install it in windows machines where, usually, it's not present.

[A]
Which version did you try? Perhaps you should give
Mono 2.0 preview
a go, it might work for you (no, the Data* controls are not yet perfect, but they have improved greatly). From my experience GTK# controls on Windows are not that great either...


q:
I'm working on an email solution in SQL Server ONLY that will use Database Mail to send out HTML formatted emails.  The catch is that the images in the HTML need to be embedded in the outgoing email. This wouldn't be a problem if I were using a .net app to generate & send the emails but, unfortunately, all I have is SQL Server.

Is it possible for SQL Server to embed images on its own?

[A]
You could try to encode the image as base64 and reference it directly in an img tag within the email (
```
<img src="data:image/png;base64[your encoded image here...]
```
) but i think most email clients correlate this technique with spam. I think you're better off referencing hosted images or simply attaching it to the email.


q:
Let's say I have committed some bad changes to Subversion repository. Then I commit good changes, that I want to keep.

What would be easiest way to roll back those bad changes in Eclipse, and keep the good changes? Assuming that files relating to bad changes are not same as those relating to the good changes. How things change if good changes were made to same files as bad changes?

I am mostly looking a way to do this via Eclipse plugins (Subclipse or Subversive) but commandline commands are also interesting.

[A]
You have two choices to do this.
The Quick and Dirty is selecting your files (using
ctrl
) in Project Explorer view, right-click them, choose
```
Replace with...
```
and then you choose the best option for you, from
```
Latest from Repository
```
, or some
```
Branch
```
version. After getting those files you modify them (with a space, or fix something, your call and commit them to create a newer revision.
A more clean way is choosing
```
Merge
```
at team menu and navigate through the wizard that will help you to recovery the old version in the actual revision.
Both commands have their command-line equivalents:
```
svn revert
```
and
```
svn merge
```
.


q:
Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:

class MyStruct():
    def __init__(self, field1, field2, field3):
        self.field1 = field1
        self.field2 = field2
        self.field3 = field3

[A]
How about a dictionary?
Something like this:
```
```
myStruct = {'field1': 'some val', 'field2': 'some val'}
```
```
Then you can use this to manipulate values:
```
```
print myStruct['field1']
myStruct['field2'] = 'some other values'
```
```
And the values don't have to be strings.  They can be pretty much any other object.


q:
I have a popup window containing a form which gathers data for a report.
When I click submit in that window, I want it to close the popup, and open the report in the original window that called the popup.

I think I can open the report in the correct window by using

{ :target => <name of window> }

in the form_tag, but I don't know how to determine or set the name of the originating window.

I also don't know how to close the popup window.

[A]
How is
this
for starters?
```
```
# The submit button in your child window's view:
<%= button_to_function 'Save', "$('my_form').submit(); window.opener.location.reload(); window.close();" %>
```
```


q: I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form?

[A]
Not sure where it went. You could roll your own extension though:
public static class MyBindingExtensions
{
```
```
public static T ReadFromRequest < T > (this Controller controller, string key)
{
    // Setup
    HttpContextBase context = controller.ControllerContext.HttpContext;
    object val = null;
    T result = default(T);

    // Gaurd
    if (context == null)
        return result; // no point checking request

    // Bind value (check form then query string)
    if (context.Request.Form[key] != null)
        val = context.Request.Form[key];
    if (val == null)
    {
        if (context.Request.QueryString[key] != null)
            val = context.Request.QueryString[key];
    }

    // Cast value
    if (val != null)
        result = (t)val;

    return result;
}

}
```
```


q: In my PHP web app, I want to be notified via email whenever certain errors occur. I'd like to use my Gmail account for sending these. How could this be done?

[A]
You could use PEAR's mail function with Gmail's SMTP Server
Note that when sending e-mail using Gmail's SMTP server, it will look like it came from your Gmail address, despite what you value is for $from.
(following code taken from
About.com Programming Tips
)
```
```
<?php
require_once "Mail.php";

$from = "Sandra Sender <sender@example.com>";
$to = "Ramona Recipient <recipient@example.com>";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

// stick your GMAIL SMTP info here! ------------------------------
$host = "mail.example.com";
$username = "smtp_username";
$password = "smtp_password";
// --------------------------------------------------------------

$headers = array ('From' => $from,
  'To' => $to,
  'Subject' => $subject);
$smtp = Mail::factory('smtp',
  array ('host' => $host,
    'auth' => true,
    'username' => $username,
    'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
  echo("
" . $mail->getMessage() . "
");
 } else {
  echo("
Message successfully sent!
");
 }
?>
```
```


q:
I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?

Edit: The question was modified after reading through the replies.  It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.

I'm looking for more detail on rolling my own catching block inside a using block.

Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...

Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply!

[A]
Yeah there is nothing different about throwing exceptions in using blocks.
Remember that the using block basically translates to:
```
```
IDisposable disposable = null;
try
{
    disposable = new WhateverYouWantedToMake();
}
finally
{
    disposable.Dispose()
}
```
```
So you will have to roll your own catching if you want to catch anything but catching/throwing is a completely separate concern from the using. The finally is almost guaranteed to execute (save an uncatchable exception (e.g. stackoverflow or outofmemory) or someone pulling the power out of the PC).


q: How do I "name" a browser window in ROR, such that I can open a page in it later, from another (popup) window (using the target="name" html parameter)

[A]
You have to use JavaScript for this:
```
```
<script type="text/javascript">
  window.name = "MyWindow";
</script>
```
```
Of course you could easily package this up into a Rails helper method. For example, in
```
app/helpers/application_helper.rb
```
add a new method:
```
```
def window_name(name)
  content_for(:window_name) do
    "<script type=\"text/javascript\">window.name = \"#{name}\";</script>"
  end
end
```
```
Next, in your layout file, add this line somewhere within the HTML
```
<head>
```
element:
```
```
<%= yield :window_name %>
```
```
Finally, in your view templates, simply add a line like this (can be anywhere you want) to output the correct JavaScript:
```
```
<% window_name 'MyWindow' %>
```
```


q: What is the best way of creating an alphabetically sorted list in Python?

[A]
```
```
list.sort()
```
```
It really is that simple :)


q: I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)

[A]
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript:
```
```
function add (a, b) {
  return a + b;
}

add(3, 4); // returns 7
```
```
This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function:
```
```
function add (a) {
  return function (b) {
    return a + b;
  }
}
```
```
This is a function that takes one argument,
```
a
```
, and returns a function that takes another argument,
```
b
```
, and that function returns their sum.
```
```
add(3)(4); // returns 7

var add3 = add(3); // returns a function

add3(4); // returns 7
```
```
The first statement returns 7, like the
```
add(3, 4)
```
statement.
The second statement defines a new function called
```
add3
```
that will
add 3 to its argument. (This is what some may call a closure.)
The third statement uses the
```
add3
```
operation to add 3 to 4, again
producing 7 as a result.


q:
It'd be really nice to target my Windows Forms app to the .NET 3.5 SP1 client framework. But, right now I'm using the HttpUtility.HtmlDecode and HttpUtility.UrlDecode functions, and the MSDN documentation doesn't point to any alternatives inside of, say, System.Net or something.

So, short from reflectoring the source code and copying it into my assembly---which I don't think would be worth it---are there alternatives inside of the .NET 3.5 SP1 client framework that you know of, to replace this functionality? It seems a bit strange that they'd restrict these useful functions to server-only code.

[A]
The
.NET 3.5 SP1 Client Profile Setup Package
is the "cut down" version of .NET that only includes what Microsoft perceive to be the "useful" bits of .NET for client applications. So, useful things like the
```
HttpUtility
```
classes are missing.
For more on that see
ScottGu's blog
, search for "Client Profile Setup Package".
To get around this you could always extract
```
System.Web.dll
```
from the GAC (it'll be in
```
c:\windows\Microsoft.NET\Framework\ ...
```
) and deploy it with your application. You will, however, need to track updates and service packs as you deploy.
Better might be to take the hit of the full .NET Framework deployment.


q:
Java has generics and C++ provides a very strong programming model with templates.
So then, what is the difference between C++ and Java generics?

[A]
C++ has templates. Java has generics, which look kinda sorta like C++ templates, but they're very, very different.
Templates work, as the name implies, by providing the compiler with a (wait for it...) template that it can use to generate type-safe code by filling in the template parameters.
Generics, as I understand them, work the other way around: the type parameters are used by the compiler to verify that the code using them is type-safe, but the resulting code is generated without types at all.
Think of C++ templates as a
really good
macro system, and Java generics as a tool for automatically generating typecasts.


q:
I have a method which takes params object[] such as:

void Foo(params object[] items)
{
    Console.WriteLine(items[0]);
}

When I pass two object arrays to this method, it works fine:

Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]

But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:

Foo(new object[]{ (object)"1", (object)"2" });
// Output: 1, expected: System.Object[]

How do I pass a single object[] as a first argument to a params array?

[A]
You need to encapsulate it into another object[] array, like this:
```
```
Foo(new Object[] { new object[]{ (object)"1", (object)"2" }});
```
```


q: What Firefox add-ons do you use that are useful for programmers?

[A]
As far as web development, especially for javascript, I find
Firebug
to be invaluable.
Web developer toolbar
is also very useful.


q:
Older K&R (2nd ed.) and other C-language texts I have read that discuss the implementation of a dynamic memory allocator in the style of malloc() and free() usually also mention, in passing, something about data type alignment restrictions. Apparently certain computer hardware architectures (CPU, registers, and memory access) restrict how you can store and address certain value types. For example, there may be a requirement that a 4 byte (long) integer must be stored beginning at addresses that are multiples of four.

What restrictions, if any, do major platforms (Intel & AMD, SPARC, Alpha) impose for memory allocation and memory access, or can I safely ignore aligning memory allocations on specific address boundaries?

[A]
Alignment is still quite important today. Some processors (the 68k family jumps to mind) would throw an exception if you tried to access a word value on an odd boundary. Today, most processors will run two memory cycles to fetch an unaligned word, but this will definitely be slower than an aligned fetch. Some other processors won't even throw an exception, but will fetch an
incorrect
value from memory!
If for no other reason than performance, it is wise to try to follow your processor's alignment preferences. Usually, your compiler will take care of all the details, but if you're doing anything where you lay out the memory structure yourself, then it's worth considering.


q: What would be the best way to design a threaded commenting system so that it doesn't hammer the database?

[A] What I normally do in this case is to have a single thread that is responsible for putting the data into the database, and have all auxiliary threads report to that thread, which then queues up the data, and writes it either serially, or in batches (depending on the requirements, and how much database activity I'm willing to put up with).


q:
I would like to quickly send email from the command line.  I realize there are probably a number of different ways to do this.

I'm looking for a simple way to do this from a linux terminal (likely a bash shell but anything should do) and an alternative way to do this on Windows.  I want to be able to whip up an email right on the command line or have the flexibility to pipe the message into the command line program.  How would you go about doing this?  If you have small scripts that would be fine as well.

[A]
```
```
$ echo "This is the email body" | mail -s "This is the subject" me@email.com
```
```
Alternatively:
```
```
$ cat | mail -s "A few lines off the top of my head" me@here.com
This is where my
multiline
message would go
^D
```
```
^D - means press
ctrl
+
d


q:
I know Windows Vista (and XP) cache recently loaded DLL's in memory...

How can this be disabled via the command prompt?

[A]
The only thing you can do is disable SuperFetch, which can be done from the command prompt with this command (there has to be a space between the = sign and disabled).
```
```
sc config Superfetch start= disabled
```
```
There is a myth out there that you can disable DLL caching, but that only worked for systems prior to Windows 2000. [
source
]


q: I see a lot of talk on here about functional languages and stuff.  Why would you use one over a "traditional" language?  What do they do better?  What are they worse at?  What's the ideal functional programming application?

[A]
One key feature in a functional language is the concept of first-class functions. The idea is that you can pass functions as parameters to other functions and return them as values.
Functional programming involves writing code that does not change state. The primary reason for doing so is so that successive calls to a function will yield the same result. You can write functional code in any language that supports first-class functions, but there are some languages, like Haskell, which do not allow you to change state. In fact, you're not supposed to make any side effects (like printing out text) at all - which sounds like it could be completely useless.
Haskell instead employs a different approach to IO: monads. These are objects that contain the desired IO operation to be executed by your interpreter's toplevel. At any other level they are simply objects in the system.
What advantages does functional programming provide? Functional programming allows coding with fewer potentials for bugs because each component is completely isolated. Also, using recursion and first-class functions allows for simple proofs of correctness which typically mirror the structure of the code.


q:
I'm attempting to create a dataset based on the properties of an object. For example, I have an instance of a Person class with properties including ID, Forename, Surname, DOB etc. Using reflection, I'm adding columns to a new dataset based on the object properties:

For Each pi As PropertyInfo In person.GetType().GetProperties()
    Dim column As New DataColumn(pi.Name, pi.PropertyType)
    table.Columns.Add(column)
Next

My problem is that some of those properies are nullable types which aren't supported by datasets. Is there any way to extract the underlying system type from a nullable type?

Thanks.

[A]
I'm guessing that the problem is recognizing whether the property is nullable or not. In C# you do this with this code:
```
```
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
```
```
... but I'm not sure what the equivalent of that last clause is in VB.NET.


q:
I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized.

I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a GScreenOverlay class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?

[A]
I would use HTML like the following:
```
```

 ... marker descriptions in here ...

```
```
You can then style this to keep the legend in the bottom right:
```
```
div#wrapper { position: relative; }
div#legend { position: absolute; bottom: 0px; right: 0px; }
```
```
```
position: relative
```
will cause any contained elements to be positioned relative to the
```
#wrapper
```
container, and
```
position: absolute
```
will cause the
```
#legend
```
div to be "pulled" out of the flow and sit above the map, keeping it's bottom right edge at the bottom of the
```
#wrapper
```
and stretching as required to contain the marker descriptions.


q:
I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself.

I'd really love for that form to be transparent and to have the transparency be user-configurable.

Is there any easy way to achieve this?

[A]
You can set the
```
Form.Opacity
```
property. It should do what you want.


q: I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.

[A]
Check out
Frinika
. It's a full-featured music workstation implemented in Java (open source). Using the API, you can run midi events through the synthesizer, read the raw sound output, and write it to a WAV file (see source code link below).
Additional information:
Frinika Developer Area
Source code for midi renderer tool


q:
We're working on an application that displays information through a Direct3D visualisation. A late client request is the ability to view this application via some Remote Desktop solution.

Has anyone done anything similar? What options are available / unavailable? I'm thinking RDC, VNC, Citrix...

Any advice?

[A]
I think you can still use all of the normal D3D tools, but you won't be able to render to a surface associated with the screen. You'll have to render to a DIB (or some such) and Blt it with GDI to a normal window HDC. RDC/VNC/Citrix should all work with this technique.
Performance will definitely suffer - but that's going to be the case over remote desktop anyway. In fact, if I were you, I would mock up a VERY simple prototype and demonstrate the performance before committing to it.
Good luck!


q:
What is the simplest and most elegant way to simulate the hover pseudo-class for non-Anchor tags in IE6?

I am specifically trying to change the cursor in this instance to that of a pointer.

[A]
I think the simplest way is to use the
hover.htc
approach. You add the hover.htc file to your site, then reference it in your stylesheet:
```
```
body { behavior:url("csshover.htc"); }
```
```
If you want to keep things as clean as possible, you can use IE conditional comments so that line is only rendered users with IE6.


q:
I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.

Something like:

Record.find(:all).date.unique.count

but of course, that doesn't seem to work.

[A]
What you're going for is the following SQL:
```
```
SELECT COUNT(DISTINCT date) FROM records
```
```
ActiveRecord has this built in:
```
```
Record.count('date', :distinct => true)
```
```


q:
I asked a question about Currying and closures were mentioned.
What is a closure? How does it relate to currying?

[A]
I'll give an example (in JavaScript):
```
```
function makeCounter () {
  var count = 0;
  return function () {
    count += 1;
    return count;
  }
}

var x = makeCounter();
x(); returns 1
x(); returns 2
...etc...
```
```
What this function,
```
makeCounter
```
, does is it returns a function, which we've called
```
x
```
, that will count up by one each time it's called. Since we're not providing any parameters to
```
x
```
, it must somehow remember the count. It knows where to find it based on what's called lexical scoping - it must look to the spot where it's defined to find the value. This "hidden" value is what is called a closure.
Here is my currying example again:
```
```
function add (a) {
  return function (b) {
    return a + b;
  }
}

var add3 = add(3);

add3(4); returns 7
```
```
What you can see is that when you call
```
add
```
with the parameter
```
a
```
(which is 3), that value is contained in the closure of the returned function that we're defining to be
```
add3
```
. That way, when we call
```
add3
```
, it knows where to find the
```
a
```
value to perform the addition.


q: Does Python have a unit testing framework compatible with the standard xUnit style of test framework? If so, what is it, where is it, and is it any good?

[A]
Python has several testing frameworks, including
```
unittest
```
,
```
doctest
```
, and
```
nose
```
. The most xUnit-like is
```
unittest
```
, which is documented on Python.org.
```
unittest
```
documentation
```
doctest
```
documentation


q:
I'm parsing text from a file and storing it in a string.  The problem is that some of the text in the original files contains ASCII art and whatnot that I would like to preserve.  When I print out the string on the HTML page, even if it does have the same formatting and everything since it is in HTML, the spacing and line breaks are not preserved.  What is the best way to print out the text in HTML exactly as it was in the original text file?

I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P

Basically, I would like suggestions on how to display ASCII art in HTML.

[A]
When you print the data use
```
nl2br()
```
to convert
```
\n
```
and
```
\r\n
```
into
```
<br>
```


q: Is there a good yacc/bison type LALR parser generator for .NET ?

[A]
The
Gardens Point Parser Generator
looks good, however I've not had a chance to try it myself.


q:
When using host headers to host multiple websites on the same IP address in IIS, is there any way of accessing that website from a browser running on the local machine?

This is normally required when a given web component only allows configuration from the local machine. It's also useful when things like ASP.Net's built in error handling isn't working and you can only view the error in the browser but don't want to allow remote users to see it.

This has baffled me for a while and everytime I come across it I end up giving up in frustration and reconfigure stuff so I can accomplish such tasks remotely.

Added: @Ishmaeel - modifying hosts doesn't seem to help - you either get a 400 error (if all websites have host headers) or whichever site is configured without a host header.

[A] Just an idea: Mapping the hostname to 127.0.0.1 in the hosts ($WINDOWS$\system32\drivers\etc) file may help. This way you should be able to pull up the local IIS site by typing the hostname as if it's a remote server


q:
I am working on a project management web application.  The user has a variety of ways to display a list of tasks.  When viewing a list page, they click on task and are redirected to the task edit page.

Since they are coming from a variety of ways, I am just curious as to the best way to redirect the user back to the calling page.  I have some ideas, but would like to get other developers input.

Would you store the calling url in session? as a cookie?  I like the concept of using an object handle the redirection.

[A]
I personally would store the required redirection info in an object and handle globally. I would avoid using a QueryString param or the like since they could try bouncing themselves back to a page they are not supposed to (possible security issue?). You could then create a static method to handle the redirection object, which could read the information and act accordingly. This encapsulates your redirection process within one page.
Using an object also means you can later extend it if required (such as adding return messages and other info).
For example (this is a 2 minute rough guideline BTW!):
```
```
public partial class _Default : System.Web.UI.Page
{

    void Redirect(string url, string messsage)
    {
        RedirectionParams paras = new RedirectionParams(url, messsage);
        RedirectionHandler(paras); // pass to some global method (or this could BE the global method)
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Redirect("mypage.aspx", "you have been redirected");
    }
}

public class RedirectionParams
{
    private string _url;

    public string URL
    {
        get { return _url; }
        set { _url = value; }
    }

    private string _message;

    public string Message
    {
        get { return _message; }
        set { _message = value; }
    }

    public RedirectionParams(string url, string message)
    {
        this.URL = url;
        this.Message = message;
    }
}
```
```


q: What's the best way to asynchronously load an BitmapImage in C# using WPF?

[A]
Assuming you're using data binding, setting
Binding.IsAsync
property to True seems to be a standard way to achieve this.
If you're loading the bitmap in the code-behind file using background thread + Dispatcher object is a common way to update UI asynchronous


q:
I have three tables: page, attachment, page-attachment

I have data like this:

page
ID    NAME
1     first page
2     second page
3     third page
4     fourth page

attachment
ID    NAME
1     foo.word
2     test.xsl
3     mm.ppt

page-attachment
ID    PAGE-ID   ATTACHMENT-ID
1     2         1
2     2         2
3     3         3

I would like to get the number of attachments per page also when that number is 0. I have tried with:

select page.name, count(page-attachment.id) as attachmentsnumber
from page
    inner join page-attachment on page.id=page-id
group by page.id

I am getting this output:

NAME        ATTACHMENTSNUMBER
second page  2
third page   1

I would like to get this output:

NAME        ATTACHMENTSNUMBER
first page   0
second page  2
third page   1
fourth page  0

How do I get the 0 part?

[A]
Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right."
```
```
select page.name, count(page-attachment.id) as attachmentsnumber
from page
    left outer join page-attachment on page.id=page-id
group by page.name
```
```


q: When and how should table stats gathering be performed for Oracle, version 9 and up? How would you go about gathering stats for a large database, where stats gathering would collide with "business hours".

[A]
Gathering stats should be done whenever there has been large changes to the data content, for example a large number of deletes or inserts.  If the table structure has changed you should gather stats also.  It is advisable to use the 'ESTIMATE' option.
Do this as an automated process out of business hours if possible, or if you have to do it during business hours then choose a time when there is minimum access to the tables you wish to gather stats for.


q: I am using forms authentication. My users are redirected to a page (written in web.config) when they login, but some of them may not have the privilages to access this default page. In this case, I want them to redirect to another page but RedirectFromLoginPage method always redirects to the default page in web.config. How do I make the users login, and then redirect to a page which depends on some criteria?

[A]
The
```
SetAuthCookie
```
allows you to issue the auth cookie but retain control over the navigation. After that method is called you can run your logic to do a typical ASP.NET redirect to wherever you want.


q: How can I set the cookies in my PHP apps as HttpOnly cookies?

[A]
Explanation here from Ilia... 5.2 only though
httpOnly cookie flag support in PHP 5.2
As stated in that article, you can set the header yourself in previous versions of PHP
```
```
header("Set-Cookie: hidden=value; httpOnly");
```
```


q:
What do *args and **kwargs mean?

def foo(x, y, *args):
def bar(x, y, **kwargs):

[A]
From the Python documentation:
If there are more positional arguments than there are formal parameter slots, a TypeError exception is raised, unless a formal parameter using the syntax "*identifier" is present; in this case, that formal parameter receives a tuple containing the excess positional arguments (or an empty tuple if there were no excess positional arguments).
If any keyword argument does not correspond to a formal parameter name, a TypeError exception is raised, unless a formal parameter using the syntax "**identifier" is present; in this case, that formal parameter receives a dictionary containing the excess keyword arguments (using the keywords as keys and the argument values as corresponding values), or a (new) empty dictionary if there were no excess keyword arguments.


q:
I want to swap two integers, and I want to know which of these two implementations will be faster:
The obvious way with a temp variable:

void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

Or the xor version that I'm sure most people have seen:

void swap(int* a, int* b)
{
    *a ^= *b;
    *b ^= *a;
    *a ^= *b;
}

It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each.  Can someone tell me which is faster and why?  The why being more important.

[A]
Number 2 is often quoted as being the "clever" way of doing it. It is in fact most likely slower as it obscures the explicit aim of the programmer - swapping two variables. This means that a compiler can't optimize it to use the actual assembler ops to swap. It also assumes the ability to do a bitwise xor on the objects.
Stick to number 1, it's the most generic and most understandable swap and can be easily templated/genericized.
This wikipedia section explains the issues quite well:
http://en.wikipedia.org/wiki/XOR_swap_algorithm#Reasons_for_avoidance_in_practice


q:
We have been working with CVS for years, and frequently find it useful to "sticky" a single file here and there.

Is there any way to do this in subversion, specifically from TortoiseSVN?


q:
I'm mainly a C# developer, but I'm currently working on a project in Python.

How can I represent the equivalent of an Enum in Python?

[A]
Before PEP 435, Python didn't have an equivalent but you could implement your own.
Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...
```
```
class Animal:
    DOG = 1
    CAT = 2

x = Animal.DOG
```
```
In Python 3.4 (
PEP 435
), you can make
Enum
the base class.  This gets you a little bit of extra functionality, described in the PEP.  For example, enum members are distinct from integers, and they are composed of a
```
name
```
and a
```
value
```
.
```
```
from enum import Enum

class Animal(Enum):
    DOG = 1
    CAT = 2

print(Animal.DOG)
# <Animal.DOG: 1>

print(Animal.DOG.value)
# 1

print(Animal.DOG.name)
# "DOG"
```
```
If you don't want to type the values, use the following shortcut:
```
```
class Animal(Enum):
    DOG, CAT = range(2)
```
```
```
Enum
```
implementations
can be converted to lists and are iterable
. The order of its members is the declaration order and has nothing to do with their values. For example:
```
```
class Animal(Enum):
    DOG = 1
    CAT = 2
    COW = 0

list(Animal)
# [<Animal.DOG: 1>, <Animal.CAT: 2>, <Animal.COW: 0>]

[animal.value for animal in Animal]
# [1, 2, 0]

Animal.CAT in Animal
# True
```
```


q:
In MS SQL Server, I create my scripts to use customizable variables:

DECLARE @somevariable int
SELECT @somevariable = -1

INSERT INTO foo VALUES ( @somevariable )

I'll then change the value of @somevariable at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.

How do I do the same with the PostgreSQL client psql?

[A]
FWIW, the real problem was that I had included a semicolon at the end of my \set command:
\set owner_password 'thepassword';
The semicolon was interpreted as an actual character in the variable:
\echo :owner_password
  thepassword;
So when I tried to use it:
CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';
...I got this:
CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';
That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").
The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.


q: Should you ever use protected member variables?  What are the the advantages and what issues can this cause?

[A]
Should you ever use protected member variables?
Depends on how picky you are about hiding state.
If you don't want any leaking of internal state, then declaring all your member variables private is the way to go.
If you don't really care that subclasses can access internal state, then protected is good enough.
If a developer comes along and subclasses your class they may mess it up because they don't understand it fully.  With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later.


q:
It is generally accepted that the use of cursors in stored procedures should be avoided where possible (replaced with set based logic etc). If you take the cases where you need to iterate over some data, and can do in a read only manner, are fast forward (read only forward) cursor more or less inefficient than say while loops? From my investigations it looks as though the cursor option is generally faster and uses less reads and cpu time.  I haven't done any extensive testing, but is this what others find?  Do cursors of this type (fast forward) carry additional overhead or resource that could be expensive that I don't know about.

Is all the talk about not using cursors really about avoiding the use of cursors when set-based approaches are available, and the use of updatable cursors etc.

[A]
People avoid cursor because they generally are more difficult to write than a simple while loops, however, a while loop can be expensive because your constantly selecting data from a table, temporary or otherwise.
With a cursor, which is readonly fast forward, the data is kept in memory and has been specifically designed for looping.
This article
highlights that an average cursor runs 50 times faster than a while loop.


q:
I'm currently using and enjoying using the Flex MVC framework PureMVC.  I have heard some good things about Cairngorm, which is supported by Adobe and has first-to-market momentum.  And there is a new player called Mate, which has a good deal of buzz.

Has anyone tried two or three of these frameworks and formed an opinion?

Thanks!

[A]
Mate
is my pick. The first and foremost reason is that it is completely unobtrusive. My application code has no dependencies on the framework, it is highly decoupled, reusable and testable.
One of the nicest features of Mate is the declarative configuration, essentially you wire up your application in using tags in what is called an event map -- basically a list of events that your application generates, and what actions to take when they occur. The event map gives a good overview of what your application does. Mate uses Flex' own event mechanism, it does not invent its own like most other frameworks. You can dispatch an event from anywhere in the view hierarchy and have it bubble up to the framework automatically, instead of having to have a direct line, like Cairngorms CairngormEventDispatcher or PureMVC's notification system.
Mate also uses a form of dependency injection (leveraging bindings) that makes it possible to connect your models to your views without either one knowing about the other. This is probably the most powerful feature of the framework.
In my view none of the other Flex application frameworks come anywhere near Mate. However, these are the contenders and why I consider them to be less useful:
PureMVC actively denies you many of the benefits of Flex (for example bindings and event bubbling) in order for the framework to be portable -- a doubious goal in my view. It is also over-engineered, and as invasive as they come. Every single part of your application depends on the framework. However, PureMVC isn't terrible, just not a very good fit for Flex. An alternative is
FlexMVCS
, an effort to make PureMVC more suitable for Flex (unfortunately there's no documentation yet, just source).
Cairngorm is a bundle of anti-patterns that lead to applications that are tightly coupled to global variables. Nuff said (but if you're interested,
here are some more of my  thoughts
, and
here too
).
Swiz
is a framework inspired by the Spring framework for Java and Cairngorm (trying to make up for the worst parts of the latter). It provides a dependency injection container and uses metadata to enable auto-wiring of dependencies. It is interesting, but a little bizzare in that goes to such lengths to avoid the global variables of Cairngorm by using dependency injection but then uses a global variable for central event dispatching.
Those are the ones I've tried or researched. There are a few others that I've heard about, but none that I think are widely used. Mate and Swiz were both presented at the recent 360|Flex conference, and there are videos available (
the Mate folks have instructions on how to watch them
)


q:
Has anyone used Lucene.NET rather than using the full text search that comes with sql server?

If so I  would be interested on how you implemented it.

Did you for example write a windows service that queried the database every hour then saved the results to the lucene.net index?

[A]
I have not done it against database yet, your question is kinda open.
If you want to search an db, and can choose to use Lucene, I also guess that you can control when data is inserted to the database.
If so, there is little reason to poll the db to find out if you need to reindex, just index as you insert, or create an queue table which can be used to tell lucene what to index.
I think we don't need another indexer that is ignorant about what it is doing, and reindexing everytime, or uses resources wasteful.


q:
On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.

I had to do the following to build Apache and mod_rewrite:

./configure --prefix=/usr/local/apache2 --enable-rewrite=shared

Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?

Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache?

(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)

[A]
Try the
```
./configure
```
option
```
--enable-mods-shared="all"
```
, or
```
--enable-mods-shared="<list of modules>"
```
to compile modules as shared objects. See further
details in Apache 2.2 docs
To just compile Apache with the ability to load shared objects (and add modules later), use
```
--enable-so
```
, then consult the documentation on compiling modules seperately in the
Apache 2.2. DSO docs
.


q:
This is a somewhat low-level question.  In x86 assembly there are two SSE instructions:

MOVDQA xmmi, m128

and

MOVNTDQA xmmi, m128

The IA-32 Software Developer's Manual says that the NT in MOVNTDQA stands for Non-Temporal, and that otherwise it's the same as MOVDQA.

My question is, what does Non-Temporal mean?

[A]
Non-Temporal SSE instructions (MOVNTI, MOVNTQ, etc.), don't follow the normal cache-coherency rules. Therefore non-temporal stores must be followed by an SFENCE instruction in order for their results to be seen by other processors in a timely fashion.
When data is produced and not (immediately) consumed again, the fact that memory store operations read a full cache line first and then modify the cached data is detrimental to performance. This operation pushes data out of the caches which might be needed again in favor of data which will not be used soon. This is especially true for large data structures, like matrices, which are filled and then used later. Before the last element of the matrix is filled the sheer size evicts the first elements, making caching of the writes ineffective.
For this and similar situations, processors provide support for non-temporal write operations. Non-temporal in this context means the data will not be reused soon, so there is no reason to cache it. These non-temporal write operations do not read a cache line and then modify it; instead, the new content is directly written to memory.
Source:
http://lwn.net/Articles/255364/


q:
What is currently the best way to get a favicon to display in all browsers that currently support it?

Please include:

Which image formats are supported by which browsers.

Which lines are needed in what places for the various browsers.

[A]
Having a
```
favicon.*
```
in your root directory is automatically detected by most browsers. You can ensure it's detected by using:
```
```
<link rel="icon" type="image/png" href="/path/image.png" />
```
```
Personally I use .png images but most formats should work.


q:
How do I avoid read locks in my database?

Answers for multiple databases welcome!

[A]
In SQL Server you can use the with(nolock) keyword in your select statements.  For example:
```
```
Select table1.columna, table2.columna
from table1 with(nolock), table2 with(nolock)
```
```
Make sure to specify with(nolock) for each table/view in the query.


q:
Is there a way clear or reset the outputcache for an entire website without a restart?

I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it.

[A]
This should do the trick:
```
```
Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

 Dim path As String
 path="/AbosoluteVirtualPath/OutputCached.aspx"
 HttpResponse.RemoveOutputCacheItem(path)

End Sub
```
```


q:
I have a container div with a fixed width and height, with overflow: hidden.

I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the height of the parent should not allow this. This is how this looks:

How I would like it to look:

![Right][2] - removed image shack image that had been replaced by an advert

Note: the effect I want can be achieved by using inline elements & white-space: no-wrap (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements.

[A]
This seems close to what you want:
```
```
#foo {
  background: red;
  max-height: 100px;
  overflow-y: hidden;
}

.bar {
  background: blue;
  width: 100px;
  height: 100px;
  float: left;
  margin: 1em;
}
```
```
```
```

```
```


q:
What's are the best practices for versioning web sites?

Which revision control systems are well suited for such a job?

What special-purpose tools exist?

What other questions should I be asking?

[A]
Firstly you can - and should - use a revision control system, most will handle binary files although unlike text files you can't merge two different set of changes so you may want to set the system up to lock these files whilst they are being changed (assuming that that's not the default mode of operation for you rcs in the first place).
Where things get a bit more interesting for Websites is managing those files that are required for the site but don't actually form part of the site - the most obvious example being something like .psd files from which web graphics are produced but which don't get deployed.
We therefore have a tree for each site which has two folders: assets and site. Assets are things that aren't in the site, and site is - well the site.
What you have to watch with this is that designers tend to have their own "systems" for "versioning" graphic files (count the layers in the PSD). You don't need necessarily to stop them doing this but you do need to ensure that they commit each change too.
Other questions?
Deployment. We're still working on this one (-: But we're getting better (I'm happier now with what we do!)
Murph


q:
We generate web pages that should always be printed in landscape mode. Web browser print dialogs default to portrait, so for every print job the user has to manually select landscape. It's minor, but would be nice for the user if we can remove this unnecessary step.

Thanks in advance to all respondents.

[A]
The
```
@page
```
rule is supposed to allow this, but is only implemented in Opera.


q:
Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. (Now I need the answer to this)

the current users My Documents  dirctory (okay this has been answered)
and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.

[A]
My docs would probably best be handled by accessing:
```
```
System.getProperty("user.home");
```
```
Look up the docs on
System.getProperty
.


q:
What is the SQL query to select all of the MSSQL Server's logins?

Thank you.  More than one of you had the answer I was looking for:

SELECT * FROM syslogins

[A]
```
```
EXEC sp_helplogins
```
```
You can also pass an "@LoginNamePattern" parameter to get information about a specific login:
```
```
EXEC sp_helplogins @LoginNamePattern='fred'
```
```


q:
I have developed some classes with similar behavior, they all implement the same interface.  I implemented a factory that creates the appropriate object and returns the interface.  I am writing a unit test for the factory.  All you get back is an interface to the object.
What is the best way to test that the factory has worked correctly?

I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.

Number 2. in the answer, would be done like the other answer?  If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.

[A]
Since I don't know how your factory method looks like, all I can advise right now is to
Check to see the object is the correct concrete implementation you were looking for:
```
```
IMyInterface fromFactory = factory.create(...);
Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1);
```
```
You can check if the factory setup the concrete instances with valid instance variables.


q:
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an ON clause in C#.

How do you represent the following in LINQ to SQL:

select DealerContact.*
from Dealer
inner join DealerContact on Dealer.DealerID = DealerContact.DealerID

[A]
It goes something like:
```
```
from t1 in db.Table1
join t2 in db.Table2 on t1.field equals t2.field
select new { t1.field2, t2.field3}
```
```
It would be nice to have sensible names and fields for your tables for a better example. :)
Update
I think for your query this might be more appropriate:
```
```
var dealercontacts = from contact in DealerContact
                     join dealer in Dealer on contact.DealerId equals dealer.ID
                     select contact;
```
```
Since you are looking for the contacts, not the dealers.


q:
We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model.  Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that.  I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results?

We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable.

EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.

[A]
It's right under your nose:
```
```
List<TableItem> myResult = (from t in db.Table select t).ToList();
```
```
Now, just cache myResult as you would have cached your old DAL's returned data.


q:
We have a whole bunch of DLLs that give us access to our database and other applications and services.

We've wrapped these DLLs with a thin WCF service layer which our clients then consume.

I'm a little unsure on how to write unit tests that only test the WCF service layer. Should I just write unit tests for the DLLs, and integration tests for the WCF services? I'd appreciate any wisdom... I know that if my unit tests actually go to the database they won't actually be true unit tests. I also understand that I don't really need to test the WCF service host in a unit test.

So, I'm confused about exactly what to test and how.

[A]
If you want to unit test your WCF service classes make sure you design them with loose coupling in mind so you can mock out each dependancy as you only want to test the logic inside the service class itself.
For example, in the below service I break out my data access repository using "Poor Man's Dependency Injection".
```
```
Public Class ProductService
    Implements IProductService

    Private mRepository As IProductRepository

    Public Sub New()
        mRepository = New ProductRepository()
    End Sub

    Public Sub New(ByVal repository As IProductRepository)
        mRepository = repository
    End Sub

    Public Function GetProducts() As System.Collections.Generic.List(Of Product) Implements IProductService.GetProducts
        Return mRepository.GetProducts()
    End Function
End Class
```
```
On the client you can mock the WCF service itself using the interface of the service contract.
```
```
<TestMethod()> _
Public Sub ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse()
    mMockery = New MockRepository()
    mView = DirectCast(mMockery.Stub(Of IProductView)(), IProductView)
    mProductService = DirectCast(mMockery.DynamicMock(Of IProductService)(), IProductService)
    mPresenter = New ProductPresenter(mView, mProductService)
    Dim ProductList As New List(Of Product)()
    ProductList.Add(New Product)
    Using mMockery.Record()
        SetupResult.For(mView.PageIsPostBack).Return(False).Repeat.Once()
        Expect.Call(mProductService.GetProducts()).Return(ProductList).Repeat.Once()
    End Using
    Using mMockery.Playback()
        mPresenter.OnViewLoad()
    End Using
    'Verify that we hit the service dependency during the method when postback is false
    Assert.AreEqual(1, mView.Products.Count)
    mMockery.VerifyAll()
End Sub
```
```


q:
I'm exploring the possibility of writing an application in Erlang, but it would need to have a portion written in Cocoa (presumably Objective-C). I'd like the front-end and back-end to be able to communicate easily. How can this best be done?

I can think of using C ports and connected processes, but I think I'd like a reverse situation (the front-end starting and connecting to the back-end). There are named pipes (FIFOs), or I could use network communications over a TCP port or a named BSD socket. Does anyone have experience in this area?

[A]
One way would be to have the Erlang core of the application be a daemon that the Cocoa front-end communicates with over a Unix-domain socket using some simple protocol you devise.
The use of a Unix-domain socket means that the Erlang daemon could be launched on-demand by
```
launchd
```
and the Cocoa front-end could find the path to the socket to use via an environment variable.  That makes the rendezvous between the app and the daemon trivial, and it also makes it straightforward to develop multiple front-ends (or possibly a framework that wraps communication with the daemon).
The Mac OS X
```
launchd
```
system is really cool this way.  If you specify that a job should be launched on-demand via a secure Unix-domain socket,
```
launchd
```
will actually create the socket itself with appropriate permissions, and advertise its location via the environment variable named in the job's property list.  The job, when started, will actually be passed a file descriptor to the socket by
```
launchd
```
when it does a simple check-in.
Ultimately this means that the entire process of the front-end opening the socket to communicate with the daemon,
```
launchd
```
launching the daemon, and the daemon responding to the communication can be secure, even if the front-end and the daemon run at different privilege levels.


q: Why are SQL distributions so non-standard despite an ANSI standard existing for SQL? Are there really that many meaningful differences in the way SQL databases work or is it just the two databases with which I have been working: MS-SQL and PostgreSQL? Why do these differences arise?

[A]
The ANSI standard specifies only a limited set of commands and data types. Once you go beyond those, the implementors are on their own. And some very important concepts aren't specified at all, such as auto-incrementing columns. SQLite just picks the first non-null integer, MySQL requires
```
AUTO INCREMENT
```
, PostgreSQL uses sequences, etc. It's a mess, and that's only among the OSS databases! Try getting Oracle, Microsoft, and IBM to collectively decide on a tricky bit of functionality.


q:
The minimum spanning tree problem is to take a connected weighted graph and find the subset of its edges with the lowest total weight while keeping the graph connected (and as a consequence resulting in an acyclic graph).

The algorithm I am considering is:

Find all cycles.

remove the largest edge from each cycle.

The impetus for this version is an environment that is restricted to "rule satisfaction" without any iterative constructs. It might also be applicable to insanely parallel hardware (i.e. a system where you expect to have several times more degrees of parallelism then cycles).

Edits:

The above is done in a stateless manner (all edges that are not the largest edge in any cycle are selected/kept/ignored, all others are removed).

[A]
What happens if two cycles overlap?  Which one has its longest edge removed first?  Does it matter if the longest edge of each is shared between the two cycles or not?
For example:
```
```
V = { a, b, c, d }
E = { (a,b,1), (b,c,2), (c,a,4), (b,d,9), (d,a,3) }
```
```
There's an a -> b -> c -> a cycle, and an a -> b -> d -> a