q:
Can you do a better code? I need to check/uncheck all childs according to parent and when an child is checked, check parent, when all childs are unchecked uncheck parent.

    $(".parent").children("input").click(function() {
    $(this).parent().siblings("input").attr("checked", this.checked);
});

$(".parent").siblings("input").click(function() {
    if (this.checked) {
        $(this).siblings("div").children("input").attr("checked", true);
        return;
    }

    var childs = $(this).siblings("div").siblings("input");

    for (i = 0; i < childs.length; i++) {
        if ($(childs.get(i)).attr("checked"))
            return;
    }

    $(this).parent().children("div").children("input").attr("checked", false);
});

[A]
```
```
$(".parent").children("input").click(function() {
    $(this).parent().siblings("input").attr("checked", this.checked);
});

$(".parent").siblings("input").click(function() {
    $(this).siblings("div").children("input").attr("checked",
        this.checked || $(this).siblings("input[checked]").length>0
    );
});
```
```


q:
I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input.  The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes.  Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.

What I would like to do is import the dictionary file once and pass it to each solver instance as they need it.  But what is the best way to do this?  Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']?  Or should I import the dictionary then pass it as an argument to the class constructor?  Is one of these better than the other?  Is there a third option?

[A]
Even though it is essentially a singleton at this point, the usual arguments against globals apply.  For a pythonic singleton-substitute, look up the "borg" object.
That's really the only difference.  Once the dictionary object is created, you are only binding new references as you pass it along unless if you explicitly perform a deep copy.  It makes sense that it is centrally constructed once and only once so long as each solver instance does not require a private copy for modification.

s: huggingface

c: devops

d: intermediate


q:
In several cases I want to add a toolbar to the top of the iPhone keyboard (as in iPhone Safari when you're navigating form elements, for example).

Currently I am specifying the toolbar's rectangle with constants but because other elements of the interface are in flux - toolbars and nav bars at the top of the screen - every time we make a minor interface change, the toolbar goes out of alignment.

Is there a way to programmatically determine the position of the keyboard in relation to the current view?

[A]
There's no way (AFAIK) to get the dimensions of the keyboard view. It is however constant, at least in every iPhone version so far.
If you calculate the toolbar position as an offset from the BOTTOM of your view, and take the size of your view into account, then you should not have to worry whether a navbar is present or not.
E.g.
```
```
#define KEYBOARD_HEIGHT 240 // example - can't remember the exact size
#define TOOLBAR_HEIGHT 30

toolBarRect.origin.y = viewRect.size.height - KEYBOARD_HEIGHT - TOOLBAR_HEIGHT;

// move toolbar either directly or with an animation
```
```
Instead of a define, you could easily create a
```
keyboardHeight
```
function that returns the size based on whether the keyboard is being displayed, and move this toolbar positioning into a separate function that reorganizes your layout.
Also it can depend on where you do this positioning as it's possible the size of your view may change between being loaded and shown based on your navbar setup. I believe the best place to do it would be in viewWillAppear.


q:
I am trying to add a timed delay in a C++ program, and was wondering if anyone has any suggestions on what I can try or information I can look at?

I wish I had more details on how I am implementing this timed delay, but until I have more information on how to add a timed delay I am not sure on how I should even attempt to implement this.

[A]
Do you want something as simple like:
```
```
#include <unistd.h>
sleep(3);//sleeps for 3 second
```
```


q: What VBA code is required to perform an HTTP POST from an Excel spreadsheet?

[A]
You can use
```
ServerXMLHTTP
```
in a VBA project by adding a reference to
```
MSXML
```
.
Open the VBA Editor (usually by editing a Macro)
Go to the list of Available References
Check Microsoft XML
Click OK.
(from
Referencing MSXML within VBA Projects
)
The
ServerXMLHTTP MSDN documentation
has full details about all the properties and methods of ServerXMLHTTP.
In short though, it works basically like this:
Call
open
method to connect to the remote server
Call
send
to send the request.
Read the response via
responseXML
,
responseText
,
responseStream
or
responseBody


q:
You do you manage the same presenter working with different repositories using the MVP pattern?

I just have multiple constructor overloads and the presenter simply uses the one that is suitable for the scenario.

AddCustomerPresenter presenter = new AddCustomerPresenter(this,customerRepository);
presenter.AddCustomer();

presenter = new AddCustomerPresenter(this,archiveRepository);
presenter.Archive();

[A]
Why not have
```
```
IRepository { /* .. */ }
CustomerRepository : IRepository { /* .. */ }
ArchiveRepository : IRepository { /* .. */ }
```
```
and then
```
```
AddCustomerPresenter {
IRepository Store {get;set;}
public AddCustomerPresenter(IRepository store) { /*...*/ }
/*...*/
}
```
```
Your presenter should NOT have any static dependency on ANY implementation of IRepository.  If you find there's no other way, you need to rework your design because it's probably flawed.


q:
I want to delete all directories and subdirectories under a root directory that are contain "tmp" in their names. This should include any .svn files too. My first guess is to use

<delete>
    <dirset dir="${root}">
          <include name="**/*tmp*" />
    </dirset>
</delete>

This does not seem to work as you can't nest a dirset in a delete tag.

Is this a correct approach, or should I be doing something else?

ant version == 1.6.5.

java version == 1.6.0_04

[A]
try:
```
```
<delete includeemptydirs="true">
    <fileset dir="${root}">
          <include name="**/*tmp*/*" />
    </fileset>
</delete>
```
```
ThankYou  flicken !


q:
I'd like to check if the current browser supports the onbeforeunload event.
The common javascript way to do this does not seem to work:

if (window.onbeforeunload) {
    alert('yes');
}
else {
    alert('no');
}

Actually, it only checks whether some handler has been attached to the event.
Is there a way to detect if onbeforeunload is supported without detecting the particular browser name?

[A]
It would probably be better to just find out by hand which browsers support it and then have your conditional more like:
```
```
if( $.browser.msie ) {
  alert( 'no' );
}
```
```
...etc.
The
```
$.browser.msie
```
is jQuery syntax, most frameworks have similar built-in functions since they use them so much internally. If you aren't using a framework then I'd suggest just taking a look at jQuery's implementation of those functions.


q:
I'm using the Excel interop in C# (ApplicationClass) and have placed the following code in my finally clause:

while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();

Although this kind of works, the Excel.exe process is still in the background even after I close Excel. It is only released once my application is manually closed.

What am I doing wrong, or is there an alternative to ensure interop objects are properly disposed of?

[A]
This worked for a project I was working on:
```
```
excelApp.Quit();
Marshal.ReleaseComObject (excelWB);
Marshal.ReleaseComObject (excelApp);
excelApp = null;
```
```
We learned that it was important to set
every
reference to an Excel COM object to null when you were done with it. This included Cells, Sheets, and everything.


q:
As Microsoft seems to have started their trickle feed of information regarding .NET 4.0, I thought I'd ask the question as I'm sure there's more out there than I've spotted!

What information has been released regarding the .NET Framework 4.0?

[A]
http://news.google.com/news?hl=en&ned=us&q=net+Framework+4.0&btnG=Search+News
is a good place to start


q:
I work in an multi-site environment that's currently using Rational ClearCase for source control and Rational ClearQuest for issue tracking (I accept your condolences ahead of time).  As a rough estimate I would say this is supporting 200 engineers.

How would you effectively migrate this SCM methodology to a comparative, all Open Source tool suite?  Not only would this save literally hundreds of thousands of dollars but I also believe it would improve developer productivity and very little downtime compared to the current system.

Platforms in use include Windows, Linux, UNIX and Solaris.

[A]
Clearcase is awesome.  I use to think like you but then after moving to perforce I realized how great dynamic views are.
I actually asked about this in
another question
.  Basically it is really, really hard and is made much easier if you can live without your revision history.
As for bug tracking my experiences are that open source bug tracking tools are terrible.  However using triggers it is usually very easy to integrate them with open source source control. As an example here is how to
integrate bugzilla and subversion


q:
I am looking for any examples or guides to using Linq over WCF (n-tier application). Please specify if you are showing something for Linq-to-SQL or Linq-to-entities. I would like to see usage examples for both.

I am wondering how things like deffered execution works over WCF (if it works at all)? Cyclic references support and so on...

Any information to make this a quick start guide to using Linq with WCF is helpful.

[A]
There isn't any LINQ provider that I'm aware of for generic WCF-based queries.
LINQ to ADO.NET Data Services
, however, lets you query an Entity model over WCF/REST.
From
Andy Conrad's blog
:
```
```
static void Main(string[] args)
    {
      var context=new WebDataContext("http://localhost:18752/Northwind.svc");

      var query = from p in context.CreateQuery<Product>("Products")
                  where p.UnitsInStock > 100
                  select p;

      foreach (Product p in query)
      {
        Console.WriteLine(p.ProductName+", UnitsInStock="+p.UnitsInStock);
      }
   }
```
```


q: I'm writing a series of Windows services.  I want them to fail if errors are thrown during startup (in OnStart() method).  I had assumed that merely throwing an error in OnStart() would do this, but I'm finding that instead it "Starts" and presents me with a message stating "The service has started, but is inactive.  Is this correct?" (Paraphrase).  How do I handle the error so it actually fails to start the service?

[A]
Move all of your startup logic to a separate method, and Throw exceptions (or call OnStop) from that seperate method.
OnStart has some oddities when starting up. I have found that if OnStart() has no more than one line in it, then I dont get the "The service started and then stopped.Some services stop automatically if they have no work to do" message, and thrown exceptions will terminate the process and log to the app event log.
Also with the seperate startup method, you can use a technique like this to debug it without attaching.
http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx


q:
I'm trying to iterate all the controls on a form and enable ClearType font smoothing. Something like this:

procedure TForm4.UpdateControls(AParent: TWinControl);
var
  I: Integer;
  ACtrl: TControl;
  tagLOGFONT: TLogFont;
begin
  for I := 0 to AParent.ControlCount-1 do
  begin
    ACtrl:= AParent.Controls[I];

    // if ParentFont=False, update the font here...

    if ACtrl is TWinControl then
      UpdateControls(Ctrl as TWinControl);
  end;
end;

Now, is there a easy way to check if ACtrl have a Font property so i can pass the Font.Handle to somethink like:

GetObject(ACtrl.Font.Handle, SizeOf(TLogFont), @tagLOGFONT);
tagLOGFONT.lfQuality := 5;
ACtrl.Font.Handle := CreateFontIndirect(tagLOGFONT);

Thank you in advance.

[A]
You use TypInfo unit, more specifically methods IsPublishedProp and GetOrdProp.
In your case, it would be something like:
```
```
if IsPublishedProp(ACtrl, 'Font') then
  ModifyFont(TFont(GetOrdProp(ACtrl, 'Font')))
```
```
A fragment from one of my libraries that should put you on the right path:
```
```
function ContainsNonemptyControl(controlParent: TWinControl;
  const requiredControlNamePrefix: string;
  const ignoreControls: string = ''): boolean;
var
  child   : TControl;
  iControl: integer;
  ignored : TStringList;
  obj     : TObject;
begin
  Result := true;
  if ignoreControls = '' then
    ignored := nil
  else begin
    ignored := TStringList.Create;
    ignored.Text := ignoreControls;
  end;
  try
    for iControl := 0 to controlParent.ControlCount-1 do begin
      child := controlParent.Controls[iControl];
      if (requiredControlNamePrefix = '') or
         SameText(requiredControlNamePrefix, Copy(child.Name, 1,
           Length(requiredControlNamePrefix))) then
      if (not assigned(ignored)) or (ignored.IndexOf(child.Name) < 0) then
      if IsPublishedProp(child, 'Text') and (GetStrProp(child, 'Text') <> '') then
        Exit
      else if IsPublishedProp(child, 'Lines') then begin
        obj := TObject(cardinal(GetOrdProp(child, 'Lines')));
        if (obj is TStrings) and (Unwrap(TStrings(obj).Text, child) <> '') then
          Exit;
      end;
    end; //for iControl
  finally FreeAndNil(ignored); end;
  Result := false;
end; { ContainsNonemptyControl }
```
```


q:
I've installed .NET Framework 3.5 SP1 on web server (Server 2008 Enterprise), so running IIS 7.0.

I want to change the version of .NET Framework used by an existing site.  So I right-click on appropriate Application Pool and selected Edit Application Pool.  The .NET Framework dropdown does not include an explicit entry for framework 3.5, but just 2.0.50727.

Is this just because the version of the core RTL in 3.5 is still 2.0? Or do I need to do something additional to get IIS to see version 3.5?  (Did try restarting IIS).

[A]
Is this just because the version of the core RTL in 3.5 is still 2.0?
YES


q: What does it indicate to see a query that has a low cost in the explain plan but a high consistent gets count in autotrace? In this case the cost was in the 100's and the CR's were in the millions.


q: Since I'm not a huge fan of any of the current solutions for managing the resources and knowledge that I have, I was thinking about making my own solution, which will involve custom code as well as possible integration of FOSS solutions. I would start development on my local machine, but if I like it, how difficult would it be to migrate over to a public server and let others also use this tool? What kinds of challenges might I be facing?

[A]
In theory, nothing, beyond just the process of moving stuff to the new machine. You can set up your own servers, on your own ports (port 80 for example).
You can even create your own fake domain at home, with just a tweak to the /etc/hosts files (or the equivalent on Windows).
Now, if you're developing on Windows and hosting on unix, you'll have platform issues, so I'd suggest against that, at least for a first project.
But other than that, it should be straightforward.


q: what is a good way to select a random element from a map?  C++.  It is my understanding that maps don't have random access iterators.  The key is a long long and the map is sparsely populated.

[A]
```
```
map<...> MyMap;
iterator item = MyMap.begin();
std::advance( item, random_0_to_n(MyMap.size()) );
```
```


q:
Is there a way to have a file that is modified / touched whenever the WC is updated to a new revision? Or, as the second-best option, whenever svn update is executed?

Here's the motivation: I want to have the SVN revision number inside my executable. So I have to run SubWCRev as part of the build. The output file of SubWCRev is re-created every time, even if the revision number has not changed. This means that the exe is linked on every build, even if nothing has changed. I want it to be linked only as needed.

[A]
Get the SubWCRev output into a temporary file
Compare this file to the current revision-number file
Overwrite it with the temp file only if the two are different
Delete the temporary file
You might even be able to do this with a .bat file (using
```
fc
```
). Something like...
```
```
REM ***UNTESTED***
FC temp.rev curr.rev | FIND "FC: no dif" > nul
IF NOT ERRORLEVEL 1 COPY /Y temp.rev curr.rev
DEL temp.rev
```
```
Edit:
As an aside, you can do this in Mercurial by making the rev-number-file depend on
```
.hg/dirstate
```
.


q: How do I limit the types of HTML that a user can input into a textbox? I'm running a small forum using some custom software that I'm beta testing, but I need to know how to limit the HTML input. Any suggestions?

[A]
Once the text is submitted, you could strip any/all tags that don't match your predefined set using a regex in PHP.
It would look something like the following:
```
```
find open tag (<)
if contents != allowed tag, remove tag (from <..>)
```
```


q: How would I upload a file to a webserver using c++ and MFC.  We are not using .Net.  Would I need to open a socket and do everything myself?  If so, where is a good reference to follow?

[A]
You don't want to use direct socket calls. It's hard to get HTTP right this way.
The easier way is to the WinINet APIs. Check out the docs for InternetOpen, this will likely be the first call you make. Functions you will likely need:
InternetOpen
InternetConnect
HttpOpenRequest
HttpSendRequest
HttpQueryInfo
InternetCloseHandle
You can find docs for all of these on msdn


q: I have an array of characters that are Points and I want to take any character and be able to loop through that array and find the top 3 closest (using Point.distance) neighbors. Could anyone give me an idea of how to do this?

[A]
This is a new and improved version of the code I posted last night. It's composed of two classes, the PointTester and the TestCase. This time around I was able to test it too!
We start with the TestCase.as
```
```
package  {

    import flash.geom.Point;
    import flash.display.Sprite;

    public class TestCase extends Sprite {

        public function TestCase() {
            // some data to test with
            var pointList:Array = new Array();
            pointList.push(new Point(0, 0));
            pointList.push(new Point(0, 0));
            pointList.push(new Point(0, 0));
            pointList.push(new Point(1, 2));
            pointList.push(new Point(9, 9));

            // the point we want to test against
            var referencePoint:Point = new Point(10, 10);

            var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);

            trace("referencePoint is at", referencePoint.x, referencePoint.y);
            for each(var result:Object in resultPoints) {
                trace("Point is at:", result.point.x, ", ", result.point.y, " that's ", result.distance, " units away");
            }
        }

    }

}
```
```
And this would be PointTester.as
```
```
package  {

    import flash.geom.Point;

    public class PointTester {

        public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{

            // this array will hold the results
            var resultList:Array = new Array();

            // loop over each point in the test data
            for each (var testPoint:Point in pointList) {

                // we store the distance between the two in a temporary variable
                var tempDistance:Number = getDistance(testPoint, referencePoint);

                // if the list is shorter than the maximum length we don't need to do any distance checking
                // if it's longer we compare the distance to the last point in the list, if it's closer we add it
                if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) {

                    // we store the testing point and it's distance to the reference point in an object
                    var tmpObject:Object = { distance : tempDistance, point : testPoint };
                    // and push that onto the array
                    resultList.push(tmpObject);

                    // then we sort the array, this way we don't need to compare the distance to any other point than
                    // the last one in the list
                    resultList.sortOn("distance", Array.NUMERIC );

                    // and we make sure the list is kept at at the proper number of entries
                    while (resultList.length > maxCount) resultList.pop();
                }
            }

            return resultList;
        }

        public static function getDistance(point1:Point, point2:Point):Number {
            var x:Number = point1.x - point2.x;
            var y:Number = point1.y - point2.y;
            return Math.sqrt(x * x + y * y);
        }
    }
}
```
```


q: What are the key differences between Flash and Flex?  I have over five years experience with flash and feel very comfortable developing with it and ActionScript3.  I find myself more and more curious about Flex and want to know when it is best to use flash or flex.  Also, is everything that can be done with MXML, able to be done with AS3?  I have a strong understanding of AS3 and OOP and would like to know the diffrences between using AS3 and MXML in Flex.

[A]
Flash and Flex provide different ways to produce different things. I am not familiar with Flash, but I would expect that it is dependent on a time-oriented way to produce something, whereas Flex is geared toward more traditional software development. That is, rather than dealing with time and frames in Flash, one is dealing with describing where components should be placed with MXML and how those components work with ActionScript.
One should also be able to write a Flex app with just AS3 and no need MXML.
The main difference between AS3 and MXML in Flex, as far as I know, is that MXML is not intended to be used with application logic, but rather it is intended to be used like HTML/CSS in web pages and puts components and content onto the Flex app. ActionScript is used to program behaviors, components, and other things outside or what MXML does. Thus, if you want to attach an event to a component one would write ActionScript code.
Hope that helps. I am still learning about Flex myself.


q: I'm thinking floats.  For the record I'm also using NHibernate.

[A]
```
decimal
```
You won't lose precision due to rounding.


q:
I am very new to the entity framework, so please bear with me...

How can I relate two objects from different contexts together?

The example below throws the following exception:

System.InvalidOperationException: The
  relationship between the two objects
  cannot be defined because they are
  attached to different ObjectContext
  objects.

void MyFunction()
{
    using (TCPSEntities model = new TCPSEntities())
    {
        EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);
        er.Roles = GetDefaultRole();
        model.SaveChanges();
     }
}

private static Roles GetDefaultRole()
{
    Roles r = null;
    using (TCPSEntities model = new TCPSEntities())
    {
        r = model.Roles.First(p => p.RoleId == 1);
    }
    return r;
}

Using one context is not an option because we are using the EF in an ASP.NET application.

[A]
You will have to use the same context (you can pass the context to the getdefaultrole method) or rethink the relationships and extend the entity.
EDIT: Wanted to add this was for the example provided, using asp.net will require you to fully think out your context and relationship designs.
You could simply pass the context.. IE:
```
```
void MyFunction()
{
    using (TCPSEntities model = new TCPSEntities())
    {
        EmployeeRoles er = model.EmployeeRoles.First(p=>p.EmployeeId == 123);
        er.Roles = GetDefaultRole(model);
        model.SaveChanges();
     }

}

private static Roles GetDefaultRole(TCPSEntities model)
{
    Roles r = null;
    r = model.Roles.First(p => p.RoleId == 1);
    return r;
}
```
```


q:
I need to, preferably in C# - but c++ will do, find a way to filter the list of printers in the windows print dialog for any windows printing.

I have come across WinAPIOverride and have figured I am going to have to write my own dll which overrides the method to get the printers list, then filter it and return it. I would then have to inject the dll into all running processes.

Can anybody assist me with something that is already developed or perhaps an easier way of accomplishing this?  The only way the list of printers comes out is from the API method call and I have even considered modifying the registry, but this will slow down the response of the print dialog box to the point that it would be annoying to the user.

[A]
I don't think that (re)writing a DLL is the easiest method. Why not use
WMI
to retrieve the wanted
information (printers in this case)
?
The following code is for retrieving all the locally installed printers:
(code samples borrowed from
here
)
```
```
ManagementScope objScope = new ManagementScope(ManagementPath.DefaultPath); //For the local Access
    objScope.Connect();

    SelectQuery selectQuery = new SelectQuery();
    selectQuery.QueryString = "Select * from win32_Printer";
    ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
    ManagementObjectCollection MOC = MOS.Get();
    foreach (ManagementObject mo in MOC) {
      listBox1.Items.Add(mo["Name"].ToString().ToUpper());
    }
```
```
To get the printers known accross a domain use this:
```
```
ConnectionOptions objConnection = new ConnectionOptions();
objConnection.Username = "USERNAME";
objConnection.Password = "PASSWORD";
objConnection.Authority = "ntlmdomain:DDI"; //Where DDI is the name of my domain
// Make sure the user you specified have enough permission to access the resource.

ManagementScope objScope = new ManagementScope(@"\\10.0.0.4\root\cimv2",objConnection); //For the local Access
objScope.Connect();

SelectQuery selectQuery = new SelectQuery();
selectQuery.QueryString = "Select * from win32_Printer";
ManagementObjectSearcher MOS = new ManagementObjectSearcher(objScope, selectQuery);
ManagementObjectCollection MOC = MOS.Get();
foreach (ManagementObject mo in MOC) {
  listBox1.Items.Add(mo["Name"].ToString().ToUpper());
}
```
```
Of course, the list is not "filtered" as you would like as you didn't specify any criteria. But I'm sure you can manage from here on by yourself.


q: Is there a way to find the maximum and minimum defined values of an enum in c++?

[A]
No, there is no way to find the maximum and minimum defined values of any enum in C++. When this kind of information is needed, it is often good practice to define a Last and First value. For example,
```
```
enum MyPretendEnum
{
   Apples,
   Oranges,
   Pears,
   Bananas,
   First = Apples,
   Last = Bananas
};
```
```
There do not need to be named values for every value between
```
First
```
and
```
Last
```
.


q: What is the use of a Dispatcher Object in WPF?

[A] A dispatcher is often used to invoke calls on another thread. An example would be if you have a background thread working, and you need to update the UI thread, you would need a dispatcher to do it.


q:
Is there any way to format a string by name rather than position in C#?

In python, I can do something like this example (shamelessly stolen from here):

>>> print '%(language)s has %(#)03d quote types.' % \
      {'language': "Python", "#": 2}
Python has 002 quote types.

Is there any way to do this in C#?  Say for instance:

String.Format("{some_variable}: {some_other_variable}", ...);

Being able to do this using a variable name would be nice, but a dictionary is acceptable too.

[A]
I think the closest you'll get is an indexed format:
```
```
String.Format("{0} has {1} quote types.", "C#", "1");
```
```
There's also String.Replace(), if you're willing to do it in multiple steps and take it on faith that you won't find your 'variables' anywhere else in the string:
```
```
string MyString = "{language} has {n} quote types.";
MyString = MyString.Replace("{language}", "C#").Replace("{n}", "1");
```
```
Expanding this to use a List:
```
```
List<KeyValuePair<string, string>> replacements = GetFormatDictionary();
foreach (KeyValuePair<string, string> item in replacements)
{
    MyString = MyString.Replace(item.Key, item.Value);
}
```
```
You could do that with a Dictionary<string, string> too by iterating it's .Keys collections, but by using a List<KeyValuePair<string, string>> we can take advantage of the List's .ForEach() method and condense it back to a one-liner:
```
```
replacements.ForEach(delegate(KeyValuePair<string,string>) item) { MyString = MyString.Replace(item.Key, item.Value);});
```
```
A lambda would be even simpler, but I'm still on .Net 2.0.  Also note that the .Replace() performance isn't stellar when used iteratively, since strings in .Net are immutable.  Also, this requires the
```
MyString
```
variable be defined in such a way that it's accessible to the delegate, so it's not perfect yet.


q: Are C++ enums signed or unsigned? And by extension is it safe to validate an input by checking that it is <= your max value, and leave out >= your min value (assuming you started at 0 and incremented by 1)?

[A]
The compiler can decide whether or not enums are signed or unsigned.
Another method of validating enums is to use the enum itself as a variable type.  For example:
```
```
enum Fruit
{
    Apple = 0,
    Banana,
    Pineapple,
    Orange,
    Kumquat
};

enum Fruit fruitVariable = Banana;  // Okay, Banana is a member of the Fruit enum
fruitVariable = 1;  // Error, 1 is not a member of enum Fruit even though it has the same value as banana.
```
```


q: Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop and then re-create the constraints?

[A]
(Copied from from
http://www.sqljunkies.com/WebLog/roman/archive/2005/01/30/7037.aspx
,
which is now archived in the Wayback Machine
)
Foreign key constraints and check constraint are very useful for enforcing data integrity and business rules. There are certain scenarios though where it is useful to temporarily turn them off because their behavior is either not needed or could do more harm than good. I sometimes disable constraint checking on tables during data loads from external sources or when I need to script a table drop/recreate with reloading the data back into the table. I usually do it in scenarios where I don't want a time consuming process to fail because one or a few of many million rows have bad data in it. But I always turn the constraints back on once the process is finished and also in some cases I run data integrity checks on the imported data.
If you disable a foreign key constraint, you will be able to insert a value that does not exist in the parent table. If you disable a check constraint, you will be able to put a value in a column as if the check constraint was not there. Here are a few examples of disabling and enabling table constraints:
```
```
-- Disable all table constraints
   ALTER TABLE MyTable NOCHECK CONSTRAINT ALL

   -- Enable all table constraints
   ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT ALL

   -- Disable single constraint

   ALTER TABLE MyTable NOCHECK CONSTRAINT MyConstraint

   -- Enable single constraint
   ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint
```
```


q:
I inherited a database built with the idea that composite keys are much more ideal than using a unique object ID field and that when building a database, a single unique ID should never be used as a primary key.  Because I was building a Rails front-end for this database, I ran into difficulties getting it to conform to the Rails conventions (though it was possible using custom views and a few additional gems to handle composite keys).

The reasoning behind this specific schema design from the person who wrote it had to do with how the database handles ID fields in a non-efficient manner and when it's building indexes, tree sorts are flawed.  This explanation lacked any depth and I'm still trying to wrap my head around the concept (I'm familiar with using composite keys, but not 100% of the time).

Can anyone offer opinions or add any greater depth to this topic?

[A]
Using 'unique (object) ID' fields simplifies joins, but you should aim to have the other (possibly composite) key still unique -- do NOT relax the not-null constraints and DO maintain the unique constraint.
If the DBMS can't handle unique integers effectively, it has big problems.  However, using both a 'unique (object) ID' and the other key does use more space (for the indexes) than just the other key, and has two indexes to update on each insert operation.  So it isn't a freebie -- but as long as you maintain the original key, too, then you'll be OK.  If you eliminate the other key, you are breaking the design of your system; all hell will break loose eventually (and you might or might not spot that hell broke loose).


q:
In WPF:

Can someone please explain the relationship between DependencyProperty and Databinding?

I have a property in my code behind I want to be the source of my databinding.
When does a DependencyProperty (or does it) come into play if I want to bind this object to textboxes on the XAML.

[A]
The target in a binding must always be a
```
DependencyProperty
```
, but any property (even plain properties) can be the source.
The problem with plain properties is that the binding will only pick up the value once and it won't change after that because change notification is missing from the plain source property.
To provide that change notification without making it a
```
DependencyProperty
```
, one can:
Implement
```
INotifyPropertyChanged
```
on the class defining the property.
Create a
```
PropertyName
```
```
Changed
```
event. (Backward compatibility.)
WPF will work better with the first choice.


q:
Which type of input is least vulnerable to Cross-Site Scripting (XSS) and SQL Injection attacks.

PHP, HTML, BBCode, etc. I need to know for a forum I'm helping a friend set up.

[A]
We need to know more about your situation.  Vulnerable how?  Some things you should always do:
Escape strings before storing them in a database to guard against SQL injections
HTML encode strings when printing them back to the user from an unknown source, to prevent malicious html/javascript
I would never execute php provided by a user.  BBCode/UBBCode are fine, because they are converted to semantically correct html, though you may want to look into XSS vulnerabilities related to malformed image tags.  If you allow HTML input, you can whitelist certain elements, but this will be a complicated approach that is prone to errors.  So, given all of the preceding, I would say that using a good off-the-shelf
BBCode
library would be your best bet.


q:
For example, this regex

(.*)<FooBar>

will match:

abcde<FooBar>

But how do I get it to match across multiple lines?

abcde
fghij<FooBar>

[A]
In the context of use within languages, regular expressions act on strings, not lines. So you should be able to use the regex normally, assuming that the input string has multiple lines.
In this case, the given regex will match the entire string, since "<FooBar>" is present. Depending on the specifics of the regex implementation, the $1 value (obtained from the "(.*)") will either be "fghij" or "abcde\nfghij". As others have said, some implementations allow you to control whether the "." will match the newline, giving you the choice.
Line-based regular expression use is usually for command line things like egrep.


q:
I need a cross platform method of determining the MAC address of a computer at run time.  For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output.  I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone.

Does anyone know a cross platform method (windows and linux) method to get the MAC address?    If not, does anyone know any more elegant methods then those I listed above?

[A]
```
netifaces
```
is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.
```
```
import netifaces

netifaces.interfaces()
# ['lo', 'eth0', 'tun2']

netifaces.ifaddresses('eth0')[netifaces.AF_LINK]
# [{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]
```
```
pypi location
Good Intro to netifaces


q:
Groovy adds the execute method to String to make executing shells fairly easy;

println "ls".execute().text

but if an error happens, then there is no resulting output.  Is there an easy way to get both the standard error and standard out?  (other than creating a bunch of code to; create two threads to read both inputstreams, then using a parent stream to wait for them to complete then convert the strings back to text?)

It would be nice to have something like;

 def x = shellDo("ls /tmp/NoFile")
 println "out: ${x.out} err:${x.err}"

[A]
```
"ls".execute()
```
returns a
```
Process
```
object which is why
```
"ls".execute().text
```
works. You should be able to just read the error stream to determine if there were any errors.
There is a extra method on
```
Process
```
that allow you to pass a
```
StringBuffer
```
to retrieve the text:
```
consumeProcessErrorStream(StringBuffer error)
```
.
Example:
```
```
def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)

println proc.text
println b.toString()
```
```


q: What are the differences between the free sql express 05 management studio and the licensed version?

[A]
See the "SQL Server 2005 Features Comparison" at
http://www.microsoft.com/sql/prodinfo/features/compare-features.mspx


q:
I've used DTCTester before to diagnose MSDTC problems. However, I just noticed DTCPing seems to do about the same thing. What's the difference between these two?

From what I can tell so far, DTCPing needs to run on both client and server machines, whereas DTCTester only needs to run from the client. Are there any other differences?

[A]
Testing DTC settings is very common when installing BizTalk Server, so from the BTS documentation, so - from
http://msdn.microsoft.com/en-us/library/aa561924.aspx
Use the DTCTester utility to verify
  transaction support between two
  computers if SQL Server is installed
  on one of the computers. The DTCTester
  utility uses ODBC to verify
  transaction support against a SQL
  Server database. For more information
  about DTCTester see How to Use
  DTCTester Tool.
Use DTCPing to verify transaction
  support between two computers if SQL
  Server is not installed on either
  computer. The DTCPing tool must be run
  on both the client and server computer
  and is a good alternative to the
  DTCTester utility when SQL Server is
  not installed on either computer. For
  more information about DTCPing, see
  How to troubleshoot MS DTC firewall
  issues.


q:
I'm working in .Net 3.5sp1 in C# for an ASP.Net solution and I'm wondering if there's any way to turn on the Class Name and Method Name drop-downs in the text editor that VB.Net has at the top. It's one of the few things from VB that I actually miss.

Edit: Also, is there any way to get the drop downs to be populated with the possible events?

e.g. (Page Events) | (Declarations)

[A]
Go To:
```
```
Tools -> Options -> Text Editor -> C# -> General -> Navigation Bar
```
```
Make sure it is clicked, and that should show something at the top of your code that has all the classes and methods listed in your file.


q:
Can anyone tell me what version of the .NET framework (CLR and BCL) is req'd for the recently-released MS Sync Framework (for support of occasionally-connected-applications)?

Its listed as Sync Framework V1 for ADO.NET v2.0 but none of its listed req'ments say anything about the .NET fx version that is required to support it.

Anyone got any experience with this...?

[A] If it specifies ADO.NET 2.0, then you'll need at least .NET 2.0. ADO.NET changed a lot between 1.1 and 2.0


q: When I have a regular textbox in a UpdatePanel (not an ASP.NET control) with some JavaScript events on it, after the UpdatePanel updates my events are gone. Is there a way to re-attach my events after the update? (Preferably without putting my events inline).

[A]
You can have a
```
setInterval()
```
loop on document load that would search for the element in the update panel and if it didn't have the events, it can re-attach them.


q: Bearing in mind that I'll be performing calculations on lat / long pairs, what datatype is best suited for use with a MySQL database?

[A]
Use MySQL's
spatial extensions
with GIS.


q:
grant {
    permission java.security.AllPermission;
};

This works.

grant file:///- {
    permission java.security.AllPermission;
};

This does not work.  Could someone please explain to me why?

[A]
The directive "grant { permission }" means grant the permission to all code no matter where it came from. In other words, when there is no codebase specified, the code could be loaded from the network or the file system.
The second directive (if it worked) would only apply to the local file system. It would be specifying all files (recursively) on the local file system. I'm not sure that "file:///" is a valid URL by itself. I know that
```
file:///tmp/-
```
works.


q:
When should one do the following?

class Foo : Control
{
    protected override void OnClick(EventArgs e)
    {
        // new code here
    }
}

As opposed to this?

class Foo : Control
{
    public Foo()
    {
        this.Click += new EventHandler(Clicked);
    }

    private void Clicked(object sender, EventArgs e)
    {
        // code
    }
}

[A]
Overriding rather than attaching a delegate will result in more efficient code, so it is generally recommended that you always do this where possible. For more information see
this MSDN article
. Here is a pertinent quote:
The protected OnEventName method also
  allows derived classes to override the
  event without attaching a delegate to
  it. A derived class must always call
  the OnEventName method of the base
  class to ensure that registered
  delegates receive the event.


q:
I'm not sure if the term's actually "Array Addition".

I'm trying to understand what does the following line do:

int var[2 + 1] = {2, 1};

How is that different from int var[3]?

I've been using Java for several years, so I'd appreciate if explained using Java-friendly words.

Edit: Thousands of thanks to everyone who helped me out, Occam's Razor applies here.

[A]
How is that different from
```
int var[3]
```
?
In no way that I can see.


q:
I know we cannot do this at class level but at method level we can always do this.

var myList=new List<string> // or something else like this

This question came to my mind since wherever we declare variable like this. We always provide the type information at the RHS of the expression.  So compiler doesn't need to do type guessing. (correct me if i am wrong).

so question remains WHY NOT at class level while its allowed at method level

[A]
The compiler guys just didn't implement the support.
It's entirely compiler magic, and the compiler doesn't actually put something into IL that says "figure out the type at runtime", it knows the type and builds it in, so it could've done that for members as well.
It just doesn't.
I'm pretty sure that if you asked an actual compiler guy on the C# compiler team, you'd get something official, but there's no magic happening here and it should be possible to do the same for members fields.


q: I want to create a script that parses or makes sense of apache's error log to see what the most recent error was. I was wondering if anyone out there has something that does this or has any ideas where to start?

[A]
There are a few things to consider first:
Firstly, your PHP user may not have access to Apache's log files.
Secondly, PHP and Apache aren't going to tell you where said log file is,
Lastly, Apache log files can get quite large.
However, if none of these apply, you can use the normal file reading commands to do it.
The easiest way to get the last error is
```
```
$contents = @file('/path/to/error.log', FILE_SKIP_EMPTY_LINES);
if (is_array($contents)) {
    echo end($contents);
}
unset($contents);
```
```
There's probably a better way of doing this that doesn't oink up memory, but I'll leave that as an exercise for the reader.
One last comment:  PHP also has an ini setting to redirect PHP errors to a log file:
```
error_log = /path/to/error.log
```
You can set this in httpd.conf or in an .htaccess file (if you have access to one) using the php_flag notation:
```
```
php_flag error_log /web/mysite/logs/error.log
```
```


q:
I have a database in the following format:

 ID    TYPE   SUBTYPE    COUNT   MONTH
 1      A      Z          1       7/1/2008
 1      A      Z          3       7/1/2008
 2      B      C          2       7/2/2008
 1      A      Z          3       7/2/2008

Can I use SQL to convert it into this:

ID    A_Z   B_C   MONTH
1     4     0     7/1/2008
2     0     2     7/2/2008
1     0     3     7/2/2008

So, the TYPE, SUBTYPE are concatenated into new columns and COUNT is summed where the ID and MONTH match.

Any tips would be appreciated. Is this possible in SQL or should I program it manually?

The database is SQL Server 2005.

Assume there are 100s of TYPES and SUBTYPES so and 'A' and 'Z' shouldn't be hard coded but generated dynamically.

[A]
```
```
select id,
sum(case when type = 'A' and subtype = 'Z' then [count] else 0 end) as A_Z,
sum(case when type = 'B' and subtype = 'C' then [count] else 0 end) as B_C,
month
from tbl_why_would_u_do_this
group by id, month
```
```
You change requirements more than our marketing team!  If you want it to be dynamic you'll need to fall back on a sproc.


q:
We're looking into developing a product that would use Amazon's cloud tools (EC2, SQS, etc), and I'm curious what tips/gotchas/pointers people that have used these technologies have.

One tip/whatever per post, please.

[A]
An important concept to grasp: the file system your EC2 instance lives on while it's running
is not persistent.
There are tools/services available that let you mount file systems backed by S3 storage, or you can upload to S3 or other storage service from the instance, but when an instance closes the associated file system is no more.
As for tools, I've found Amazon's tools to be great, but you should probably be comfortable with the command line if you're taking this route.


q:
Let's say I've got a website that works better if a client has installed and logged into a desktop application.  I'd like to be able to do 2 things:

Alter the website if they haven't installed the app (to make it easy for them to find a link to the installer)

If they've installed the app on a couple of machines, determine which machine they are browsing from

I'd like something that works on Windows and OSX, on any of the major browsers.  Linux is a bonus.

A few thoughts:

Websites can detect if you've got Flash installed.  How does that work and could it be used for both of my goals?

Could I just let the client serve HTTP on localhost and do some javascript requests to fetch a local ID?  I know google desktop search did something like this at one point.  Is this a standard practice?

Thanks!

[A]
You can have a browser plugin (activex for IE or Netscape plugin for the rest of the browsers) that can communicate with the application. When the webpage is loaded, it can try to instantiate the plugin and if it succeeded, it can use it as a proxy to the application. If it fails, then either the app is not installed or the plugin was explictly disabled by the user. Either way, your website should degrade its functionality accordingly.
Update
: Forgot to answer your questions:
Flash does it exactly this way. Flash is a browser plugin that is created by the web pages.
You can have a machine ID generated at the application/plugin install time and your plugin can pass that machine ID to the webpage when it is created.
On the topic of using local webserver
:
I would stay away from having a local webserver, mainly because of security considerations. It takes quite a lot of work to make sure your local webserver is locked down sufficiently and there are no XSS vulnerabilities that other malicious websites can exploit to make it do stuff on their behalf.
Plus, having a webserver means that either it has to run as a system-wide process, or if it runs as the user, you can have the website interact with only one user's instance of the application, even though multiple users can be logged on and running it at the same time.
Google Desktop Search suffered from both the XSS security vulnerability (though they fixed it) and the limitation of only one user being able to use it on a machine (I don't know if they fixed this one yet, though chances are they did).


q: Can I programatically set the position of a WPF ListBox's scrollbar?  By default, I want it to go in the center.

[A]
I don't think ListBoxes have that, but ListViews have the
EnsureVisible
method that moves the scrollbar to the place needed in order to make sure an item is shown.


q:
I created a class derived from System.Configuration.Install for my installer.

But the code in Uninstall() is being called when I try to update the application.

How can I detect that the user is trying to update instead of uninstall?

Maybe this post explains it better than me:

My problem boils down to: when the
  user performs an update (i.e. double
  clicks on MyAppVer2.msi when they
  already have MyAppVer1.msi installed)
  the Uninstall method inside my
  Installer is called first, but I have
  no apparent property to check from
  inside this method to detect that an
  update is being performed so that I
  can branch my code appropriately.

[A]
Blind guess here, but I'd start out by checking the
Installer.Context
property for a
parameter
. If that's no help, there may be something in the savedState parameter passed to
Uninstall
.
Last chance would be to
prompt the user
, and set the child installers as appropiate.


q:
When I call Response.Redirect(someUrl) I get the following HttpException:

Cannot redirect after HTTP headers have been sent.

Why do I get this? And how can I fix this issue?

[A]
A Redirect can only happen if the first line in an HTTP message is "
```
HTTP/1.x 3xx Redirect Reason
```
".
If you already called
```
Response.Write()
```
or set some headers, it'll be too late for a redirect. You can try calling
```
Response.Headers.Clear()
```
before the Redirect to see if that helps.


q:
We just did a move from storing all files locally to a network drive. Problem is that is where my VS projects are also stored now. (No versioning system yet, working on that.) I know I heard of problems with doing this in the past, but never heard of a work-around. Is there a work around?

So my VS is installed locally. The files are on a network drive. How can I get this to work?

EDIT: I know what SHOULD be done, but is there a band-aid I can put on right now to fix this and maintain the network drive?

EDIT 2: I am sure I am not understanding something, but Bob King has the right idea. I'll work with the lead web developer when he gets back into the office to figure out a temporary solution until we get some sort of version control setup. Thanks for the ideas.

[A]
I would not recommend doing that if you have (or even if you don't have) multiple people who are working on the projects. You're just asking for trouble.
If you're the only one working on it, on the other hand, you'll avoid much of the trouble. Performance is going to out the window, though. As far as how to get it to work, you just open the solution file from VS. You'll likely run into security issues, but can correct that using CASPOL. As I said, though, performance is going to be terrible. Again, not recommended at all.
Do yourself and your team a favor and install SVN or some other form of source control and put the code in there ASAP.
EDIT: I'll partially retract my comments. Bob King explains below the reason they run VS projects from a network drive and it makes sense. I would say unless you're doing it for a specific reason like Bob, stay away from it. Otherwise, get your ducks in a row before setting up such a development environment.


q:
Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:

// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()

In Python, I have seen the above but I have also seen underscores being used:

# python example
this_is_my_variable = 'a'
def this_is_my_function():

Is there a more preferable, definitive coding style for Python?

[A]
See Python
PEP 8: Function and Variable Names
:
Function names should be
lowercase, with words separated by underscores
as necessary to improve readability.
Variable names follow the same convention as function names.
mixedCase
is allowed only in contexts where that's already the prevailing style (e.g.
threading.py
), to retain backwards compatibility.


q: I have a complex query with group by and order by clause and I need a sorted row number (1...2...(n-1)...n) returned with every row. Using a ROWNUM (value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation) gives me a non-sorted list (4...567...123...45...). I cannot use application for counting and assigning numbers to each row.

[A]
Is there a reason that you can't just do
```
```
SELECT rownum, a.*
  FROM (<<your complex query including GROUP BY and ORDER BY>>) a
```
```


q: Do objects added to the SqlException.Data collection need to be [Serializable]?

[A] Well, strictly speaking, no... you can add any type to an Exception's Data dictionary... but why would you ask? What boundary do you think they are going to be serialized across?


q:
An application currently in development has the requirements for using MS Word to perform spell check on certain textareas within the application.

I currently have Office 2007 (which is the Office 12 com objects).

My question is, if I add in the Office 12 objects what will happen on boxes which have Office 2003?  This is in regards to both other development boxes as well as the end users.

Am I correct in believing that the end result will be that the spell capabilities will not be available for those users?  And if I used an Office 11 object would that mean that the users would be unable to perform the spellchecks if they have Office 07 installed?

[A]
I am guessing here, but if it is as you can't use the 2007 PIA (Primary Interop Assembly) with a 2003 installation, you could try accessing the PIA via reflection as I would guess the calls you want won't change between the two, and then it won't matter - you'll use whichever is installed.  If you are installing the PIA as well, you can then either get the user to tell you which they have, or be a little more clever and just try 2007 and if it fails, try 2003.
Like I said, I'm guessing here but it might be worth a try.
EDIT: I found this
link
about Office PIA's. This refers to Excel but actually covers Office in general. I don't envy the task you have. Looks like you'll need to detect the PIA (which may or may not be installed) and act accordingly. Sounds like a job for reflection to me.


q: Elementree has become the accepted standard for interacting with xml.  What is the prevalent web service/SOAP library in use today?

[A]
I'm not sure about an accepted standard, but I've found
SOAPpy
to be fairly straight-forward and useful library for handling SOAP-based web services.
SOAPy is a SOAP/XML Schema Library for Python. Given either a WSDL or SDL document, SOAPy discovers the published API for a web service and exposes it to Python applications as transparently as possible.
IBM provide a
good walk-through and example
on their site for getting started with SOAPpy.
SOAPpy's no longer under active development, but is instead being folded into Zolera SOAP Infrastructure (ZSI) at the
Python Web Services Project
. This project however has alos
not seen much activity
since November last year.


q:
Often times when mixing jQuery with asp.net I need to use asp .net angle bracket percent, <% %>, syntax within a  jQuery selector.

If I would like to separate the JavaScript from markup into different files is there still a way to evaluate my JavaScript file so the angle bracket percents are interpolated before reaching the client browser?

[A]
No, you'll need to refactor your JavaScript to accept that information as parameters.
So, instead of
```
```
jQuery('#<%=MainPanel.ClientId%>').hide('slow');
```
```
do something like this:
```
```
function hidePanel(panelId) {
        jQuery('#' + panelId).hide('slow');
}
```
```
which you can call from your page with
```
```
hidePanel('<%=MainPanel.ClientId%>');
```
```


q: Short of cutting and pasting, is there a way to sort the methods in my classes in Visual Studio 2008? I like orderly code.

[A]
You may find or be able to make a macro to do this, but there is no built in functionality of VS to sort your methods. Some third party productivity tools like
Resharper
and
CodeRush
provide some functionality to reorder your code.


q:
Our team would like to move from the Visual SourceSafe (VSS) to the Team Foundation Server (TFS). I know that the TFS is much more than just a version control system, but for the first time I would like to use it this way.

Currently our projects are organized within the single solution that consists of the shared part (common library) and many customer projects.

Is there some kind of migration guide that would describe such a challenge? Or TFS enforces its own usage scenarios (versioning of projects, releases, etc.)?

[A]
TFS and VSS are radically different beasts.
That said, the major problems with moving from VSS to TFS is generally in the developer's mind.
Check out the following blogs:
TFS from a VSS User's perspective:
http://blogs.msdn.com/robcaron/archive/2006/10/29/901115.aspx
And of course, the original
http://sstjean.blogspot.com/2006/10/document-from-vss-to-tfs-introduction.html


q:
You're stepping through C/C++ code and have just called a Win32 API that has failed (typically by returning some unhelpful generic error code, like 0).  Your code doesn't make a subsequent GetLastError() call whose return value you could inspect for further error information.

How can you get the error value without recompiling and reproducing the failure?  Entering "GetLastError()" in the Watch window doesn't work ("syntax error").

[A]
```
ERR,hr
```
in a watch window usually does the trick


q:
Does anybody know a way with JavaScript or CSS to basically grey out a certain part of a form/div in HTML?

I have a 'User Profile' form where I want to disable part of it for a 'Non-Premium' member, but want the user to see what is behind the form and place a 'Call to Action' on top of it.

Does anybody know an easy way to do this either via CSS or JavaScript?

Edit: I will make sure that the form doesn't work on server side so CSS or JavaScript will suffice.

[A]
Add this to your HTML:
```
```

```
```
And this to your CSS:
```
```
.darkClass
{
    background-color: white;
    filter:alpha(opacity=50); /* IE */
    opacity: 0.5; /* Safari, Opera */
    -moz-opacity:0.50; /* FireFox */
    z-index: 20;
    height: 100%;
    width: 100%;
    background-repeat:no-repeat;
    background-position:center;
    position:absolute;
    top: 0px;
    left: 0px;
}
```
```
And finally this to turn it off and on with JavaScript:
```
```
function dimOff()
{
    document.getElementById("darkLayer").style.display = "none";
}
function dimOn()
{
    document.getElementById("darkLayer").style.display = "";
}
```
```
Change the dimensions of the darkClass to suite your purposes.


q:
I'm slowly moving all of my LAMP websites from mysql_ functions to PDO functions and I've hit my first brick wall.  I don't know how to loop through results with a parameter.  I am fine with the following:

foreach ($database->query("SELECT * FROM widgets") as $results)
{
   echo $results["widget_name"];
}

However if I want to do something like this:

foreach ($database->query("SELECT * FROM widgets WHERE something='something else'") as $results)
{
   echo $results["widget_name"];
}

Obviously the 'something else' will be dynamic.

[A]
According to the
PHP documentation
is says you should be able to to do the following:
```
```
$sql = "SELECT * FROM widgets WHERE something='something else'";
foreach ($database->query($sql) as $row) {
   echo $row["widget_name"];
}
```
```


q:
How do I change the system-wide short date format in Ubuntu?  For example, Thunderbird is showing dates in the DD/MM/YY format, and I would like to change it to MM/DD/YY or YYYY-MM-DD.

The best information I can find so far is in this thread:

http://ubuntuforums.org/showthread.php?t=193916

Edit: I want to change the system-wide date format, so that all my applications use this new date format.

[A]
Thunderbird uses the system's date format, and that format depends on the system's locale settings. You have two options:
modify the system locale, the instructions are in the forum thread you linked above, or
set
```
LC_TIME
```
to a locale that uses the format you want. The
article
linked by
Craig H
suggests
```
en_DK
```
.


q: What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?

[A]
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
```
```
public class Foo
{
     public bool DoSomething() { return false; }
}

public class Bar : Foo
{
     public new bool DoSomething() { return true; }
}

public class Test
{
    public static void Main ()
    {
        Foo test = new Bar ();
        Console.WriteLine (test.DoSomething ());
    }
}
```
```
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you
SHOULD ALWAYS OVERRIDE
. The only place where you need to use "new" is when the method is not related in any way to the base class version.


q:
I've done some Python but have just now starting to use Ruby

I could use a good explanation of the difference between "self" in these two languages.

Obvious on first glance:

Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.

Python methods receive self as an explicit argument, whereas Ruby does not.

Ruby sometimes has methods explicitly defined as part of self using dot notation.

Initial Googling reveals

http://rubylearning.com/satishtalim/ruby_self.html

http://www.ibiblio.org/g2swap/byteofpython/read/self.html

[A]
Well, I don't know much about Ruby. But the obvious point about Python's "self" is that it's not a "keyword" ...it's just the name of an argument that's sent to your method.
You can use any name you like for this argument. "Self" is just a convention.
For example :
```
```
class X :
    def __init__(a,val) :
        a.x = val
    def p(b) :
        print b.x

x = X(6)
x.p()
```
```
Prints the number 6 on the terminal. In the constructor the self object is actually called a. But in the p() method, it's called b.
Update : In October 2008, Guido pointed out that having an explicit self was also necessary to allow Python decorators to be general enough to work on pure functions, methods or classmethods :
http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html


q: iMacros is a very nice tool which allows to authomatically fill HTML forms and extract content, includes cycles and many other features. The problem is that it is quite tricky to make it extracting content properly. For example, I have failed to extract all London-to-Tokio flight prices for all the dates between 1/10/08 to 1/12/08 to find a cheapest one from expedia. Sometimes it just crashes. Does anyone know any good alternative?

[A]
Bah, I installed it but never really used it: I am happy enough with
Greasemonkey
.
Chickenfoot
can make it more edible...
Searching for URLs, I found also
DéjàClick
and
Selenium IDE
but I don't really know them.
There are lot of other tools for Web automation, most of them professional (read "payware"...).
Alternatively, for just data extraction, I would use cURL or wget and a good HTML parser...


q:
Following the development of Ruby very closely I learned that detailed character encoding is implemented in Ruby 1.9. My question for now is: How may Ruby be used at the moment to talk to a database that stores all data in UTF8?

Background: I am involved in a new project where Ruby/RoR is at least an option. But the project needs to rely on an internationalized character set (it's spread over many countries), preferably UTF8.

So how do you deal with that? Thanks in advance.

[A]
Although I haven't tested it, the character-encodings library (currently in alpha) adds methods to the String class to handle UTF-8 and others. Its page on RubyForge is
here
. It is designed for Ruby 1.8.
It is my experience, however, that, using Ruby 1.8, if you store data in your database as UTF-8, Ruby will not get in the way as long as your character encoding in the HTTP header is UTF-8. It may not be able to operate on the strings, but it won't break anything. Example:
```
```
file.txt:
¡Hola! ¿Como estás? Leí el artículo. ¡Fue muy excellente!
```
```
Pardon my poor Spanish; it was the best example of Unicode I could come up with.
```
```
in irb:
str = File.read("file.txt")
   => "\302\241Hola! \302\277Como est\303\241s? Le\303\255 el art\303\255culo. \302\241Fue muy excellente!\n"
str += "Foo is equal to bar."
   => "\302\241Hola! \302\277Como est\303\241s? Le\303\255 el art\303\255culo. \302\241Fue muy excellente!\nFoo is equal to bar."
str = "    " + str + "    "
   => "    \302\241Hola! \302\277Como est\303\241s? Le\303\255 el art\303\255culo. \302\241Fue muy excellente!\nFoo is equal to bar.    "
str.strip
   => "\302\241Hola! \302\277Como est\303\241s? Le\303\255 el art\303\255culo. \302\241Fue muy excellente!\nFoo is equal to bar."
```
```
Basically, it will just treat the UTF-8 as ASCII with odd characters in it. It will not sort lexigraphically if the code points are out of order; however, it will sort by code point. Example:
```
```
"\302" <=> "\301"
   => -1
```
```
How much are you planning on operating on the data in the Rails app, anyway? Most sorting etc. is usually done by your database engine.


q: Is there a macro that does it? Which DTE objects to use?

[A]
I don't know what DTE functions to use, but you could very simply record a macro that could pretty much do it:
Go to the top of the file
ctrl - shift - R (start recording)
ctrl - I (incremental search)
{ (search for the first { character).
F9 (set breakpoint)
ctrl - ] (go to matching } character)
ctrl - shift - R (stop recording)
Now just run this over and over (ctrl - shift P repeatedly) until you reach the end of the file.
If you have namespaces, then change 4. to:
( (search for "(" at the start of the function definition)
esc (stop incremental search)
ctrl - I (incremental search again)
{ (start of function body)
This kind of thing can be infinitely modified to suit your codebase


q:
I have been adding dependency injection to my code because it makes by code much easier to Unit test through mocking.

However I am requiring objects higher up my call chain to have knowledge of objects further down the call chain.

Does this break the Law of Demeter? If so does it matter?

for example: a class A has a dependency on an interface B, The implementation of this interface to use is injected into the constructor of class A. Anyone wanting to use class A must now also have a reference to an implementation of B. And can call its methods directly meaning and has knowledge of its sub components (interface B)

Wikipedia says about the law of Demeter:  "The fundamental notion is that a given object should assume as little as possible about the structure or properties of anything else (including its subcomponents)."

[A]
Does it break the law?
Strictly speaking, I think it does.
Does it matter?
The main danger of breaking the law is that you make your code more brittle.
If you really keep it to just the tests, it seems like that danger is not too bad.
Mitigation
My understanding of the
Law of Demeter
is that it can be followed by having "wrapper methods" which prevent directly calling down into objects.


q:
There are a ton of drivers & famous applications that are not available in 64-bit. Adobe for instance does not provider a 64-bit Flash player plugin for Internet Explorer. And because of that, even though I am running 64-bit Vista, I have to run 32-bit IE. Microsoft Office, Visual Studio also don't ship in 64-bit AFAIK.

Now personally, I haven't had much problems building my applications in 64-bit. I just have to remember a few rules of thumb, e.g. always use SIZE_T instead of UINT32 for string lengths etc.

So my question is, what is preventing people from building for 64-bit?

[A] Just a guess, but I would think a large part of it would be support - If Adobe compiles the 64 bit version, they have to support it.  Even though it may be a simple compile switch, they'd still have to run through a lot of testing, etc, followed by training their support staff to respond correctly, when they do run into issues fixing them either results in a new version of the 32 bit binary or a branch in the code, etc.  So while it seems simple, for a large application it can still end up costing a lot.


q:
How do you change controls' Z-order in MFC at design time - i.e. I can't use SetWindowPos or do this at runtime - I want to see the changed z-order in the designer (even if I have to resort to direct-editing the .rc code).

I have an MFC dialog to which I am adding controls.  If there is overlap between the edges of the controls, I want to bring one to the front of the other.  In Windows Forms or WPF, etc. I can Bring to Front, Send to Back, Bring Forward, Send Back.  I don't find these options in MFC, nor can I tell how it determines what is in front, as a control just added is often behind a control that was there previously.  How can I manipulate the Z-order in MFC?  Even if I have to manipulate the .rc file code directly (i.e. end-run around the designer).

[A]
```
```
GetDlgItem(IDC_MYCONTROL)->SetWindowPos(HWND_TOP,
                                        0, 0, 0, 0,
                                        SWP_NOMOVE | SWP_NOSIZE);
```
```


q: What is the correct way to implement the "find as you type" behavior on a TComboBox descendant component whose style is csOwnerDrawFixed?

[A]
Use a TTimer (let's call it timIncSearch). Set (at design time) the following properties:
Enabled:=False;
Interval:=400; //empirically found - it's the delay used in Windows Explorer
...and in OnTimer you'll wrote your searching engine. Be sure that the first line here will be timIncSearch.Enabled:=False; Also because you use csOwnerDrawFixed perhaps it's better to enforce a repaint of your control.
As an aside, - just guessing because you didn't give us many details - perhaps you must hook OnEnter and OnExit events to custom open and close the DropDown list. (Normaly, this is achieved by setting the AutoDropDown property accordingly)
In your ComboBox.KeyPress you'll write
```
with timIncSearch do
begin
Enabled:=False;
Enabled:=True;
end;
```
...also take care here, perhaps you must have a 'case Key of' construct to handle the #13 separately (or whatever).
Other hints:
depending on your situation, perhaps you must hook (also?) the OnKeyDown (if you want to process special keys like eg. BackSpace, Del, Arrows etc. -
taking
in account that the event repeats itself while the key it's pressed down) and/or OnKeyUp (if you want to do similar processing as above but
without
taking in account the keyboard's key auto-repeat feature).


q:
I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature?

I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both static and non-static methods in the same class?

If this is not possible, is there a good way to implement something like this that can be applied generically to any situation?

EDIT

From the responses I've received, it's clear that there is no way to do this. I'm going with a different naming system to work around this problem.

[A]
You can call static methods from instance methods without having to specify the type name:
```
```
class Foo
{
    static void Bar()
    {
    }

    void Fizz()
    {
        Bar();
    }
}
```
```
... so it makes sense that you wouldn't be allowed to have a static method and an instance method with the same signature.
What are you trying to accomplish? It's hard to suggest a workaround without knowing specifics. I'd just rename one of the methods.


q:
C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.

    private void SetProgressBar(string text, int position, int max)
    {
        try
        {
            int percent = (100 * position) / max; //when max is 0 bug hits
            string txt = text + String.Format(". {0}%", percent);
            SetStatus(txt);
        }
        catch
        {
        }
    }

[A]
```
```
int percent = 0
if (max != 0) percent = (100*position) / max
```
```


q:
If you have a hash (or reference to a hash) in perl with many dimensions and you want to iterate across all values, what's the best way to do it.  In other words, if we have
$f->{$x}{$y}, I want something like

foreach ($x, $y) (deep_keys %{$f})
{
}

instead of

foreach $x (keys %f)
    {
    foreach $y (keys %{$f->{$x})
    {
    }
}

[A]
It's easy enough if all you want to do is operate on values, but if you want to operate on keys, you need specifications of how levels will be recoverable.
a. For instance, you could specify keys as
```
"$level1_key.$level2_key.$level3_key"
```
--or any separator, representing the levels.
b. Or you could have a list of keys.
I recommend the latter.
Level can be understood by
```
@$key_stack
```
and the most local key is
```
$key_stack->[-1]
```
.
The path can be reconstructed by:
```
join( '.', @$key\_stack )
```
Code:
```
```
use constant EMPTY_ARRAY => [];
use strict;
use Scalar::Util qw<reftype>;

sub deep_keys (\%) {
    sub deeper_keys {
        my ( $key_ref, $hash_ref ) = @_;
        return [ $key_ref, $hash_ref ] if reftype( $hash_ref ) ne 'HASH';
        my @results;

        while ( my ( $key, $value ) = each %$hash_ref ) {
            my $k = [ @{ $key_ref || EMPTY_ARRAY }, $key ];
            push @results, deeper_keys( $k, $value );
        }
        return @results;
    }

    return deeper_keys( undef, shift );
}

foreach my $kv_pair ( deep_keys %$f ) {
    my ( $key_stack, $value ) = @_;
    ...
}
```
```
This has been tested in Perl 5.10.


q:
I am trying to get the value of some ListViewSubItems, but I have no idea what values it uses for its keys.  I have some simple code:

    protected override void OnItemDrag(ItemDragEventArgs e)
    {
        base.OnItemDrag(e);
        ListViewItem item = e.Item as ListViewItem;
        string val = item.SubItems[???].ToString();
    }

The ??? part is where I am having a problem.  I cannot figure out what the keys are.  I have tried the column names of the ListView with no luck.  I would like to use this method instead of using numeric indices.

[A]
Subitems are only ordered by column index unluckily. So you'd have to access them like:
```
```
protected override void OnItemDrag(ItemDragEventArgs e)
{
    base.OnItemDrag(e);
    ListViewItem item = e.Item as ListViewItem;
    string val = item.SubItems[0].ToString();
}
```
```


q:
I'm trying:

import commands
print commands.getoutput("ps -u 0")

But it doesn't work on os x.
os instead of commands gives the same output:
USER   PID %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND

nothing more

[A]
It works if you use os instead of commands:
```
```
import os
print os.system("ps -u 0")
```
```


q:
Just that, if you embed an icon:

[Embed(source='icons/checkmark.png')]
private static var CheckMark:Class;

You end up with a dynamic class. You can pretty easily assign the icon to a button at runtime by calling the setStyle method:

var btn:Button = new Button();
btn.setStyle("icon", CheckMark);

But what if you wanted to alter the icon at runtime, like changing it's alpha value or even redrawing pixels, before assigning it to the button?

So far I can't find a satisfactory answer...

[A]
This is the only answer I could find that seemed close:
Dynamic Icons
(example with View Source)
His solution involves a custom "DynamicIcon" class which is used in the button's icon setting, and a custom Button class which adds one method to the Button class to draw dynamic icons.
The end result is that you are able to send BitmapData to the DynamicIcon class, which will show up in the button. So, embed your image, instantiate your asset class, get the bitmapasset and modify it however you need to and send the bitmapData to the icon.
It's an interesting problem and it seems like there should be an easier solution, but this works without a lot of hassle.


q:
I am using sybase database to query the daily transaction report. I had subquery within my script.

Here as it goes:

SELECT orders.accountid ,items.x,etc
(SELECT charges.mistotal FROM charges where items.id = charges.id)
FROM items,orders
WHERE date = '2008-10-02'

Here I am getting the error message as:

Subquery cannot return more than one values

My values are 7.50, 25.00

I want to return the 25.00, but when I use

(SELECT TOP 1 charges.mistotal FROM charges where items.id = charges.id)

My result is 7.50 but I want to return 25.00

Does anyone has any better suggestion?

[A]
Under what criteria you choose to select the 25.00 instead of the 7.5?
If its related to the maximum value, you can try using the
MAX()
function on that field.
If its related to the chronologically last row added, try using the
MAX()
on the datetime field, if you have details on the hours and minutes it was added.


q:
I've been playing with the .NET built in localization features and they seem to all rely on putting data in resx files.

But most systems can't rely on this because they are database driven. So how do you solve this issue? Is there a built in .NET way, or do you create a translations table in SQL and do it all manually?  And if you have to do this on the majority of your sites, is there any reason to even use the resx way of localization?

An example of this is I have an FAQ list on my site, I keep this list in the database so I can easily add/remove more, but by putting it in the database, I have no good way have translating this information into multiple languages.

[A]
In my opinion, localizing dynamic content (e.g., your FAQ) should be done by you in your database. Depending on how your questions are stored, I would probably create a "locale" column and use that when selecting the FAQ questions from the database. I'm not sure if this would scale  very well when you started localizing lots of tables.
For static content (e.g, form field labels, static text, icons, etc) you should probably be just fine using file-based resources. If you really wanted to, however, it looks like it wouldn't be super hard to create a custom resource provider implementation that could handle this.
Here's some related links:
http://channel9.msdn.com/forums/Coffeehouse/250892-Localizing-with-a-database-or-resx-files/
http://weblogs.asp.net/scottgu/archive/2006/05/30/ASP.NET-2.0-Localization-_2800_Video_2C00_-Whitepaper_2C00_-and-Database-Provider-Support_2900_.aspx
http://www.arcencus.nl/Blogs/tabid/105/EntryID/20/Default.aspx
http://msdn.microsoft.com/en-us/library/aa905797.aspx
http://www.codeproject.com/KB/aspnet/customsqlserverprovider.aspx


q:
In svn, I have a branch which was created, say at revision 22334. Commits were then made on the branch.

How do I get a list of all files that were changed on the branch compared to what's on the trunk? I do not want to see files that were changed on the trunk between when the branch was created and "now".

[A]
This will do it I think:
```
```
svn diff -r 22334:HEAD --summarize <url of the branch>
```
```


q:
I have a rather big number of source files that I need parse and extract all string literals and put them in a file as play old java constant.

For exemple:

Label l = new Label("Cat");

Would become:

Label l = new Label(Constants.CAT);

And in Constants.java I would have:

public final static String CAT = "Cat";

I do not want the strings to be externalized in a property text file.

One reason is for consistency and code readability.

The other is that our client code uses GWT, which does not support Java property text file mechanism.

I could write some sort of parser (using ant replace task maybe)?

But I wondered if an IDE already does this sort of thing automatically.

[A]
Eclipse does do this automatically.  Right-click the file, choose "Source", then "Externalize strings"
This doesn't do exactly what you requested (having the strings in a Constants.java file as Strings) but the method used is very powerful indeed.  It moves them into a properties file which can be loaded dynamically depending on your locale.  Having them in a separate Java source file as you suggest means you'll either have ALL languages in your application at once or you'll ship different applications depending on locale.
We use it for our applications where even the basic stuff has to ship in English and Japanese - our more complicated applications ship with 12 languages - we're not a small software development company by any means :-).
If you
do
want them in a Java file, despite the shortcomings already mentioned, it's a lot easier to write a program to morph the properties file into a Java source file than it is to try and extract the strings from free-form Java source.
All you then need to do is modify the Accessor class to use the in-built strings (in the separate class) rather than loading them at run time.


q:
My group is a Perl shop in an organization that is very heterogenous.  Although we support the odd Java, PHP, or Python installation, we're using Perl for nearly all of our web applications and systems/data marshalling tasks.  All of our boxes are Linux, although we interface with IIS systems as well.

We're coming under some pressure from management to move to Java for at least some of our work.  I'd like to use the right tool for the right task, but for our work, and due to our collective experience, Perl seems like the right tool for everything.

My initial thought is to use Java for applications that are open to the organization at large, since there is more Java mindshare out there than Perl.

Does anyone have similar experience?  If I'm given the choice, what kinds of tasks should we start with applying Java?  What kinds of tasks should we insist on sticking with Perl?  Does it make any difference?  Why or why not?

[A]
If your team is going to be supporting the applications, then stick with what you know.
If another team is supporting your apps then you may need to consider Java as it definetly has a greater penetration in today's corporate world.
Management are told that Java is the only way, or "real enterprises use Java", and therefore they think they have to use Java.  I know where I work they think that Java is the only language out there, and things like C# are just for 'tactical' projects and not 'strategic' - whatever that means.
You should use the best tool for the job.


q: I'm using subversion (TortoiseSVN) and I want to remove the .svn folders from my project for deployment, is there an automated way of doing this using subversion or do I have to create a custom script for this?

[A]
Use
```
```
svn export <url-to-repo> <dest-path>
```
```
It gets just the source, nothing else. Look in
svn export
(in
Version Control with Subversion
) for more information.


q:
I need to get the "td" element of a table.  I do not have the ability to add a mouseover or onclick event to the "td" element, so I need to add them with JQUERY.

I need JQUERY to add the mouseover and onclick event to the all "td" elements in the table.

Thats what I need, maybe someone can help me out?

[A]
```
```
$(function() {
    $("table#mytable td").mouseover(function() {
        //The onmouseover code
    }).click(function() {
        //The onclick code
    });
});
```
```


q:
I thought people would be working on little code projects together, but I don't see them, so here's an easy one:

Code that validates a valid US Zip Code. I know there are ZIP code databases out there, but there are still uses, like web pages, quick validation, and also the fact that zip codes keep getting issued, so you might want to use weak validation.

I wrote a little bit about zip codes in a side project on my wiki/blog:

https://benc.fogbugz.com/default.asp?W24

There is also a new, weird type of zip code.

https://benc.fogbugz.com/default.asp?W42

I can do the javascript code, but it would be interesting to see how many languages we can get here.

[A]
Javascript Regex Literal
:
US Zip Codes:
```
/(^\d{5}$)|(^\d{5}-\d{4}$)/
```
```
```
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test("90210");
```
```
Some countries use
Postal Codes
, which would fail this pattern.


q:
I have a Selenium test case that enters dates into a date selector made up of three pulldowns (year, month, and day).

select validity_Y label=2008
select validity_M label=08
select validity_D label=08

This part gets repeated a lot throughout the test case. I'd like to reduce it by defining my custom action "selectValidity", so that I can have less redundancy, something like

selectValidity 2008,08,08

What is the best (easiest, cleanest) way to add macros or subroutines to a test case?

[A]
You aren't allowed to make WinForms calls from other threads.  Look at BeginInvoke in the form -- you can call a delegate to show the form from the UI thread.
Edit: From the comments (do not set CheckForIllegalCrossThreadCalls to false).
More Info
Almost every GUI library is designed to only allow calls that change the GUI to be made in a single thread designated for that purpose (called the UI thread). If you are in another thread, you are required to arrange for the call to change the GUI to be made in the UI thread. In .NET, the way to do that is to call Invoke (synchronous) or BeginInvoke (asynchronous). The equivalent Java Swing call is invokeLater() -- there are similar functions in almost every GUI library.


q:
Is there a way to run some custom Javascript whenever a client-side ASP.NET validator (RequiredFieldValidator, RangeValidator, etc) is triggered?

Basically, I have a complicated layout that requires I run a custom script whenever a DOM element is shown or hidden. I'm looking for a way to automatically run this script when a validator is displayed. (I'm using validators with Display="dynamic")

[A]
The best solution I've identified for my specific situation is this:
Create a global JS data structure mapping control IDs to a visibility state.
Register the client IDs of the validators (or anything else, for that matter) in this data structure.
Every 250 milliseconds, loop through the global data structure and compare the cached visiblity state with the element's current state. If the states are different, update the cache and run the custom resize script.
This is ugly in lots of ways, and it's only a solution for my specific scenario, not the abstract case where we want to piggyback arbitrary code onto the showing/hiding of a validator. I'd love a better suggestion!


q:
I personally like the exclusive or, ^, operator when it makes sense in the context of boolean checks because of its conciseness.  I much prefer to write

if (boolean1 ^ boolean2)
{
  //do it
}

than

if((boolean1 && !boolean2) || (boolean2 && !boolean1))
{
  //do it
}

but I often get confused looks from other experienced Java developers (not just the newbies), and sometimes comments about how it should only be used for bitwise operations.

I'm curious as to the best practices regarding the usage of the ^ operator.

[A]
You can simply use
```
!=
```
instead.


q:
I would like to create a Crystal Reports report using pre-existing LINQ classes that live in a different project than where the report lives.  I can't find a way to do this.  I'm using VS2008.

Whenever I expand the "Project Data" tree, I see only classes in my current project.  The "History" tree shows me the last 5 class in the OTHER project, but I need more than those 5.  I found the "Make New Connection" option under "ADO.NET", but it looks like it's looking for XML sources and DLLs.

[A]
How about a private helper method in the test fixture
```
```
private Dave GetDave_With_Wamu_And_Woodforest_AccountsHookedUp()
```
```


q:
For my server app, I need to check if an ip address is in our blacklist.

What is the most efficient way of comparing ip addresses? Would converting the IP address to integer and comparing them efficient?

[A]
Depends what language you're using, but an IP address is usually stored as a 32-bit unsigned integer, at least at the network layer, making comparisons quite fast. Even if it's not, unless you're designing a high performance packet switching application it's not likely to be a performance bottleneck. Avoid premature optimization - design your program for testability and scalability and if you have performance problems then you can use a profiler to see where the bottlenecks are.
Edit: to clarify, IPv4 addresses are stored as 32-bit integers, plus a netmask (which is not necessary for IP address comparisons). If you're using the newer and currently more rare IPv6, then the addresses will be 128 bits long.


q:
Does the compiler optimize out any multiplications by 1? That is, consider:

int a = 1;
int b = 5 * a;

Will the expression 5 * a be optimized into just 5? If not, will it if a is defined as:

const int a = 1;

[A]
It will pre-calculate any constant expressions when it compiles, including string concatenation. Without the
```
const
```
it will be left alone.
Your first example compiles to this IL:
```
```
.maxstack 2
.locals init ([0] int32, [1] int32)

ldc.i4.1   //load 1
stloc.0    //store in 1st local variable
ldc.i4.5   //load 5
ldloc.0    //load 1st variable
mul        // 1 * 5
stloc.1    // store in 2nd local variable
```
```
The second example compiles to this:
```
```
.maxstack 1
.locals init ( [0] int32 )

ldc.i4.5 //load 5
stloc.0  //store in local variable
```
```


q:
I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs.
A link to read about it would be great.
A trivial explained example would be even better.
Thank you.

[A]
Where have you seen the phrase used?
"Binding" in Python generally refers to the process by which a variable name ends up pointing to a specific object, whether by assignment or parameter passing or some other means, e.g.:
```
```
a = dict(foo="bar", zip="zap", zig="zag") # binds a to a newly-created dict object
b = a # binds b to that same dictionary

def crunch(param):
  print param

crunch(a) # binds the parameter "param" in the function crunch to that same dict again
```
```
So I would guess that "lambda binding" refers to the process of binding a lambda function to a variable name, or maybe binding its named parameters to specific objects?  There's a pretty good explanation of binding in the Language Reference, at
http://docs.python.org/ref/naming.html


q:
I'm a Java head mainly, and I want a way to generate a pseudo-random number between 0 and 74. In Java I would use the method:

Random.nextInt(74)

I'm not interested in a discussion about seeds or true randomness, just how you accomplish the same task in Objective-C. I've scoured Google, and there just seems to be lots of different and conflicting bits of information.

[A]
Same as C, you would do
```
```
#include <time.h>
#include <stdlib.h>
...
srand(time(NULL));
int r = rand() % 74;
```
```
(assuming you meant including 0 but excluding 74, which is what your Java example does)
Edit:
Feel free to substitute
```
random()
```
or
```
arc4random()
```
for
```
rand()
```
(which is, as others have pointed out, quite sucky).


q:
We all hear a lot about scaling issues in Rails.

I was just curious what the actual costs in handling a HTTP request is in the Rails framework.  Meaning, what has to happen for each and every request which comes in?  Is there class parsing?  Configuration?  Database Connection establishment?

[A]
That actually depends a lot on which web server you're using, and which configuration you're using, not to mention the application design itself. Configuration and design issues involved include:
Whether you're using fastcgi, old-school cgi, or some other request handling mechanism (affects whether you're going to have to rerun all of the app initialization code per request or not)
Whether you're using memcache (or an alternate caching strategy) or not (affects cost of database requests)
Whether you're using additional load balancing techniques or not
Which session persistence strategy you're using (if needed)
Whether you're using "development" mode or not, which causes code files to be reloaded whenever they're changed (as I recall; maybe it's just per-request) or not
Like most web app frameworks, there are solutions for connection pooling, caching, and process management. There are a whole bunch of ways to manage database access; the usual, default ones are not necessarily the highest performance, but it's not rocket science to adjust that strategy.
Someone who has dug into the internals more deeply can probably speak in more excruciating detail, but most apps use either FastCGI on Apache or an alternate more rails-friendly web server, which means that you only have app setup once per process.


q: What Abstract Datatypes should be added to OpenJDK7 ?

[A]
If you look at these two links you will see what some people feel is missing:
http://commons.apache.org/collections/
http://code.google.com/p/google-collections/
My favourite missing one is Bag... it is easy to implement, but annoying to have to implement it.
Mulimaps would also nice to have in the standard packages.


q:
I am pretty sure I have seen this before, but I haven't found out / remembered how to do it.  I want to have a line of code that when executed from the Delphi debugger I want the debugger to pop-up like there was a break point on that line.

Something like:

FooBar := Foo(Bar);
SimulateBreakPoint; // Cause break point to occur in Delphi IDE if attached
WriteLn('Value: ' + FooBar);

Hopefully that makes sense. I know I could use an exception, but that would be a lot more overhead then I want.  It is for some demonstration code.

Thanks in advance!

[A]
To trigger the debugger from code (supposedly, I don't have a copy of delphi handy to try):
```
```
asm int 3 end;
```
```
See this page:
http://17slon.com/blogs/gabr/2008/03/debugging-with-lazy-breakpoints.html


q: How can I check if a given number is even or odd in C?

[A]
I'd say just divide it by 2 and if there is a 0 remainder, it's even, otherwise it's odd.
Using the modulus (%) makes this easy.
eg.
4 % 2 = 0 therefore 4 is even
5 % 2 = 1 therefore 5 is odd


q:
I have a function that takes a struct, and I'm trying to store its variables in array:

int detect_prm(Param prm) {
  int prm_arr[] = {prm.field1, prm.field2, prm.field3};

  return 0;
}

But with gcc -Wall -ansi -pedantic-errors -Werror I get the following error:

initializer element is not computable at load time

It looks fine to me, what's wrong?

[A]
This is illegal in C. Initializer lists must be constant compile time expressions. Do the following instead:
```
```
int prm_arr[3];

prm_arr[0] = prm.field1;
prm_arr[1] = prm.field2;
prm_arr[2] = prm.field3;
```
```


q:
If I have two variables:

Object obj;
String methodName = "getName";

Without knowing the class of obj, how can I call the method identified by methodName on it?

The method being called has no parameters, and a String return value. It's a getter for a Java bean.

[A]
Use
method invocation
from reflection:
```
```
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", parameterTypes);
method.invoke(objectToInvokeOn, params);
```
```
Where:
```
"class name"
```
is the name of the class
```
objectToInvokeOn
```
is of type Object and is the object you want to invoke the method on
```
"method name"
```
is the name of the method you want to call
```
parameterTypes
```
is of type
```
Class[]
```
and declares the parameters the method takes
```
params
```
is of type
```
Object[]
```
and declares the parameters to be passed to the method


q:
Basically I have the following class:

class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};

The methods stateA() and stateB() should be able return pointers to stateA() and stateB().
How to typedef the StateMethod?

[A]
My philosophy is don't use raw member function pointers. I don't even really know how to do what you want using raw pointer typedef's the syntax is so horrible. I like using boost::function.
This is
almost
certainly wrong:
```
```
class X
{
  public:
    typedef const boost::function0<Method> Method;

    // some kind of mutually recursive state machine
    Method stateA()
    { return boost::bind(&X::stateB, this); }
    Method stateB()
    { return boost::bind(&X::stateA, this); }
};
```
```
This problem is definitely a lot harder than first meets the eye