Question:
I am working on a windows service that polls for a connection to a network enabled devices every 15 seconds.  If the service is not able to connect to a device, it throws an exception and tries again in 15 seconds.  All of this works great.

But, lets say one of the devices is down for a day or more.  I am filling up my exception log with the same exception every 15 seconds.  Is there a standard way to prevent an exception from being written to the event log if the exception being thrown hasn't changed in the last x number of hours?

Answer:
Maybe have a workflow that if the polls fails for a certain number of times, the polling interval is increased. e.g. polls every 15 seconds for like 3 times, if it fails then increase the polling interval to one minute, if it fails for n times then increase the time to one hour.
To be honest the workflow above doesnt really solve your problem. If I were you, I would reverse the workflow. Instead of the server polling for devices, why not do it the other way round? When a device connected to a networked machine, your client side service sends a message to the server, so that the server knows that the device is connected and alive.
Hope this helps...
RWendi


Question:
How can you find out the number of active users when you're using a StateServer?   Also is it possible to query the StateServer and retrieve the contents in the Session State?

I know that this is all possible if you use SqlServer for a backing store, but I want them to be in memory.

Answer:
Tracking the number of users would need to be done at the application level, not the session level.
You should be able to see what is currently in the session with the following:
```
```
StringBuilder builder = new StringBuilder();
foreach ( String key in Session.Contents ) {
    builder.AppendFormat("{0}: {1}<br />", key, Session[key]);
}
Response.Write(builder.ToString());
```
```


Question: Is this possible?  I want to have the To:, Body, and an Attachment all pre-populated so all the user has to do is click send.  Thanks!

Answer:
Open a new mail message (
```
ipm.note
```
is the
message class
for emails)
```
```
outlook.exe /c ipm.note
```
```
Open a new mail message and populate sender:
```
```
outlook.exe /c ipm.note /m someone@microsoft.com
```
```
Open a new mail message with attachment:
```
```
outlook.exe /c ipm.note /a filename
```
```
Combination: (First one below didn't work in Office 2016, second did)
```
```
outlook.exe /c ipm.note /m someone@microsoft.com&subject=test%20subject&body=test%20body
 outlook.exe /c ipm.note /m "someone@microsoft.com&subject=test%20subject&body=test%20body"
```
```
The %20 has to be used to produce a blank space.
More details at
Command Line for Creating a Pre-Addressed E-mail Message
Command-line switches can be found
here
This works for instance with a classic Outlook 2016 (build 16.0.4849.1000).
But, as
Snozzlebert
notes
in the comments
, for a  Outlook 365 Version 2001 (Build 12430.20184) the syntax would be:
```
```
outlook.exe /c ipm.note /m "someone@microsoft.com?subject=test"
```
```
the culprit was the
```
&
```
after the email-address - replacing it with
```
?
```
solved the problem.
It seems that Microsoft changed the syntax to the HTML mailto syntax.


Question: Are there any plugins/tools available to go through the classpath of an eclipse project (or workspace) and highlight any unused jars?

Answer:
ClassPathHelper
is a good start.
It automatically identifies orphan jars and much more.
The only limitation is with dependencies that are not defined in classes, e.g. in dependency injection framework configuration files.
You also have other options/complements, such as:
workingfrog "Relief"
, which relies on the ability to deal with real objects by examining their shape, size or relative place in space it gives a "physical" view on java packages, types and fields and their relationships, making them easier to handle.
Unnecessary Code Detector
: a eclipse PlugIn tool to find unnecessary (dead) public java code.


Question: Anyone have a good resource or provide a sample of a natural order sort in C# for an FileInfo array?  I am implementing the IComparer interface in my sorts.

Answer:
The easiest thing to do is just P/Invoke the built-in function in Windows, and use it as the comparison function in your
```
IComparer
```
:
```
```
[DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
private static extern int StrCmpLogicalW(string psz1, string psz2);
```
```
Michael Kaplan has some
examples of how this function works here
, and the changes that were made for Vista to make it work more intuitively. The plus side of this function is that it will have the same behaviour as the version of Windows it runs on, however this does mean that it differs between versions of Windows so you need to consider whether this is a problem for you.
So a complete implementation would be something like:
```
```
[SuppressUnmanagedCodeSecurity]
internal static class SafeNativeMethods
{
    [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
    public static extern int StrCmpLogicalW(string psz1, string psz2);
}

public sealed class NaturalStringComparer : IComparer<string>
{
    public int Compare(string a, string b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a, b);
    }
}

public sealed class NaturalFileInfoNameComparer : IComparer<FileInfo>
{
    public int Compare(FileInfo a, FileInfo b)
    {
        return SafeNativeMethods.StrCmpLogicalW(a.Name, b.Name);
    }
}
```
```


Question:
Is it legal to more or less "copy" (or euphemistically, be very "inspired by") the idea and UI of a copyrighted program? This question popped in my mind when looking at "Things" which is a Mac-only program.

How legal would it be for someone to make a Windows version of this program with a basically identical UI design and feature set? Where are the legal boundaries of what counts as copyright infringement?

Unless you specify otherwise, I am assuming an "IANAL" for any answer, so you don't have to write that. ;)

Answer:
Specific elements of a design can be copyrighted. Apple won the "trashcan" icon, but effectively nothing else during the Microsoft/Apple lawsuit over a look and feel. As long as the code is entirely your own, the graphics are your own (and yes, copying too closely a
specific
graphic element like the trashcan can be a problem) and you aren't doing cloning elements that are trademark/tradedress related, you should be within the law (in the US).
Of course, that doesn't mean that someone can't
sue
you. Meritless lawsuits are started all the time for intimidation. Also note that patents can cover the interaction of the user with a UI, so copyright might not be your primary problem in some cases.


Question: I have a private const int defined in a C# class. I want compilation to fail with an error if the value of this int mod 3 != 0. How can I accomplish this?

Answer:
Although there is an
#error
pre-processor directive for generating compile-time errors, there is no way for it to be based on the existence of a const value. It only works with compiler symbols, like "DEBUG", for which a value can't be assigned.


Question:
I'm experiencing an issue with ActiveMQ and would like to trace/view all ActiveMQ activity.  The only log file I can find is one associated with persistent data (if this is turned on).  Are there any other log files I view or generate to tell me what's happening under the hood of ActiveMQ and why my consumers aren't consuming messages?  Any other suggestions?

Thanks in advance!

Answer:
activemq has a jmx interface that you can connect to.
this gives us access to consumer counts messages queued dequeue and all sorts of data on memory usage etc.
http://activemq.apache.org/jmx.html
Has all the details to get you started.
I find it excellent in finding out whats going on with activemq.
A quick firing up of jconsole and you will be well on your way to finding out what is going on.
Paul


Question:
I want to do a select in MySql that combines several columns... something like this pseudocode:

SELECT payment1_paid AND payment2_paid AS paid_in_full
FROM denormalized_payments
WHERE payment1_type = 'check';

Edit: payment1_paid and payment2_paid are booleans.

I can't use any other language for this particular problem than MySql.

Thanks for any help!

Edit: Sorry to everybody who gave me suggestions for summing and concatenating, but I've voted those early answers up because they're useful anyway. And thanks to everybody for your incredibly quick answers!

Answer:
Just do
```
```
Select CONCAT(payment1_paid, payment2_paid) as paid_in_full
from denormalized_payments
where payment1_type = 'check';
```
```
You can concat any number of field you want.


Question:
I need to have a single instance application (as per this answer), but it needs to be deployed via click once.

The problem is that I require that click once doesn't automatically detect an update an attempt to load a newer version while the application is running.  If it is running, then I need the other instance to be made active. Usually, when selecting a Click Once link, the very first thing it does is attempt to find an update. I want to intercept this and check for an already running instance prior to launching the normal update process.

Does anyone know how this is possible within a Click Once deployment scenario?

Answer:
I don't think you'll be able to do it quite like this as the check before run is outside of your code.
However you can change the clickonce deployment options to check for updates during code execution.
If you need more control then you can use the
ApplicationDeployment Update
or
CheckForUpdate
methods to have absolute over the update process.


Question:
This is the sequel to this question.

I would like to combine three columns into one on a MySql select. The first two columns are boolean and the third is a string, which is sometimes null. This causes strange results:

Select *, (payment1_paid && ((payment2_paid || payment2_type ="none"))) as paid_in_full from payments

Note: payment1_paid is boolean, payment2_paid is boolean, payment2_type is varchar.

Note: Please ignore how ridiculous the structure of this table is. Behind every piece of bad code there is a long explanation :)

Edit: Null is not interesting to me for the varchar value. I only want to know if it's really "none."

Thanks in advance for your help!

Answer:
I guess you want NULL to be false? Try
```
(payment_paid IS NULL || payment2_type = "none")
```


Question:
Back in the earlier days of the internet I remember that in certain browsers, every time you downloaded an image or a file, the URL of where that file was downloaded from would be written into that file's properties (I guess the summary tab?). I think Netscape v2 did this if I remember correctly.

I really miss that kind of functionality as every once in a while I'll run into a neat little program stored somewhere in the depths of my hard drive and wonder where I got it from originally.

I googled around but I'm not quite sure what terms to use to describe what I'm looking for. So I'm wondering if anyone knows of a Firefox plug-in or something similar that would do this?

Answer:
For the IE Browser I use the hell out of Fidler to look at all traffic going across the wire.
For FireFox, you can use the FireBug plugin. There is a "Net" tab that will show you request information that is going across the wire.
Most of the time you can use one of these tools to see what URL was requested in order to start a download. You can also view all the get and post information that might need to be sent in order to have your request succeed.
Fidler is here:
http://www.fiddlertool.com/fiddler/
FireBug is here:
https://addons.mozilla.org/en-US/firefox/addon/1843
Best of Luck!


Question:
So I'm reading The Art & Science of Javascript, which is a good book, and it has a good section on JSONP. I've been reading all I can about it today, and even looking through every question here on StackOverflow. JSONP is a great idea, but it only seems to resolve the "Same Origin Problem" for getting data, but doesn't address it for changing data.

Did I just miss all the blogs that talked about this, or is JSONP not the solution I was hoping for?

Answer:
JSONP results in a SCRIPT tag being generated to another server with any parameters that might be required as a GET request. e.g.
```
```
<script src="http://myserver.com/getjson?customer=232&callback=jsonp543354" type="text/javascript">
</script>
```
```
There is technically nothing to stop this sort of request altering data on the server, e.g. specifying newName=Tony.  Your response could then be whether the update succeeded or not.  You will be limited by whatever you can fit on a querystring.  If you are going with this approach add some random element as a parameter so that proxy's won't cache it.
Some people may consider this goes against the way GET's are supposed to work i.e. they shouldn't cause data to change.


Question:
Has anyone ever tried, or had any success at getting Wascana (Eclipse CDT + MinGW for Windows) to compile FFMPEG under Windows. Apparently it is possible, there is even a tutorial at Craig Shaw's website but I have not been able to make it work.

I run ./configure on the FFMPEG source code then create a new project in Eclipse and point it at the source but it doesn't recognise it as a Makefile project. I think I need to create a builder which works with MinGW but my feeble attempts so far have been unsuccessful.

Answer:
Hey, I can answer my own question! After a lot of fiddling around, I have come up with the procedure:
NOTE: This is for Wascana 0.9.3 and a Sep 2008 SVN version of FFMPEG.
Prepare Environment
After installing Wascana, you'll need to update various MinGW and MSYS packages. Download and unpack the following (you can download them from the MinGW website):
MSYS packages:
bash-3.1
coreutils-5.97
m4-1.4.7
make-3.81
MinGW packages:
w32api-3.12
MinGW Runtime 3.15
Build
Unpack the FFMPEG source code and configure like so (do not compile it yet):
./configure --enable-memalign-hack --disable-shared --enable-static --disable-mmx --disable-mmx2 --disable-optimizations --disable-stripping
Launch Wascana/Eclipse and create a new C project.
Do not select "Hello World" project, just select a Makefile project and select the MinGW toolchain.
Set the project path to wherever your FFMPEG source code is.
Click finish and the source should build itself!
Install
Right click the project and select Make Targets > Create.
In the dialog, set both the Make Target and Target name to "install".
Run the target you just created. This will install the FFMPEG libraries.
Execute and Debug
Open the Debug Dialog
Right-click on "C/C++ Local Application" and choose "New"
Fill in the project name and select the EXE you want to run (in my case, ffplay_g.exe)
Go to the debugger tab and change the debugger to "MinGW gdb Debugger"
I also had to make sure a copy of SDL.dll was in the ffmpeg directory.
Phew, what an ordeal. That all worked for me, hopefully it will work for you too!


Question: I need to write an extension method on a byte[].  Is that possible?

Answer:
Sure, just make the first parameter of type
```
byte[]
```
.


Question: When I press the standard Ctrl + E, C (an other variants) in VS2008 whilst editing a CSS file, it says that command is not available. How do I setup a shortcut to apply a plain old /* */ comment to selected text in VS? Thanks

Answer:
Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module...
Paste the following in the source editor:
```
```
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module CommentCSS
    Sub CommentCSS()
        Dim selection As TextSelection
        selection = DTE.ActiveDocument.Selection

        Dim selectedText As String
        selectedText = selection.Text

        If selectedText.Length > 0 Then
            selection.Text = "/*" + selectedText + "*/"
        End If
    End Sub
End Module
```
```
You can create a keyboard shortcut by going to Tools|Options... and selecting
Keyboard
under the
Environment
section in the navigation on the left.  Select your macro and assign any shortcut you like.
You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the
Macros
section in the navigation on the left.  Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.


Question:
My realtime app generates a data log: 100 words of data @10Khz.  I need to analyze it and produce some plots of the results.   There are intermediate calculations involved - I need to take some differences, averages, etc.   Excel would work fine, except for:

the 32000 item limit on graph data series is too small - that's only 3 seconds of data.

the glacial speed at which it processes changes to graphs containing large data series is unbearable.

What are good alternatives to Excel for manipulating and plotting large quantities of data?  I'm looking for something interactive, not a library.

Answer:
For this sort of stuff we typically roll our own, but I know that isn't the solution you want. Can you use a good quality database (eg Oracle) to do the manipulation, then maybe put the summarized data back into Excel for the plotting? I believe Excel will link to databases these days, so you could make it quite automated.
Otherwise there are statistical tools like [SAS][1], but get your cheque book out first.
[1]:
http://www.sas.com/technologies/analytics/statistics/stat/index.html
SAS


Question:
I have an app which could benefit from the user being able to choose to set an image as the wallpaper (the background image on the "slide to unlock" screen).

Is there a way for non-jailbreak third-party apps to do this? A search for "wallpaper" in the iPhone documentation returns nothing.

Answer:
```
```
<configuration>
   <system.web>
      <compilation>
         <assemblies>
            <add assembly="<AssemblyName>, Version=<Version>, Culture=<Culture>, PublicKeyToken=<PublicKeyToken>"/>
         </assemblies>
      </compilation>
   </system.web>
</configuration>
```
```


Question:
I have a table like as follows:

SoftwareName    Count    Country
Project         15       Canada
Visio           12       Canada
Project         10       USA
Visio           5        USA

How do I query it to give me a summary like...

SoftwareName    Canada    USA    Total
Project         15        10     25
Visio           12        5      17

How to do in T-SQL?

Answer:
```
```
SELECT SoftwareName,
  SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada,
  SUM( CASE Country WHEN 'USA'    THEN [Count] ELSE 0 END ) AS USA,
  SUM( [Count] ) AS Total
FROM [Table]
GROUP BY SoftwareName;
```
```


Question:
I have heard that LINQ2SQL has been written to support multiple database vendor providers however for internal political reasons at MS, only SQL Server has been supported.

Is this a fair summary of the situation, and if so has a timetable been released as to when other databases will be supported?

I am aware of Matt Warren's BUILDING AN IQUERYABLE PROVIDER series on the wayward weblog, but I would prefer not to build something now that will be released (probably better than I will do it) later

Answer:
Check the
ADO.NET Entity Framework
(and
Linq to Entities
), you can look here also a
Sample Entity Framework Provider for Oracle
, and
here
are more examples about creating Data Providers for EF.


Question:
I know that it is possible (in theory) to create a new type at run-time, but is it possible to modify a method body of an existing type at run-time? My plan (if I can get this to work) is to tag up methods with a custom attribute, and then at run-time search for methods with the attribute, and insert some of my own code into the method body.

Any suggestions?

I suppose if I can't get that approach to work, I could always go with a virtual method in a base class (with the attributes), combined with a static factory to spit out a derived dynamic type with my run-time generated method in the child class. This would not be quite as clean to use though.

Answer:
Are you planning to do this for arbitrary types?  I would suppose not given that you are going to decorate the methods with an attribute.
Given that, I would think the better approach would be to define abstract methods in a super class for your types.  A method on the super class can house the boiler-plate method code, and delegate to the concrete implementations via the abstract methods for the individual type's behavior of that method.
Generally speaking though, unless you get into create code files and compiling dynamic assemblies at runtime, what you are looking to do can't be done.  There are likely far more practical OO principles and patterns you can use to achieve close to the same result.


Question:
I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type:

java CliMain arg1 arg2

And another running GUI instance would perform an appropriate action.

What is the easiest way of implementing something like this?

Answer:
You could have the GUI application listen on a TCP port (on the
```
localhost
```
interface) and the CLI application would connect to it.
One way to do this would be to use REST over HTTP.


Question:
Does anyone know a good SMTP/IMAP server library for C#?

I only found some long abandoned projects.

Only SERVER SIDE libraries, please no more posts about client libs.

Thanks,
Fionn

Answer:
For SMTP, there's
```
System.Net.Mail
```
. For IMAP, I don't know.  But once you fetch the email from the server, you'll want to parse it. The MIME parsing is the hard part.  For that, I use, and recommend,
```
SharpMimeTools
```
.


Question: What's an easy to use SNMP client library for c++?

Answer:
Probably the best choice is
net-snmp
.  Note that the library has "C" linkage but will work just fine with C++.


Question:
I'm trying to convert some strings that are in French Canadian and basically, I'd like to be able to take out the French accent marks in the letters while keeping the letter. (E.g. convert é to e, so crème brûlée would become creme brulee)

What is the best method for achieving this?

Answer:
I've not used this method, but Michael Kaplan describes a method for doing so in his blog post (with a confusing title) that talks about stripping diacritics:
Stripping is an interesting job (aka
On the meaning of meaningless, aka All
Mn characters are non-spacing, but
some are more non-spacing than
others)
```
```
static string RemoveDiacritics(string text)
{
    var normalizedString = text.Normalize(NormalizationForm.FormD);
    var stringBuilder = new StringBuilder(capacity: normalizedString.Length);

    for (int i = 0; i < normalizedString.Length; i++)
    {
        char c = normalizedString[i];
        var unicodeCategory = CharUnicodeInfo.GetUnicodeCategory(c);
        if (unicodeCategory != UnicodeCategory.NonSpacingMark)
        {
            stringBuilder.Append(c);
        }
    }

    return stringBuilder
        .ToString()
        .Normalize(NormalizationForm.FormC);
}
```
```
Note that this is a followup to his earlier post:
Stripping diacritics....
The approach uses
String.Normalize
to split the input string into constituent glyphs (basically separating the "base" characters from the diacritics) and then scans the result and retains only the base characters. It's just a little complicated, but really you're looking at a complicated problem.
Of course, if you're limiting yourself to French, you could probably get away with the simple table-based approach in
How to remove accents and tilde in a C++ std::string
, as recommended by @David Dibben.


Question:
So I just love it when my application is working great in Firefox, but then I open it in IE and... Nope, please try again.

The issue I'm having is that I'm setting a CSS display property to either none or table-cell with JavaScript.

I was initially using display: block, but Firefox was rendering it weird without the table-cell property.

I would love to do this without adding a hack in the JavaScript to test for IE.  Any suggestions?

Thanks.

Answer:
Well,
IE7 does not have
```
display: table(-cell/-row)
```
so you will have to figure something else out or do browser targeting (which I agree, is bad hack). As a quick fix (I don't know what you're trying to achieve, appearance-wise) you could try
```
display: inline-block
```
and see what it looks like.
Maybe figure out a way to do
```
display: block
```
and solve the problem of "Firefox rendering it weird" instead? Can you describe what you mean by the weird rendering exactly?


Question:
What's the most elegant way of implementing a DropDownList in ASP.NET that is editable without using 3rd party components.

As a last resort I will probably try using a TextBox with an AutoCompleteExtender with an image to 'drop down' the list; or a TextBox overlapping a HTML Select with some JavaScript to fill values from the Select to the TextBox. But I'm really hoping there is a more terse and maintainable solution.

Thanks in advance.

Answer:
One Control on a Page
You can follow
this simple example for an Editable DropDownlist on Code Project
that uses standard ASP.NET TextBox and DropDownList controls combined with some JavaScript.
However, the code did not work for me until I added a reference to get the ClientID values for the TextBox and DropDownList:
```
```
<script language="javascript" type="text/javascript">

function DisplayText()
{
    var textboxId = '<% = txtDisplay.ClientID %>';
    var comboBoxId = '<% = ddSelect.ClientID %>';
    document.getElementById(textboxId).value = document.getElementById(comboBoxId).value;
    document.getElementById(textboxId).focus();
}
</script>

<asp:TextBox style="width:120px;position:absolute" ID="txtDisplay" runat="server"></asp:TextBox>

<asp:DropDownList ID="ddSelect" style="width:140px" runat="server">
    <asp:ListItem Value="test1" >test1</asp:ListItem>
    <asp:ListItem Value="test2">test2</asp:ListItem>
</asp:DropDownList>
```
```
Finally, in the code behind just like in the original example, I added the following to page load:
```
```
protected void Page_Load(object sender, EventArgs e)
{
    ddSelect.Attributes.Add("onChange", "DisplayText();");
}
```
```
Multiple Controls on a Page
I placed all of the above code in its own ASCX User Control to make it reusable across my project. However, the code as presented above only works if you require just one editable DropDownList on a given page.
If you need to support multiple custom DropDownList controls on a single page, it is necessary to set the JavaScript function name to be unique to avoid conflicts. Do this by once again using the ClientID:
in the ASCX file:
```
```
function DisplayText_<% = ClientID %>(){...}
```
```
in the code behind:
```
```
/// ...
ddSelect.Attributes.Add("onChange", "DisplayText_" + ClientID + "();");
///..
```
```
This is one way to avoid using 3rd party controls.


Question:
I'm looking for a relativity cheap .NET Micro Framework development board for use on a personal robotics project. I'd don't need much for I/O, but I want at least one serial port and one Ethernet port.

I would prefer not to have to spend more than US$300 on the board, but if there is an obvious reason to get a better one I'm flexible.

Currently I'm looking at this device from SJJ Embedded Micro Solutions. Has anyone had experience with this device?

Answer:
I have not had experience with the SJJ Embedded board, but I might just have to give it a shot.
I'm working on a robotics project as a hobby, and I'm currently prototyping with
Lego Mindstorms
and the Robotics SDK from Microsoft. I had planned on swapping to an
Arduino
which uses a C-like programming language and weighs in at around US$30 assembled.


Question:
I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as Console.

For example, if I want to add an extension to Console, called 'WriteBlueLine', so that I can go:

Console.WriteBlueLine("This text is blue");

I tried this by adding a local, public static method, with Console as a 'this' parameter... but no dice!

public static class Helpers {
    public static void WriteBlueLine(this Console c, string text)
    {
        Console.ForegroundColor = ConsoleColor.Blue;
        Console.WriteLine(text);
        Console.ResetColor();
    }
}

This didn't add a 'WriteBlueLine' method to Console... am I doing it wrong? Or asking for the impossible?

Answer:
You can't add
static
methods to a type.  You can only add (pseudo-)instance methods to an instance of a type.
The point of the
```
this
```
modifier is to tell the C# compiler to pass the instance on the left-side of the
```
.
```
as the first parameter of the static/extension method.
In the case of adding static methods to a type, there is no instance to pass for the first parameter.


Question: I was browsing the Hidden Features of C# question and thought I would try out one of the features I was unfamiliar with.  Unfortunately I use Visual Studio 2005 and the feature in question was introduced later.   Is there a good list for new features in C# 3.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)?

Answer:
Here's a link to the MS page on .NET 3.0:
http://msdn.microsoft.com/en-us/library/bb822048.aspx
...and on VS 2008 for C#:
http://msdn.microsoft.com/en-us/library/bb383815.aspx
I haven't tried VS2008 and .NET 3.0 out, but I figure the links might help ;)


Question:
'''use Jython'''

import shutil

print dir(shutil)

There is no, shutil.move, how does one move a file with Jython?
and while we at it, how does one delete a file with Jython?

Answer:
```
os.rename()
```
to move, and
```
os.unlink()
```
to delete -- just like Python pre-
```
shutil
```
.


Question:
I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the --no-site-packages option, but doing this while developing a PyGTK app can be a bit tricky.
The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (with --no-site-packages) aware of specific modules that are located elsewhere on the system.

What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?

Answer:
One way is to add the paths to your code using sys.path.
```
```
import sys

sys.path.append(somepath)
```
```
Another way is to use site, which processes .pth files in addition to adding to sys.path.
```
```
import site

site.addsitedir(sitedir, known_paths=None)
```
```
https://docs.python.org/library/site.html
But you probably don't want to add this to all your related code.
I've seen mention of sitecustomize.py being used to perform something like this, but after some testing I couldn't get it to work as might be expected.
Here it mentions that auto-import of sitecustomize.py ended in 2.5, if your not on 2.5 try it out.  (just add one of the path add methods above to the file and drop it in the directory your program is run)
A work around method is mentioned in the post for users of 2.5 and up.
http://code.activestate.com/recipes/552729/


Question:
Why don't we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we have plenty of languages with full-fledged type inference systems (that work for varying levels of "work").

Edit: By return type polymorphism I mean overloading the function signature only in the return type. For example, C++ and Java only allow overloading in the type of the formal parameters, not in the return type.

Answer:
If by "return type polymorphism" you mean overloading based on the return value type, I'm not sure about other languages, but for C++ here's the answer (pretty much from the horse's mouth):
Function return types don't come into play in overload resolution simply because Stroustrup (I assume with input from other C++ architects) wanted overload resolution to be 'context independent'. See 7.4.1 - "Overloading and Return Type" from the "C++ Programming Language, Third Edition".
The reason is to keep resolution for
  an individual operator or function
  call context-independent.
They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all).  Indeed, many functions are called without using the result or the result would be used as part of a larger expression.  One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.
And, Lord knows, C++ overload resolution is complex enough as it stands...


Question:
What does the following code do? A link to something in the PHP manual would also be nice.

if ($_SERVER['SERVER_PORT'] <> 443) {
    doSomething();
}

Answer:
Same as !=, "Not equal"
```
```
false <> true // operator will evaluate expression as true
false != true // operator will evaluate expression as true
```
```
Here is some reference:
PHP Comparison Operators


Question:
I am building a utility page for a web app that I am working on.   I have an element that I want to use as a "console" of sorts.

I get entries for the console via Ajax calls (using prototype's Ajax.PeriodicalUpdater).

The problem I'm having is that when I insert new lines to the bottom of the "console", the scrollbar stays in the initial position (so I always see the top lines unless I manually scroll down).

How can I make the scrollbar automatically stay at the bottom?

I am using prototype for a few libraries that require it in this project, so I would prefer to stick with that or regular javascript if possible.

Just as a note, I already tried this:

onComplete: function() {
    $('console').scrollTop = $('console').scrollHeight;
}

It almost works, except that it is always "one step behind", and I can't see the most recent item.

Answer:
```
```
new Ajax.PeriodicalUpdater(container, url, {
    onComplete: function() {
        (function() {
            container.scrollTop = container.scrollHeight;
        }).defer();
    }
});
```
```


Question:
I wrote this scheme code to compute one solution of the quadratic equation ax2 + bx + c = 0

(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a)))

However, someone told me that this procedure is hard to understand. Why?

What would a cleaned up version of this procedure look like?
Please let me know why the new procedure would be easier to understand.

Thanks

Answer:
Well, one reason is that it's all on one line. You can make it more readable using something called
pretty-printing
, where you break it up into multiple lines and use whitespace:
```
```
(define (solve-quadratic-equation a b c)
  (define disc (sqrt (- (* b b)
                        (* 4.0 a c))))
  (/ (+ (- b) disc)
     (* 2.0 a)))
```
```
This way you can more clearly see the structure of the expressions.
And here's a quote from
SICP
:
There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as
```
```
(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))
```
```
which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form
```
```
(+ (* 3
      (+ (* 2 4)
         (+ 3 5)))
   (+ (- 10 7)
      6))
```
```
following a formatting convention known as
pretty-printing
, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.


Question:
Programs that index filesystems seem to know which parts have changed since their last index and only rescan that part. How can I determine where the filesystem/files have changed since my last index. Don't care what language you answer in but I'm thinking c and windows.

An example of such a program is Sequoia View which generates a treemap of your hard disk.

Answer:
A fairly simplistic method would be to take the file system's reported files sizes, dates (as integer values), and file names in a given directory and calculate a
checksum
you could then associate with that directory.  You would still need to perform this calculation on all of the directories using file system data  but you wouldn't have to go in depth (opening files to check for differences) unless a checksum reported a difference.
For tracking specific changes at the file level you would store checksums based on individual file attributes, and of the course the presence of or absence of files and subdirectories since the last scan.
This wouldn't necessarily guarantee that changes have not occurred as there are file system utilities for altering all manner of attributes though it would be a good first step for a basic scan.
You may find the
source code
for
fswatch
helpful.


Question:
Is anyone familiar with this?

Write a procedure that takes as inputs
  a procedure that computes f and a
  positive integer n and returns the
  procedure that computes the nth
  repeated application of f. The
  procedure should be able to be used as
  follows:

((repeated square 2) 5)
625

I know that the following code I've created for the composition of functions will help make the solution simpler, but I'm not sure where to go from here:

(define (compose f g) (lambda (x) (f (g x))))

Answer:
Well, you probably want something like this, right?
```
```
((repeated square 3) 5)
-> (square ((repeated square 2) 5))
-> (square (square ((repeated square 1) 5)))
-> (square (square (square ((repeated square 0) 5))))
-> (square (square (square (identity 5))))
```
```
(I don't know whether
```
identity
```
is predefined in Scheme.  If not, it's easy to write.)
Now, this is not directly reproducible because you can't magically enclose code outside of the call to
```
repeated
```
with arbitrary stuff.  However, what do these reduction steps look like when rewritten using
```
compose
```
?  Can you make out a pattern in the resulting list of steps and reproduce it?


Question:
How do you programmatically set a DataContext that specifies the selected item of a list?

More simply, how do you reproduce this type of binding in code?

<StackPanel>
    <ListBox Name="listBox1" />
    <TextBox Name="textBox1" DataContext="{Binding ElementName=listBox1, Path=SelectedItem}" />
</StackPanel>

Answer:
You need to set a Name for the textbox so you can refer to it in code.  Then you should just be able to assign an object to the DataContext property.  You can create a data binding programatically like so:
```
```
Binding binding = new Binding();
binding.ElementName = "listBox1";
binding.Path = new PropertyPath("SelectedItem");
binding.Mode = BindingMode.OneWay;
txtMyTextBox.SetBinding(TextBox.TextProperty, binding);
```
```


Question:
I'm having trouble getting pictures supported with PIL - it throws me this:

IOError: decoder jpeg not available

I installed PIL from binary, not realizing I needed libjpeg.

I installed libjpeg and freetype2 through fink.

I tried to reinstall PIL using instructions from http://timhatch.com/ (bottom of the page)

Download PIL 1.1.6 source package and have the Developer Tools already installed

Patch setup.py with this patch so it can find the Freetype you already have.

patch -p0 < leopard_freetype2.diff

sudo apt-get install libjpeg if you have fink (otherwise, build by hand and adjust paths)

But I'm still getting the same error.

I'm on Leopard PPC.

Answer:
Is the python path still looking at the old binary version of libjpeg?
You will need to modify it to point to the new place if it is.
When you compiled the new version of the PIL did it say that it found libjpeg? It will compile happily without it (iirc) and the first sign of trouble you will see is at include time.
You will need to adjust the path at ./configure time.
The diff might just not work for you. You should test some more and then perhaps file a bug.


Question: How would I implement a binary search using just an array?

Answer:
Ensure that your array is sorted since this is the crux of a binary search.
Any indexed/random-access data structure can be binary searched.  So when you say using "just an array", I would say arrays are the most basic/common data structure that a binary search is employed on.
You can do it recursively (easiest) or iteratively.  Time complexity of a binary search is O(log N) which is considerably faster than a linear search of checking each element at O(N). Here are some examples from
Wikipedia: Binary Search Algorithm
:
Recursive:
```
```
BinarySearch(A[0..N-1], value, low, high) {
    if (high < low)
        return -1 // not found
    mid = low + ((high - low) / 2)
    if (A[mid] > value)
        return BinarySearch(A, value, low, mid-1)
    else if (A[mid] < value)
        return BinarySearch(A, value, mid+1, high)
    else
       return mid // found
    }
```
```
Iterative:
```
```
BinarySearch(A[0..N-1], value) {
   low = 0
   high = N - 1
   while (low <= high) {
       mid = low + ((high - low) / 2)
       if (A[mid] > value)
           high = mid - 1
       else if (A[mid] < value)
           low = mid + 1
       else
           return mid // found
   }
   return -1 // not found
}
```
```


Question: What are the usual methods to compare two polygons for similarity? Vertices are in 2D.

Answer:
You will find
some methods exposed here
.
Turning function
Graph matching
Shape signature by deformation
It is used in domains such as
image retrieval
(p. 52), where turning function is illustrated.


Question:
Can someone explain to me how XOR swapping of two variables with no temp variable works?

void xorSwap (int *x, int *y)
{
    if (x != y) {
        *x ^= *y;
        *y ^= *x;
        *x ^= *y;
    }
}

I understand WHAT it does, but can someone walk me through the logic of how it works?

Answer:
Most people would swap two variables x and y using a temporary variable, like this:
```
```
tmp = x
x = y
y = tmp
```
```
Here’s a neat programming trick to swap two values without needing a temp:
```
```
x = x xor y
y = x xor y
x = x xor y
```
```
More details in
Swap two variables using XOR
On line 1 we combine x and y (using XOR) to get this “hybrid” and we store it back in x. XOR is a great way to save information, because you can remove it by doing an XOR again.
On line 2. We XOR the hybrid with y, which cancels out all the y information, leaving us only with x. We save this result back into y, so now they have swapped.
On the last line, x still has the hybrid value. We XOR it yet again with y (now with x’s original value) to remove all traces of x out of the hybrid. This leaves us with y, and the swap is complete!
The computer actually has an implicit “temp” variable that stores intermediate results before writing them back to a register. For example, if you add 3 to a register (in machine-language pseudocode):
```
```
ADD 3 A // add 3 to register A
```
```
The ALU (Arithmetic Logic Unit) is actually what executes the instruction 3+A. It takes the inputs (3,A) and creates a result (3 + A), which the CPU then stores back into A’s original register. So, we used the ALU as temporary scratch space before we had the final answer.
We take the ALU’s implicit temporary data for granted, but it’s always there. In a similar way, the ALU can return the intermediate result of the XOR in the case of x = x xor y, at which point the CPU stores it into x’s original register.
Because we aren’t used to thinking about the poor, neglected ALU, the XOR swap seems magical because it doesn’t have an explicit temporary variable. Some machines have a 1-step exchange XCHG instruction to swap two registers.


Question:
How to add new item in existing string array in C#.net?

I need to preserve the existing data.

Answer:
I would use a List if you need a dynamically sized array:
```
```
List<string> ls = new List<string>();
ls.Add("Hello");
```
```


Question:
I want to compute for month difference of 2 dates which will return a float value.

example:

date1='4/23/2008'
date2='12/31/2008'

that will be 7.y months. I want to find the y value. can someone give me the formula to make this in sql codes? tnx..

Answer:
There's no standard sql to handle this universally. It depends on what database you're using. Basically, you need to convert the two date strings to the date format your database engine uses internally and subtract the two dates, what the result of the subtraction means will, again, depend. In Oracle, you'd use
```
to_date()
```
for the conversion and the result of the subtraction will be a float representing the time in number of days.
In short, search your db's manual for a section about date handling or data types.


Question:
I've heard of "error" when using floating point variables.  Now I'm trying to solve this puzzle and I think I'm getting some rounding/floating point error.  So I'm finally going to figure out the basics of floating point error.

What is a simple example of floating point/rounding error (preferably in C++) ?

Edit:  For example say I have an event that has probability p of succeeding.  I do this event 10 times (p does not change and all trials are independent).  What is the probability of exactly 2 successful trials?  I have this coded as:

double p_2x_success = pow(1-p, (double)8) * pow(p, (double)2) * (double)choose(8, 2);

Is this an opportunity for floating point error?

Answer:
Generally, floating point error refers to when a number that cannot be stored in the IEEE floating point representation.
Integers are stored with the right-most bit being 1, and each bit to the left being double that (2,4,8,...).  It's easy to see that this can store any integer up to 2^n, where n is the number of bits.
The mantissa (decimal part) of a floating point number is stored in a similar way, but moving left to right, and each successive bit being half of the value of the previous one.  (It's actually a little more complicated than this, but it will do for now).
Thus, numbers like 0.5 (1/2) are easy to store, but not every number <1 can be created by adding a fixed number of fractions of the form 1/2, 1/4, 1/8, ...
A really simple example is 0.1, or 1/10.  This can be done with an infinite series (which I can't really be bothered working out), but whenever a computer stores 0.1, it's not exactly this number that is stored.
If you have access to a Unix machine, it's easy to see this:
```
```
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 0.1
0.10000000000000001
>>>
```
```
You'll want to be really careful with equality tests with floats and doubles, in whatever language you are in.
(As for your example, 0.2 is another one of those pesky numbers that cannot be stored in IEEE binary, but as long as you are testing inequalities, rather than equalities, like p <= 0.2, then you'll be okay.)


Question:
I hope someone will be able to answer my question.

I have Subversion set up, served by Apache2+SSL, doing web development.

I want a post-commit hook that runs svn update on my testing server, so when someone commits, it will automatically update the testing site. The hook doesn't work because the certificate is a self generated one and it's not trusted.

I've tried to accept (p)ermanently, but it doesn't.

Any ideas?

Answer:
You didn't say what platform your testing server is running, but if it's a Windows box, then you need to add the certificate to your testing server's certificate store. The following technet articles might be of some use:
Certificate stores: Public Key
A Step-by-Step Guide to Advanced Certificate Management


Question:
FindBugs has found a potential bug in my code. But it is not a bug.

Is it possible to mark this occurrence as 'not a bug' AND have it removed from the bug list?

I have documented quite clearly why for each case it is not a bug.

For example. A class implements the comparable interface. it has the compareTo method. I have however not overridden the equals method.

FindBugs does not like this as the JavaDocs state that it is recommended that

(x.compareTo(y)==0) == (x.equals(y))

Although in my case the above condition is and always will be true.

Answer:
Probably by adding a
filter
as parameter of findbugs
Match clauses can only match information that is actually contained in the bug instances
```
```
<Match>
   <Class name="com.foobar.MyClass" />
   <Method name="myMethod" />
   <Bug pattern="EQ_COMPARETO_USE_OBJECT_EQUALS" />
</Match>
```
```


Question:
If f is a numerical function and n is a positive integer, then we can form the nth repeated application of f, which is defined to be the function whose value at x is f(f(...(f(x))...)). For example, if f is the function x + 1, then the nth repeated application of f is the function x + n. If f is the operation of squaring a number, then the nth repeated application of f is the function that raises its argument to the 2^nth power. Write a procedure that takes as inputs a procedure that computes f and a positive integer n and returns the procedure that computes the nth repeated application of f. Your procedure should be able to be used as follows:

((repeated square 2) 5)
625

You can use this to simplify the answer:

 (define (compose f g) (lambda (x) (f (g x))))

Answer:
Did you just delete and reask this question?  I'm copying my former answer here (thankfully, my browser had cached it):
Well, you probably want something like this, right?
```
```
((repeated square 3) 5)
-> (square ((repeated square 2) 5))
-> (square (square ((repeated square 1) 5)))
-> (square (square (square ((repeated square 0) 5))))
-> (square (square (square (identity 5))))
```
```
(I don't know whether identity is predefined in Scheme. If not, it's easy to write.)
Now, this is not directly reproducible because you can't magically enclose code outside of the call to repeated with arbitrary stuff. However, what do these reduction steps look like when rewritten using compose? Can you make out a pattern in the resulting list of steps and reproduce it?


Question:
What would be the best way to avoid SQL injection on the C#.net platform.

Please post an C# implementation if you have any.

Answer:
There's no algorithm needed - just don't use string concatenation to build SQL statements. Use the SqlCommand.Parameters collection instead. This does all the necessary escaping of values (such as replacing
```
'
```
with
```
''
```
) and ensures the command will be safe because somebody else (i.e. Microsoft) has done all the testing.
e.g. calling a stored procedure:
```
```
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("MySprocName", connection))
{
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.AddWithValue("@Param1", param1Value);
    return command.ExecuteReader();
}
```
```
This technique also works for inline SQL statements, e.g.
```
```
var sql = "SELECT * FROM MyTable WHERE MyColumn = @Param1";
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(sql, connection))
{
    command.Parameters.AddWithValue("@Param1", param1Value);
    return command.ExecuteReader();
}
```
```


Question:
What is the recommended practice? Should I add the my sub-folder under the fitnesse folder to version control?

Context: working on a single developer rails pet project. I've my rails project under version-control (Subversion) however my fitnesse wiki pages lie under the fitnesse program folder.

Fitnesse seems to have its own version-control... (I see numbered zips along with each of my wiki pages) Is it reliable? Where does it store the revisions?

Answer:
FitNesse stores old revisions of every page in a zip file in the same directory as the page's files. The zip filename marks the timestamp of the revision. It works similar to wikipedia - history, but not full-fledged version control.
In our company we wanted a setup where whenever we checkout a (possibly old) revision of the source, we also check out FitNesse tests that pass for that specific version.
Therefore, we installed FitNesse (the fitnesse directory, including the FitNesse executable and the FitNesseRoot directory) inside our source tree in version control, setting a rule to not import *.zip within the FitNesseRoot directory (as we have version control to keep history for us and don't need them).
This works excellent with sane SCMs (I used svn w/ svn-tortoise).
When we moved to Microsoft Foundation Server source control we had many issues with the checkout-edit-checkin workflow. Then again, this workflow is simply a bad idea in general, and should only be used by insane control-freaks.
(edit: answered commenter's question)


Question: I have checked with the wikipedia article, and it seems like it is missing the c++ version of a code example.  I am not able to fully appreciate the Facade pattern without this, can you please help explain it to me using C++?

Answer:
I've done a search and replace on the C# example. This might not help you, because if you understand C++ then you should be able to understand the C# as it uses the same constructs and keywords (classes, functions, namespaces, public, etc)
```
```
// "Subsystem ClassA"
#include <iostream>
class SubSystemOne
{
public:
    void MethodOne()
    {
        std::cout << " SubSystemOne Method" << std::endl;
    }
}

// Subsystem ClassB"

class SubSystemTwo
{
public:
    void MethodTwo()
    {
        std::cout << " SubSystemTwo Method" << std::endl;
    }
}

// Subsystem ClassC"

class SubSystemThree
{
public:
    void MethodThree()
    {
            std::cout << " SubSystemThree Method" << std::endl;
    }
}

// Subsystem ClassD"

class SubSystemFour
{
public:
    void MethodFour()
    {
        std::cout << " SubSystemFour Method" << std::endl;
    }
}

// "Facade"

class Facade
{
    SubSystemOne one;
    SubSystemTwo two;
    SubSystemThree three;
    SubSystemFour four;

public:
    Facade()
    {
    }

    void MethodA()
    {
        std::cout << "\nMethodA() ---- " << std::endl;
        one.MethodOne();
        two.MethodTwo();
        four.MethodFour();
    }
    void MethodB()
    {
        std::cout << "\nMethodB() ---- " << std::endl;
        two.MethodTwo();
        three.MethodThree();
    }
}

int Main()
{
    Facade facade = new Facade();

    facade.MethodA();
    facade.MethodB();

    return 0;
}
```
```


Question: I want to scale an image in C# with quality level as good as Photoshop does. Is there any C# image processing library available to do this thing?

Answer:
When you draw the image using GDI+ it scales quite well in my opinion. You can use this to create a scaled image.
If you want to scale your image with GDI+ you can do something like this:
```
```
Bitmap original = ...
Bitmap scaled = new Bitmap(new Size(original.Width * 4, original.Height * 4));
using (Graphics graphics = Graphics.FromImage(scaled)) {
  graphics.DrawImage(original, new Rectangle(0, 0, scaled.Width, scaled.Height));
}
```
```


Question: Can anyone explain to me how to get the visual state manager to work with a WPF application? It's just been added to the new wpftoolkit. I installed it as told, but even the sample doesn't show the VSM. In silverlight it work, but not in WPF. If installed the latest Blend 2 and updated with the SP1.

Answer:
Read these 2 articles on VSM in WPF:
http://dotnet.org.za/rudi/archive/2008/10/29/silverlight-love-for-wpf.aspx
http://windowsclient.net/wpf/wpf35/wpf-35sp1-toolkit-visual-state-manager-overview.aspx
Their is a registry setting that needs to be "turned on" for VSM in WPF support for blend... Read more
here


Question: Please give me some insight on how to get the best start on applying Aspect Oriented Programming to my C#.net applications?

Answer:
I recommend trying
Spring.NET
. It lets you create "Interceptor" classes that can be wrapped around calls into business objects simply by adding entries into the application's config file.
We've used it to do connection/transaction handling, error logging and authentication. Which keeps all of those "aspects" out of the business logic code.


Question:
What is the time complexity? Why?

(define (mult a b)
      (define (internal a accum)
        (if (= a 1) accum
            (internal (- a 1) (+ accum b))))
      (internal a b))

(define (to-the-power-of m n)
  (define (internal x accum)
    (if (= x 0) accum
        (internal (- x 1) (mult accum m))))
  (internal n 1))

Answer:
Assuming addition and multiplication are both counted as a single operation, this function performs O(m^n) operations.
First consider the mult function. It (mult a b) will perform exactly a-1 additions. Since, the asymptotic growth is the same, lets approximate this by a, for mathematical simplicity.
Now for the to-the-power-of function, this performs n calls to the mult function. These calls are to (mult 1 m), yield m, then to (mult m m), yielding m^2, then to (mult m^2 m), yielding m^3 and so on upto m^n. So the total number of operations performed here is the sum m^0 + m^1 + ... + m^n. This is (m^n - 1) / (m-1) which grows as m^n.


Question:
Let's suppose I have an applet running within a page in a browser.
What happens when the browser is closed by the user?

Is the applet notified so that it can perform some kind of close action on its side (closing connections opened to a server, cleaning static variables, ...)?

Also, I assume the same behavior would apply for a page refresh or page navigation (instead of browser close). The browser remains opened but the applet is gone. Although when you close the browser you also close the JVM so I'm unsure at this point.

Thanks,
JB

Answer:
Yes, the
destroy() method
should be called before the
browser unloads the object
.
destroy()
is the last of four "
life-cycle methods
" of the Java applet (the others are
init()
,
start()
, and
stop()
).  They're actually called at different times depending on your
browser
and
virtual machine
.  If you'd like to know exactly when each is called, implement each method within your applet, and System.out some feedback.
Ideally, destroy() should be
called by the environment
, and should only be called once.  If it seems like destroy() is not being called, you might declare a public finalize() method, which calls destroy.  You could also try to call destroy() from javascript as the window object unloads, but again, be sure that you're not calling destroy() unnecessarily.
```
```
public void finalize () {
    destroy();
}
```
```


Question:
I'm having difficulty parsing some JSON data returned from my server using jQuery.ajax()

To perform the AJAX I'm using:

$.ajax({
  url: myUrl,
  cache: false,
  dataType: "json",
  success: function(data){
    ...
  },
  error: function(e, xhr){
    ...
  }
});

And if I return an array of items then it works fine:

[ { title: "One", key: "1" }, { title: "Two", key: "2" } ]

The success function is called and receives the correct object.

However, when I'm trying to return a single object:

{ title: "One", key: "1" }

The error function is called and xhr contains 'parsererror'.  I've tried wrapping the JSON in parenthesis on the server before sending it down the wire, but it makes no difference.  Yet if I paste the content into a string in Javascript and then use the eval() function, it evaluates it perfectly.

Any ideas what I'm doing wrong?

Anthony

Answer:
Is your server sending data as Content-Type
```
"*/json"
```
? If not, modify the response headers accordingly. Sending
```
"application/json"
```
would be fine, for example.


Question:
Has anyone tested sorting with Selenium? I'd like to verify that sorting a table in different ways work (a-z, z-a, state, date, etc.). Any help would be very much appreciated.

/Göran

Answer:
You can get value of fields like this:
```
```
//div[@id='sortResult']/div[1]/div  (this'd be row 1 of the search result)
 //div[@id='sortResult']/div[2]/div   ( row 2)
```
```
(I'm making some assumptions about the HTML structure here, but you get my drift...)
These can be quite fragile assertions, I'd recommend you anchor these xpath references to an outer container element (not the root of your document, as lots of "automatic" tools do).
When you click sort, the value changes. You'll have to find out what the values are supposed to be.
Also watch out for browser compatibility with such xpaths. They're not always ;)


Question:
How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)?

Currently, i have this:

afplay file.mp3

while true:
do osascript -e "set volume 10"
end

But i would like it to execute killall afplay when the user is finished with it, regardless if it is command-c or another keypress.

Answer:
```
trap 'killall afplay' EXIT
```


Question: How can I customise the Site Actions menu to remove or rename 'standard' menu items? Where are the site actions menu items defined?

Answer:
The site actions menu is defined in the Siteaction.xml in Template\layouts\editingMenu under the 12 hive.  The following link shows how to manually remove items.
Customize Site Actions Menu
I have added options to the menu using features, but have never tried to hide OTB option in code.  I would be interested in your results.
Good luck!


Question:
There is this example code, but then it starts talking about millisecond / nanosecond problems.

The same question is on MSDN, Seconds since the Unix epoch in C#.

This is what I've got so far:

public Double CreatedEpoch
{
  get
  {
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (this.Created.ToLocalTime() - epoch);
    return span.TotalSeconds;
  }
  set
  {
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    this.Created = epoch.AddSeconds(value);
  }
}

Answer:
A Unix tick is 1 second (if I remember well), and a .NET tick is 100 nanoseconds.
If you've been encountering problems with nanoseconds, you might want to try using AddTick(10000000 * value).


Question:
Say I have an input file, and a target directory. How do I determine if the input file is on the same hard-drive (or partition) as the target directory?

What I want to do is the copy a file if it's on a different, but move it if it's the same. For example:

target_directory = "/Volumes/externalDrive/something/"
input_foldername, input_filename = os.path.split(input_file)
if same_partition(input_foldername, target_directory):
    copy(input_file, target_directory)
else:
    move(input_file, target_directory)

Answer:
In C, you would use
```
stat()
```
and compare the
```
st_dev
```
field. In python,
```
os.stat
```
should do the same.
```
```
import os
def same_partition(f1, f2):
    return os.stat(f1).st_dev == os.stat(f2).st_dev
```
```


Question:
I'm using a BindingList<T> in my Windows Forms that contains a list of "IComparable<Contact>" Contact-objects. Now I'd like the user to be able to sort by any column displayed in the grid.

There is a way described on MSDN online which shows how to implement a custom collection based on BindingList<T> which allows sorting. But isn't there a Sort-event or something that could be caught in the DataGridView (or, even nicer, on the BindingSource) to sort the underlying collection using custom code?

I don't really like the way described by MSDN. The other way I could easily apply a LINQ query to the collection.

Answer: Not for custom objects. In .Net 2.0, I had to roll my on sorting using BindingList. There may be something new in .Net 3.5 but I have not looked into that yet. Now that there is LINQ and the sorting options that come with if this now may be easier to implement.


Question:
I'm at a client doing some quick fixes to their access application. It was a while I had a go with access, but I'm recovering quickly. However, I've discovered an interesting problem:

For some reports, I get a "Record is deleted" error. I've checked the reports, and it seems like there's a problem with one table. When opening that table, I find a record where all columns are marked "#deleted". So obviously, this row seems to be the culprit. However, when I try to delete that row, nothing really happens. If I re-open the table, the row still exists.

Is there a corruption in the db? How can I remove this record for good?

Edit: It's a MS2000-version

Solution: Simply compress/repair did not work. I converted the database to the 2003 file format instead, which did the trick. I've marked the first answer suggesting compress/repair, since it pointed me in the right direction. Thanks!

Answer:
Have you tried the built in Access compact/repair tool? This should flush deleted records from the database.
The exact location varies according to the version of Access you're running, but on Access 2003 it's under Tools > Database Utilities > Compact and repair database. Some earlier versions of Access had two separate tools - one for compact, one for repair - but they were accessed from a similar location. If they are separate on the version the client has, you need to run both.
This should be a non-destructive operation, but it would be best to test this on a copy of the MDB file (apologies for stating the obvious).


Question:
I am in the process of moving from VSS to SVN and I'm not sure how to share files in SVN.

Basically we have the following structure in VSS

$MOSS
  - Components
    - ComponentA
      - bin
    - ComponentB
      - bin
  - GAC Mirror

GAC Mirror holds a shared copy of all the Dlls from the bin folders of the components to allow for easy copying to the GAC.

In VSS all you do is drag the Dll from the bin folder to the GAC Mirror folder and it works it's life out.

How would I do this in SVN?

Thanks in advance.

Answer:
We had the same problem.  The simple answer is that you can't share files in SVN - in the end we had to restructure our directories and use batch files.
e.g. for source code files that were shared, we moved them to an Include folder, and have all the projects reference that folder.
For binary files that need to be copied to more than one location we store them just once in SVN, and then use batch files to copy them across to the target locations on each developers machine (or also on the build machine).


Question:
How do I get the substring " It's big \"problem  " using a regular expression?

s = ' function(){  return " It\'s big \"problem  ";  }';

Answer:
```
```
/(["\']).*?(?<!\\)(\\\\)*\1/is
```
```
should work with any quoted string


Question: I'me looking for a function that would receive a time and would round it to the next/previous hour / half-hour / quarter / minute.

Answer:
Try this function
```
```
CREATE FUNCTION [dbo].[RoundTime] (@Time datetime, @RoundTo float)
RETURNS datetime
AS
BEGIN
   DECLARE @RoundedTime smalldatetime
   DECLARE @Multiplier float

   SET @Multiplier= 24.0/@RoundTo

   SET @RoundedTime= ROUND(CAST(CAST(CONVERT(varchar,@Time,121) AS datetime) AS float) * @Multiplier,0)/@Multiplier

   RETURN @RoundedTime
END

select dbo.roundtime('13:15',0.5)
```
```
The 1st param is the time to be rounded and the 2nd will be base on your list (0.5-half hour, 1-one hour, ...)


Question:
I'm currently using the ActiveRecord-based session store for my Rails app and I have a background process which clears out inactive sessions every 30 minutes.

I'd like to switch to Rails' new cookie-based session store but how do I set the expiry time of the session to 30 minutes, as opposed to the default 'at end of session' value?

Answer:
The
session options
page on the Rails wiki hints that this is only possible through a plugin:
Set the session cookie expire time
Unfortunately Rails has no way to dynamically set the expiry time of the session cookie. So it is recommended that you use the following plugin, which allows you to accomplish it:
http://blog.codahale.com/2006/04/08/dynamic-session-expiration-times-with-rails/
Of course take into account that the plugin is old, and may not work with your current version of Rails (I haven't looked at the specifics)


Question:
I was wondering if in Java I would get any odd behaviour if I synchronise twice on the same object?

The scenario is as follows

pulbic class SillyClassName {

    object moo;
    ...
    public void method1(){
        synchronized(moo)
        {
            ....
            method2();
            ....
        }
    }

    public void method2(){
        synchronized(moo)
        {
            doStuff();
        }
    }
}

Both methods use the object and are synchronised on it. Will the second method when called by the first method stop because it's locked?

I don't think so because it's the same thread but I'm unsure of any other odd results that might occur.

Answer:
In java, the
```
synchronized
```
keyword on a method basically synchronizes on the current object, so in effect it's doing what you suggest above implicitly.
You won't experience problems with synchronizing on one object in one method and then synchronizing on the same object in another method because, as you say, the current thread already holds the lock on that object.


Question: I'd like to have a page in php that normally displays information based on the GET request sent to it. However, I'd like for it to also be able to process certain POST requests. So, how can I tell if any data was sent by POST so I can act on it?

Answer:
Use
```
$_SERVER['REQUEST_METHOD']
```
to determine whether your page was accessed via a GET or POST request.
If it was accessed via post then check for any variables in
```
$_POST
```
to process.


Question:
We have a CustomAction that sets some registry key HKEY LOCAL_MACHINE. This wasn't working on Vista with UAC, until we made the action "deferred". The installer worked in other cases. Anyone knows why?

We are using WIX to create the installer.

Answer:
Your custom action was being run immediately when it was encountered in the InstallExecuteSequence; instead of when the actual install script was being executed.  This caused your custom action to be executed with the users permissions rather than with the system's elevated permissions.  This series of blog posts will explain in detail what is happening,
http://blogs.msdn.com/rflaming/archive/2006/09/23/768146.aspx
.  You shouldn't have custom actions that effect the state of the machine that do not run as deferred custom actions.


Question: If it said "oneword", then I could write "#oneword", but what do I write when there is a space in the word?

Answer:
You can't have multiple words for the id, but you can for class.
```
```

lalala

.one {
    color: black;
}

.two {
    font-weight: bold;
}
```
```


Question:
I have two XML files with two different XSD schemas and different namespaces. They have both an identical substructure. And now i need to copy that node (and all childs) from one XML document to the other one.

Clone would do, if the namespaces were the same. Is there a nice way to do it?
(The substructure will change later on - but will be kept identical.)

Answer:
Basically, you need an XSL transformation that creates new elements with equal names, but a different namespace.
Consider the following input XML:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns="http://tempuri.org/ns_old">
    <child attrib="value">text</child>
</test>
```
```
Now you need a template that says "copy structure and name of everything you see, but declare a new namespace while you're at it":
```
```
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:old="http://tempuri.org/ns_old"
>
  <xsl:output method="xml" version="1.0"
    encoding="UTF-8" indent="yes" omit-xml-declaration="no"
  />

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="old:*">
    <xsl:element name="{local-name()}" namespace="http://tempuri.org/ns_new">
      <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>
```
```
When you run the above XML through it, this produces:
```
```
<?xml version="1.0" encoding="UTF-8"?>
<test xmlns="http://tempuri.org/ns_new">
  <child attrib="value">text</child>
</test>
```
```
All your
```
http://tempuri.org/ns_old
```
elements have effectively changed their namespace. When your input XML has more than one namespace at the same time, the XSL must most likely be extended a bit.


Question:
What is the equivalent to web controls in frameworks other than ASP.Net?

Specifically I'd like to know about Java, PHP and Ruby on Rails.

What are the relative merits/faults of each of these frameworks for web development?

I've had some exposure to ASP.Net and have been asked to look into developing an app that will have configurable controls on it. I know how I'd do this in ASP.Net, but it's to run on a linux box and in my experience Mono is not mature/stable when running ASP.Net.

Clarification

Basicly what I mean by webcontrols is a set of reusable componenet that I can initialize with various values.

So if for example I want to have a reusable component which draws a graph of some kind on the page. and i want to lay out several of these to graph different things.

Answer:
I believe there aren't.
ASP.NET Web controls are a hodgepodge of
```
<input>
```
and
```
<submit>
```
HTML elements put together to make use of the ASP.NET Web Forms Page Lifecycle. This in turn to facilitate windows-forms like behavior in a web application.
AFAIK in other frameworks they still make use of the plain HTML control elements coupled with Javascript to modify behavior.


Question:
The java.net.InetAddress.GetByName(String host) method can only return A records so to lookup other record types I need to be able to send DNS queries using the dnsjava library.

However that normally relies on being able to parse /etc/resolv.conf or similar to find the DNS server addresses and that doesn't work on Android.

The current DNS settings on Android can apparently only be obtained from within a shell by using the getprop command.

Can anyone tell me how to get those settings from Java other than by spawning a shell with Runtime.exec() and parsing the output from getprop?

Answer:
I don't think it's possible for general case. For WiFi I found this:
```
```
WiFiManager wifi = (WifiManager) getSystemService(WIFI_SERVICE);
DhcpInfo info = wifi.getDhcpInfo();
```
```


Question:
<a id="lblShowTimings"
     runat="server"
     title='<%# Eval("SHOW_Name") %>'
     onclick='PopulateTicketDiv(<%#Eval("SHOW_ID") %>)'>  <-- this is the problem
  %#Eval("SHOW_Time") %>
</a>

Can Eval be passed as an argument to a javascript function?
If so whats the syntax?

Answer:
Yes.  What you want to do is this, though:
```
```
onclick='<%# "PopulateTicketDiv(" +Eval("SHOW_ID") + " );" %>'
```
```


Question:
How can I restart(recycle) IIS Application Pool from C# (.net 2)?

Appreciate if you post sample code?

Answer:
If you're on
IIS7
then this will do it if it is stopped.  I assume you can adjust for restarting without having to be shown.
```
```
// Gets the application pool collection from the server.
[ModuleServiceMethod(PassThrough = true)]
public ArrayList GetApplicationPoolCollection()
{
    // Use an ArrayList to transfer objects to the client.
    ArrayList arrayOfApplicationBags = new ArrayList();

    ServerManager serverManager = new ServerManager();
    ApplicationPoolCollection applicationPoolCollection = serverManager.ApplicationPools;
    foreach (ApplicationPool applicationPool in applicationPoolCollection)
    {
        PropertyBag applicationPoolBag = new PropertyBag();
        applicationPoolBag[ServerManagerDemoGlobals.ApplicationPoolArray] = applicationPool;
        arrayOfApplicationBags.Add(applicationPoolBag);
        // If the applicationPool is stopped, restart it.
        if (applicationPool.State == ObjectState.Stopped)
        {
            applicationPool.Start();
        }

    }

    // CommitChanges to persist the changes to the ApplicationHost.config.
    serverManager.CommitChanges();
    return arrayOfApplicationBags;
}
```
```
If you're on
IIS6
I'm not so sure, but you could try getting the web.config and editing the modified date or something.  Once an edit is made to the web.config then the application will restart.


Question: We'd like to start our bug numbers to something other than 1 for a new Bugzilla installation.  Is there a way to do this?

Answer:
I'm not sure about Bugzilla's backend, but if it uses a SQL database, you should be able to find the table that controls the bug ID number and set the autoincrement value to something else. That is, if Bugzilla uses autoincrement.
But I don't have a copy of Bugzilla to provide more info.


Question: Can someone define what exactly 'POCO' means? I am encountering the term more and more often, and I'm wondering if it is only about plain classes or it means something more?

Answer:
"Plain Old C# Object"
Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.
EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.
TO CLARIFY:  In other words, they don’t derive from
some special base class, nor do they return any special types for their properties.
See below for an example of each.
Example of a POCO:
```
```
public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}
```
```
Example of something that isn’t a POCO:
```
```
public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}
```
```
The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is
not
just a plain old object anymore.


Question:
I'd like to warn users when they try to close a browser window if they didn't save the changes they made in the web form.

I'm using ASP.NET 3.5 (with ASP.NET Ajax).

Is there a common solution which I could easily implement?

EDIT: maybe my question wasn't clear: I am specifically looking for a way which integrates gracefully in the ASP.NET Server Controls methodology.

Answer:
On the Page_Unload event (or call this function in your body tag,
```
<body onunload="onPageUnload();">
```
), you can have a check if the form has data in it.  Then you could run some Java:
```
```
<script language="text/javascript">
   function onPageUnload() {
        var oConfirm = window.confirm("You have unsaved form data, are you sure you want to close this window?");
        if(oConfirm){
            //Close
        }else{
            //Dont
        }
    }
</script>
```
```
See how that works out for ya
EDIT:  It may not prevent the closing of the window, but it will alert your user that they have unsaved data in your form.
Confirmed does NOT work cross-browser, I will investigate a different method and post it up here.


Question:
I have been using Flex for a while and have not used remoting as of yet. Currently my apps use a webservice that generates xml that I use for databinding.

What would be the benefit to using remoting over an xml webservice in this use case? Is there a general guideline when I should choose remoting over webservices?

Why would I want to use remoting?

I have downloaded http://www.fluorinefx.com/, but have yet to do any real tinkering...

Thanks.

Answer:
Speaking personally I use remoting because I prefer AMF to SOAP/XML for the simple reason of speed and packet size.
Ted has a good discussion in the relative merits of XML vs. AMF
here
Something to consider is what you have already in place on the server and where you think the future of your clients lies.  Do you anticipate replacing or extending your clients?  If yes then Web Services are a good architectural choice.  If you are committing to Flex in the short/medium term then you may be able to squeeze better performance out of remoting with AMF3 vs. your web services.
P.S. I once had a link to a very good site which had measurements of the relative performance of AMF and SOAP - I'll see if I can find it and post a link.
P.P.S.
here it is
, but it seems not to be working at the moment.


Question:
I have a makefile template to compile a single DLL (for a plugin system).
The makefile of the user looks like this:

EXTRA_SRCS=file1 file2
include makefile.in

In the makefile.in I have:

plugin.dll: plugin.os $(patsubst %,%.os,$(EXTRA_SRCS))

Where plugin.os is the main C++ file to be compiled. Btw, the files ending is .os are the object files compiled for shared library (i.e. using the -fpic option with gcc)

Now, the problem is that the extra sources will probably (but not necessarily) be header files. Ideally I would like to add them as dependencies for the target plugin.os and the file.cpp, but only if they exist.

The method should work for both windows and linux, or at least be adaptable to each. However, I only use the GNU version of make.

Answer:
Use the "wildcard" function:
```
```
$(wildcard *.h)
```
```
EDIT: in order to match a specific list, do
```
```
$(wildcard $(HEADER_FILES))
```
```
There is no need to use $(filter ...), the wildcard function automatically filters files which don't exist.


Question:
I'm trying to code opposite action to this:

std::ostream outs; // properly initialized of course
std::set<int> my_set; // ditto

outs << my_set.size();
std::copy( my_set.begin(), my_set.end(), std::ostream_iterator<int>( outs ) );

it should be something like this:

std::istream ins;

std::set<int>::size_type size;
ins >> size;

std::copy( std::istream_iterator<int>( ins ), std::istream_iterator<int>( ins ) ???, std::inserter( my_set, my_set.end() ) );

But I'm stuck with the 'end' iterator -- input interators can't use std::advance and neither I can use two streams with the same source...

Is there any elegant way how to solve this? Of course I can use for loop, but maybe there's something nicer :)

Answer:
(Edited: I should have read the question closer...)
While somewhat suspect, you can get approximately the right behavior by having an entry in the file that will "fail" the first loop, then clear the fail bit on the stream and start reading more.
Data, without an explicit size, but like this
```
1 1 2 3 5 8 Fibb
```
Fed to the code below seems to do what I meant, at least on VS2005 with STLPort.
```
typedef std::istream_iterator < int, char, std::char_traits ,ptrdiff_t> is_iter;
std::copy( is_iter(cin), is_iter(), inserter(my_set,my_set.end()));
cin.clear();
std::cin >> instr;
```


Question: What is the difference between int *a[3] and int (*a)[3]?

Answer:
There is no difference between
```
int a[3]
```
and
```
int (a)[3]
```
, they both declare
```
a
```
as an array of 3
```
int
```
s.  There is a difference between
```
int *a[3]
```
and
```
int (*a)[3]
```
, the former declares an array of 3 pointers to
```
int
```
whereas the second declares a pointer to an array of 3
```
int
```
s.  The parenthesis make a difference here because in C brackets have a higher precedence than *.


Question:
I have the following legacy code:

public class MyLegacyClass
{
    private static final String jndiName = "java:comp/env/jdbc/LegacyDataSource"

    public static SomeLegacyClass doSomeLegacyStuff(SomeOtherLegacyClass legacyObj)
    {
       // do stuff using jndiName
    }
}

This class is working in a J2EE-Container.

Now I would like to test the class outside of the container.

What is the best strategy?
Refactoring is basically allowed.

Accessing the LegacyDataSource is allowed (the test does not have to be a "pure" unit-test).

EDIT: Introducing additional runtime-frameworks is not allowed.

Answer:
Refactor the code to use dependency injection.  Then use you preferred DI framework (Spring, Guice, ...) to inject your resources.  That will make it easy to switch between resource objects and strategies at runtime.
In this case, you can inject your datasource.
EDIT: Based on your new restriction, you can accomplish the same thing by using a strategy pattern to set your datasource at runtime.  You can probably just use a properties file to distinguish which strategy to create and supply the datasource.  This would require no new framework, you would just be hand coding the same basic functionality.  We used this exact idea with a ServiceLocator to supply a mock datasource when testing outside of the Java EE container.


Question:
When you have a complex property, should you instantiate it or leave it to the user to instantiate it?

For example (C#)

A)

 class Xyz{
     List<String> Names {get; set;}
 }

When I try to use, I have to set it.

...
Xyz xyz = new Xyz();
xyz.Name = new List<String>();
xyz.Name.Add("foo");
...

Where as if I modify the code

B)

 class Xyz{
     public Xyz(){
         Names = new List<String>();
     }
     List<String> Names {get; }
 }

which in this case, I can make the List read-only.

Another scenario might arise, I suppose where you would intentionally not want to set it. For example in

C)

 class Xyz{
     String Name {get; set;}
 }

I would thing it bad practice to initialize.

Are there some rules of thumb for such scenarios?

Answer:
This is my normal solution:
```
```
class XYZ
{
   public XYZ () { Names = new List<string>(); }
   public List<string> Names { get; private set; }
}
```
```
(Note that it doesn't work with XmlSerialization, as you need getters and setters on all XmlSerialized properties.) (You can override this, but it seems like too much work for little effort).
As
OregonGhost
pointed out - you need to add
```
[XmlArray]
```
for this to work with XmlSerialization.
This still breaks the rules of encapsulation, as if you wanted to be entirely correct, you would have:
```
```
class XYZ
{
   public XYZ () { AllNames = new List<string>(); }
   private List<string> AllNames { get; set; }
   public void AddName ( string name ) { AllNames.Add(name); }
   public IEnumerable<string> Names { get { return AllNames.AsReadOnly(); } }
}
```
```
As this goes against the design of almost all the rest of the .Net framework, I usually end up using the first solution.
However, this does have the added benefit that XYZ can track the changes to it's collection of names, and that XYZ is the only place where the collection of names can be modified.
I have implemented this for a few cases, but it causes too much friction with other programmers when I do it for everything.


Question:
I have a menu of product brands that I want to split over 4 columns.  So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column.  Here's how I'm calculating the item count for a column (using C#):

int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m));

All that conversion seems really ugly to me.  Is there a better way to do math on integers in C#?

Answer:
A longer alternative with Mod.
```
```
ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;
```
```


Question:
How to host the WCF service in windows service?

Thanks
Sekar

Answer:
I just saw this today come across Channel 9:
http://channel9.msdn.com/shows/Endpoint/endpointtv-Screencast-Hosting-WCF-Services-in-Windows-Services/


Question:
I have a simple application with the following code:

   FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles();
   List<Thread> threads = new List<Thread>(files.Length);

   foreach (FileInfo f in files)
   {
       Thread t = new Thread(delegate()
       {
            Console.WriteLine(f.FullName);
       });
       threads.Add(t);
   }

   foreach (Thread t in threads)
       t.Start();

Lets say in 'I=initialDirectory' directory I have 3 files.  This application should then create 3 threads, with each thread printing off one of the file names; however, instead each thread will print off the name of the last file in the 'files' array.

Why is this?  Why is the current file 'f' variable not getting setup in the anonymous method correctly?

Answer:
The anonymous method keeps a
reference
to the variable in the enclosing block -- not the actual value of the variable.
By the time the methods are actually executed (when you start the threads)
```
f
```
has been assigned to point to the last value in the collection, so all 3 threads print that last value.


Question: How can I get the start and end positions of all matches using the re module? For example given the pattern r'[a-z]' and the string 'a1b2c3d4' I'd want to get the positions where it finds each letter. Ideally, I'd like to get the text of the match back too.

Answer:
```
```
import re
p = re.compile("[a-z]")
for m in p.finditer('a1b2c3d4'):
    print(m.start(), m.group())
```
```


Question:
Is it better to write many small methods (or functions), or to simply write the logic/code of those small processes right into the place where you would have called the small method?  What about breaking off code into a small function even if for the time being it is only called from one spot?

If one's choice depends on some criteria, what are they; how should a programmer make a good judgement call?

I'm hoping the answer can be applied generally across many languages, but if necessary, answers given can be specific to a language or languages.  In particular, I'm thinking of SQL (functions, rules and stored procedures), Perl, PHP, Javascript and Ruby.

Answer:
I always break long methods up into logical chunks and try to make smaller methods out of them.  I don't
normally
turn a few lines into a separate method until I need it in two different places, but sometimes I do just to help readability, or if I want to test it in isolation.
Fowler's
Refactoring
is all about this topic, and I highly recommend it.
Here's a handy rule of thumb that I use from Refactoring.  If a section of code has a comment that I could re-word into a method name, pull it out and make it a method.


Question:
A VBScript cannot edit the registry by default on Vista.  How do I get elevation (even if the user has to do something when they run the script) so that the script can edit the registry?

The error is:

---------------------------
Windows Script Host
---------------------------
Script: blah blah blah.vbs
Line:   6
Char:   1
Error:  Permission denied
Code:   800A0046
Source:     Microsoft VBScript runtime error

---------------------------
OK
---------------------------

Answer:
To make it work with native VBScript, you will most likely need a code signing certificate and sign your script with that. More info is in that thread at
tek-tips.com
.
You could try to write the intended changes to a .reg file and call
```
regedit.exe
```
with that. Maybe this triggers UAC. Did not tried that, though. I have no Vista around right now. :-)


Question: I'm building a auto updater and I need to know what kind of upload speeds people get on a 56K modem?

Answer:
Theoretically 33.6 kbit/s upload = 4.2 kB/s[1].
From own experience, I would say half of that :)
[1]
http://en.wikipedia.org/wiki/ITU-T_V-Series_Recommendations#Simultaneous_transmission_of_data_and_other_signals


Question: How to optimize queries which are already written?

Answer:
If you can not change the them:
Indexes and statistics.
So you don't optimize the query but their execution plan.


Question:
We are ready to start a brand new project at work, no legacy code. We did use Subsonic in the past and we pretty happy with it. But that was before Linq.

Has anyone had to face this same issue (Linq x Subsonic)?

What was your decision? What were the reasons?

Any insight appreciated.

Answer:
The one thing I love about LINQ, which I don't think SubSonic handles as gracefully, is automatically dealing with joins.
```
```
FROM a in db.Orders
where a.Total > 100
SELECT new {a.Item.Desc, a.Customer.Name};
```
```
will automatically generate SQL like thisL
```
```
select i.DESC, c.NAME
from  ORDERS o
inner join ITEMS on o.ItemID = i.ItemID
inner join CUSTOMERS c on o.CustomerID = c.CUSTOMERID
where o.TOTAL > 100
```
```


Question:
With the Ajax Control Toolkit, one can easily drag and drop all types of great extender onto controls, but they register a boatload of JavaScript to do it.

How do I control this?

If the ScriptManager is in the MasterPage, is there anyway to control the loading of a script on one page that isn't in another?

For example: calendar extender is on one page, but the script for it gets loaded on every page that is a child of the master page.

Answer:
The one thing I love about LINQ, which I don't think SubSonic handles as gracefully, is automatically dealing with joins.
```
```
FROM a in db.Orders
where a.Total > 100
SELECT new {a.Item.Desc, a.Customer.Name};
```
```
will automatically generate SQL like thisL
```
```
select i.DESC, c.NAME
from  ORDERS o
inner join ITEMS on o.ItemID = i.ItemID
inner join CUSTOMERS c on o.CustomerID = c.CUSTOMERID
where o.TOTAL > 100
```
```


Question:
for some reason, templatetags do not render in templates for django admin.

with this snippet from:
http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags

{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}

when placed in admin index.html, if a user is logged in, it shows "Please log in"

same with templatetags, can not get any app ones to show, do anything. there is no error/they do not get processed either

Answer:
That's only an example, the
```
is_logged_in
```
variable is not actually defined in any templates unless you put it in the context.
If you added that line and got
```
Please log in.
```
it does mean that the tag is rendering.  If it fails the
```
if
```
and goes to the
```
else
```
it is clearly being run.  You need to find something in the template you can actually use for the
```
if
```
case, though.  I haven't messed with the admin templates in newforms-admin, but depending if they use RequestContext and on which ContextProcessors you have enabled - you might be able to say
```
{% if not request.user.is_anonymous %} ...
```
or something similar.


Question: As they are in .Net 3.5. I know they are in 4.0, as that's what the DLR works with, but I'm interested in the version we have now.

Answer:
LINQ expression trees can represent anything you can put in a normal C# expression. As such, they can't be used to directly represent
```
while
```
loops,
```
for
```
loops, etc.
However, it's theoretically possible to use lambda expressions and recursion to carry out any iteration you may need. In practice it may be easier to drop
```
Enumerable
```
methods into your tree.


Question: Can source code examples be kept in a SQL database while retaining all formatting (tabs, newlines, etc.)? If so what data type would be used?

Answer:
Yes, use a
```
TEXT
```
type (or
```
MEDIUMTEXT
```
or
```
LONGTEXT
```
- you get the idea)


Question:
I can't find any proper documentation on how to specify relations
using the declarative syntax of SQLAlchemy.. Is it unsupported? That is, should I use the "traditional" syntax?

I am looking for a way to specify relations at a higher level, avoiding having to mess with foreign keys etc.. I'd like to just declare "addresses = OneToMany(Address)" and let the framework handle the details.. I know that Elixir can do that, but I was wondering if "plain" SQLA could do it too.

Thanks for your help!

Answer:
Assuming you are referring to
the declarative plugin
, where everything I am about to say is documented with examples:
```
```
class User(Base):
    __tablename__ = 'users'

    id = Column('id', Integer, primary_key=True)
    addresses = relation("Address", backref="user")

class Address(Base):
    __tablename__ = 'addresses'

    id = Column('id', Integer, primary_key=True)
    user_id = Column('user_id', Integer, ForeignKey('users.id'))
```
```


Question:
If I write Session["asdf"] = 234;

In my asp.net web app, does this mean the client will have a cookie stored on their browser?

Answer:
Yes, but 234 won't be stored in the cookie. The cookie will only contain a unique ID (for example,
```
lit3py55t21z5v55vlm25s55
```
). Every time ASP.NET sees that unique ID, it will look up the corresponding session information.
If you don't want to use cookies, you can put the session ID in the URL. Read this
MSDN article's
section on Cookieless SessionIDs.


Question:
I need to write some registration data (unique computer number, and corresponding activation code).

The Computer Number needs to be visible from other programs and all accounts ({Admin|Non Admin} with User Access Control turned {On|Off} )

It's acceptable to write the Computer Number and Activation Code only from an Admin account, but it needs to be readable from any of the other accounts.

Currently (and I need to test this more) it seems that  if the the CN and Activation Code are written with UAC off then when the user switches UAC ON the Computer Number isn't visible.

Answer:
Yes, but 234 won't be stored in the cookie. The cookie will only contain a unique ID (for example,
```
lit3py55t21z5v55vlm25s55
```
). Every time ASP.NET sees that unique ID, it will look up the corresponding session information.
If you don't want to use cookies, you can put the session ID in the URL. Read this
MSDN article's
section on Cookieless SessionIDs.


Question:
I am writing a macro for Visual studio that will generate some code.

I would like for the macro to generate for both C# and VB, is there a way to determine what language is being used in the active (current) document?

Answer:
Have you considered using
T4
?
T4 is a code generator built right into Visual Studio. If you're using C#, you'll have a sub .cs file, or if you're using VB, a sub .vb file. That's the file that will hold the result of the generation. This is the same visual metaphor used to the express the template/generated file relationship with .designer files you've seen elsewhere in Visual Studio.


Question:
I am developing a JSP application and am being forced to load a COM object. Can such a thing can be done?

If yes, how?

Answer:
It is possible using a COM bridge like
JACOB
.
JACOB is a JAVA-COM Bridge that allows you to call COM Automation components from Java. It uses JNI to make native calls into the COM and Win32 libraries.