q:
What is the best way to layout a large django project?  The tutorials provide simple instructions for setting up apps, models, and views, but there is less information about how apps and projects should be broken down, how much sharing is allowable/necessary between apps in a typical project (obviously that is largely dependent on the project) and how/where general templates should be kept.

Does anyone have examples, suggestions, and explanations as to why a certain project layout is better than another?  I am particularly interested in the incorporation of large numbers of unit tests (2-5x the size of the actual code base) and string externalization / templates.

[A]
This page does a good job of addressing some of my questions:
http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/
Specifically:
To define custom template tags or filters, you must create a sub-directory in the application’s directory called templatetags, and it must contain a file named __init__.py so that it can be imported as a Python module.
To define unit tests which will automatically be noticed by Django’s testing framework, put them in a module called tests (which can be either a file named tests.py or a directory called tests). The testing framework will also find any doctests in that module, but the preferred place for those is, of course, the docstrings of the classes or functions they’re designed to test.
To provide custom SQL which will be executed immediately after your application is installed, create a sub-directory called sql inside the application’s directory; the file names should be the same as the names of the models whose tables they’ll operate on; for example, if you have an app named weblog containing a model named Entry, then the file sql/entry.sql inside the app’s directory can be used to modify or insert data into the entries table as soon as it’s been created.
The note about tests.py and tests (the directory) also holds for models, which helps address the problem of having way to many tests (or models) for one file.
I would still like to see some examples / suggestions for app/project break down, and  big django sites that work well.


q: What options do I have to publish Flash video from webcams other than Adobe's Flash Media Server and Red5? I would prefer a solution in .NET, Python or PHP but can't find anything.

[A]
Besides another commercial product, like
Wowza Media Server
, you could go with a CDN (Content Delivery Network), like
Limelight Networks
or
Voxel.net
.  You might even be able to find a local hosting provider that would serve up live Flash video for you.
(Live Flash video in a non-trivial thing to do, so the options are a bit limited.)

s: huggingface

c: devops

d: intermediate


q: I'm using Hudson and Maven 2 for my automated build/CI.  I can build fine with maven from the command line, but when I run the same goal with Hudson, the build fails complaining of missing artifacts.  I'm running Hudson as a windows XP service.


q:
Like the title says: Can reflection give you the name of the currently executing method.

I'm inclined to guess not, because of the Heisenberg problem.  How do you call a method that will tell you the current method without changing what the current method is?  But I'm hoping someone can prove me wrong there.

Update:

Part 2:  Could this be used to look inside code for a property as well?

Part 3:  What would the performance be like?

Final Result

I learned about MethodBase.GetCurrentMethod().  I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.

To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.

[A]
I think you should be able to get that from creating a
StackTrace
.  Or, as @
edg
and @
Lars Mæhlum
mention, MethodBase.
GetCurrentMethod
()


q:
A friend of mine told me there was a way to connect two private IPs without using a proxy server. The idea was that both computers connected to a public server and some how the server joined the private connections and won't use any more bandwidth.

Is this true? How's this technique named?

[A]
This is true.  It's the way
FogCreek Copilot
works
Take a look at item 2 on Joel's
Copilot 2.0 post
.


q:
I have a database with two tables (Table1 and Table2). They both have a common column [ColumnA] which is an nvarchar.

How can I select this column from both tables and return it as a single column in my result set?

So I'm looking for something like:

ColumnA in Table1:
a
b
c

ColumnA in Table2:
d
e
f

Result set should be:
a
b
c
d
e
f

[A]
```
```
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
```
```
Also, if you know the contents of Table1 and Table2 will
NEVER
overlap, you can use UNION ALL in place of UNION instead.  Saves a little bit of resources that way.
-- Kevin Fairchild


q:
I am looking for a simple JavaScript example that updates DOM.

Any suggestions?

[A]
I believe that this tutorial on jQuery has an example that might help you:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery


q: I am looking for some advice on what should I concentrate my efforts to get the needed skills to become a Java developer for Oracle applications. I'm bit confused as there are lot of technologies in the Java world. Where should I start? What to avoid? Is JDeveloper a good IDE for a beginner?

[A]
You should be able to do everything related to Oracle using
JDBC
, so make sure you bone up on that API.  Other than that, it depends on the type of application.  Standalone apps may use Swing (the Java UI toolkit) or in the future JavaFX, which is supposed to make Swing obsolete and may do so in a few years.  Web/enterprisey apps will make use of Java Enterprise Edition, so take a look at the servlet API, and if the app uses Enterprise JavaBeans, look at the
Java Persistence API
, which you would probably be using instead of JDBC.
I haven't used JDeveloper, but I haven't found anything wrong with the free IDEs like
Eclipse
or
Netbeans
, and my personal favorite is JetBrains's
IntelliJ IDEA
.


q:
This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.

array(
  0 => '-- SELECT --',
  1 => 'Afghanistan',
  2 => 'Albania',
  3 => 'Algeria',
  4 => 'American Samoa',
  5 => 'Andorra',)

The id's need to stay intact. So making them -1 or -2 will unfortunately not work.

[A]
My shortcut in similar cases is to add a space at the start of Canada and two spaces at the start of United States. If displaying these as options in a SELECT tag, the spaces are not visible but the sorting still brings them to the front.
However, that may be a little hacky in some contexts. In Java the thing to do would be to extend StringComparator, override the compare() method making the US and Canada special cases, then sort the list (or array) passing in your new comparator as the sort algorithm.
However I would imagine it might be simpler to just find the relevant entries in the array, remove them from the array and add them again at the start. If you are in some kind of framework which will re-sort the array, then it might not work. But in most cases that will do just fine.
[edit] I see that you are using a hash and not an array - so it will depend on how you are doing the sorting. Could you simply put the US into the hash with a key of -2, Canada with -1 and then sort by ID instead? Not having used PHP in anger for 11 years, I don't recall whether it has built-in sorting in its hashes or if you are doing that at the application level.


q:
Comparing string in C# is pretty simple.  In fact there are several ways to do it.  I have listed some in the block below.  What I am curious about are the differences between them and when one should be used over the others?  Should one be avoided at all costs?  Are there more I haven't listed?

string testString = "Test";
string anotherString = "Another";

if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}

(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)

[A]
From MSDN:
"The CompareTo method was designed primarily for use in sorting or
  alphabetizing      operations. It should not be used when the primary
  purpose of the method call is to     determine whether two strings are
  equivalent. To determine whether two strings are    equivalent, call
  the Equals method."
They suggest using
```
.Equals
```
instead of
```
.CompareTo
```
when looking solely for equality.  I am not sure if there is a difference between
```
.Equals
```
and
```
==
```
for the
```
string
```
class.  I will sometimes use
```
.Equals
```
or
```
Object.ReferenceEquals
```
instead of
```
==
```
for my own classes in case someone comes along at a later time and redefines the
```
==
```
operator for that class.


q: I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems.  SNMP, WMI, that sort of thing.  With most classes I can mock up objects to test them, but how do you deal with unit testing a real system?  For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?

[A]
Assuming you meant "How do I test against things that are hard/impossible to mock":
If you have a class that "goes out and gets the Win32_LogicalDisk object for a server" AND does something else (consumes the 'Win32_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use
Dependency Injection
to allow you to mock the 'Win32_LogicalDisk' object.  For instance:
```
```
class LogicalDiskConsumer(object):

    def __init__(self, arg1, arg2, LogicalDiskFactory)
        self.arg1=arg1
        self.arg2=arg2
        self.LogicalDisk=LogicalDiskFactory()

    def consumedisk(self):
        self.LogicalDisk.someaction()
```
```
Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32_LogicalDisk'.


q: In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?

[A]
Here's one way to do it:
```
```
import inspect

def get_subclasses(mod, cls):
    """Yield the classes in module ``mod`` that inherit from ``cls``"""
    for name, obj in inspect.getmembers(mod):
        if hasattr(obj, "__bases__") and cls in obj.__bases__:
            yield obj
```
```


q:
I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.

Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.

Thanks,
Adam

[A]
Does this help?
http://www.quirksmode.org/js/iframe.html
I only tested this in firefox, but if you have something like this:
```
```
<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>
```
```
You can get its address by using:
```
```
document.getElementById('myframe').src
```
```
Not sure if I understood your question correctly but anyways :)


q:
So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests.  I believe it--my code is difficult to test right now.  So how do I avoid global state?

The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments.  For example, I have a static class named "Globals" with a static member called "DBConnectionString."  When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString.  I load file paths, server names, and other information in the Globals class.

Some of my functions rely on the global variables.  So, when I test my functions, I have to remember to set certain globals first or else the tests will fail.  I'd like to avoid this.

Is there a good way to manage state information?  (Or am I understanding global state incorrectly?)

[A]
Dependency injection is what you're looking for. Rather than have those functions go out and look for their dependencies, inject the dependencies into the functions. That is, when you call the functions pass the data they want to them. That way it's easy to put a testing framework around a class because you can simply inject mock objects where appropriate.
It's hard to avoid some global state, but the best way to do this is to use factory classes at the highest level of your application, and everything below that very top level is based on dependency injection.
Two main benefits: one, testing is a heck of a lot easier, and two, your application is much more loosely coupled. You rely on being able to program against the interface of a class rather than its implementation.


q:
How do you shade alternating rows in a SQL Server Reporting Services report?

Edit: There are a bunch of good answers listed below--from quick and simple to complex and comprehensive. Alas, I can choose only one...

[A]
Go to the table row's BackgroundColor property and choose "Expression..."
Use this expression:
```
```
= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
```
This trick can be applied to many areas of the report.
And in .NET 3.5+ You could use:
```
```
= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
```
Not looking for rep--I just researched this question myself and thought I'd share.


q:
I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the .classpath file so that I can see the javadoc for the dependency in Eclipse. Then when I run Maven's eclipse plugin to regenerate the .classpath file it of course wipes out that change.

Is there a way to configure Maven's eclipse plug-in to automatically add classpath attributes for javadoc when running Maven's eclipse plug-in?

I'm only interested in answers  where the javadoc and/or sources are not provided for the dependency in the maven repository, which is the case most often for me. Using downloadSources and/or downloadJavadocs properties won't help this problem.

[A]
Would having the sources for the dependency help? You can tell the eclipse plugin to download those (and refer to them in the .classpath) with
```
-DdownloadSources=true
```


q: I would like to generate a random floating point number between 2 values.  What is the best way to do this in C#?

[A]
```
```
// generate a random number starting with 5 and less than 15
Random r = new Random();
int num = r.Next(5, 15);
```
```
For doubles you can replace Next with NextDouble


q: Every time I publish the application in ClickOnce I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?

[A]
You'll probably need to create a piece of code that updates AssemblyInfo.cs according to the version number stored in the .csproj file. (The ClickOnce deploy version is stored inside an XML tag.)
You'd then change your .csproj file to run this bit of code when Publish|Release build is performed. The MSBuild folks have blogged about how to perform custom actions during certain build types; check the
MSBuild team blog
.


q:
For this directory structure:

.
|-- README.txt
|-- firstlevel.rb
`-- lib
    |-- models
    |   |-- foo
    |   |   `-- fourthlevel.rb
    |   `-- thirdlevel.rb
    `-- secondlevel.rb

3 directories, 5 files

The glob would match:

firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb

[A]
In Ruby itself:
```
```
Dir.glob('**/*.rb') perhaps?
```
```


q: How do you generate C# classes for accessing WMI?

[A]
To generate strongly typed WMI classes, use the Management Strongly typed class generator (MgmtClassGen.exe).  It's usually in C:\Program Files\Microsoft Visual Studio X\SDK\vX\Bin.  The parameters are
at MSDN
and they even have
a page
describing the code generated.  If you have to do a lot of work with WMI, it's a lifesaver.


q: Are there any tools that will spider an asp.net website and create a static site?

[A]
http://www.httrack.com/
Have used for this purpose a few times, may need to do a little tidying up of urls, and some css linked images might not make it, depends on how good a job you want to do.
If you have dreamweaver, you can use that to manage the links if you need to clean up the file names afterwards.
Optionally use the link checker extension for firefox to check it all afterwards.


q:
Do you attach the images?

Use absolute urls?

How do you best avoid getting flagged as spam?

[A]
Campaign Monitor is a great resources for html email:
http://www.campaignmonitor.com/resources/#building
Also
http://www.email-standards.org/
, but seems down right now.


q: As Jeff Atwood asked: "What’s your logging philosophy? Should all code be littered with .logthis() and .logthat() calls? Or do you inject logging after the fact somehow?"

[A]
My logging philosophy is pretty easily summarized in four parts:
Auditing, or business logic logging
Log those things that are required to be logged.  This comes from the application requirements, and may include logging every change made to any database (as in many financial applications) or logging accesses to data (as may be required in the health industry to meet industry regulations)
As this is part of the program requirements many do not include it in their general discussions of logging, however there is overlap in these areas, and for some applications it is useful to consider all logging activities together.
Program logging
Messages which will help developers test and debug the application, and more easily follow the data flow and program logic to understand where implementation, integration, and other errors may exist.
In general this logging is turned on and off as needed for debugging sessions.
Performance logging
Add later logging as needed to find and resolve performance bottlenecks and other program issues which aren't causing the program to fail, but will lead to better operation.  Overlaps with Program logging in the case of memory leaks and some non-critical errors.
Security logging
Logging user actions and interactions with external systems where security is a concern.  Useful for determining how an attacker broke a system after an attack, but may also tie into an intrusion detection system to detect new or ongoing attacks.


q:
I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).

I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals?

[A]
It's useful for the
```
chmod
```
and
```
mkdir
```
functions in Unix land, but aside from that I can't think of any other common uses.


q:
I recently downloaded ndepend and ran an analysis on an open source project I participate in.

I did not now where to look next - a bit of visual and information overload and it turned out I don't even know where to start.

Can anyone suggest starting points?

What information should I look for first?

What points out problems in the code (in a BIG way)?

What would the low hanging fruit that can immediately seen?

[A]
Scott Hanselman / Stuart Celarier / Patrick Cauldwell's
poster
with ndepend metrics has some useful information on it. Rather than trying to break down all the heuristics being used I'd focus on only a few at a time starting with "zone of pain / zone of uselessness" and cyclomatic complexity.
There is also a
podcast
which covers some of the basics of the tool.
Between that and running nDepend on a few different projects you may be able to start gathering useful data that you can make into insights.


q:
In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?

My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data.

Do I have to choose between performance and data integrity?

If so, is in general better to go one way or is it particular to the case?

Are there other alternatives?

[A]
Maybe something like this?
```
```
const std::vector<mydata>& getData()
{
  return _myPrivateData;
}
```
```
The benefit here is that it's very, very simple, and as safe as you getin C++.  You can cast this, like RobQ suggests, but there's nothing you can do that would prevent someone from that if you're not copying.  Here, you would have to use
```
const_cast
```
, which is pretty easy to spot if you're looking for it.
Iterators, alternatively, might get you pretty much the same thing, but it's more complicated.  The only added benefit of using iterators here (that I can think of) is that you can have better encapsulation.


q: How can I create an empty one-dimensional string array?

[A]
Not sure why you'd want to, but the C# way would be
```
```
string[] newArray = new string[0];
```
```
I'm guessing that VB won't be too dissimilar to this.
If you're building an empty array so you can populate it with values later, you really should consider using
```
```
List<string>
```
```
and converting it to an array (if you really need it as an array) with
```
```
newListOfString.ToArray();
```
```


q:
I heard on a recent podcast (Polymorphic) that it is possible to cache a user control as opposed to the entire page.

I think my header control which displays static content and my footer control could benefit from being cached.

How can I go about caching just those controls?

[A]
Take a look
here
You can use
```
VaryByParam
```
and
```
VaryByControl
```
in the output cache.


q: What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion?  All the .svn folders are already in place.  I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN  Repository browser.

[A]
Dunno exactly what happens within eclipse, I presume it does some funky stuff in the .metadata directory of the workspace.  That said, I would recommend the following to get eclipse to learn about the svn settings of the project:
Delete the project from the workspace (keep "Delete project contents on disk" unchecked)
File > Import... > General > Existing Projects into Workspace
Browse to the folder containing the original project(s) of interest
Import the projects into your workspace
This seems to have the side effect of subclipse noticing the subversion settings when importing the "new" projects into your workspace.


q:
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:

ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"

where subCategory is a page property that looks like this:

protected SubCategory subCategory
{
    get
    {
        var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
        return subCategory;
    }
}

[A]
I dont' think calling a Generic Method on a webservice is possible.
If you look at the service description of two identical methods, one generic, one not:
```
```
[WebMethod]
public string[] GetSearchList(string prefixText, int count)
{
}

[WebMethod]
public string[] GetSearchList2<T>(string prefixText, int count)
{
}
```
```
They are identical.  It appears that both SOAP 1.x and HTTP POST do not allow this type of operation.


q:
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.)

I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.

[A]
```
```
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
```
```
```
```
'a,b,c,d'
```
```
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
```
```
my_string = ','.join(map(str, my_list))
```
```


q:
I'm on .NET 2.0, running under Medium Trust (so TimeZoneInfo and the Registry are not allowed options).  I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST.

This probably isn't even a valid scenario unless I have some very robust support, a la TimeZoneInfo, to differentiate between all of the different varieties of Time Zones in the first place.

[A]
Well, since
```
TimeZoneInfo
```
is excluded, you're probably not going to find a solution in the framework itself (but don't quote me on that).
In which case, have you considered reflectoring the
```
TimeZoneInfo
```
class and using what you find there?


q:
Scenario: Document library in SharePoint with column x of "Person or Group" type.  From within a VBA macro (or VSTO add-in) we're trying to access the MetaProperty on the document to set/get the user name.  Any attempt to access the value via the ContentTypeProperties collection throws a

Type MisMatch error (13).

The Type property of the MetaProperty object says it's msoMetaPropertyTypeUser.  I cannot find any examples of how to work with MetaProperties of this type.  Anyone have any experience with this?

Thanks!

[A]
Are you executing the programs directly or going through the shell?  If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.
EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick.  No shell, no shell evaluation.  Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that.


q: Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications?  If so, any success stories or tragedies to avoid?  If you did use it, how did you handle security?

[A]
I use WebORB for .NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following:
Override your DataContext's constructor and add the following code:
```
```
this.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(q => q.Payments);
dlo.LoadWith<Order>(q => q.Customer);
this.LoadOptions = dlo;
```
```
This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum.
Hope this helps you in some way. It's definitely one of those little "gotchas" when working with Flex/WebORB and LINQ.


q: I see __all__ in __init__.py files. What does it do?

[A]
It's a list of public objects of that module, as interpreted by
```
import *
```
. It overrides the default of hiding everything that begins with an underscore.


q: Does the Java language have delegate features, similar to how C# has support for delegates?

[A]
Short story: no
.
Introduction
The newest version of the Microsoft Visual J++ development environment
supports a language construct called
delegates
or
bound method
references
. This construct, and the new keywords
```
delegate
```
and
```
multicast
```
introduced to support it, are not a part of the Java
TM
programming language, which is specified by the
Java Language
Specification
and amended by the
Inner Classes Specification
included
in the
documentation for the JDKTM 1.1 software
.
It is unlikely that the Java programming language will ever include
this construct. Sun already carefully considered adopting it in 1996,
to the extent of building and discarding working prototypes. Our
conclusion was that bound method references are unnecessary and
detrimental to the language. This decision was made in consultation
with Borland International, who had previous experience with bound
method references in Delphi Object Pascal.
We believe bound method references are
unnecessary
because another
design alternative,
inner classes
, provides equal or superior
functionality. In particular, inner classes fully support the
requirements of user-interface event handling, and have been used to
implement a user-interface API at least as comprehensive as the
Windows Foundation Classes.
We believe bound method references are
harmful
because they detract
from the simplicity of the Java programming language and the
pervasively object-oriented character of the APIs. Bound method
references also introduce irregularity into the language syntax and
scoping rules. Finally, they dilute the investment in VM technologies
because VMs are required to handle additional and disparate types of
references and method linkage efficiently.


q:
My app has many controls on its surface, and more are added dynamically at runtime.

Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc).

What are your tips and tricks to improve WinForms app performance?

[A]
Are you making good use of
```
SuspendLayout()
```
and
```
ResumeLayout()
```
?
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx


q:
Is there any efficiency difference in an explicit vs implicit inner join?
For example:

SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;

vs.

SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;

[A]
Performance wise, they are exactly the same (at least in SQL Server).
PS: Be aware that the
```
IMPLICIT OUTER JOIN
```
syntax is deprecated since SQL Server 2005. (The
```
IMPLICIT INNER JOIN
```
syntax as used in the question is still supported)
Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing


q: Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good.

[A]
Expert .NET 2.0 IL Assembler  by Serge Lidin
There was a 1.1 version of the same book, but I haven't seen anything for the latest .NET release.  It's an excellent book.  I used it to write an OCR component in MSIL, as a learning project.
[Edit] @Curt is right, 3.0 and 3.5 are just extensions to 2.0, I hadn't plugged that in to my head yet.  Now I've thought of a fun geek project... compare the disassembly of standard 2.0 code to the new LINQ/Lambda way of performing common tasks like filtering lists.  For some reason I assumed that the magic was happening in new IL features, not just the compiler.


q:
Can you cast a List<int> to List<string> somehow?

I know I could loop through and .ToString() the thing, but a cast would be awesome.

I'm in C# 2.0 (so no LINQ).

[A]
Is C# 2.0 able to do
```
List<T>.Convert
```
? If so, I think your best guess would be to use that with a delegate:
```
```
List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Convert(delegate (int i) { return i.ToString(); });
```
```
Something along those lines.
Glenn's answer is probably the correct code ;-)


q: I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?

[A]
Well, for one I'd say a main advantage is that F# compiles against the .NET platform which makes it easy to deploy on windows. I've seen examples which explained using F# combined with ASP.NET to build web applications ;-)
On the other hand, Haskell has been around for waaaaay longer, so I think the group of people who are real experts on that language is a lot bigger.
For F# I've only seen one real implementation so far, which is the Singularity proof of concept OS. I've seen more real world implementations of Haskell.


q:
Having briefly looked at Haskell recently, what would be a brief, succinct, practical explanation as to what a monad essentially is?

I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.

[A]
But,
You could have invented Monads!
sigfpe says:
But all of these introduce monads as something esoteric in need of explanation. But what I want to argue is that they aren't esoteric at all. In fact, faced with various problems in functional programming you would have been led, inexorably, to certain solutions, all of which are examples of monads. In fact, I hope to get you to invent them now if you haven't already. It's then a small step to notice that all of these solutions are in fact the same solution in disguise. And after reading this, you might be in a better position to understand other documents on monads because you'll recognise everything you see as something you've already invented.
Many of the problems that monads try to solve are related to the issue of side effects. So we'll start with them. (Note that monads let you do more than handle side-effects, in particular many types of container object can be viewed as monads. Some of the introductions to monads find it hard to reconcile these two different uses of monads and concentrate on just one or the other.)
In an imperative programming language such as C++, functions behave nothing like the functions of mathematics. For example, suppose we have a C++ function that takes a single floating point argument and returns a floating point result. Superficially it might seem a little like a mathematical function mapping reals to reals, but a C++ function can do more than just return a number that depends on its arguments. It can read and write the values of global variables as well as writing output to the screen and receiving input from the user. In a pure functional language, however, a function can only read what is supplied to it in its arguments and the only way it can have an effect on the world is through the values it returns.


q: Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them?

[A]
if you set ENV['GEM_PATH'] correctly before using rubygems, then gems will work
sometimes
under IronRuby.  I'm actually looking at fixing this right now.
Also, this kind of question is probably better suited for the
IronRuby mailing list
than it is for StackOverflow.


q:
How can one determine, in code, how long the machine is locked?

Other ideas outside of C# are also welcome.

I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.

I'll write it up anyway and see if it works. Thanks everyone!

[A]
Below is the 100% working code to find if the PC is locked or not.
Before using this use the namespace
```
System.Runtime.InteropServices
```
.
```
```
[DllImport("user32", EntryPoint = "OpenDesktopA", CharSet = CharSet.Ansi,SetLastError = true, ExactSpelling = true)]
private static extern Int32 OpenDesktop(string lpszDesktop, Int32 dwFlags, bool fInherit, Int32 dwDesiredAccess);

[DllImport("user32", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern Int32 CloseDesktop(Int32 hDesktop);

[DllImport("user32", CharSet = CharSet.Ansi,SetLastError = true,ExactSpelling = true)]
private static extern Int32 SwitchDesktop(Int32 hDesktop);

public static bool IsWorkstationLocked()
{
    const int DESKTOP_SWITCHDESKTOP = 256;
    int hwnd = -1;
    int rtn = -1;

    hwnd = OpenDesktop("Default", 0, false, DESKTOP_SWITCHDESKTOP);

    if (hwnd != 0)
    {
        rtn = SwitchDesktop(hwnd);
        if (rtn == 0)
        {
            // Locked
            CloseDesktop(hwnd);
            return true;
        }
        else
        {
            // Not locked
            CloseDesktop(hwnd);
        }
    }
    else
    {
        // Error: "Could not access the desktop..."
    }

    return false;
}
```
```


q:
I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?

string[] sa = {"one", "two", "three"};
sa[1].Dump();

var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'

[A]
As the comment says, you cannot apply indexing with
```
[]
```
to an expression of type
```
System.Collections.Generic.IEnumerable<T>
```
. The IEnumerable interface only supports the method
```
GetEnumerator()
```
. However with LINQ you can call the extension method
```
ElementAt(int)
```
.


q:
Given a string of JSON data, how can I safely turn that string into a JavaScript object?

Obviously I can do this unsafely with something like:

var obj = eval("(" + json + ')');

but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.

[A]
I'm not sure about other ways to do it but here's how you do it in
Prototype (JSON tutorial)
.
```
```
new Ajax.Request('/some_url', {
  method:'get',
  requestHeaders: {Accept: 'application/json'},
  onSuccess: function(transport){
    var json = transport.responseText.evalJSON(true);
  }
});
```
```
Calling
```
evalJSON()
```
with true as the argument sanitizes the incoming string.


q:
I'm wanting to parse a string into a nullable int in C#.  ie. I want to get back either the int value of the string or null if it can't be parsed.

I was kind of hoping that this would work

int? val = stringVal as int?;

But that won't work, so the way I'm doing it now is I've written this extension method

public static int? ParseNullableInt(this string value)
{
    if (value == null || value.Trim() == string.Empty)
    {
        return null;
    }
    else
    {
        try
        {
            return int.Parse(value);
        }
        catch
        {
            return null;
        }
    }
}

Is there a better way of doing this?

EDIT:  Thanks for the TryParse suggestions, I did know about that, but it worked out about the same.  I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?

[A]
```
int.TryParse
```
is probably a tad easier:
```
```
public static int? ToNullableInt(this string s)
{
    int i;
    if (int.TryParse(s, out i)) return i;
    return null;
}
```
```
Edit
@Glenn
```
int.TryParse
```
is "built into the framework". It and
```
int.Parse
```
are
the
way to parse strings to ints.


q: I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this?

[A]
```
svn log
```
has a
```
--verbose
```
parameter. I don't have a repository here to test with, but does that return a list of modified files?
You can also use
```
svn diff -r <revision>
```
to retrieve the full change details, which you can parse or read manually to find out which files were changed.


q:
Is there a better way to flash a window in Java than this:

public static void flashWindow(JFrame frame) throws InterruptedException {
        int sleepTime = 50;
        frame.setVisible(false);
        Thread.sleep(sleepTime);
        frame.setVisible(true);
        Thread.sleep(sleepTime);
        frame.setVisible(false);
        Thread.sleep(sleepTime);
        frame.setVisible(true);
        Thread.sleep(sleepTime);
        frame.setVisible(false);
        Thread.sleep(sleepTime);
        frame.setVisible(true);
}

I know that this code is scary...But it works alright. (I should implement a loop...)

[A]
Well, there are a few minor improvements we could make. ;)
I would use a Timer to make sure callers don't have to wait for the method to return. And preventing more than one flashing operation at a time on a given window would be nice too.
```
```
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import javax.swing.JFrame;

public class WindowFlasher {

    private final Timer timer = new Timer();
    private final Map<JFrame, TimerTask> flashing
                              = new ConcurrentHashMap<JFrame, TimerTask>();

    public void flashWindow(final JFrame window,
                            final long period,
                            final int blinks) {
        TimerTask newTask = new TimerTask() {
            private int remaining = blinks * 2;

            @Override
            public void run() {
                if (remaining-- > 0)
                    window.setVisible(!window.isVisible());
                else {
                    window.setVisible(true);
                    cancel();
                }
            }

            @Override
            public boolean cancel() {
                flashing.remove(this);
                return super.cancel();
            }
        };
        TimerTask oldTask = flashing.put(window, newTask);

        // if the window is already flashing, cancel the old task
        if (oldTask != null)
            oldTask.cancel();
        timer.schedule(newTask, 0, period);
    }
}
```
```


q: Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase.  Does anyone have any experience building Adobe Flex applications with a .NET back-end?  If so, what architecture did you use and what third-party tools if any did you employ.  I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative?

[A]
I've mainly used plain ASP.NET pages that return XML for situations that are mainly one-way (data from ASP.NET --> Flex/Flash) communication. The Flex side just uses a URLLoader to hit the ASP.NET page and loads the result as XML.
If the communication needs to be a little more two-sided (sending more than a couple parameters to ASP.NET lets say), I have used standard ASP.NET webservices.
I've never used WebOrb or Flex remoting because I've never really needed that type of interaction between the server and the SWF.
Hope that helps.


q: Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share?

[A]
Don't do it. You're practically guaranteed to fail. Use
```
PreparedStatement
```
(or its equivalent) instead.


q:
I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces

ISomethingV01
ISomethingV02
etc

and I do this

public interface ISomething{
      void method();
}

then I have to add method 2 so now what I do?

public interface ISomethingV2:ISomething{
      void method2();
}

or same other way?

[A]
The purpose of an interface is to define an abstract pattern that at type must implement.
It would be better implement as:
```
```
public interface ISomething

public class Something1 : ISomething
public class Something2 : ISomething
```
```
You do not gain anything in the form of code reusability or scalable design by creating multiple versions of the same interface.


q: Why does the order in which libraries are linked sometimes cause errors in GCC?

[A]
I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs.
Depending on different linkers HP/Intel/GCC/SUN/SGI/IBM/etc you can get unresolved functions/variables etc, on some platforms you have to list libraries twice.
For the most part we use structured hierarchy of libraries, core, platform, different layers of abstraction, but for some systems you still have to play with the order in the link command.
Once you hit upon a solution document it so the next developer does not have to work it out again.
My old lecturer used to say, "
high cohesion & low coupling
", it’s still true today.


q:
Given this HTML:

<ul id="topnav">
    <li id="topnav_galleries"><a href="#">Galleries</a></li>
    <li id="topnav_information"><a href="#">Information</a></li>
</ul>

And this CSS:

#topnav_galleries a, #topnav_information a {
    background-repeat: no-repeat;
    text-indent: -9000px;
    padding: 0;
    margin: 0 0;
    overflow: hidden;
    height: 46px;
    width: 136px;
    display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }

How would I go about turning the topnav list into an inline list?

[A]
Try this:
```
```
#topnav {
    overflow:hidden;
}
#topnav li {
    float:left;
}
```
```
And for IE you will need to add the following:
```
```
#topnav {
    zoom:1;
}
```
```
Otherwise your floated < li > tags will spill out of the containing < ul >.


q:
I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.

My IDL file for the COM object has the interface that I am calling into as:

HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);

The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.

The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?

[A]
If i recall correctly, you'll need to wrap the
```
SAFEARRAY
```
in a
```
VARIANT
```
in order for it to get through, and then use a
VBArray object
to unpack it on the JS side of things:
```
```
HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)
{
   // ...

   _variant_t ret;
   ret.vt = VT_ARRAY|VT_VARIANT;
   ret.parray = rgBstrStringArray;
   *pvarBstrStringArray = ret.Detach();
   return S_OK;
}
```
```
then
```
```
var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();
```
```


q: Is there a way to always have LF line endings in Visual Studio? I can never seem to find it!

[A]
Visual Studio 2008 doesn't retain the advanced save options after the solution is closed.  I would be willing to hand edit a lot of files if that would make it work consistently, but I am not willing to change all of the settings every time I open VS.
This is too bad.  Since VS does support forcing the line-endings to whatever is desired in the backend, its just not hooked up properly in the UI.  Maybe Microsoft will fix this isn a service pack.


q: I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?

[A]
If your asking what I think your asking, you can find them
Here
... page 476 and on.
It's written around optimization techniques for Python; It's mostly Big-O notation of time efficiencies not much memory.


q:
I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?

Oh and all of these machines are running either Ubuntu or OS X.

[A]
You can use Port Fowarding to do this. Take a look here:
http://portforward.com/help/portforwarding.htm
There are instructions on how to set up your router to port forward request on this page:
http://www.portforward.com/english/routers/port_forwarding/routerindex.htm


q:
I work on a large Visual C++ (MFC) project in VS.NET 2005.

I have noticed strange behavior in Visual C++ 2005. Often, I will change one line of code in a .CPP file but many .CPP files will compile as a result of this. I have never seen this until VS.NET 2005. Theortically, changing a line of code in a .CPP file should simply require recompilation of that .CPP file and re-linking of the PE file.

What am I not understanding about the build process.

[A]
This is a strange bug in the VS2005 dependency behavior. To find out one suggestion would be to take the following steps:
Go to
Tools
-> Options ->
Projects and Solutions -> Build and
Run -> MSBuild Project Build output
Verbosity
and select
Detailed
Compile your project.
This will give you a detailed output of the build which
"may"
help you arrive at a solution to your problem.


q:
I have 1 process that receives incoming connection from port 1000 in 1 linux server. However, 1 process is not fast enough to handle all the incoming request.

I want to run multiple processes in the server but with 1 end-point. In this way, the client will only see 1 end-point/process not multiple.

I have checked LVS and other Load Balancing Solution. Those solutions seem geared towards multiple servers load-balancing.

Any other solution to help on my case?

i am looking something more like nginx where i will need to run multiple copies of my app.

Let me try it out.

Thanks for the help.

[A]
The question is a little unclear to me, but I suspect the answer you are looking for is to have a single process accepting tasks from the network, and then forking off 'worker processes' to actually perform the work (before returning the result to the user).
In that way, the work which is being done does not block the acceptance of more requests.
As you point out, the term load balancing carries the implication of multiple servers - what you want to look for is information about how to write a linux network daemon.
The two kes system calls you'll want to look at are called
fork and exec
.


q:
I'm working on a Rails app and am looking to include some functionality from "Getting the Hostname or IP in Ruby on Rails" that I asked.

I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents:

require 'socket'

module GetIP
  def local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

    UDPSocket.open do |s|
      s.connect '64.233.187.99', 1
      s.addr.last
    end
  ensure
    Socket.do_not_reverse_lookup = orig
  end
end

I had also tried defining GetIP as a class but when I do the usual ruby script/console, I'm not able to use the local_ip method at all. Any ideas?

[A]
You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know.
The methods on a module never come into use unless the module is included into a class.  Instance methods on a class require there to be an instance of the class.  You probably want a class method instead.  And the file itself should be loaded, generally through the require statement.
If the following code is in the file getip.rb,
```
```
require 'socket'

class GetIP
  def self.local_ip
    orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true

    UDPSocket.open do |s|
      s.connect '64.233.187.99', 1
      s.addr.last
    end
  ensure
    Socket.do_not_reverse_lookup = orig
  end
end
```
```
Then you should be able to run it by saying,
```
```
require 'getip'
GetIP.local_ip
```
```


q:
When an AutoCompleteExtender is displayed in IE6 it seems to ignore z-index and renders below any select controls (like dropdownlists) in IE6.

<asp:TextBox ID="TextBox1" runat="server"  />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
    TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
    FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Text="Item 1" Value="0" />
    <asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>

How do I make it render above dropdownlists?

[A]
Nothing renders below select controls in IE6. It's one of the many "features" microsoft bestowed upon us when they gifted IE to the world
You have to hide them, then re-show them.
Observe the
standard lightbox script
- which does exactly this
(note that link is just to the first thing I found on google which had the source to lightbox.js as a demonstration. It's got nothing to do with anything else)


q:
I have a scenario where I need to make a call to a telephone(landline/mobile)  or send SMS to a particular set of users only using ASP.NET and C#. The web application is not a mobile application.

How do I go about doing these? What typically would be the hardware requirements? I would be extremely grateful if you could provide me with pointers and reference websites.

[A]
Not sure if you're looking for hardware solutions to automate yourself, or external services. However, I've used BT's
Web21C
pretty extensively.
They have an excellent .Net API and a host of functionality. Their pricing is the best in the UK, but might fall down with US SMS, which is obviously cheaper - there are plenty of other SMS API providers though.
What BT do offer, which is rare, is an API interface for automating call dialling, conferencing and managing call flow.


q:
Sometimes when I'm editing page or control the .designer files stop being updated with the new controls I'm putting on the page.  I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the .designer file.  I'm using Visual Studio 2008

EDIT: Sorry I should have noted I've already tried:

Closing & re-opening all the files & Visual Studio

Making a change to a runat="server" control on the page

Deleting & re-adding the page directive

[A]
If you open the .aspx file and switch between design view and html view and
back it will prompt VS to check the controls and add any that are missing to
the designer file.
In VS2013-15 there is a
Convert to Web Application
command under the
Project
menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control.
PS: This should not be done in debug mode, as not everything is "recompiled" when debugging.
Some people have also reported success by (making a backup copy of your .designer.cs file and then) deleting the .designer.cs file.  Re-create an empty file with the same name.
There are many comments to this answer that add tips on how best to re-create the designer.cs file.


q:
Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example http://somewhere.overtherainbow.com/userid/123424/

I want you to notice the ending path /userid/123424/

How do you do this in ASP.NET?

[A] Also, check out ASP.NET MVC or if you're set on webforms, the new System.Web.Routing namespace in ASP.NET 3.5 SP1


q:
Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).

CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);

Is it possible to have the count column calculated for me whenever I do an insert?

e.g. do something like:

INSERT INTO log (date='foo');

and have count calculated by mysql.

Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.

[A]
You definitly have to declare what to insert. This should be possible by using the
INSERT ... SELECT
statement.
```
```
INSERT INTO log (date, count)
    SELECT DATE() as date, count(id) as count
    from foo;
```
```
Which should insert a new row into the log table, containing todays date and the number of  rows in the foo table. (Assuming the foo table has an id column.. Use the primary key or another indexed column)


q:
I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs.

Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls?

[A]
The main advantages are that you can create unique id's without connecting to the database. And id's are globally unique so you can easilly combine data from different databases. These seem like small advantages but have saved me a lot of work in the past.
The main disadvantages are a bit more storage needed (not a problem on modern systems) and the id's are not really human readable. This can be a problem when debugging.
There are some performance problems like index fragmentation. But those are easilly solvable (comb guids by jimmy nillson:
http://www.informit.com/articles/article.aspx?p=25862
)
Edit
merged my two answers to this question
@Matt Sheppard I think he means that you can duplicate rows with different GUIDs as primary keys. This is an issue with any kind of surrogate key, not just GUIDs. And like he said it is easilly solved by adding meaningfull unique constraints to non-key columns. The alternative is to use a natural key and those have real problems..


q:
What are the main differences (if any) between the box models of IE8 and Firefox3?

Are they the same now?

What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards?

[A]
The Internet Explorer box model has been "fixed" since Internet Explorer 6 so long as your pages are in standard compliants mode.
See:
Quirks mode
and
Internet Explorer box model bug
.
Until I learnt about doctype declerations getting IE to work properly was a real PAIN, because IE runs in "quirks mode" by default. So having a standards mode doctype will eliminate a whole bunch of the most painful CSS problems.


q:
How does a virtual machine generate native machine code on the fly and execute it?

Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it?

Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing?

Or would you generate a temporary shared library (.dll or .so or whatever) and load it into memory using standard functions like LoadLibrary ?

[A]
As far as i know it compiles everything in memory because it has to run some heuristics to    to optimize the code (i.e.: inlining over time) but you can have a look at the
Shared Source Common Language Infrastructure 2.0
rotor release. The whole codebase is identical to .NET except for the Jitter and the GC.


q:
I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the Comments tab enabled. The problem is that when I format a document comment that contains:

* @see <a href="test.html">test</a>

the code formatter inserts a space in the closing HTML, breaking it:

* @see <a href="test.html">test< /a>

Why? How do I stop this happening?

This is not fixed by disabling any of the options on the Comments tab, such as Format HTML tags. The only work-around I found is to disable Javadoc formatting completely by disabling both the Enable Javadoc comment formatting and Enable block comment formatting options, which means I then have to format comment blocks manually.

[A]
I can only assume it's a bug in Eclipse. It only happens with
@see
tags, it happens also for all 3 builtin code formatter settings.
There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for
@see
in the
Eclipse Bugzilla
.


q:
I'm using Struts 2.

I'd like to return from an Action to the page which invoked it.

Say I'm in page x.jsp, I invoke Visual action to change CSS preferences in the session; I want to return to x.jsp rather than to a fixed page (i.e. home.jsp)

Here's the relevant struts.xml fragment:

<action
   name="Visual"
   class="it.___.web.actions.VisualizationAction">
   <result name="home">/pages/home.jsp</result>
</action>

Of course my VisualizationAction.execute() returns home.

Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?

Must I use a more involved method (i.e. extracting the request page and forwarding to it)?

T.I.A.

[A]
```
```
return INPUT;
```
```
will do the trick. INPUT constant is defined in Action interface itself. It indicates that action needs more input.
By calling page if you meant the page that took you to the action input page, then your input page will have to store HTTP header "Referer" in the request scope for the Action.


q:
I'm generating ICalendar (.ics) files.

Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event

How do I get them to work for Outlook ?

Thanks

Tom

[A]
I'm using Entourage, so this may not match up exactly with the behavior you're seeing, but I hope it helps.
Using the iCalendar from your reply, Entourage wouldn't even import the data. Using a known-good file, I got it to import, then successfully update. Comparing the two files, the only structural differences are as follows:
My known-good doesn't have a
```
VERSION
```
element
My known-good doesn't have a
```
PRODID
```
element
My known-good doesn't have a
```
STATUS
```
element
My known-good doesn't have a
```
SEQUENCE
```
element
Since Microsoft's support for open standards tends to lag, I'd suggest trying without the
```
VERSION
```
info.


q:
Can you suggest some good MVC framework for perl -- one I am aware of is catalyst

The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly.

[A]
I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework.
In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives.
If Catalyst doesn't seem right to you, then you could build upon the lightweight framework
CGI::Application
to suit your needs or take a look at some of the lesser known MVC frameworks like
PageKit
and
Maypole
.


q: How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?

[A]
I think it's not possible if you want to use object model (i.e. XElement\XDocument) to query XML. Obviously, you can't build XML objects tree without reading enough data. However you can use
XmlReader
class.
The XmlReader class reads XML data
  from a stream or file. It provides
  non-cached, forward-only, read-only
  access to XML data.


q:
I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries:

SELECT *
FROM  story_category
WHERE category_id NOT IN (
    SELECT DISTINCT category.id
    FROM category INNER JOIN
       story_category ON category_id=category.id);

I tried to delete them executing:

DELETE FROM story_category
WHERE category_id NOT IN (
    SELECT DISTINCT category.id
    FROM category
      INNER JOIN story_category ON category_id=category.id);

But I get the next error:

#1093 - You can't specify target table 'story_category' for update in FROM clause

How can I overcome this?

[A]
Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question
In MySQL, you can't modify the same table which you use in the SELECT part.
This behaviour is documented at:
http://dev.mysql.com/doc/refman/5.6/en/update.html
Maybe you can just join the table to itself
If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.
```
```
UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col
```
```
Alternatively, try nesting the subquery deeper into a from clause ...
If you absolutely need the subquery, there's a workaround, but it's
ugly for several reasons, including performance:
```
```
UPDATE tbl SET col = (
  SELECT ... FROM (SELECT.... FROM) AS x);
```
```
The nested subquery in the FROM clause creates an
implicit temporary
table
, so it doesn't count as the same table you're updating.
... but watch out for the query optimiser
However, beware that from
MySQL 5.7.6
and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the
```
optimizer_switch
```
variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.
```
```
SET optimizer_switch = 'derived_merge=off';
```
```
Thanks to
Peter V. Mørch
for this advice in the comments.
Example technique was from Baron Schwartz,
originally published at Nabble
, paraphrased and extended here.


q: If possible I want to catch pressure sensitive input from a Wacom tablet in Python. Are there any Python libraries available that can do this?

[A]
You could perhaps take a look at the
software
described
here
. It is a gnome applet, written in Python.
From the web site:
"The gnome wacom applet is a small gnome panel applet that shows how much pressure is being applied to your wacom tablet by the current device. Clicking on the panel icon brings up a dialog allowing you to select a different device and check what pressure and tilt information is being recieved from it. This dialog also contains a small drawing test area to give your pen a quick test."
Google is your friend


q: I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files.

[A]
Perhaps the following would work:
Generate your icon image using PIL
Convert the image to .ico format using the python interface to ImageMagick,
PythonMagick
I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports the .ico format.


q:
I want to call a function from a .NET DLL (coded in C#) from an Inno Setup script.

I have:

marked the Register for COM interop option in the project properties,

changed the ComVisible setting in the AssemblyInfo.cs file,

added these lines to the ISS script:

[Files]

Source: c:\temp\1\MyDLL.dll; Flags: dontcopy

[Code]

function MyFunction(): string;

external 'MyFunction@files:MyDLL.dll stdcall setuponly';

but I still get the following error:

Runtime Error (at -1:0):

Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll.

What am I doing wrong?

[A]
You're trying to import a C-style function from your .NET dll - this doesn't really have anything to do with COM interop. COM interop allows you to activate your .NET objects as COM objects, it doesn't expose them as C/C++ exported functions/types.
If your function doesn't need to return any data, why not make a simple .exe that calls your function and just run that from your setup?
Also: See the
innosetup support newsgroups
where you might get better support.


q: I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?

[A]
That format doesn't exist. You need to do a combination of two things,
```
```
select convert(varchar(4),getdate(),100)  + convert(varchar(4),year(getdate()))
```
```


q:
I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.

from Tkinter import *
import tkMessageBox

root = Tk()
root.withdraw()

# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))

Any idea how to check that?

[A]
I believe you want:
```
```
if 'normal' != root.state():
    tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
```
```


q: How can I add horizontal scroll capabilities to the asp.net listbox control?

[A]
If you really, really need it, one idea would be to create a custom
ListBox class whose HTML looks like this: sets the width of the SELECT
to that of your widest value's width (the max width of the scrollbar,
for example). Now wrap that SELECT inside of a DIV of the 'constrained'
size and let it scroll on overflow.
Here's a quick example starting down those lines, here's the type of
HTML you want spit out by a control:
```
```
<div style="width:200px; height:100px; overflow:auto;">
<SELECT size="4">
<OPTION
Value="1">blahblahblahblahblahblahblahblahblahblah blahblah</OPTION>
<OPTION Value="2">2</OPTION>
<OPTION Value="3">3</OPTION>
<OPTION Value="4">4</OPTION>
</SELECT>
</div>
```
```
so in essence I'd recommend creating a composite custom control for
this, which renders this HTML. They're pretty easy to make, Google on
the terms 'composite control asp.net'.
The toughest part will be matching up the div dimensions to that of the
select box, to make the scrollbars work/line up properly. That's why
it's kinda tricky.
Source
Also, take a look at this:
Automatically Adding/Hide Horizontal Scroll bar in the ListBox control
EDIT
: Make sure you have enough height to include the scroll bar height or else you'll get the vertical scroll bar on both controls.


q: I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.

[A]
Use this:
```
response.setStatus(403)
```
.


q:
This happened to me in Visual Studio 2008 pre and post 2008 sp1 on more than one computer and to someone else I know, so it can't be an isolated incident.

Seemingly random, every so often I lose all syntax highlighting in my aspx page (the html) so that Visual Studio now looks like a really expensive version of notepad.

Does anyone know why does happens?  Better yet, anyone know how to fix it?

[A]
You have basically experienced Visual Studio giving up.  It gives up for many reason, the page is too complicated to highlight which is usually because there are too many syntax errors.  The highlighting is done with some very complicated and intelligent RegEx statements essentially, however if Visual Studio is unable to apply them it just displays black text.
One thing to try is to fix all the syntax issues, if any.
By the way this "giving up" happens in most IDE's.  I have seen it happen once or twice in Elcipse too.


q:
I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. GroovyShell maintains variable state over multiple eval calls, but not class definitions or methods.

goal: Create a base class during startup. As OSGi bundles load, create derived classes as needed.

[A]
This might be what you are looking for?
From
Groovy in Action
```
```
def binding = new Binding(x: 6, y: 4)
def shell = new GroovyShell(binding)
def expression = '''f = x * y'''
shell.evaluate(expression)
assert binding.getVariable("f") == 24
```
```
An appropriate use of Binding will allow you to maintain state?


q:
Example

I have Person, SpecialPerson, and User. Person and SpecialPerson are just people - they don't have a user name or password on a site, but they are stored in a database for record keeping. User has all of the same data as Person and potentially SpecialPerson, along with a user name and password as they are registered with the site.

How would you address this problem? Would you have a Person table which stores all data common to a person and use a key to look up their data in SpecialPerson (if they are a special person) and User (if they are a user) and vice-versa?

[A]
Personally, I would store all of these different user classes in a single table.  You can then either have a field which stores a 'Type' value, or you can imply what type of person you're dealing with by what fields are filled in.  For example, if UserID is NULL, then this record isn't a User.
You could link out to other tables using a one to one-or-none type of join, but then in every query you'll be adding extra joins.
The first method is also supported by LINQ-to-SQL if you decide to go down that route (they call it 'Table Per Hierarchy' or 'TPH').


q:
In Java, what would the best way be to have a constantly listening port open, and still send upon receipt of a packet. I am not particularly savvy with network programming at the moment, so the tutorials I have found on the net aren't particularly helpful.

Would it make sense to have the listening socket as a serversocket and run it in a separate thread to the socket I'm using to send data to the server?

In a loosely related question. Does anyone know if programming simply for java, in netbeans then exporting it for use on a blackberry (using a plugin) the sockets would still work ?

[A]
If you can afford the threading, try this (keep in mind I've left out some details like exception handling and playing nice with threads). You may want to look into
```
SocketChannels
```
and/or NIO async sockets / selectors. This should get you started.
```
```
boolean finished = false;
int port = 10000;
ServerSocket server = new ServerSocket(port);

while (!finished) {
    // This will block until a connection is made
    Socket s = server.accept();
    // Spawn off some thread (or use a thread pool) to handle this socket
    // Server will continue to listen
}
```
```


q:
How do you rewrite this in Linq?

SELECT Id, Name FROM TableA WHERE TableA.Id IN (SELECT xx from TableB INNER JOIN Table C....)

So in plain english, I want to select Id and Name from TableA where TableA's Id is in a result set from a second query.

[A]
```
```
from a in TableA
where (from b in TableB
       join c in TableC on b.id equals c.id
       where .. select b.id)
.Contains(a.Id)
select new { a.Id, a.Name }
```
```


q:
I was wondering if there is an open source library or algorithm that can expand a non-numeric range.  For example, if you have 1A to 9A you should get

1A, 2A, 3A, 4A, 5A, 6A, 7A, 8A, 9A.

I've tried Googling for this and the best I could come up with were Regex that would expand numerics with dashes (1-3 becoming 1,2,3).

[A] I was trying to leave it somewhat open because the number of possibilities is staggering.  I believe this one of those questions that could not be answered 100% here without going through a lot of technical detail about is considered a "good" or "bad" range.  I'm just trying to find a jumping point for ideas on how other people have tackled this problem.  I was hoping that someone wrote a blog post explaining how they went about it solving this problem or created a whole library to handle this.


q:
I inserted some values into a table. There is a column whose value is auto-generated. In the next statement of my code, I want to retrieve this value.

Can you tell me how to do it the right way?

[A]
```
```
SELECT @@Scope_Identity as Id
```
```
There is also @@identity, but if you have a trigger, it will return the results of something that happened during the trigger, where scope_identity respects your scope.


q:
Is there a limit with the number of SSL connections?

We are trying to connect through SSL with 2000 sessions. We have tried it a couple of times but it always dies at 1062nd. Is there a limit?

[A]
Yes, everything has a limit. As far as I'm aware, there is no inherit limit with "SSL".. it is after all just a protocol.
But, there is a limited amount of memory, ports, CPU on the machine you are connected to, from and every single one in between.
The actually server you are connected to may have an arbitrary limit set too.
This question doesn't have enough information to answer beyond "YES".


q: Let's say I want to run a .NET application on a machine where the .NET framework is not available; Is there any way to compile the application to native code?

[A]
Yes, using
Ngen
, the Native Image Generator. There are, however, a number of things you need to be aware of:
You still need the CLR to run your executable.
The CLR will not dynamically optimize your assemblies based on the environment it's run in (e.g. 486 vs. 586 vs. 686, etc.)
All in all, it's only worth using Ngen if you need to reduce the startup time of your application.


q:
Can't get to my site. Apache gives the following error message:

[Fri Sep 05 08:47:42 2008] [error] (OS 10060)A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.  : proxy: HTTP: attempt to connect to 10.10.10.1:80 (10.10.10.1) failed

[A] Can you connect to the proxied host (10.10.10.1) directly?  Is it functioning normally?


q:
I'm curious about everyones practices when it comes to using or distributing libraries for an application that you write.

First of all, when developing your application do you link the debug or release version of the libraries? (For when you run your application in debug mode)

Then when you run your app in release mode just before deploying, which build of the libraries do you use?

How do you perform the switch between your debug and release version of the libraries? Do you do it manually, do you use macros, or whatever else is it that you do?

[A]
I would first determine what requirements are needed from the library:
Debug/Release
Unicode support
And so on..
With that determined you can then create configurations for each combination required by yourself or other library users.
When compiling and linking it is very important that you keep that libraries and executable consistent with respect to configurations used i.e. don't mix release & debug when linking.
I know on the Windows/VS platform this can cause subtle memory issues if debug & release libs are mixed within an executable.
As Brian has mentioned to Visual Studio it's best to use the Configuration Manager to setup how you want each configuration you require to be built.
For example our projects require the following configurations to be available depending on the executable being built.
Debug+Unicode
Debug+ASCII
Release+Unicode
Release+ASCII
The users of this particular project use the Configuration Manager to match their executable requirements with the project's available configurations.
Regarding the use of macros, they are used extensively in implementing compile time decisions for requirements like if the debug or release version of a function is to be linked. If you're using VS you can view the pre-processor definitions attribute to see how the various macros are defined e.g. _DEBUG _RELEASE, this is how the configuration controls whats compiled.
What platform are you using to compile/link your projects?
EDIT: Expanding on your updated comment..
If the
Configuration Manager
option is not available to you then I recommend using the following properties from the project:
Linker
->
Additional Library Directories
or
Linker
->
Input
Use the macro
```
$(ConfigurationName)
```
to link with the appropriate library configuration e.g. Debug/Release.
```
```
$(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.lib
```
```
Build Events
or
Custom Build Step
configuration property
Execute a copy of the required library file(s) from the dependent project prior (or after) to the build occurring.
```
```
xcopy $(ProjectDir)\..\third-party-prj\$(ConfigurationName)\third-party.dll $(IntDir)
```
```
The macro
```
$(ProjectDir)
```
will be substituted for the current project's location and causes the operation to occur relative to the current project.
The macro
```
$(ConfigurationName)
```
will be substituted for the currently selected configuration (default is
```
Debug
```
or
```
Release
```
) which allows the correct items to be copied depending on what configuration is being built currently.
If you use a regular naming convention for your project configurations it will help, as you can use the
```
$(ConfigurationName)
```
macro, otherwise you can simply use a fixed string.


q:
I've had some trouble forking of processes from a Perl CGI script when running on Windows. The main issue seems to be that 'fork' is emulated when running on windows, and doesn't actually seem to create a new process (just another thread in the current one). This means that web servers (like IIS) which are waiting for the process to finish continue waiting until the 'background' process finishes.

Is there a way of forking off a background process from a CGI script under Windows? Even better, is there a single function I can call which will do this in a cross platform way?

(And just to make life extra difficult, I'd really like a good way to redirect the forked processes output to a file at the same time).

[A]
perlfork
:
Perl provides a fork() keyword that
  corresponds to the Unix system call of
  the same name. On most Unix-like
  platforms where the fork() system call
  is available, Perl's fork() simply
  calls it.
On some platforms such as Windows
  where the fork() system call is not
  available, Perl can be built to
  emulate fork() at the interpreter
  level. While the emulation is designed
  to be as compatible as possible with
  the real fork() at the the level of
  the Perl program, there are certain
  important differences that stem from
  the fact that all the pseudo child
  ``processes'' created this way live in
  the same real process as far as the
  operating system is concerned.


q: Is there a way with WPF to get an array of elements under the mouse on a MouseMove event?

[A]
Can you use the
VisualTreeHelper.HitTest
?
http://lukieb.blogspot.com/2008/07/visualtreehelperhittest.html


q:
How do you automatically set the focus to a textbox when a web page loads?

Is there an HTML tag to do it or does it have to be done via Javascript?

[A]
You need to use javascript:
```
```
<BODY onLoad="document.getElementById('myButton').focus();">
```
```
@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:
```
```
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
```
```
And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.


q: I am using js2-mode to edit Javascript in Emacs, but I can't seem to get it to stop using tabs instead of spaces for indentation. My other modes work fine, just having issues w/ js2.

[A]
Do you have
```
(setq-default indent-tabs-mode nil)
```
in your .emacs? It works fine for me in emacs 23.0.60.1 when I do that. js2-mode uses the standard emacs function indent-to, which respects indent-tabs-mode, to do its indenting.


q: I have jQuery but I'm not sure if it has any built-in sorting helpers. I could make a 2d array of each item's text, value, and selected properties, but I don't think that javascript's built in Array.sort() would work correctly.

[A]
Well, in IE6 it seems to sort on the nested array's [0] item:
```
```
function sortSelect(selectToSort) {
    var arrOptions = [];

    for (var i = 0; i < selectToSort.options.length; i++)  {
        arrOptions[i] = [];
        arrOptions[i][0] = selectToSort.options[i].value;
        arrOptions[i][1] = selectToSort.options[i].text;
        arrOptions[i][2] = selectToSort.options[i].selected;
    }

    arrOptions.sort();

    for (var i = 0; i < selectToSort.options.length; i++)  {
        selectToSort.options[i].value = arrOptions[i][0];
        selectToSort.options[i].text = arrOptions[i][1];
        selectToSort.options[i].selected = arrOptions[i][2];
    }
}
```
```
I'll see if this works in other browsers...
Edit: it works in Firefox too, woo hoo!
Is there an easier way than this though? is there some method built into javascript or jQuery that sorts selects that I am missing, or is this the best way?


q:
In an application that I'm writing I have some code like this:

NSWorkspace* ws = [NSWorkspace sharedWorkspace];
NSString* myurl = @"http://www.somewebsite.com/method?a=%d";

NSURL* url = [NSURL URLWithString:myurl];

[ws openURL:url];

The main difference being that myurl comes from somewhere outside my control. Note the %d in the URL which isn't entirely correct and means that URLWithString fails, returning nil.

What is the "correct" way of handling this? Do I need to parse the string and properly encode the arguments? Or is there some clever method in Cocoa that does all the hard work for me?

[A]
I think the behaviour here is correct, because %d is not a valid component of a URL (% is the escape, but expects two hex characters to follow it).
You can't just URL encode the URL as given to you, because that would encode the /s and ?s as well, which you don't want.
So, the question is, what's the correct behaviour here?
Perhaps you would want it to be turned into...
```
```
http://www.somewebsite.com/method?a=%25d
```
```
(i.e. the % is encode to the encoded version of % in a URL, so when method gets the input, it sees a as being set to %d)
I don't think there's any library function which will do that sort of thing for you, since there's no 'correct' way to do it. About he only correct thing you can do is return an error message saying the URL you were given is invalid (just as URLWithString is)
If you wanted to try to handle the input, I guess you would need to search the URL for any % symbols which are not immediately followed by two hex characters, and then replace the % with %25 in that case. That should be quite possible with a regular expression, though I suspect there may be some additional complexities if your URLs start containing encoded versions of characters outside the ASCII character set.


q:
I've used subversion for a  while, and used the svnmerge.py script for a while in my old job to manage merges between branches. I believe Subversion 1.5 is now out, and was supposed to have some branch / merge management system integrated with it.

So, can someone give me a quick overview of how to track merges in a branch with Subversion 1.5? Are there any pitfalls with using this support? Do I need to ensure all the team upgrades to 1.5 before using this support?

[A]
Usage
Merge tracking is managed by the client and stored in a property (
svn:mergeinfo
).
To use merge tracking you just merge as usual but without the revision range:
```
```
svn merge trunkURL
```
```
The client will take care of reading the properties to see what revision(s) need to be merged in and then update the properties with the newly-merged revision(s).
Here
is a pretty basic overview of the process.
Pitfalls, etc.
I personally haven't run into any problems with merge tracking, but my usage of the feature has been pretty light.
Upgrading
There are two upgrades you'll need to do to get merge tracking:
Server: Your server
must
be running 1.5 to get merge tracking support.
Client: You can use a 1.x client against a 1.5 server,
but you won't get merge tracking.
Just upgrade everyone.


q:
I'm building a website that requires very basic markup capabilities. I can't use any 3rd party plugins, so I just need a simple way to convert markup to HTML. I might have a total of 3 tags that I'll allow.

What is the best way to convert ==Heading== to <h2>Heading</h2>, or --bold-- to <b>bold</b>? Can this be done simply with Regex, or does somebody have a simple function?

I'm writing this in C#, but examples from other languages would probably work.

[A]
It's not really a simple problem, because if you're going to display things back to the user, you'll need to also sanitise the input to ensure you don't create any
cross site scripting
vulnerabilities.
That said, you could probably do something pretty simple as you describe most easily with a regular expression replacement.
For example
```
```
replace the pattern ==([^=]*)== with <h2>\1</h2>
```
```


q:
How can I change default Generate Method Stub behavior in Visaul Studio to generate method with body

throw new NotImplementedException();

instead of

throw new Exception("The method or operation is not implemented.");

[A]
Taken from:
http://blogs.msdn.com/ansonh/archive/2005/12/08/501763.aspx
Visual Studio 2005 supports targeting the 1.0 version of the compact framework.  In order to keep the size of the compact framework small, it does not include all of the same types that exist in the desktop framework.  One of the types that is not included is NotImplementedException.
You can change the generated code by editing the code snippet file:
C:\Program Files\Microsoft Visual Studio 8\VC#\Snippets\1033\Refactoring\MethodStub.snippet
and changing the Declarations section to the following:
```
```
<Declarations>
            <Literal Editable="true">
                <ID>signature</ID>
                <Default>signature</Default>
            </Literal>
            <Literal>
                <ID>Exception</ID>
                <Function>SimpleTypeName(global::System.NotImplementedException)</Function>
            </Literal>
        </Declarations>
```
```


q:
My work has a financial application, written in VB.NET with SQL, that several users can be working on at the same time.

At some point, one user might decide to Post the batch of entries that they (and possibly other people) are currently working on.

Obviously, I no longer want any other users to add, edit, or delete entries in that batch after the Post process has been initiated.

I have already seen that I can lock all data by opening the SQL transaction the moment the Post process starts, but the process can be fairly lengthy and I would prefer not to have the Transaction open for the several minutes it might take to complete the function.

Is there a way to lock just the records that I know need to be operated on from VB.NET code?

[A]
add
```
```
with (rowlock)
```
```
to your SQL query
SQL Server Performance article
EDIT:
ok, I misunderstood the question. What you want is transaction isolation. +1 to Joel :)


q:
Details:

Only disable after user clicks the submit button, but before the posting back to the server

ASP.NET Webforms (.NET 1.1)

Prefer jQuery (if any library at all)

Must be enabled if form reloads (i.e. credit card failed)

This isn't a necessity that I do this, but if there is a simple way to do it without having to change too much, I'll do it. (i.e. if there isn't a simple solution, I probably won't do it, so don't worry about digging too deep)

[A]
in JQuery:
```
```
$('#SubmitButtonID').click(function() { this.disabled = true; });
```
```


q:
I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?

(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)

[A]
Subversion has native support for moving files.
```
```
svn move SOURCE DESTINATION
```
```
See the online help (svn help move) for more information.


q:
I've seen people doing things like this in their HTML:

<!--[if IE]>
  <link rel="stylesheet" href="ie.css" type="text/css" />
<![endif]-->

Does this work across all modern browsers and is there a list of browser types that will work with that kind of if statement?

Edit

Thanks Ross.  Interesting to find out about gt, lt, gte, & lte.

[A]
This works across all browsers because anything except IE sees
```
<!--IGNORED COMMENT-->
```
. Only IE reads the comment if it contains a conditional clause. Have a look at
this article
You can also specify which version of IE. For example:
```
```
<!--[if IE 8]>
<link rel="stylesheet type="text/css" href="ie8.css" />
<![endif]-->
```
```


q:
I want to do this:

//*fu

which returns all nodes whose name ends in fu, such as <tarfu /> and <snafu />, but not <fubar />

[A]
Do something like:
```
```
//*[ends-with(name(), 'fu')]
```
```
For a good XPath reference, check out
W3Schools
.


q: I have a list of Foo. Foo has properties Bar and Lum. Some Foos have identical values for Bar. How can I use lambda/linq to group my Foos by Bar so I can iterate over each grouping's Lums?

[A]
```
```
var q = from x in list
        group x by x.Bar into g
        select g;

foreach (var group in q)
{
    Console.WriteLine("Group " + group.Key);
    foreach (var item in group)
    {
        Console.WriteLine(item.Bar);
    }
}
```
```


q:
I have a large codebase that targetted Flash 7, with a lot of AS2 classes.  I'm hoping that I'll be able to use Flex for any new projects, but a lot of new stuff in our roadmap is additions to the old code.

The syntax for AS2 and AS3 is generally the same, so I'm starting to wonder how hard it would be to port the current codebase to Flex/AS3.  I know all the UI-related stuff would be iffy (currently the UI is generated at runtime with a lot of createEmptyMovieClip() and attachMovie() stuff), but the UI and controller/model stuff is mostly separated.

Has anyone tried porting a large codebase of AS2 code to AS3?  How difficult is it?  What kinds of pitfalls did you run into?  Any recommendations for approaches to doing this kind of project?

[A]
Some notable problems I saw when attempting to convert a large number of AS2 classes to AS3:
Package naming
```
```
class your.package.YourClass
{
}
```
```
becomes
```
```
package your.package
{
    class YourClass
    {
    }
}
```
```
Imports are required
You must explicitly import any outside classes used -- referring to them by their fully qualified name is no longer enough.
Interface methods can't be labelled 'public'
This makes total sense, but AS2 will let you do it so if you have any they'll need to be removed.
Explicit 'override' keyword
Any functions that override a parent class function must be declared with the
override
keyword, much like C#.  Along the same lines, if you have interfaces that extend other interfaces and redeclare functions, those overrides must be removed (again, as with
public,
this notation didn't make sense anyway but AS2 let you do it).
All the Flash builtin stuff changed
You alluded to this above, but it's now
flash.display.MovieClip
instead of just
MovieClip,
for example.  There are a lot of specifics in this category, and I didn't get far enough to find them all, but there's going to be a lot of annoyance here.
Conclusion
I didn't get to work on this conversion to the point of success, but I was able in a matter of hours to write a quick C# tool that handled every aspect of this except the
override
keyword.  Automating the imports can be tricky -- in my case the packages we use all start with a few root-level packages so they're easy to detect.


q: Looking for a string to pass to String#matches(String) that will match IPv4, and another to match IPv6.


q:
Have just started using Google Chrome, and noticed in parts of our site, e.g. all the links on the page, are bright red. They should be black with a dotted underline.

Is there some gotcha in WebKit rendering that turns all links red regardless of the style?

[A]
Have you set a
```
:visited
```
setting in your stylesheet?


q: I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?


q: I have a collection of objects to which I'd like to just add a new property. How do I do that with LINQ?

[A]
```
```
var a = from i in ObjectCollection select new {i.prop1, i.prop2, i.prop3, ..., newprop = newProperty}
```
```


q:
If I have a

<input id="uploadFile" type="file" />

tag, and a submit button, how do I determine, in IE6 (and above) if a file has been selected by the user.

In FF, I just do:

var selected = document.getElementById("uploadBox").files.length > 0;

But that doesn't work in IE.

[A]
This works in IE (and FF, I believe):
```
```
if(document.getElementById("uploadBox").value != "") {
   // you have a file
}
```
```