Question:
I am working in Visual Studio 2008 on an ASP.NET application, which has been deployed to a test server.  I would like to make a build without debug information to place in production, but the configuration manager only shows "Debug" in the configuration dropdown for my project.

My other Visual Studio projects show "Debug", "Release", "New...", and "Edit...".

Why do I not see a release option, or the new and edit commands?

Answer:
The Configuration Manager for the Solution allows you to delete either (or both) of these default build configurations (through the Edit... option you mention above). I would bet that someone deleted the Release configuration.
You can get it back by recreating it, or copy the appropriate lines from a solution you make from scratch real quick. A file diff shows the following:
Default solution file:
```
```
GlobalSection(SolutionConfigurationPlatforms) = preSolution
    Debug|Any CPU = Debug|Any CPU
    Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.ActiveCfg = Release|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
```
```
Solution after I manually deleted the Release configuration:
```
```
GlobalSection(SolutionConfigurationPlatforms) = preSolution
    Debug|Any CPU = Debug|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
    {EDD50911-B94E-49A4-A08B-A2E91228A04B}.Debug|Any CPU.Build.0 = Debug|Any CPU
EndGlobalSection
```
```


Question:
Hey I have a windows server running python CGI scripts and I'm having a little trouble with smtplib. The server is running python 2.1 (unfortunately and I can not upgrade it). Anyway I have the following code:

session = smtplib.SMTP("smtp-auth.ourhosting.com", 587)
session.login(smtpuser, smtppass)

and it's giving me this error:

exceptions.AttributeError :  SMTP instance has no attribute 'login' :  <traceback object at 006BB1D0>

I'm assuming this is because the login() method was added after python 2.1. so how do I fix this?

I have to either add the module by uploading the files to the same directory as the cgi script (though I believe smtplib is written in C and needs to be compiled which we can't do on this server)

OR

Do it whatever way is expected by the libsmtp in python 2.1.

Answer: Do it whatever way is expected by the libsmtp in python 2.1


Question:
I'm still learning Grails and seem to have hit a stumbling block.

Here are the 2 domain classes:

class Photo {
    byte[] file

    static belongsTo = Profile
}

class Profile {
    String fullName
    Set photos

    static hasMany = [photos:Photo]
}

The relevant controller snippet:

class PhotoController {

    def viewImage = {

      def photo = Photo.get( params.id )
      byte[] image = photo.file
      response.outputStream << image

    }
}

Finally the GSP snippet:

<img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" />

Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that
profileInstance.photos.get(1).id is not correct.

Answer:
As it is a Set, if you want the first element, you will have to go:
```
```
profileInstance.photos.toArray()[0].id
```
```
or
```
```
profileInstance.photos.iterator().next()
```
```


Question:
Say I'm mapping a simple object to a table that contains duplicate records and I want to allow duplicates in my code.  I don't need to update/insert/delete on this table, only display the records.

Is there a way that I can put a fake (generated) ID column in my mapping file to trick NHibernate into thinking the rows are unique?  Creating a composite key won't work because there could be duplicates across all of the columns.

If this isn't possible, what is the best way to get around this issue?

Thanks!

Edit:  Query seemed to be the way to go

Answer:
The NHibernate mapping makes the assumption that you're going to want to save changes, hence the requirement for an ID of some kind.
If you're allowed to modify the table, you could add an identity column (SQL Server naming - your database may differ) to autogenerate unique Ids - existing code should be unaffected.
If you're allowed to add to the database, but not to the table, you could try defining a view that includes a RowNumber synthetic (calculated) column, and using that as the data source to load from. Depending on your database vendor (and the products handling of views and indexes) this
may
face some performance issues.
The other alternative, which I've not tried, would be to map your class to a SQL query instead of a table. IIRC, NHibernate supports having named SQL queries in the mapping file, and you can use those as the "data source" instead of a table or view.


Question:
I've been adding css support for handheld to my website but haven't been able to find a good tool for testing.

I tried using the webdeveloper plugin for Firefox but it doesn't work for me. Maybe that is because all my css is in the html and not a seperate css file.

Are there any other testing tools available aside from going out and buying a handheld device?

Answer:
If you have Visual Studio, there should be device emulators which let you test mobile IE, or they can be found standalone on Microsoft's site.
Here are some for WM 5
.  There is an
OpenWave simulator
available to test that browser.
Blackberry simulators
are available as well, to test the Blackberry browser.  You can (kind of) test iPhone support with Safari, although you can't verify the viewport meta-tag.  There's an
Opera Mini simulator
here.
Also, get your CSS out of your HTML :)


Question: Is there any way to reboot the JVM?  As in don't actually exit, but close and reload all classes, and run main from the top?

Answer:
AFAIK there is no such way.
Notice that if there were a way to do that, it would highly depend on the current loaded code to properly release all held resources in order to provide a graceful restart (think about files, socket/tcp/http/database connections, threads, etc).
Some applications, like Jboss AS, capture Ctrl+C on the console and provide a graceful shutdown, closing all resources, but this is application-specific code and not a JVM feature.


Question:
Is there a substitute in emacs for the vi "gf" command?
meaning try to open the file which is under the cursor right now
if a real file name is in fact there.

Thanks

Answer:
You want the
```
find-file-at-point
```
function (which is also aliased to
```
ffap
```
).  It's not bound to a key by default, but you can use
```
```
M-x ffap
```
```
Or, you can put in your
```
.emacs
```
file:
```
```
(ffap-bindings)
```
```
This will replace many of the normal
```
find-file
```
key bindings (like
```
C-x C-f
```
) with
```
ffap
```
-based versions.  See the commentary in
```
ffap.el
```
for details.


Question:
How can I change the background color of a Tab Control.  I changed the forms color, but the tabs stay the same.

Thanks.

Answer:
Check the Back Style of the Tab Control. If it's Normal. you'll get a gray background (with normal Windows settings). If it's Transparent then it will inherit the background colour of the form.
If you want it to be an entirely different colour, you might have to add a rectangle to the form (make the background non-transparent), maximise it within the tab and then set the colour of the rectangle.
As for the tabs them selves, I don't see a way of setting their colour independently.


Question:
On a Linux box, the common interface names look like eth0, eth1, etc. I know how to find at least one IP address using gethostbyname or similar functions, but I don't know any way to specify which named interface I want the IP address of. I could use ifconfig and parse the output, but shelling out for this information seems... inelegant.

Is there a way to, say, enumerate all the interfaces and their IP addresses (and maybe MAC addresses) into a collection? Or at least something along the lines of gethostbyinterface("eth0")?

Answer:
edit:
I saw you don't like shelling. Then you can look at how ifconfig does its job (it extracts at least some information from /proc).
When you have interface name, you can do this (in your shell):
```
```
ifconfig eth0 | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
```
```
To enumerate interfaces you can use this:
```
```
ifconfig | egrep '^[^ ]' | awk '{print $1}'
```
```
Combined:
```
```
for x in `ifconfig | egrep '^[^ ]' | awk '{print $1}'`; do
  echo -n "${x}"
  echo -n "    "
  ifconfig "${x}" | grep 'inet addr' | sed -e 's/:/ /' | awk '{print $3}'
done
```
```


Question:
Sometimes while developing in Visual Studio IDE, when you use "Find in Files"  dialog to find something, the search fails and you will see the following message in the "Find Results" window.

No files were found to look in. Find stopped progress

Once this message shows up, all the subsequent searches will result in the same message. Nothing fixes the problem including restarting the computer except pressing Ctrl + ScrLk.

What causes Visual Studio to get into this state and is there a setting to permanently prevent it from happening?

Answer:
I don't think there is anything you can do to prevent it.
It seems to occur after I have stopped a build with CTRL+Break...Maybe I am pressing CTRL+Scroll Lock during that time???
I have only had it happen to me 2-3 times, and that was several months apart.
What he is saying is that occasionally when performing a search within Visual Studio you get the mentioned error message. Even though you know there is stuff to find. It is some weird state that Visual Studio gets into. If you press the (CTRL+Scroll Lock) it will 'fix' the issue.


Question:
When I changed the rankdir of my graph from LR to TD, my record nodes also changed their layout direction so they no longer look like a 'record'. I tried applying a separate rankdir to the nodes, but this had no effect.

How does one keep the record nodes with the correct layout?

digraph sample {
  graph [rankdir=TD];
  node [shape=record];

  A [label="ShouldBeTop | ShouldBeBottom"];
  B [label="Top | Bottom"];
  A -> B;
}

Answer:
Taking into account that rankdir effectively replaces the notion of "top" and "bottom" for the given graph, that's not surprising.
I am afraid that there is no easy remedy for this, save hacking the source (and that would not be easy at all). You can surround your labels in "{}" with some kind of mass search-replace solution to get the requested effect:
```
```
digraph sample { graph [rankdir=TD]; node [shape=record];

A [label="{ShouldBeTop | ShouldBeBottom}"];
B [label="{Top | Bottom}"]; A -> B;
}
```
```


Question:
I have a source XML file that is used to create C# files that are then compiled as part of a project.

Currently I have a BeforeBuild target that runs my XML to C# converter.

The problem is that by the time the BeforeBuild step is run the old files appear to have been stored by the build system so the new files are ignored.

How can I get around this? It seems that Transforms would be the way but they are limited in what they can do.

Answer:
Well we have something similar-ish here. We gen a .cs off an xml file using a .tt. Both files are part of a specific csproj. Going properties->BuildEvents on the csproj gives this little snippet in the Pre-build event command line:
```
```
del "$(ProjectDir)MyCsFile.cs"
copy /b /y "$(ProjectDir)\MyXmlFile.xml" "$(TargetDir)"
"$(ProjectDir)tt.bat" "$(ProjectDir)MyTemplateFile.tt"
```
```
No idea if that's of any use to you, I hope it might suffice as a last chance workaround.


Question: I need some basic CMS functionality with rich text editing. On stack overflow there is a regular textarea edit control, with support for Markdown style syntax formatting. That would be beyond my users, so I want something like a rich edit control that you can type into on the web site. I know it is possible, as loads of sites do it, but I don't know where to start.

Answer:
TinyMCE
is probably one of the more popular versions of this sort of thing. You can customize it to fit your needs, in terms of what functionality you want to offer your viewers. a few alternatives (tend to be lighter weight than a full TinyMCE install):
FCKeditor
Xinha


Question:
If I've got an array of values that are basically zerofilled string representations of various numbers and another array of integers, will array_intersect() still match elements of different types?

For example, would this work:

$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);

$intersect = array_intersect($arrayOne, $arrayTwo);

// $intersect would then be = "array(4, 5)"

And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run array_intersect() after?

Answer:
$ cat > test.php
```
```
<?php
$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);

$intersect = array_intersect($arrayOne, $arrayTwo);

print_r($intersect );

?>
```
```
$ php test.php
Array
(
)
$
So no, it will not.   But if you add
```
```
foreach($arrayOne as $key => $value)
{
   $arrayOne[$key] = intval($value);
}
```
```
you will get
$ php test.php
Array
(
    [1] => 4
    [2] => 5
)


Question: Is there an event that fires when a WCF service gets started or shut down?  Hopefully, independent of whether it is self hosted or hosted in IIS?

Answer:
Sure, the constructor of your object (especially if you are using a Singleton style). Please pardon the shameless self promotion, but I've written two articles on how to get started with a WCF (Net.Tcp) client/server system... The first is non-IIS (to which the service starts on your own terms), the latter is how to modify the first to be hosted in IIS to which my first sentense would apply:
1)
Client Server Programming with WCF
2)
Duplex WCF Services Hosted in IIS Using Net.Tcp


Question:
SQL Server 2005.

I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them.  Naturally, the data has become unreliable and there are orphaned entries in the foreign key field.

Setup:

Two tables, TableUser and TableOrder.
TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'.

How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID?

For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.

Answer:
Here's one way:
```
```
select * from TableOrder where UserID not in (select UserID from TableUser);
```
```
There are many different ways to write this sort of query.


Question: Does anyone has a good solution for a C# version of the C++ __FUNCTION__ macro? The compiler does not seem to like it.

Answer:
Try using this instead.
```
```
System.Reflection.MethodBase.GetCurrentMethod().Name
```
```
C# doesn't have
```
__LINE__
```
or
```
__FUNCTION__
```
macros like C++ but there are equivalents


Question:
It seems that the following piece of HTML is ignored in IE7 but works ok in IE6/FF. It supposes to override all the html links to be opened in the desired frame

<HEAD>
 <title>LeftPane</title>
 <base target="rightFrame">
</HEAD>

The above code is the header of a left frame that holds an Infragistics UltraWebTree (tree menu) which doesn't support the TargetFrame property.

Is there another way to add the target attribute to all the links elements on the desired page.

Any server or client-side code workarounds?

The site is built on ASP.Net 1.1 and Infragistics V 2.0

Update
the web page is aspx an the doctype is

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

Answer:
The
```
href=""
```
attibute is
mandatory on the base tag
- that's one possible explanation.  You don't say what doctype you're using, but
target is not allowed in strict XHTML
.
Edit: tested it without href and it worked ok... that leaves the doctype, or something else.


Question:
If I have a table like this:

CREATE TABLE sizes (
    name ENUM('small', 'medium', 'large')
);

Is MySQL going to store those strings in every row, or internally will it use something smaller like integers to know which enum value to refer to?

I want to use an enum in a table but I'm worried if it's as wasteful as storing a string in every row.

Answer:
It converts them to integers on INSERT / UPDATE and back to strings on SELECT so the internal storage is as integers but you don't get exposed to that.
You can retrieve the integer like
```
SELECT mycolumn + 0
```
.
See
ENUMs in MySQL 5


Question:
I'm an old hand at embedded programming but new to CE and having a lot of trouble doing reasonably simple things, because I am not familiar with the API and struggling to understand the obscure MSDN docs.

All I want to do is minimize and maximise two separate applications that are running from one of the applications.

E.g. Application A decides that now it is time for it to appear and then minimises application B (App B being a third party application e.g. Notepad, no access to source code etc) and then at a later stage maximising B and minimising itself.

Application A would be written by myself.

I'm sure this must be very simple, but where to find answers.. :)

Thanks in advance.
EOI

Answer:
Firstly you will need to locate the window handle (hwnd) using the
FindWindow
API function or some alternate means. Next use the
ShowWindow
API function specifying either
SW_HIDE
or
SW_SHOW
to hide or show the window respectively. Note that Windows CE 5.0 does not technically support the Win32 window states like SW_MINIMIZE, SW_MAXIMIZE, etc.
A simple example would be:
```
```
HWND hWnd = ::FindWindow( _T("Notepad"), NULL);
::ShowWindow(hWnd, SW_HIDE);
```
```


Question:
I'm new to .NET, so please be patient with me ;)

On my Windows Form, I have a DataGridView that is bound to a data source. Since my grid is read-only, I have a set of controls (textbox, checkbox, etc.) outside the grid that will be used to edit the data.

I want the controls to be binded to the currently selected row in the grid. Currently, if I set the DataBindings of the controls to the same data source as the grid, only the first record is showned even if I move the record pointer in the grid.

What am I missing?

Environment: Windows Form, C#, Visual Studio 2008.

Answer:
You want to check out the custom datagridviewcolumn types that are available with the datagridview.
Add in special columns and then bind a list of business objects to the grid (or a DataSet).
I think you can even ask the grid to autogenerate sensible columns based upon the objects you give it.
I wouldn't recommend trying to stuff normal controls into the datagrid per se, there is a grid column framework based on cells, columns and editingcontrols that deals with this stuff. Have a little searchy on Google based on those kind of words (e.g DataBinding/DataGridViewEditingControl), i'm afraid I don't have my DataGridView resources to hand right now.
Oh wait, sorry I re-read. You'll want to look at the BindingContext object.


Question: We have 3 applications using 3 different spring configuration files. But we have one database and one datasource, so one session factory.Hhow can we import the session factory bean into the 3 different spring config files?

Answer:
If you are using XML configuration:
Put your database settings in a Spring configuration called "database-config.xml" and import it in the other configuration files.
```
```
<import resource="database-config.xml"/>
```
```
As to how you share it among three applications is more of a Configuration Management issue. You could use ant / maven to check it out of a repository and move it into the correct location.


Question:
ok so basically I am asking the question of their name
I want this to be one input rather than Forename and Surname.

Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g.

name = "Thomas Winter"
print name.split()

and what would be output is just "Winter"

Answer:
Like this:
```
```
print name.split()[-1]
```
```


Question:
I had a painful experience with the "Analysis of Algorithms" classes back in college but have recently found a need for it in the real world.  -- Anyway, I'm looking for a simple-yet-effective crash course.  Any ideas?

Related Sidenote:  It sure would be nice if there were a "Cartoon Guide to Algorithm Analysis", taught by Dilbert.

UPDATE:  A very similar question can be found at: How to get started on ALGORITHMS?

Answer:
There are a lot of good books on the subject.  I like
An Introduction to the Analysis of Algorithms
.  Also check out the algorithms course on
MIT OpenCourseWare
(using
CLRS
as the course text).  It's a little bit deep, but having it online allows you to go at your own pace.
A couple of other books that I've started reading recently are
Algorithms in a Nutshell
and the
Algorithm Design Manual
.  They both take a lighter approach than most algorithms books.  Instead of heavy math and formal proofs these books give you realistic problem statements and show you the steps taken to refine an algorithm.  They also show you how to
estimate
and
measure
the complexity of a solution.  I would highly recommend either book.


Question:
In a simple winform application, I call a function that endlessy create files on a button click event. I add Application.DoEvents() to the loop.

I press the red X to close the form.

the form closes, but files continue to be created ...

I think its on the buttons thread, but shouldnt it be a background one ? trying changing Thread.CurrentThread.IsBackGround to True on the loop function does not help.

Ideas ?

Answer:
The fact that you're using
```
Application.DoEvents
```
is the first sign of a problem: it shows that you're doing too much in the UI thread. It's almost never appropriate in a well-structured program. The UI thread is not meant to have any long-running tasks. (Admittedly if it takes a long time to draw your UI you have little choice - but that suggests you should simplify your UI... and it's not applicable in this case, I suspect.)
Instead, you should be performing the long-running task (creating the files) in a separate thread.
BackgroundWorker
is a perfect fit for this - you can use it to report progress back to the UI, and the UI can call
```
CancelAsync
```
method to request that it stops. You need to check the
```
CancellationPending
```
property from within the worker thread, to see whether cancellation has been requested, and stop appropriately.
EDIT: Just to clarify what I believe is happening - I suspect your form is closing, but the program won't terminate until the event loop has finished. You're keeping the event loop going with your file-creation loop, hence the problem.
Note that there isn't a thread for the button - there's just one for your whole UI. (In certain cases you may need more than one UI thread, but that's rare - and you'd know it if you'd done it.)


Question:
I'm building an XML document with PHP's SimpleXML extension, and I'm adding a token to the file:

$doc->addChild('myToken');

This generates (what I know as) a self-closing or single tag:

<myToken/>

However, the aging web-service I'm communicating with is tripping all over self-closing tags, so I need to have a separate opening and closing tag:

<myToken></myToken>

The question is, how do I do this, outside of running the generated XML through a preg_replace?

Answer:
From the documentation at
SimpleXMLElement->__construct
and
LibXML Predefined Constants
, I think this should work:
```
```
<?php
$sxe = new SimpleXMLElement($someData, LIBXML_NOEMPTYTAG);

// some processing here

$out = $sxe->asXML();
?>
```
```
Try that and see if it works. Otherwise, I'm afraid, it's preg_replace-land.


Question:
I am using XmlSerializer to write and read an object to xml in C#.  I currently use the attributes XmlElement and XmlIgnore to manipulate the serialization of the object.

If my xml file is missing an xml element that I require, my object still deserializes (xml -> object) just fine.   How do I indicate (preferably via Attributes) that a certain field is "required"?

Here is a sample method of what I am using currently:

[XmlElement(ElementName="numberOfWidgets")]
public int NumberThatIsRequired {
    set ...;
    get ...;
}

My ideal solution would be to add something like an XmlRequired attribute.

Also, is there a good reference for what Attributes are available to manipulate the behavior of XmlSerializer?

Answer:
I've got an answer for the second part:
"Attributes that control XML serialization"
.
Still investigating the first part...
EDIT: I strongly suspect you can't do this through XML deserialization itself. I've just run xsd.exe on a sample schema which includes a required attribute - and it's exactly the same if the attribute is marked as being optional. If there were a way of requiring properties to be set, I'd expect it to be implemented in that case.
I suspect you've basically got to just validate your tree of objects after deserializing it. Sorry about that...


Question:
I have two vb.net class:

Public MustInherit Class Class1
    Private m_sProperty1 As String = ""
    Public Property sProperty1() As String
        Get
            Return m_sProperty1
        End Get
        Set(ByVal value As String)
            m_sProperty1 = value
        End Set
    End Property
End Class

<ComClass("classid","interfaceid","eventid")> _
Public Class Class2
    Inherits Class1

    Private m_sProperty2 As String = ""
    Public Property sProperty2() As String
        Get
            Return m_sProperty2
        End Get
        Set(ByVal value As String)
            m_sProperty2 = value
        End Set
    End Property
End Class

When I reference the compiled DLL through VB6, Class2 only exposes sProperty2.  How can I access the inherited property of the base class (sProperty1) through COM?

Answer:
I'll take a guess as I'm not up to speed on .NET
I would imagine your declaration is taking your public methods of Class2 and creating a COM interface out of them.  It will only take methods (and properties) on Class2 and not inherited ones (otherwise you would get all public methods all the way down to your base class).
The solution would probably be to declare Class1 as a COM class also (it may be possible to mark it as private) then specify that the COM interfaceid of Class2 descends from the COM interfaceid of Class1.
Some thing like that shoudl do the trick.


Question:
In my Python app, I have an XML document that I'd like to transform using my XSL file.  I'm currently using xml.etree to generate the XML document, but I haven't found anything within Python 2.5 that will allow me to natively transform my XML document.

I've already found one library (libxslt) which can execute the transformation, but I figured Python would have a native library that achieves the desired result.

Any thoughts?

Answer: There is no XSLT processor in Python 2.5.


Question:
Let's say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):

CREATE PROCEDURE incrementCounter AS

DECLARE @current int
SET @current = (select CounterColumn from MyTable) + 1

UPDATE
    MyTable
SET
    CounterColumn = current
GO

We're assuming I have a table called 'myTable' that contains one row, with the 'CounterColumn' containing our current count.

Can this stored procedure be executed multiple times, at the same time?

i.e. is this possible:

I call 'incrementCounter' twice.  Call A gets to the point where it sets the 'current' variable (let's say it is 5).  Call B gets to the point where it sets the 'current' variable (which would also be 5).  Call A finishes executing, then Call B finishes.  In the end, the table should contain the value of 6, but instead contains 5 due to the overlap of execution

Answer:
This is for SQL Server.
Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with
BEGIN TRANSACTION
Statement ...
Statement ...
COMMIT TRANSACTION
(It's common to use BEGIN TRAN and END TRAN for short.)
Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious.
Contrary to a popular misconception, this will work in your case with default transaction level settings.


Question:
We have a fairly complex web application (.NET 3.5) that need to be launched from a CD-ROM (or DVD, or from an USB key).

I'm thinking of using Cassini and SqlCe for the database (we use LinqToSql for data access, so I think it's the only choice without rewriting the entire data access classes). Is anyone ever done something like that?

Notes :
http://www.microsoft.com/belux/msdn/nl/community/columns/desmet/hostaspnet2.mspx
Kind of does what I want.

Answer:
Where are you going to get the web server to serve the ASP.NET pages? You can open stuff like straight HTML, Flash or Silverlight directly in the browser, but unless I am missing something, you need IIS to do the server side ASP.NET.
I don't know your requirements, but you might want to consider a WinForms app or even MFC (if you can't guarantee .NET is installed on the target computers).
This doesn't answer your database question though. SqlCE should work as the required assemblies can be distributed with your application. Another option is SQLite along with Subversion for your data layer. I have no experience with Cassini though.


Question:
I want to create a view that consists solely of a UITextView. When the view is first shown, by default, I'd like the keyboard to be visible and ready for text entry. This way, the user does not have to touch the UITextView first in order to begin editing.

Is this possible? I see the class has a notification called UITextViewTextDidBeginEditingNotification but I'm not sure how to send that, or if that is even the right approach.

Answer:
to accomplish that just send the becomeFirstResponder message to your UITextField, as follows (assuming you have an outlet called textField, pointing to the field in question):
```
```
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [textField becomeFirstResponder];
}
```
```


Question:
I am performing two validations on the client side on the samve event.
I have defined my validations as shown below

btnSearch.Attributes["OnClick"] = "javascript:return prepareSave(); return prepareSearch();"

Pseudo code for

prepareSave():
{
  if (bPendingchanges)
    {
     return confirm('Need to save pending changes first, click OK and loose changes or cancel to save them first')
    }
  else
   {return true}
}

Pseudo code for

prepareSearch():
{
  if (bNoSearchText)
    {
      alert('Please specify search criteria before proceeding')
      return false;
   }
  else
   {return true;}
}

When bPendingchanges=false, I never get the second validation running.
Anyone who can quickly spot what I have overlooked here? Please?

Answer:
Your second
```
return
```
statement will never be reached. Execution stops after
```
javascript:return prepareSave()
```
.
Looks like you want to return true if both functions return true - therefore, do:
```
```
btnSearch.Attributes["OnClick"] = javascript: return prepareSave() && prepareSearch();
```
```


Question:
I want to assign a resource I already have a second name, similar to using the BasedOn property of Styles. Specifically I have a brush that I use for a group of elements called ForegroundColor and I would like to use it in a control template (a ComboBox) calling it MouseOverBackgroundBrush. I would like to do something like this:

<ResourceCopy x:key="MouseOverBackgroundBrush" Value="{StaticResource ForegroundColor}" />

Is there a way to do this or is there a better way to go about this in Xaml?

Answer:
This is a feature that doesn't have very good support in XAML. I believe that you'll either need to repeat yourself (and change both locations anytime you need to change the brush)
or
if you don't mind a bit of code behind, you can accomplish the duplication like this:
```
```
Resources["MouseOverBackgroundBrush"] = Resources["ForegroundColor"];
```
```


Question:
If I have a button like the one in this image :

http://www.freeimagehosting.net/image.php?4cd775814c.png

how could I make the text display itself vertically ? As in

j
B
u
t
t
o
n
1

I would like to know how to do the same thing for JLabel . I'm sure there has to be a better way than to create as many labels as there are characters in the string . Right ?

EDIT: how can I insert an image into my post ? The button for the image shows the image in the preview section , but when I actually post the data , I only get some text back , like the tags are getting messed up .

Answer:
You can use HTML for JButton or JLabel. So
```
```
button = new JButton("J
b
u
t
t
o
n
1");
```
```
should do the trick.


Question:
This question is related to my previous one.

Can you explain or provide a link to an explanation of how Excel VBA code password protection actually works in versions prior to 2007? What is the difference in Excel 2007 and previous versions in terms of password protection?

Also does Excel's password protection actually encrypt the code? How does Excel execute the code if it is encrypted?

Lastly, how does password removal software for excel work?

Answer:
VBA security is widely considered to be pretty poor.  The VBA code isn't compiled, and the source is available in the excel file. The password protection is pretty easy to circumvent.
As I understand it, Office 2003 and earlier saves the vba code as part of the binary format of the worksheet (or document / presentation).  When you fire up the VBA IDE, it simply looks to see whether the VBA code has been "protected" or not.  This doesn't mean it's encrypted - just unavailable for viewing.  The theory is that this stops your users from meddling with your code, but a hard-core coder would be able to get around the password.
So Excel doesn't need to unencrypt any code - it just needs to stop people from viewing it.
Office 2007
does
encrypt macros (don't ask me how or what algorithm).  This is necessary presumably because XLSM files (or any Office 2007 file) are just zip files with a different extension.  Anyone can get into those files and poke around.
To answer your last question - how does the password removal work on older Office formats, I'm not entirely sure.  Different vendors will possibly approach the problem different ways, but I suspect the most common approach will be a brute-force attack on the passwords until a match is found.
The Excel VBProject object has a Protection property which will return different enumerations depending on the protection status of the macro (
```
vbext_pp_locked
```
if the macro is protected, for example).  If you were to keep trying passwords programmatically until the
```
vbext_pp_locked
```
evaluated to false, you would have found your password.


Question:
In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid.

I.e. instead of just

dynamic foo = GetSomeDynamicObject();

have the ability to cast or transform it to constrain it to a known contract, such as

IFoo foo2 = foo.To<IFoo>;

or even just

IFoo foo2 = foo as IFoo;

Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?

Answer:
I'm not aware of anything really resembling duck typing, I'm afraid. I've
blogged about the idea
, but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.


Question:
I have to simultaneously load data into a table and run queries on it. Because of data nature, I can trade integrity for performance. How can I minimize the overhead of transactions?

Unfortunately, alternatives like MySQL cannot be used (due to non-technical reasons).

Answer:
You want transaction isolation read uncommitted. I don't recommend it but that's what you asked for :)
This will allow you to breach transaction isolation and read uncommitted inserted data.
Please read this Ask Tom article:
http://www.oracle.com/technology/oramag/oracle/05-nov/o65asktom.html
.
UPDATE: I was actually mistaking, Oracle doesn't really support read uncommitted isolation level, they just mention it :).


Question: What is the best way to tokenize/split a NSString in Objective-C?

Answer:
Found answer
here
:
```
```
NSString *string = @"oop:ack:bork:greeble:ponies";
NSArray *chunks = [string componentsSeparatedByString: @":"];
```
```


Question:
Consider the following file

var1 var2 variable3
1     2    3
11    22   33

I would like to load the numbers into a matrix, and the column titles into a variable that would be equivalent to:

variable_names = char('var1', 'var2', 'variable3');

I don't mind to split the names and the numbers in two files, however preparing matlab code files and eval'ing them is not an option.

Note that there can be an arbitrary number of variables (columns)

Answer:
Just use textscan with different format specifiers.
```
```
fid = fopen(filename,'r');
heading = textscan(fid,'%s %s %s',1);
fgetl(fid); %advance the file pointer one line
data = textscan(fid,'%n %n %n');%read the rest of the data
fclose(fid);
```
```
In this case 'heading' will be a cell array containing cells with each column heading inside, so you will have to change them into cell array of strings or whatever it is that you want. 'data' will be a cell array containing a numeric array for each column that you read, so you will have to cat them together to make one matrix.


Question: Is there a way to increase the font-size in the Firefox extension Firebug?

Answer:
Right click on the bug icon in the status bar.
Select "Open Firebug in New Window"
Select "View" > "Text Size" > "Increase Text Size"
The changes should stick if you revert back to opening Firebug in the same window.
Update
In new versions you can simply click on the bug icon in the code navigator and choose 'Text size'.


Question: If I have a query to return all matching entries in a DB that have "news" in the searchable column (i.e. SELECT * FROM table WHERE column LIKE %news%), and one particular row has an entry starting with "In recent World news, Somalia was invaded by ...", can I return a specific "chunk" of an SQL entry? Kind of like a teaser, if you will.

Answer:
You can use substring function in a SELECT part. Something like:
```
```
SELECT SUBSTRING(column, 1,20) FROM table WHERE column LIKE %news%
```
```
This will return the first 20 characters from column
column


Question: I want to display from cache for a long time and I want a slightly different behavior on page render vs loading the page from cache.  Is there an easy way I can determine this with JavaScript?

Answer: One way you could do it is to include the time the page was generated in the page and then use some javascript to compare the local time to the time the page was generated.  If the time is different by a threshold then the page has come from a cache.  The problem with that is if the client machine has its time set incorrectly, although you could get around this by making the client include its current system time in the request to generate the page and then send that value back to the client.


Question:
I have a project to recognize the footprint of animals. It is similar to facial recognition.

There is a need to store footprint images in a database and compare them with images captured by camera.

What is the appropriate programming language to do this?

Answer:
I think the question is rather how you represent the data and determine likeness/sameness/distance measuring rather than an implementation language.
Lisp is a strong candidate, as is C/C++ - but really you are probably better off with whatever language you/your team knows best.
Again, figure out the data representation first.
Also - find another imaging/matching solution out there.  There are already ones for license plates, fingerprint, etc - and maybe just use that source.  The roblem is mostly solved...


Question: I'd like to create a popup dialog box in silverlight  in which i can manipulate controls, enter data, and return a value. I want it to be modal, so that when it is open, the page "Below" is inaccessible. I havent found an easy way to do this yet. Any suggestions?

Answer:
I haven't found a perfect solution either. The closest I have seen is this:
Using Popup to create a Dialog class
If it is ok to be non-modal, you can try this tip using HtmlPage.PopupWindow().
How to Popup a Browser Window


Question:
I'll preface this by saying I'm a C# programmer who inherited horrible code with no documentation.  I have an unmanaged C++ library wrapped with managed code that worked fine in VS2003 with .Net 1.1 Framework.  I'm trying to get it upgraded to at least .Net 2.0.

I have the unmanaged C++ library that was compiled with "MSVC 8.x" (thus equivalent to VS 2005, I assume).  I've been trying to migrate everything to VS2008 and still have some issues with this library at runtime.

My question is this: should this library work with VS2008?  Or should I be developing in VS2005 if the library was compiled with VC8.x?

Any thoughts would be greatly appreciated.  Thanks!

Answer:
It should work, I expect that you are having issues with your marshalling. It is probably stuff that was declared incorrectly for PInvoking that managed to work in .NET 1.1 but not in later versions.
You don't say what sort of problems you are having at run time, nor do you state how you access your library. For example, do you compile your library along with your project? If so, can you turn on unmanaged debugging in your C# project and step into the code you are having trouble with? How are you calling the unmanaged code? Is it through PInvoke, or do you have managed C++ wrappers?
In my experience, the best solution for calling out to a legacy unmanaged library is to add a managed wrapper library for your legacy library written in managed C++. This way you present a managed interface for your library for all .NET languages to consume and you don't have to worry about getting your PInvoke signatures correct.
Your project should look something like this.
C# Application -> Manage C++ Wrapper DLL -> Legacy DLL


Question:
I'm not a designer, so I'm looking for some free WPF themes.

Any suggestions?

Answer:
The only one that I have found (for sale) is
reuxables
. A little pricey, if you ask me, but you do get 9 themes/61 variations.
UPDATE 1:
A WPF Contrib project ... which does have 1
theme
that they never released.
UPDATE 2:
Rudi Grobler (above) just created CodePlex
community
for this ... starting with converted themes he mentions above. See his blog
post
for more info. Way to go Rudi!
UPDATE 3:
As another answer below has mentioned, since this question and my answer were written, the WPF Toolkit has incorporated some free
themes
, in particular, the themes from the Silverlight Toolkit. Rudi's
project
goes a little further and adds several more ... but depending on your situation, the WPF Toolkit might be all you need (and you might be installing it already).


Question:
You'll have to forgive my ignorance, but I'm not used to using wide character sets in c++, but is there a way that I can use wide string literals in c++ without putting an L in front of each literal?

If so, how?

Answer:
Why do you not want to prefix string literals with an L?  It's quite simple - strings without an L are ANSI strings (
```
const char*
```
), strings with an L are wide-character strings (
```
const wchar_t*
```
).  There is the
```
TEXT()
```
macro, which makes a string literal into an ANSI or a wide-character string depending on of the current project is set to use Uncode:
```
```
#ifdef UNICODE
#define TEXT(s) L ## s
#else
#define TEXT(s) s
#endif
```
```
There's also the
```
_T()
```
macro, which is equivalent to
```
TEXT()
```
.


Question:
I would like to set up some WMV Video Streaming, using Windows 2003's Streaming Media Server and Silverlight.

Now, unfortunately Silverlight only supports HTTP, which means that people can just download the videos. While that in itself is not a problem, I wonder what options there are to prevent them being playable outside of the network.

Of course, DRM comes into mind. Is there an easy way to get it and set it up? I do not want to have some complicated User-Scheme, it essentially boils down to "If you can reach the server (which is only in the internal network), you get a license, otherwise not".

Any experience with WMV DRM or Content Protection in that area?
What would I need on top of Windows 2003 Server and Silverlight 2?

Answer: DRM is a negative sum game.  You lose money and time in implementing it that you could have spent on something useful to your users, and your content becomes less valuable to your users.  It is also impossible to implement effectively.  I'm not going to address any specific DRM scheme, but the core of the argument is that in order to show content to the user, the user's computer must be able to decrypt it.  Therefore, the decryption code, and the decryption keys, must be present on the user's computer.  Encryption can only protect data from interception and tampering between two secure endpoints.  If one of the endpoints is compromised (and you are assuming this in your distrust of the user), then cryptographic techniques are useless.


Question:
I have a short preliminary interview with Microsoft in less than 2 hours.
I've been told that they might ask questions in Java and/or C++.
Where can I find a quick overview of both languages?
I don't need to full tutorial, just something that goes over the language-specific features and a refresher of the semantics.
I also only have 1.5 hours to study so...
Any ideas?

Thx!

Answer: An hour and a half is a bit fast to learn a language. You can try Wikipedia, but you may want to avoid discussion of either language if you don't know them. Instead focus on the languages you do know. Learning a new language is not difficult, but you shouldn't try to rush it and then sound like you know more than you do. They'll figure that one out pretty quickly, and it will be worse if you don't admit your lack of knowledge. We had someone who tried that with my company, and he lasted less than a week.


Question:
I have a query in which I am pulling the runtime of an executable. The database contains its start time and its end time. I would like to get the total time for the run.
So far I have:

SELECT startTime, endTime,
cast(datediff(hh,starttime,endtime) as varchar)
+':'
+cast(datediff(mi,starttime,endtime)-60*datediff(hh,starttime,endtime) as varchar) AS RUNTIME
FROM applog
WHERE runID = 33871
ORDER BY startTime DESC

When I execute this I get expected values and also some unexpected.
For example, if starttime = 2008-11-02 15:59:59.790 and endtime = 2008-11-02 19:05:41.857 then the runtime is = 4:-54.
How do I get a quere in MS SQL SMS to return the value 3:06 for this case?

Thanks.

Eoin Campbell's I selected as the answer is the most bulletproof for my needs. David B's is do-able as well.

Answer:
Here's
a way to do it:
```
```
-- Find Hours, Minutes and Seconds in between two datetime
DECLARE @First datetime
DECLARE @Second datetime
SET @First = '04/02/2008 05:23:22'
SET @Second = getdate()

SELECT DATEDIFF(day,@First,@Second)*24 as TotalHours,
DATEDIFF(day,@First,@Second)*24*60 as TotalMinutes,
DATEDIFF(day,@First,@Second)*24*60*60 as TotalSeconds
```
```


Question:
I'm using jQuery and wanting to target the nth <li> in a list after clicking the nth link.

<ul id="targetedArea">
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>
<div id="clickedItems">
  <a></a>
  <a></a>
  <a></a>
  <a></a>
</div>

I can target them individually, but I know there must be a faster way by passing which <a> element I clicked on.

$("#clickedItem a:eq(2)").click(function() {
  $("#targetedArea:eq(2)").addClass('active');
  return false;
});

Cheers,

Steve

Answer:
how about something like this:
```
```
$('#clickedItems a').click(function() {
// figure out what position this element is in
   var n = $('#clickedItems a').index($(this) );
// update the targetedArea
   $('#targetedArea li:eq('+n+')').html('updated!');
   return false;
});
```
```
assuming a 1:1 relationship between your
```
<a>
```
and
```
<li>
```
elements it will update the appropriate
```
<li>
```


Question:
How can i draw a dotted line in .NET/WinForms/GDI+?

Pen p = new Pen (Color.Black)

gives me only solid line pen.

I am trying to have a dotted (or dashed) lines; can't seem to be able to google it up successfully.

Will much appreciate any help on this one.

Answer:
```
```
p.DashStyle = DashStyle.Dash;
```
```
I believe.


Question:
I want to select records that are 1 month old or newer.

The query is: SELECT * FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)

Using Propel in Symfony, I do:

$c = new Criteria

  $c->add(FoobarPeer::CREATED_AT, "DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::GREATER_THAN);

What Propel generates is: SELECT * FROM foobar WHERE created_at > 'DATE_SUB(curdate(), INTERVAL 1 MONTH)' - in other words, it puts the MySQL function in single quotes, which makes it a (meaningless) string and I get no records.

What I've done for now is:

$c->add(FoobarPeer::CREATED_AT, "created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)", Criteria::CUSTOM);

But I don't want to use custom workarounds unless I have to. Any hints besides using Criteria::CUSTOM?

Answer:
I think there is no option more than using Criteria::CUSTOM or doing a custom SQL query like this:
```
```
$con = Propel::getConnection(DATABASE_NAME);

$sql = "SELECT foobar.* FROM foobar WHERE created_at > DATE_SUB(curdate(), INTERVAL 1 MONTH)";
$stmt = $con->prepare($sql);
$stmt->execute();

$books = FoobarPeer::populateObjects($stmt);
```
```
That's because Propel tries to be DBMS-agnostic, to help migration by doing a simple configuration value change, so it doesn't have any DBMS specific functions built in.


Question:
I know that php has md5(), sha1(), and the hash() functions, but I want to create a hash using the MySQL PASSWORD() function.  So far, the only way I can think of is to just query the server, but I want a function (preferably in php or Perl) that will do the same thing without querying MySQL at all.

For example:

MySQL hash -> 464bb2cb3cf18b66

MySQL5 hash -> *01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229

Thanks!

Answer:
Why do you want to use mysql password() function?
Even the Mysql documentation advises against this:
http://dev.mysql.com/doc/refman/5.0/en/encryption-functions.html#function_password
The PASSWORD() function is used by the authentication system in MySQL Server; you should not use it in your own applications
You can use md5() for example, wich is present in almost every programming language, php and perl included.


Question:
A little example

TTest<T> = class
private
  f : T;
public
  function ToString : string;
end;

If  is an object then this should work

TTest<T>.ToString;
begin
  Result := f.ToString;
end;

But what happens when  is say an integer? This would be ok in .net. of course.

I know it won't work, but how do I code this to work with objects AND simple types?

Answer:
The last example will not work. You need to add a constraint in order to use methods. In this case TObject will be enough:
```
```
TTest<T: TObject>.ToString;
begin
  Result := T.ToString;
end;
```
```
You can use simple types with unrestrained generics, but you are very limited in the use. Because the only valid operations are assignment and comparison (equal and not equal).
In Delphi simple types are no classes, so they don't have methods.
But you can do the following:
```
```
type
  TToString<T> = reference to function(const AValue: T): string;
  TGenContainer<T> = class
  private
    FValue: T;
    FToString : TToString<T>;
  public
    constructor Create(const AToString: TToString<T>);

    function ToString: string;

    property Value: T read FValue write FValue;
  end;

constructor TGenContainer<T>.Create(const AToString: TToString<T>);
begin
  FToString := AToString;
end;

function TGenContainer<T>.ToString: string;
begin
  Result := FToString(FValue);
end;

procedure TForm2.Button1Click(Sender: TObject);
var
  gen : TGenContainer<Integer>;
begin
  gen := TGenContainer<Integer>.Create(
    function(const AValue: Integer): string
    begin
      Result := IntToStr(AValue);
    end);
  try
    gen.Value := 17;
    Memo1.Lines.Add(gen.ToString);
  finally
    gen.Free;
  end;
end;
```
```
This works fine.


Question:
I'm writing a simple C++ class in which I would like cache picture thumbnails versions of images downloaded from the web.  As such, I would like to use a hash function which takes in URL strings and outputs a unique string suitable as a filename.

Is there a simple way to do this without re-writing the function myself?  I searched around for a simple library, but couldn't find anything.  Surely this is a common problem.

Answer:
A simpler approach is to replace everything which is not a character or a number with an underscore.
EDIT: Here's a naive implementation in C:
```
```
#include <cctype>

char *safe_url(const char *str) {
    char *safe = strdup(str);
    for (int i = 0; i < strlen(str); i++) {
        if (isalpha(str[i]))
            safe[i] = str[i];
        else
            safe[i] = '_';
    }
}
```
```


Question: Is anyone using the OSGi Bundle Repository and what for?

Answer:
I am using it!
When you develop an osgi bundle and the target platform doesn't include the libraries (jar/bundle) your bundle relies on, it needs to added to the target platform. you could either repackage your jar to make it an osgi bundle or just download the bundle from the OBR.
Eclipse also provides an OBR call
Orbit
, and springsource one is called
Enterprise Bundle Repository
.


Question:
For reference, this would be for Visual Studio 2008 with a fair amount of WinForms working with the VS Designer.

Given the same price bracket, would there be certain specs you look for in a development rig vs what one would get for a gaming machine?

Edit: The reason I ask is on my laptop that I can run low-mid end games decently on, there's still a fair amount of time redrawing when switching between apps sometimes.(I keep about 20 tabs open average on  a browser and have like 10-15 apps open at a time), and working with the VS designer on things like a TableLayoutPanel takes up to 10-15 seconds for changes and so forth. I'd like a really smooth experience.

Answer:
Any new video card you could buy today would be more than adequate for non-3D software development. In fact whatever integrated video came with your system is fine. The only exception would be for multiple monitor support, in that case you would need to get an extra $50 video card since most (all?) motherboards only have a single monitor output.
Edit: in response to the edit, the lag you're describing sounds like your machine is out of RAM and is swapping to disk, rather than you being video card limited. You'll want at least 2-3GB of ram in your system if you're running vs2008 plus 20 other applications. That's about the max. you can install if you're running a 32-bit operating system. If you want more than that you'll need to go to a 64-bit OS and you'll need to make sure all your hardware has 64-bit drivers. Also very few laptops out there support more than 4GB of RAM.


Question: I'm in need of a macro that will enter data into a webpage search field and than copy the results to excel.

Answer:
It's just a simple "File Open". No need for a macro.
Excel can open URLs directly. If the URL contains any tables, those will be formatted appropriately.
Try this:
Run Excel
File | Open
Type
```
http://finance.yahoo.com/q?s=MSFT
```
as the file name
Ignore the warning


Question:
I've got a canvas that's 800x600 inside a window that's 300x300. When I press a certain key, I want it the canvas to move in that direction.

I've done this inside the window's code behind:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    Key keyPressed = e.Key;

    if (keyPressed == Key.W)
    {
        gcY += 5;
    }
    if (keyPressed == Key.S)
    {
        gcY -= 5;
    }
    if (keyPressed == Key.A)
    {
        gcX += 5;
    }
    if (keyPressed == Key.D)
    {
        gcX -= 5;
    }

    gameCanvas.RenderTransform = new TranslateTransform(gcX, gcY);
}

Well, it works, but the movement is jerky. And if I hold on to a key, W for instance, then it pauses for a split second, before moving.

Is there anyway to make the movement smoother and to get rid of the pause when you hold down a key?

Thanks.

Answer:
Yes, you could incorporate the time into your calculation. Currently you add/substract 5 whenever the event fires, and that's not really predictable.
To smoothe the movement make sure you don't fire more often than X times per second by using a DateTime.
like:
```
```
private static DateTime nextUpdate

if (nextUpdate <= DateTime.Now)
{
//Move
nextUpdate = DateTime.Now.AddMilliseconds(100);
}
```
```
I don't have VS right now, so I'm not perfectly sure for the syntax, but you get the idea.


Question:
I need to take production data with real customer info (names, address, phone numbers, etc) and move it into a dev environment, but I'd like to remove any semblance of real customer info.

Some of the answers to this question can help me generating NEW test data, but then how do I replace those columns in my production data, but keep the other relevant columns?

Let's say I had a table with 10000 fake names. Should I do a cross-join with a SQL update? Or do something like

UPDATE table
SET lastname = (SELECT TOP 1 name FROM samplenames ORDER By NEWID())

Answer:
Anonymizing data can be tricky and if not done correctly can lead you to trouble, like what happened to
AOL when they released search data a while back
. I would attempt to create test data from scratch at all costs before I tried to convert existing customer data. Things may lead you to be able to figure out who the data belonged to using things such as behavioral analysis and other data points that you might not consider sensitive. I would rather be safe than sorry.


Question:
Why does this test program result in a java.lang.IllegalMonitorStateException?

public class test {
    static Integer foo = new Integer(1);
    public static void main(String[] args) {
        synchronized(foo) {
            foo++;
            foo.notifyAll();
        }
        System.err.println("Success");
    }
}

Result:

Exception in thread "main" java.lang.IllegalMonitorStateException
        at java.lang.Object.notifyAll(Native Method)
        at test.main(test.java:6)

Answer:
You have noted correctly that
```
notifyAll
```
must be called from a synchronized block.
However, in your case, because of auto-boxing, the object you synchronized on is not the same instance that you invoked
```
notifyAll
```
on. In fact, the new, incremented
```
foo
```
instance is still confined to the stack, and no other threads could possibly be blocked on a
```
wait
```
call.
You could implement your own, mutable counter on which synchronization is performed. Depending on your application, you might also find that
AtomicInteger
meets your needs.


Question:
I occasionally work on an old project that uses classic asp as a front end and an access database as a backend.

I'd like to create a new column in one of the tables that contains logic to calculate its value from the other columns in the row.

I know how to do this in a more modern DBMS, but I don't think that access supports it. Keep in mind I'm not using the access frontend, just the Jet DB engine via ODBC.

Any pointers?

Answer:
Can you just make a calculated column?
```
```
SELECT Table1.Col_1, Table1.Col_2, [Col_1]*[Col_2] AS Col_3
FROM Table1;
```
```


Question:
I am using the code below to display all the files from a directory in a drop down menu. Does anyone know how to make this alphabetical? I presume it has something to do with the sort function, I just can't figure out how!

<?php
$dirname = "images/";
$images = scandir($dirname);
$dh = opendir($dirname);

while ($file = readdir($dh)) {
if (substr($file, -4) == ".gif") {
print "<option value='$file'>$file</option>\n"; }
}
closedir($dh);
?>

Answer:
Why are you reading all the filenames using scandir() and then looping through them with the readdir() method? You could just do this:
```
```
<?php

$dirname = "images/";
$images = scandir($dirname);

// This is how you sort an array, see http://php.net/sort
sort($images);

// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; }
    }
}

?>
```
```
Also you might want to use
natsort()
, which works the same way as
sort()
but sorts in "natural order". (Instead of sorting as
```
1,10,2,20
```
it will sort as
```
1,2,10,20
```
.)


Question:
I have a list of stores, departments within the stores, and sales for each department, like so (created using max(sales) in a subquery, but that's not terribly important here I don't think):

toronto    baskets 500
vancouver  baskets 350
halifax    baskets 100
toronto    noodles 275
vancouver  noodles 390
halifax    noodles 120
halifax    fish    200

I would like to ask for the highest-selling department at each store. The results should look like this:

toronto    baskets 500
vancouver  noodles 275
halifax    fish    200

Whenever I use GROUP BY, it includes all the listings from my subquery. Is there a nice clean way to do this without a temporary table?

Answer:
This works in Oracle, other implementations may have different syntax for analytic functions (or lack them entirely):
```
```
select store
     , max(department) keep(dense_rank last order by sales)
     , max(sales)
  from (
        ...query that generates your results...
       )
 group by store
```
```


Question:
I know you cannot use a alias column in the where clause for T-SQL; however, has Microsoft provided some kind of workaround for this?

Related Questions:

Unknown Column In Where Clause

Can you use an alias in the WHERE clause in mysql?

“Invalid column name” error on SQL statement from OpenQuery results

Answer:
One workaround would be to use a derived table.
For example:
```
```
select *
from
   (
   select a + b as aliased_column
   from table
   ) dt
where dt.aliased_column = something.
```
```
I hope this helps.


Question:
I currently have two text boxes which accept any number. I have a text block that takes the two numbers entered and calculates the average.

I was wondering if there was a way I could bind this text block to both text boxes and utilize a custom converter to calculate the average? I currently am catching the text changed events on both text boxes and calculating the average that way, but I am under the assumption data binding would be more efficient and easier.

Answer:
You're looking for
```
MultiBinding
```
.
Your
```
XAML
```
will look something like this:
```
```
<TextBlock>
  <TextBlock.Text>
    <MultiBinding Converter="{StaticResource myConverter}">
      <Binding Path="myFirst.Value" />
      <Binding Path="mySecond.Value" />
    </MultiBinding>
  </TextBlock.Text>
</TextBlock>
```
```
With reasonable replacements for
```
myConverter
```
,
```
myFirst.Value
```
, and
```
mySecond.Value
```
.


Question: I'd like to set up a large linear programming model to solve an interesting problem.  I would be most comfortable in Java.  What tools/libraries are available?

Answer:
I used
lp_solve
with success. It looks like there is a native Java API, but I've only used the text file interface. It supports the semi-standard MPS and LP file formats, which I found more convenient for trying out different solvers (such as
glpsol
).


Question:
When hosting a WCF service on IIS you have an option of manually configuring the endpoint or declaratively by means of WebServiceHostFactory. It doesn't seem to be that difficult to manually create the endpoint so I figured I would ask.

What are the benefits of using WebServiceHostFactory?

Are there any performance implications to dynamically creating the endpoints?

Answer:
Can you clarify : are you asking specifically about
Web
ServiceHostFactory (emph: "Web")? Or just the  difference between IIS hosting it vs starting your own server through code?
WebServiceHostFactory is new in .NET 3.5, and supports some of the newer AJAX/JSON stuff.
Actually, within IIS (using .svc), you are already using a ServiceHostFactory - simply the default one shipped with WCF. You can write your own factory if you want, and I've done this in the past to create a factory that
only
listens on https (I had an issues on a farm hosting multiple sites, where it couldn't identify the correct site for http, but https was fine - so I completely disabled http via the factory).
Performance shouldn't be any different as long as you don't go mad and listen on 200 end-points...
Generally, manually creating the server is used when you are hosting the server in (for example) a windows service. IIS is fine for some things, but app-pools get recycled, so aren't ideal for a server that needs to retain long-lived state. IIS has the advantage of being much easier to configure, especially with security (SSL etc) and compression.


Question:
I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:

warning: HEAP[test.exe]:
warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1

How can I track down where this is happening at? Viewing the memory doesn't give me any clues.

Thanks!

Answer:
So you're busting your heap. Here's a nice
GDB tutorial
to keep in mind.
My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way.
Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).


Question: How do I query the iPhone's current IP address?

Answer:
You can try to use similar to this service:
Whatismyip
and capture the string :)
Credit to Erica Sadun's iPhone Developer's Cookbok, 2nd ed, page 555.


Question:
Question: Is there an easy way (library function) to perform a bitwise AND or OR on numbers larger than 32-bit in ActionScript?

From the docs:
"Bitwise operators internally manipulate floating-point numbers to change them into 32-bit integers. The exact operation performed depends on the operator, but all bitwise operations evaluate each binary digit (bit) of the 32-bit integer individually to compute a new value."

Bummer...

I can't use the & or | ops - does AS expose a library function to do this for Numbers?

Specifics: I'm porting a bunch of java to flex and the java maintains a bunch of 'long' masks.  I know that I can split the Java masks into two ints on the flex side.  Since all of my mask manip is localized this won't be too painful.  However, I'd like to keep the port as 1-1 as possible.

Any suggestions?
Thanks!

Answer:
According to
http://livedocs.adobe.com/flex/3/html/help.html?content=03_Language_and_Syntax_11.html
, there are no 64-bit integers (signed or unsigned)...only 32-bit.
The Number type, as you mentioned above, has a 53-bit mantissa, which is too short for you.
I searched for a BigNum FLEX implementation, but couldn't find one.
I'm guessing that you will have to simulate this with either an array of ints or a class with a high and low int.
Good Luck,
Randy Stegbauer


Question:
I am developing an iPhone application, in my table view I wanted custom color for Cell Selection Style, I read the UITableViewCell Class Reference but there are only three constants defined for Selection style (Blue, Gray, None). I saw one application that used a different color than those defined in the reference.

How can we use a color other than those defined in the reference?

Answer:
Override didSelectRowAtIndexPath: and draw a UIView of a color of your choosing and insert it behind the UILabel inside the cell. I would do it something like this:
```
```
UIView* selectedView; //inside your header

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

  UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
  selectedView = [[UIView alloc] initWithFrame:[cell frame]];
  selectedView.backgroundColor = [UIColor greenColor]; //whatever

  [cell insertSubview:selectedView atIndex:0]; //tweak this as necessary
  [selectedView release]; //clean up

}
```
```
You can choose to animate this view out when it gets deselected and will satisfy your requirements.


Question: Please advise how to scrape AJAX pages.

Answer:
Depends on the ajax page.  The first part of screen scraping is determining how the page works.  Is there some sort of variable you can iterate through to request all the data from the page?  Personally I've used
Web Scraper Plus
for a lot of screen scraping related tasks because it is cheap, not difficult to get started, non-programmers can get it working relatively quickly.
Side Note: Terms of Use is probably somewhere you might want to check before doing this.  Depending on the site iterating through everything may raise some flags.


Question:
Whats the normal procedure of clearing a form after POST? Just loop through the textboxes and cleat all text? I have an ASP.NET application with several forms and I am trying to avoid them sending the data twice?

Thanks

Answer:
You can inject some javascript code to execute after postback.
```
```
document.forms[0].reset();
document.forms[1].reset();
```
```
From server side, I haven't found an easy way to reset the form contents other than iterating through the controls inside a loop or doing a
Server.Transfer
back to the same page.


Question:
I'm tasked with replicating a production environment to create many test/sit environments.

One of the things I need to do is build up Perl, with all the modules which have been installed (including internal and external modules) over the years. I could just use CPAN.pm autobundle, but this will result in the test environment having much newer versions of the external modules that production has.

What is the easiest/best way to get and install (a lot of) version specific Perl modules.

Answer:
Make your own CPAN mirror with exactly what you want.
Stratopan.com
, a service, and
Pinto
, tools that's built on top of, can help you do that.
The CPAN tools only install the latest version of any distribution because PAUSE only indexes the latest version. However, you can create your own, private CPAN that has exactly the distributions that you want. Once you have your own CPAN mirror with only what you want, you point your CPAN tools at only that mirror so it only installs those versions. More on that in a minute.
Now, you want to have several versions of that. You can create as many mirrors as you like, and you can also put the mirrors in source control so you can check out any version of the mirror that you like.
Tools such as CPAN::Mini::Inject can help you set up your own CPAN. Check out
my talks on Slideshare
for the basic examples, and some of
my videos on Vimeo
for some of the demonstrations. Look at anything that has "CPAN" or "BackPAN" in the title. I think I might have some stuff about it in
The Perl Review
too, or should by the next issue. :)
Lately, I've been working on a program called dpan (for DarkPAN) that can look at random directories, find Perl distributions in them, and create the structure and index files that you need. You run dpan, you get a URL to point your CPAN client toward, and off you go. It's part of my MyCPAN-Indexer project, which is in
Github
. It's not quite ready for unsupervised public use because I mostly work with corporate clients to customize their setup. If you're interested in that, feel free to ask me questions though.
Also, I recently released
CPAN::PackageDetails
that can help you build the right index file. It's still a bit young too, but again, if you need something special, just ask.


Question:
My question is how do I configure an EJB 3.0 style message driven bean to use a configured JMS datasource in jboss.

For example, my MDB looks something like:

@MessageDriven(mappedName = "ExampleMDB", activationConfig = {

        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "MyTopic"),
        @ActivationConfigProperty(propertyName = "channel", propertyValue = "MyChannel"),

})
@ResourceAdapter(value = "wmq.jmsra.rar")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
@TransactionManagement(TransactionManagementType.BEAN)
public class MyMDB implements MessageListener {
 .....
}

But I would like the bean to attached to a given JMS datasource ( in the case of jboss 4.2.2 this is in deploy/jms/jms-ds.xml). Perhaps this is not even possible but is worth asking.

Answer:
Make your own CPAN mirror with exactly what you want.
Stratopan.com
, a service, and
Pinto
, tools that's built on top of, can help you do that.
The CPAN tools only install the latest version of any distribution because PAUSE only indexes the latest version. However, you can create your own, private CPAN that has exactly the distributions that you want. Once you have your own CPAN mirror with only what you want, you point your CPAN tools at only that mirror so it only installs those versions. More on that in a minute.
Now, you want to have several versions of that. You can create as many mirrors as you like, and you can also put the mirrors in source control so you can check out any version of the mirror that you like.
Tools such as CPAN::Mini::Inject can help you set up your own CPAN. Check out
my talks on Slideshare
for the basic examples, and some of
my videos on Vimeo
for some of the demonstrations. Look at anything that has "CPAN" or "BackPAN" in the title. I think I might have some stuff about it in
The Perl Review
too, or should by the next issue. :)
Lately, I've been working on a program called dpan (for DarkPAN) that can look at random directories, find Perl distributions in them, and create the structure and index files that you need. You run dpan, you get a URL to point your CPAN client toward, and off you go. It's part of my MyCPAN-Indexer project, which is in
Github
. It's not quite ready for unsupervised public use because I mostly work with corporate clients to customize their setup. If you're interested in that, feel free to ask me questions though.
Also, I recently released
CPAN::PackageDetails
that can help you build the right index file. It's still a bit young too, but again, if you need something special, just ask.


Question:
I'd like to receive error logs via email. For example, if a Warning-level error message should occur, I'd like to get an email about it.

How can I get that working in CodeIgniter?

Answer:
You could extend the Exception core class to do it.
Might have to adjust the reference to CI's email class, not sure if you can instantiate it from a library like this. I don't use CI's email class myself, I've been using the Swift Mailer library. But this should get you on the right path.
Make a file MY_Exceptions.php and place it in /application/libraries/ (Or in /application/core/ for CI 2)
```
```
class MY_Exceptions extends CI_Exceptions {

    function __construct()
    {
        parent::__construct();
    }

    function log_exception($severity, $message, $filepath, $line)

    {
        if (ENVIRONMENT === 'production') {
            $ci =& get_instance();

            $ci->load->library('email');
            $ci->email->from('your@example.com', 'Your Name');
            $ci->email->to('someone@example.com');
            $ci->email->cc('another@another-example.com');
            $ci->email->bcc('them@their-example.com');
            $ci->email->subject('error');
            $ci->email->message('Severity: '.$severity.'  --> '.$message. ' '.$filepath.' '.$line);
            $ci->email->send();
        }

        parent::log_exception($severity, $message, $filepath, $line);
    }

}
```
```


Question:
I'm looking for suggestions for a beginner level ASP/XML test.  Essentially I'm trying to hire an extremely junior programmer.  I'm in the process of trying to hire a junior programmer to help maintain a large code base of somewhat repetitive ASP pages.  I'm slowly in the process of making more modular, maintainable code but until that happens I'm trying to get away from having to change "one little thing" too often.

Anyway I'm looking for suggestions of ways to test for ability to handle these tasks.  The applications I've been getting are people with minimal technical experience looking to "break into IT."  I'm all for giving someone a chance, but I also want to test for some base level ability.

Answer:
I would ask some basic math questions involving sets, statistics and the like. That kind of question can be somewhat hard, as they don´t depend on a background in IT.
If you want to include some programming questions I would ask something in the line:
"How do you implement integer division without using the division operator"
Another idea is teach them on the spot a made up language, something like
logo
, with four basic commands and some loop directives and ask then to draw squares, circles and what not with it.


Question: What does "type-safe" mean?

Answer:
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Some simple examples:
```
```
// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";
```
```
This also applies to method arguments, since you are passing explicit types to them:
```
```
int AddTwoNumbers(int a, int b)
{
    return a + b;
}
```
```
If I tried to call that using:
```
```
int Sum = AddTwoNumbers(5, "5");
```
```
The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.
In a loosely typed language, such as javascript, I can do the following:
```
```
function AddTwoNumbers(a, b)
{
    return a + b;
}
```
```
if I call it like this:
```
```
Sum = AddTwoNumbers(5, "5");
```
```
Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:
```
```
function AddTwoNumbers(a, b)
{
    return Number(a) + Number(b);
}
```
```
Or, possibly:
```
```
function AddOnlyTwoNumbers(a, b)
{
    if (isNaN(a) || isNaN(b))
        return false;
    return Number(a) + Number(b);
}
```
```
if I call it like this:
```
```
Sum = AddTwoNumbers(5, " dogs");
```
```
Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".
Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.
While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.
Now, back to C#...
C# supports a language feature called
covariance
, this basically means that you can substitute a base type for a child type and not cause an error, for example:
```
```
public class Foo : Bar
 {
 }
```
```
Here, I created a new class (Foo) that subclasses Bar. I can now create a method:
```
```
void DoSomething(Bar myBar)
```
```
And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.
However, you cannot do the inverse:
```
```
void DoSomething(Foo myFoo)
```
```
In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.
Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)


Question:
This drop down list, displaying all the files from a folder, one of which will be selected for use. Is there a way to show which file is selected when you load the page? At the moment it says "select a file" every time.

<select name="image" type="text" class="box" id="image" value="<?=$image;?>">
<option value='empty'>Select a file</option>
<?php

$dirname = "images/";
$images = scandir($dirname);

// This is how you sort an array, see http://php.net/sort
natsort($images);

// There's no need to use a directory handler, just loop through your $images array.
foreach ($images as $file) {
    if (substr($file, -4) == ".gif") {
        print "<option value='$file'>$file</option>\n"; }
    }
?>
</select>

Answer:
Type safety means that the compiler will validate types while compiling, and throw an error if you try to assign the wrong type to a variable.
Some simple examples:
```
```
// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";
```
```
This also applies to method arguments, since you are passing explicit types to them:
```
```
int AddTwoNumbers(int a, int b)
{
    return a + b;
}
```
```
If I tried to call that using:
```
```
int Sum = AddTwoNumbers(5, "5");
```
```
The compiler would throw an error, because I am passing a string ("5"), and it is expecting an integer.
In a loosely typed language, such as javascript, I can do the following:
```
```
function AddTwoNumbers(a, b)
{
    return a + b;
}
```
```
if I call it like this:
```
```
Sum = AddTwoNumbers(5, "5");
```
```
Javascript automaticly converts the 5 to a string, and returns "55". This is due to javascript using the + sign for string concatenation. To make it type-aware, you would need to do something like:
```
```
function AddTwoNumbers(a, b)
{
    return Number(a) + Number(b);
}
```
```
Or, possibly:
```
```
function AddOnlyTwoNumbers(a, b)
{
    if (isNaN(a) || isNaN(b))
        return false;
    return Number(a) + Number(b);
}
```
```
if I call it like this:
```
```
Sum = AddTwoNumbers(5, " dogs");
```
```
Javascript automatically converts the 5 to a string, and appends them, to return "5 dogs".
Not all dynamic languages are as forgiving as javascript (In fact a dynamic language does not implicity imply a loose typed language (see Python)), some of them will actually give you a runtime error on invalid type casting.
While its convenient, it opens you up to a lot of errors that can be easily missed, and only identified by testing the running program. Personally, I prefer to have my compiler tell me if I made that mistake.
Now, back to C#...
C# supports a language feature called
covariance
, this basically means that you can substitute a base type for a child type and not cause an error, for example:
```
```
public class Foo : Bar
 {
 }
```
```
Here, I created a new class (Foo) that subclasses Bar. I can now create a method:
```
```
void DoSomething(Bar myBar)
```
```
And call it using either a Foo, or a Bar as an argument, both will work without causing an error. This works because C# knows that any child class of Bar will implement the interface of Bar.
However, you cannot do the inverse:
```
```
void DoSomething(Foo myFoo)
```
```
In this situation, I cannot pass Bar to this method, because the compiler does not know that Bar implements Foo's interface. This is because a child class can (and usually will) be much different than the parent class.
Of course, now I've gone way off the deep end and beyond the scope of the original question, but its all good stuff to know :)


Question:
Via command line, I usually do this:

cp -rRp /path/to/a\_folder/. /path/to/another\_folder

This copies just the contents underneath a_folder to another_folder. In SVN I need to do the same thing, but can't figure it out. I always end up with this:

/path/to/another\_folder/a\_folder

SVN throws up even when I try this:

svn copy file:///path/to/a\_folder/* file:///path/to/another\_folder

It says it does not exist.

EDIT:

This would probably help. The directory structure for my project looks like this:

my_project
  /branches
  /tags
  /trunk
  /vendor
    /1.1

I need to get the contents of 1.1 under vendor into the trunk without it actually copying the 1.1 folder.

Answer:
Have you considered using svn merge?
Given a repo like this:
```
```
trunk/a_folder/foo
trunk/a_folder/bar
trunk/new_folder/baz
```
```
use these commands to merge the foo and bar directories:
```
```
cd trunk/new_folder
svn merge -r1:HEAD http://svn/repo/trunk/a_folder .
```
```


Question:
Can an abstract class have a constructor?

If so, how can it be used and for what purposes?

Answer:
Consider this:
```
```
abstract class Product {
    int value;
    public Product( int val ) {
        value= val;
    }
    abstract public int multiply();
}

class TimesTwo extends Product {
    public int mutiply() {
       return value * 2;
    }
}
```
```
The superclass is abstract and has a constructor.


Question: I have been using PLT Scheme, but it has some issues. Does anyone know of a better implementation for working through SICP?

Answer:
Use
MIT Scheme
.
It's recommended by the authors of SICP, and is used at MIT for the
6.001: Structure and Interpretation of Computer Programs
course.


Question:
I'm looking for one line code examples in various languages for getting a valid MD5 result (as a string, not a bytehash or what have you).  For instance:

PHP:
$token = md5($var1 . $var2);

I found VB especially troublesome to do in one line.

Answer:
Python
```
```
token = __import__('md5').new(var1 + var2).hexdigest()
```
```
or, if
```
md5
```
is alrady imported:
```
```
token = md5.new(var1 + var2).hexdigest()
```
```
Thanks to Greg Hewgill


Question:
Here is some simple Perl to count the number of times a value occurs in an array. This runs without any warnings.

use warnings;
use strict;

my @data = qw(1 1 2 3 4 5 5 5 9);
my %histogram;
foreach (@data)
{
    $histogram{$_}++;
}

When the loop body is changed to

$histogram{$_} = $histogram{$_} + 1;

Perl warns "Use of uninitialized value in addition".

What is going on under the hood? Why is the value initialized when supplied as an operand to the ++ operator and uninitialized with the + operator?

Answer:
The + operator evaluates both the form to the left and the form to the right of it, then returns the sum of both.  The hash call evaluation does not see any special context.
The ++ operator has some special magic built in. Quoting from the perlop manpage, regarding the ++ operator:
"undef" is always treated as numeric, and in particular is changed to 0 before incrementing (so that a post-increment of an undef value will return 0 rather than "undef").
edit
: To elaborate on the difference, ++ changes the value in place, while + just takes its arguments as input.  When + sees an undefined value, typically something has gone wrong, but for ++, your hash manipulation example is very typical -- the user wants to treat undef as 0, instead of having to check and initialize everytime.  So it seems that it makes sense to treat these operators this way.


Question:
I'm using a RichTextBox (.NET WinForms 3.5) and would like to override some of the standard ShortCut keys....
For example, I don't want Ctrl+I to make the text italic via the RichText method, but to instead run my own method for processing the text.

Any ideas?

Answer:
Set the RichtTextBox.ShortcutsEnabled property to true and then handle the shortcuts yourself, using the KeyUp event. E.G.
```
```
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.textBox1.ShortcutsEnabled = false;
            this.textBox1.KeyUp += new KeyEventHandler(textBox1_KeyUp);
        }

        void textBox1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Control == true && e.KeyCode == Keys.X)
                MessageBox.Show("Overriding ctrl+x");
        }
    }
}
```
```


Question: I have a Tapestry PropertyModel for gender.  Right now the dropdown just shows Male and Female because those are the only values in my model. I'd like to add a "Choose an Option" option.  Is there a standard way to do this without having to add a fake value to my model?  I'd also like it to be smart enough to know that if the field is required, they can't leave it set to "Choose an Option".

Answer:
One solution is to use the LabeledPropertySelectionModel to wrap the real model like:
```
```
new LabeledPropertySelectionModel(new GenderModel(), "Choose an Option")
```
```
The JavaDoc for that class says:
Decorates an underlying IPropertySelectionModel adding an initial property. The label option, and value of the initial property are configurable.


Question: Are the two events the same or are there differences that we should take note when coding the keyboard presses?

Answer:
The key down event happens as soon as the user presses a key, the key up event happens when they release the key after pressing it.
So if you use the key up event, and the user presses a key and holds it for 5 seconds, nothing will happen until they let go of it.
(Note: I know nothing about .net, I've just used 'key up' and 'key down' events in other libraries.)


Question:
I've got an embedded Windows Media player in an HTML page, and when the audio gets to the end, it just starts again from the beginning.

According to the documentation, there's an autorewind parameter/attribute and also a loop.

The problem is, I've set both of those to false (and/or zero) and it doesn't seem to make any difference.

Might this be a bug? My client is WMP 10.00.00.4058. Maybe there's some kind of setting on the server which tells files to loop, is that a crazy idea?

Answer:
compare your html code with this:
stolen from
http://www.programmingforums.org/post147977.html
```
```
<object width="320" height="290"
classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95"
id="mediaplayer1">
<param name="Filename" value="kids.mpg">
<param name="AutoStart" value="True">
<param name="ShowControls" value="True">
<param name="ShowStatusBar" value="False">
<param name="ShowDisplay" value="False">
<param name="AutoRewind" value="True">
<embed
type="application/x-mplayer2"
pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/MediaPlayer/"
width="320" height="290" src="/support/dreamweaver/ts/documents/kids.mpg"
filename="kids.mpg" autostart="True"
showcontrols="True" showstatusbar="False"
showdisplay="False" autorewind="True">
</embed>
</object>
```
```


Question:
I have a menu with an animation going on, but I want to disable the click while the animation is happening.

<div></div>
<div></div>
<div></div>

$("div").click(function() {
  $(this).animate({height: "200px"}, 2000);
  return false;
});

However, I want to disable all the buttons while the event is happening, AND disable the div that was clicked.

I was thinking of adding a class to the div that's clicked and putting the click only on the divs without that class:

$("div").not("clicked").click(function() {
  $(this).animate({height: "200px"}, 2000).addClass("clicked");
  return false;
});

But this doesn't appear to work (I think it does logically)?

Any help appreciated.

Cheers,

Steve

Answer:
```
```
$("div").click(function() {
    if (!$(this).parent().children().is(':animated')) {
        $(this).animate({height: "200px"}, 2000);
    }
    return false;
});
```
```


Question: I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?

Answer:
Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like
this
example, you can use other libraries, like
cookie-js
, a small
(< 100 lines)
utility for cookie access.
I personally use jQuery on my projects, and I use the
jQuery Cookie Plugin
, it's really simple to use:
```
```
var cookieName = "increment";

if ($.cookie(cookieName) == null){
  $.cookie(cookieName, 1, { expires: 10 });
}else{
  var newValue = Number($.cookie(cookieName)) + 1;
  $.cookie(cookieName, newValue, { expires: 10 });
}
```
```


Question: I know that this question has already been asked HERE but sadly none of the answers suggest a javascript standalone shell that has auto completion.  I am reopening this question again, in the hope that some new answers might be found.

Answer:
http://www.faqts.com/knowledge_base/view.phtml/aid/1438
lists some JavaScript interpreters.  I am not about to download them to confirm they have (tab?) completion.
[I'm not sure what you mean by auto-completion, since that implies more of an IDE-type approach].
Is this for web-based development/debugging?  If so, I can really recommend the squarefree
JS shell
bookmarklet for Firefox, which was listed in the linked post.  True, it is not standalone, but does have tab completion.


Question:
I wanted to try a little design by contract in my latest C# application and wanted to have syntax akin to:

public string Foo()
{
    set {
        Assert.IsNotNull(value);
        Assert.IsTrue(value.Contains("bar"));
        _foo = value;
    }
}

I know I can get static methods like this from a unit test framework, but I wanted to know if something like this was already built-in to the language or if there was already some kind of framework floating around. I can write my own Assert functions, just don't want to reinvent the wheel.

Answer:
Aside from using an external library, you have a simple assert in System.Diagnostics:
```
```
using System.Diagnostics

Debug.Assert(value != null);
Debug.Assert(value == true);
```
```
Not very useful, I know.


Question:
I have written a few MSBuild custom tasks that work well and are use in our CruiseControl.NET build process.

I am modifying one, and wish to unit test it by calling the Task's Execute() method.

However, if it encounters a line containing

Log.LogMessage("some message here");

it throws an InvalidOperationException:

Task attempted to log before it was initialized. Message was...

Any suggestions? (In the past I have mostly unit-tested Internal static methods on my custom tasks to avoid such problems.)

Answer:
If you have implemented the interface ITask you will have to initialise the Log class yourself.
Otherwise you should just inherit from
Task
in Microsoft.Build.Utilities.dll
That implements
ITask
and does a lot of the leg work for you.
Here is the reference page for building a custom task, it explains quite a lot of it.
Building a custom MSBuild task reference
Also worth a look is
How to debug a custom MSBuild task
Other then that could you post the MSBuild XML you are using for calling your custom task.
The code itself would obviously be the most help :-)


Question:
I have a web application that's branded according to the user that's currently logged in. I'd like to change the favicon of the page to be the logo of the private label, but I'm unable to find any code or any examples of how to do this. Has anybody successfully done this before?

I'm picturing having a dozen icons in a folder, and the reference to which favicon.ico file to use is just generated dynamically along with the HTML page. Thoughts?

Answer:
The favicon is declared in the head tag with something like:
```
```
<link rel="shortcut icon" type="image/ico" href="favicon.ico">
```
```
You should be able to just pass the name of the icon you want along in the view data and throw it into the head tag.


Question:
I want to convert a BYTE* into  an gdi+ Image object.

How can I do this?

The BYTE* seems a Dib point.

I found Image has a method named Image::FromStream() which may help,
But I can not find any reference about how to convert a BYTE* into a IStream object.
How can I do this?

Thanks in advance!

Actually, it is hard to believe MS provide a IStream interface, but do not provide any c++ MemoryStream class which implements the interface.

Answer:
Do you know the format of the image data the
```
BYTE
```
pointer points at? For Image to be able to construct itself from a stream, the data must be in one of the supported standard image formats (GIF, PNG, JPEG etc).
The
IStream
interface looks to be simple enough to implement on your own, if there's no suitable "memory stream" or similiar.