q:
I have an RFID reader connected to an Arduino board. I'd like to connect to it over its serial interface, and whenever the RFID reader omits a signal ( when it has read an (RF)ID ), I'd like to retrieve it in my C++ program.

I already have the code for simply printing the RFID to serial from the Arduino.

What I don't know, is how to read it from C++ in Linux ?

I have looked at libserial, which looks straightforward. However, how can I have the C++ program react to a signal and then read the RFID, instead of listening continously? Is this necessary?

EDIT: In most examples I have read, the (c++) program sends input, and recieves output. I just want to listen and recieve output from the Arduino.

[A]
The
Communications
part of the Interface section in the Arduino Playground has several examples of interfacing, including one with the Arduino as Linux TTY.
Try the
Syntax and Programs
forum and the
Software Development
forum on the Arduino site. There have been discussions about interfacing to many different languages and computers in the past.
And finally check out the
Processing
and
Wiring
sites. The Arduino IDE is based on the Processing language, and the Wiring environment and dev board is related to Arduino. Both sites have lots more examples and links to even more resources.
Edit:
I just realized that I didn't answer your actual question. These are all general communications resources, but some may have hints towards how to alert the computer of a new RFID input.


q:
In ActionScript 3.0, is there an automatic way to calculate the number of days, hours, minutes and seconds between two specified dates?

Basicly, what I need is the ActionScript equivalent of the .NET Timespan class.

Any idea?

[A]
You can covert the two date times into milliseconds since the epoch, perform your math and then use the resultant milliseconds to calculate these higher timespan numbers.
```
```
var someDate:Date = new Date(...);
var anotherDate:Date = new Date(...);
var millisecondDifference:int = anotherDate.valueOf() - someDate.valueOf();
var seconds:int = millisecondDifference / 1000;
....
```
```
The
LiveDocs
are useful for this type of thing too. Sorry if the ActionScript is a bit off, but it has been a while.
I'd also recommend creating a set of static class methods that can perform these operations if you're doing a lot of this type of math. Sadly, this basic functionality doesn't really exist in the standard APIs.

s: huggingface

c: devops

d: intermediate


q: As kind of a follow up to this question about prefixes, I agree with most people on the thread that prefixes are bad. But what about if you are using getters and setters? Then you need to differeniate the publicly accessible getter name from the privately stored variable. I normally just use an underscore, but is there a better way?

[A]
In a case sensitive language I just use:
```
```
private int myValue;

public int MyValue
{
    get { return myValue; }
}
```
```
Otherwise I would use an underscore
```
```
Private _myValue As Integer

Public ReadOnly Property MyValue As Integer
    Get
        Return _myValue
    End Get
End Property
```
```


q:
In SQL Server you can use the IsNull() function to check if a value is null, and if it is, return another value. Now I am wondering if there is anything similar in C#.

For example, I want to do something like:

myNewValue = IsNull(myValue, new MyValue());

instead of:

if (myValue == null)
  myValue = new MyValue();
myNewValue = myValue;

Thanks.

[A]
It's called the null coalescing (
```
??
```
) operator:
```
```
myNewValue = myValue ?? new MyValue();
```
```


q:
I'm used to writing classes like this:

public class foo {
  private string mBar = "bar";
  public string Bar {
    get { return mBar; }
    set { mBar = value; }
  }
  //... other methods, no constructor ...
}

Converting Bar to an auto-property seems convenient and concise, but how can I retain the initialization without adding a constructor and putting the initialization in there?

public class foo2theRevengeOfFoo {
  //private string mBar = "bar";
  public string Bar { get; set; }
  //... other methods, no constructor ...
  //behavior has changed.
}

You could see that adding a constructor isn't inline with the effort savings I'm supposed to be getting from auto-properties.

Something like this would make more sense to me:

public string Bar { get; set; } = "bar";

[A]
In the default constructor (and any non-default ones if you have any too of course):
```
```
public foo() {
    Bar = "bar";
}
```
```
This is no less performant that your original code I believe, since this is what happens behind the scenes anyway.


q:
http://thedailywtf.com/Articles/The-Hot-Room.aspx

You see how at the bottom there're links to the next and previous articles ("Unprepared For Divide_By_Zero" and "A Completely Different Game")? How do I do that, but selecting the next and previous non-private articles? This works for selecting the next article:

SELECT * FROM articles WHERE id > ? AND private IS NULL

But I cannot find a way to select the previous article.

What is the proper/efficient way to do this, preferably in one query?

[A]
Here's how I would do it:
```
```
-- next
SELECT * FROM articles WHERE id > ? AND private IS NULL ORDER BY id ASC LIMIT 1

-- previous
SELECT * FROM articles WHERE id < ? AND private IS NULL ORDER BY id DESC LIMIT 1
```
```
I'm not sure how to do it in one query. The only thing I can think of is possibly getting both the article you're displaying and the next article in one query, but that might be too confusing.


q:
I have two databases with the same structure. The tables have an integer as a primary key as used in Rails.

If I have a patients table, I will have one patient using primary key 123 in one database and another patient using the same primary key in the other database.

What would you suggest for merging the data from both databases?

[A]
Set both your databases up with entries in config/database.yml, then generate a new migration.
Use ActiveRecord::Base.establish_connection to switch between the two databases in the migration like this:
```
```
def self.up
  ActiveRecord::Base.establish_connection :development
  patients = Patient.find(:all)
  ActiveRecord::Base.establish_connection :production
  patients.each { |patient| Patient.create patient.attributes.except("id") }
end
```
```
YMMV depending on the number of records and the associations between models.


q:
I have seen Jetbrain's ReSharper tool on many "must-have" tool lists. I've installed it on a few occasions over the last few years and it's turned my Visual Studio sluggish and erratic. I generally uninstall it after a week or two because it make VS flaky, I want to like it, but I can't get past the instability.

So what's the deal? Am I having bad luck? Does the tool have issues but the usefulness out weighs the issues? Anyone else out there have trouble with it? Are there some troublesome options to turn off?

[A]
I've experienced a lot of what you're talking about over the years as well, but I have to say having recently moved to the 4.0 version of ReSharper, a lot of that overhead has been cut down dramatically and it seems to be quite a bit more functional to boot.
Try it again. What's the worst that can happen? You'll uninstall it again? No big loss.


q:
After maintaining lots of code littered with #region (in both C# and VB.NET), it seems to me that this construct is just a bunch of "make work" for the programmer. It's work to PUT the dang things into the code, and then they make searching and reading code very annoying.

What are the benefits? Why do coders go to the extra trouble to put this in their code.

Make me a believer!

[A]
Often times, both partials and #regions are used as a crutch for bad design (e.g. class is too big or tries to do too many things).
The
best
use I've had for #regions so far is the grouping of functionality that is seen in many different classes. For example, value objects that have getters, setters, constructors and supporting fields. I might very well group those ideas into regions. Its a matter of opinion, however, as to whether that makes code cleaner or harder to read.


q:
Is there a Generics Friendly way of using Collection.EMPTY_LIST in my Java Program.

I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this.

Something like users = Collections<User>.EMPTY_LIST;

[A]
By doing the following:
```
```
List<User> users = Collections.emptyList();
```
```
The type of the returned list from
```
Collections.emptyList();
```
will be
inferred
as a
```
String
```
due to the left-hand-side of the assignment.  However, if you prefer to not have this inference, you can define it explicitly by doing the following:
```
```
List<User> users = Collections.<User>emptyList();
```
```
In this particular instance, this may appear as redundant to most people (in fact, I've seen very little code out in the wild that makes use of explicit type arguments), however for a method with the signature:
```
void doStuff(List<String> users)
```
it would be perfectly clean for one to invoke
```
doStuff()
```
with an explicit type argument as follows:
```
```
doStuff(Collections.<String>emptyList());
```
```


q:
How do I get modrewrite to ENTIRELY ignore the /vip/ directory so that all requests pass directly to the folder?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^vip/.$ - [PT]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

See also How do I ignore a directory in mod_rewrite?  -- reposting because I wasn't sufficiently clear about the problem first time around.

[A]
Replace:
```
```
RewriteRule ^vip/.$ - [PT]
```
```
with:
```
```
RewriteRule ^vip/.*$ - [PT,L]
```
```


q:
Does anyone have a good resource on dlls and how they are used / generated in Visual Studio?  A few questions I'm rather hazy on specifically are:

How refresh files work

How dll version numbers are generated

The difference between adding a reference by project vs browsing for the specific dll

Any other tips are welcome as well.

[A]
See the question on
DLL information
for some background.
Version numbers for unmanaged DLLs are stored in the DLL's rc file, same as for an exe.  For managed DLLs I believe it uses AssemblyFileInfo attribute, usually in AssemblyInfo.cs for a Visual Studio generated project:
```
```
[assembly: AssemblyFileVersion("1.0.0.0")]
```
```
If you add the reference by project then VS will be able to copy the correct flavour (debug/release) of the referenced assembly to your output directory. It can also use this information to implicitly add a dependency between the projects so it builds then in the right order.


q:
Is there a way to get stored procedures from a SQL Server 2005 Express database using C#? I would like to export all of this data in the same manner that you can script it our using SQL Server Management Studio, without having to install the GUI.

I've seen some references to do thing via the PowerShell but in the end a C# console app is what I really want.

To clarify....

I'd like to script out the stored procedures. The list via the Select * from sys.procedures is helpful, but in the end I need to script out each of these.

[A]
This blog post
suggests running this against your database:
```
```
select * from sys.procedures
```
```


q:
I want to use a timer in my simple .NET application written in C#. The only one I can find is the Windows.Forms.Timer class. I don't want to reference this namespace just for my console application.

Is there a C# timer (or timer like) class for use in console applications?

[A]
System.Timers.Timer
And as MagicKat says:
System.Threading.Timer
You can see the differences here:
http://intellitect.com/system-windows-forms-timer-vs-system-threading-timer-vs-system-timers-timer/
And you can see MSDN examples here:
http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx
And here:
http://msdn.microsoft.com/en-us/library/system.threading.timer(VS.80).aspx


q:
I'm writing an implementation of the XXTEA encryption algorithm that works on "streams", ie, can be used like: crypt mykey < myfile > output.

One of the requisites is that it doesn't have access to the file at all (it only reads an fixed size block until find an EOF). The algorithm needs that the data bytes is multiple of 4, so its needed to add a padding.

For plain text a good solution is to pad with NULLs, and in the decryption just ignore the NULLs, but the same strategy cannot be used for binary streams (that can contain embedded NULLs).

I've read the common solutions, like padding with the number of missing chars (if it miss 3 chars, then append an 3, 3, 3 at the end) and etc, but I wonder: theres a more elegant solution?

[A]
Read:
http://msdn.microsoft.com/en-us/library/system.security.cryptography.paddingmode.aspx
It has a list of common padding methods, like:
PKCS7 - The PKCS #7 padding string consists of a sequence of bytes, each of which is equal to the total number of padding bytes added.
The ANSIX923 padding string consists of a sequence of bytes filled with zeros before the length.
The ISO10126 padding string consists of random data before the length.
Examples:
Raw data: 01 01 01 01 01
PKCS #7: 01 01 01 01 01 03 03 03
ANSIX923 01 01 01 01 01 00 00 03
ISO10126: 01 01 01 01 01 CD A9 03


q: I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python?

[A]
Look at
zipfile
for compressing a folder and it's subfolders.
Look at
smtplib
for an email client.


q:
In a related question I asked about creating a generic container. Using polymorphic templates seems like the right way to go.

However, I can't for the life of me figure out how a destructor should be written. I want the owner of the memory allocated to be the containers even if the example constructor takes in an array of T (along with its dimensions), allocated at some other point.

I would like to be able to do something like

MyContainer<float> blah();
...
delete blah;

and

MyContainer<ComplexObjectType*> complexBlah();
...
delete complexBlah;`

Can I do something like this? Can I do it without smart pointers?

Again, thanks for your input.

[A]
It can be done, but this is pretty advanced stuff.
You'll need to use something like the boost MPL library (
http://www.boost.org/doc/libs/1_36_0/libs/mpl/doc/index.html
) so that you can get MyContainer's destructor to select the right kind of destructing it will need to do on individual items on the container. And you can use the boost TypeTraits library to decide what kind of deleting is required (
http://www.boost.org/doc/libs/1_36_0/libs/type_traits/doc/html/index.html
). I'm sure it will have a trait that will let you decide if your contained type is a pointer or not, and thus decide how it needs to be destructed. You may need to implement traits yourself for any other types you want to use in MyContainer that have any other specific deletion requirements. Good luck with it! If you solve it, show us how you did it.


q: I like having my warning level set at W4 but all new projects start at W3.  Is there some way to change the default value for warning levels for new projects?

[A]
I don't know how to do it at the IDE but you cand always edit the new project templates at:
```
```
%PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\ProjectTemplates\
```
```
If you're using the express version there could be a minor variation in the path:
```
```
%PROGRAM_FILES%\Microsoft Visual Studio 9.0\Common7\IDE\{Version}\ProjectTemplates\
```
```
Where {Version} is the express flavor you are using, VCSExpress, VBExpress, etc.
The templates are zip files, just edit the project changing:
```
```
<WarningLevel>3</WarningLevel>
```
```
to
```
```
<WarningLevel>4</WarningLevel>
```
```


q:
this code always returns 0 in PHP 5.2.5 for microseconds:

<?php
$dt = new DateTime();
echo $dt->format("Y-m-d\TH:i:s.u") . "\n";
?>

Output:

[root@www1 ~]$ php date_test.php
2008-10-03T20:31:26.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:27.000000
[root@www1 ~]$ php date_test.php
2008-10-03T20:31:28.000000

Any ideas?

[A]
This seems to work, although it seems illogical that
http://us.php.net/date
documents the microsecond specifier yet doesn't really support it:
```
```
function getTimestamp()
{
        return date("Y-m-d\TH:i:s") . substr((string)microtime(), 1, 8);
}
```
```


q:
I have a form with many input fields.

When I catch the submit form event with jQuery, is it possible to get all the input fields of that form in an associative array?

[A]
Associative? Not without some work, but you can use generic selectors:
```
```
var items = new Array();

$('#form_id:input').each(function (el) {
    items[el.name] = el;
});
```
```


q:
How do I iterate over a range of numbers in Bash when the range is given by a variable?

I know I can do this (called "sequence expression" in the Bash documentation):

 for i in {1..5}; do echo $i; done

Which gives:

1

  2

  3

  4

  5

Yet, how can I replace either of the range endpoints with a variable? This doesn't work:

END=5
for i in {1..$END}; do echo $i; done

Which prints:

{1..5}

[A]
You can use
```
```
for i in $(seq $END); do echo $i; done
```
```


q:
Greetings,

I need to include a property in my class which is a collection of System.IO.FileInfo objects.  I am not really sure how to do this and how I would add and removed objects from an instance of the the class (I would assume like any other collection).

Please let me know if I need to add more information.

Thank you

Update: Am I approaching this the wrong way? I have read comments that adding to a collection which is a property is bad practice.  If this is true what is good practice?  I have a bunch of objects I need to store in a collection.  The collection will be added to and removed from before a final action will be taken on it.  Is this a correct approach or am I missing something?

[A]
```
File
```
is a static class. So let's assume you meant
```
FileInfo
```
.
There are lots of ways, you can:
Expose a private field
Use Iterators
Expose a private field through a ReadOnlyCollection<>
For example,
```
```
class Foo {
    public IEnumerable<FileInfo> LotsOfFile {
        get {
            for (int i=0; i < 100; i++) {
                yield return new FileInfo("C:\\" + i + ".txt");
            }
        }
    }
    private List<FileInfo> files = new List<FileInfo>();
    public List<FileInfo> MoreFiles {
        get {
            return files;
        }
    }
    public ReadOnlyCollection<FileInfo> MoreFilesReadOnly {
        get {
            return files.AsReadOnly();
        }
    }

}
```
```
With this code, you can easily add to the property
```
MoreFiles
```
:
```
```
Foo f = new Foo();
f.MoreFiles.Add(new FileInfo("foo.txt"));
f.MoreFiles.Add(new FileInfo("BAR.txt"));
f.MoreFiles.Add(new FileInfo("baz.txt"));
Console.WriteLine(f.MoreFiles.Count);
```
```


q:
I was looking into sorting tables by a column designated given some input, and from what I've found, there is no easy way to do this. The best I've found is a switch statement:

SELECT Column1, Column2, Column3, Column4
FROM Table
ORDER BY CASE WHEN @OrderBY = 'Column1' THEN Column1
              WHEN @OrderBY = 'Column2' THEN Column2
              WHEN @OrderBY = 'Column3' THEN Column3
              WHEN @OrderBY = 'Column4' THEN Column4

Is it possible to do this without having a CASE statement like that? If the table gets bigger and more columns need to be sorted by, this could become messy.

The only way I've been able to do this is by just concatenating a big SQL string, which sort of defeats the advantages of Stored Procedures, and makes the SQL hard to write and maintain.

[A]
I generally convert the stored procedure to a function that returns a table ( so you can select FROM it ... and add the dynamic order by columns to it in the application code:
```
```
Select
    *
From
   myTableFUnction()
Order by
   1, 2, 3, 6  <-- defined by application code in the SQL for the query
```
```
Ron


q: I would like users to submit a URL that is valid but also is an image, ending with .jpg, .png, or .gif.

[A]
```
(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?
```
That's a (slightly modified) version of the official URI parsing regexp from
RFC 2396
. It allows for
```
#fragments
```
and
```
?querystrings
```
to appear after the filename, which may or may not be what you want. It also matches any valid domain, including
```
localhost
```
, which again might not be what you want, but it could be modified.
A more traditional regexp for this might look like the below.
```
^https?://(?:[a-z0-9\-]+\.)+[a-z]{2,6}(?:/[^/#?]+)+\.(?:jpg|gif|png)$
          |-------- domain -----------|--- path ---|-- extension ---|
```
EDIT
See my
other comment
, which although isn't answering the question as completely as this one, I feel it's probably a more useful in this case. However, I'm leaving this here for
karma-whoring
completeness reasons.


q:
When I retrieve a record using LINQ that has a DateTime field only the ToString() is available.

Where are all the other DateTime methods?

I have to Convert.ToDateTime the DateTime? that the Field returns?

What is the difference between (DateTime) and (DateTime?)

[A]
The namespace collision aside, I know that SQL's datetime has a different epoch (and therefore a different range of valid dates) than C# datetime.
Try to send a
```
new DateTime()
```
to a stored procedure and see what I mean.


q:
Is it possible, in Java, to enforce that a class have a specific set of subclasses and no others? For example:

public abstract class A {}
public final class B extends A {}
public final class C extends A {}
public final class D extends A {}

Can I somehow enforce that no other subclasses of A can ever be created?

[A]
Give class
```
A
```
a constructor with package-level accessibility (and no other constructors).
Thanks, Dave L., for the bit about no other constructors.


q:
What is the best way to persist/save printer settings in .Net?
There used to be a bug in .Net 1.1 in the serialization of the PrinterSetting object and there were some workarounds but I'm wondering if there isn't a better or easier way of doing this in the more recent versions of the framework.

The main use case is to allow a user to define, using the standard printer setting user interfaces, all print details (including printer-specific options) for a given printer and have these saved so they get restored the next time the user prints to that printer.

[A]
You should use the class
```
PrinterSettings
```
.


q:
I keep hearing that Flex is open source and I figured that a great way to learn about the inner workings would be to look at it. I can easily find the Flex SDK (http://opensource.adobe.com/wiki/display/flexsdk/Get+Source+Code), but I'm wanting to look at the class definitions for the MXML core library (like NumericStepper). Have I misunderstood, or is this kind of thing available somewhere?

Note, I'm looking for the source of some core MXML components so I can see how they work internally, not for the compiler's source. Does what I've linked above have what I'm looking for and I just can't find it in the director structure?

[A]
The open source stuff appears to be at:
```
```
http://opensource.adobe.com/wiki/display/flexsdk/Downloads
```
```
I don't know if everything is available there yet, there may be issues with third-party stuff.


q: I'm looking for a word processing component for .NET that would act like an embedded MS Word in my WinForm/WPF .NET app.  The main goal being for users to be able to create rich formatted text.  I don't really want to have to write a highly custom RichTextBox component.  Any suggestions?

[A]
Obviously I have no idea what your particular project requirements are, but
ScintillaNET
is a fabulous control and is flexible enough to do a lot more than just syntax highlighting.  I can foresee cases where it certainly wouldn't be appropriate, but it is at least worth investigating.  After a fair amount of searching it has perfectly filled a void in an application of mine where I need to do extensive contextual highlighting of prose.
Edit
I'm revoking this comment because I've thought about it a minute longer and the finite number of styles that Scintilla provides would make it inappropriate for rich text editing.  However, it is still an excellent solution for any situation where you can determine programmatically how styling will be applied.


q:
In Javascript, I have an object:

obj = { one: "foo", two: "bar" };

Now, I want do do this

var a = 'two';
if(confirm('Do you want One'))
{
  a = 'one';
}

alert(obj.a);

But of course it doesn't work.  What would be the correct way of referencing this object dynamically?


q: What's the best .NET communication component or protocol for very low bandwidth and intermittently connected communication (i.e.: < 10 kilobits/sec)?

[A]
Probably
```
System.Net.Sockets.
```
```
Socket
```
. There is also a
```
TcpClient
```
and
```
UdpClient
```
in that namespace.


q:
I am totally new to SQL. I have a simple select query similar to this:

SELECT COUNT(col1) FROM table1

There are some 120 records in the table and shown on the GUI.
For some reason, this query always returns a number which is less than the actual count.

Can somebody please help me?

[A]
Try
```
```
select count(*) from table1
```
```
Edit:
To explain further,
```
count(*)
```
gives you the rowcount for a table, including duplicates and nulls.
```
count(isnull(col1,0))
```
will do the same thing, but
slightly
slower, since
```
isnull
```
must be evaluated for each row.


q:
I'm trying to get into java again (it's been a few years). I never really did any GUI coding in java. I've been using Netbeans to get started with this.

When using winforms in C# at work I use a usercontrols to build parts of my UI and add them to forms dynamically.

I've been trying to use JPanels like usercontrols in C#. I created a JPanel form called BlurbEditor. This has a few simple controls on it. I am trying to add it to another panel at run time on a button event.

Here is the code that I thought would work:

mainPanel.add(new BlurbEditor());
mainPanel.revalidate();
//I've also tried all possible combinations of these too
//mainPanel.repaint();
//mainPanel.validate();

This unfortunately is not working. What am I doing wrong?

[A]
Try
```
mainPanel.invalidate()
```
and then if necessary,
```
mainPanel.validate()
```
.  It also might be worth checking that you're doing this all in the event dispatch thread, otherwise your results will be spotty and (generally) non-deterministic.


q:
I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images.

I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it won't be able to sufficiently scale in terms of performance or capabilities.

Requirements are:

Cross-platform (Linux, MacOS X,
Windows)

Low complexity overhead

Plays well with wxpython (at least won't step on each other's toes unduly)

Interactivity. Detect when objects are clicked on, moused over, etc.

Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good.

Your thoughts?

[A]
I am a fan of
pyglet
which is a completely self contained library for doing graphical work under win32, linux, and OS X.
It has very low overhead, and you can see this for yourself from the tutorial on the website. It
should
play well with wxpython, or at least I seem to recall posts to the mailing list about wxpython and pyglet being used together.
It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do.
mactorii
is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P


q:
In the same spirit of other platforms, it seemed logical to follow up with this question: What are common non-obvious mistakes in Java? Things that seem like they ought to work, but don't.

I won't give guidelines as to how to structure answers, or what's "too easy" to be considered a gotcha, since that's what the voting is for.

See also:

Perl - Common gotchas

.NET - Common gotchas

[A]
Going first, here's one I caught today. It had to do with
```
Long
```
/
```
long
```
confusion.
```
```
public void foo(Object obj) {
    if (grass.isGreen()) {
        Long id = grass.getId();
        foo(id);
    }
}
private void foo(long id) {
    Lawn lawn = bar.getLawn(id);
    if (lawn == null) {
        throw new IllegalStateException("grass should be associated with a lawn");
    }
}
```
```
Obviously, the names have been changed to protect the innocent :)


q:
I'm thinking the answer is no, but I'd love it it anybody had any insight into how to crawl a tree structure to any depth in SQL (MySQL), but with a single query

More specifically, given a tree structured table (id, data, data, parent_id), and one row in the table, is it possible to get all descendants (child/grandchild/etc), or for that matter all ancestors (parent/grandparent/etc) without knowing how far down or up it will go, using a single query?

Or is using some kind of recursion require, where I keep querying deeper until there are no new results?

Specifically, I'm using Ruby and Rails, but I'm guessing that's not very relevant.

[A]
You're almost definitely going to want to employ some recursion for that. And if you're doing that, then it would be trivial (in fact easier) to get the entire tree rather than bits of it to a fixed depth.
In really rough pseudo-code you'll want something along these lines:
```
```
getChildren(parent){
    children = query(SELECT * FROM table WHERE parent_id = parent.id)
    return children
}

printTree(root){
    print root
    children = getChildren(root)
    for child in children {
        printTree(child)
    }
}
```
```
Although in practice you'd rarely want to do something like this. It will be rather inefficient since it's making one request for every row in the table, so it'll only be sensible for either small tables, or trees that aren't nested too deeply. To be honest, in either case you probably want to limit the depth.
However, given the popularity of these kinds of data structure, there may very well be some MySQL stuff to help you with this, specifically to cut down on the numbers of queries you need to make.
Edit: Having thought about it, it makes very little sense to make all these queries. If you're reading the entire table anyway, then you can just slurp the whole thing into RAM - assuming it's small enough!


q: I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window.  I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work.  Any ideas?

[A]
```
```
myWindow.document.writeln(documentString)
```
```


q: I'm not looking for a full implementation, I'm more interested in how they do it.  I know they use GWT, but I'd like a more low level answer.  Naively, I would start by thinking when you click the popout link they simply open a new window and copy content into it.  There are lots of reasons why that won't work out well, so I'm wondering if anyone knows or has ideas on how they do this or how it could be done.

[A]
I recently needed to solve exactly this problem in an app. I ended up using this great little jQuery plugin to do the trick: WindowMsg (see link at bottom) While I'm sure there are other ways to accomplish the same task, that plugin does works thusly:
first you create a new child window from your original window using window.open
you save a reference to the window object returned by window.open
you call a library method in the child window that adds a hidden form for the library to store data in
you call a library method in the parent window that uses window.document.forms to populate form fields on the child window (the library abstracts all of this stuff so you wouldn't even know there was a form involved unless you looked at the source) window.document.forms works the same on all major browsers so this abstraction in x-browser compatible
finally, the child window refers back to its parent window using window.opener and can communicate back via a parallel hidden form on the parent
the library implements a convenient helper that takes a callback function to run on each side to make the callback chain easy to deal with
In my experience working with the library, it would have also been quite nice if they had included the JSON 2 lib from JSON.org. Out of the box, WindowMsg only allows you to send string messages between windows, but with some pretty simple use of the JSON 2 lib, I was able to hack it to allow the sending of full JSON objects between windows. I bet more mature libraries (such as whatever google uses) include that kind of serialization and de-serialization baked in.
I am putting this link here because for some reason, the Stack Overflow formatter turns it into an anchor link with no closing tag and I don't want my whole post to be one giant hyperlink!
WindowMsg:
http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/


q:
There's another post on SO relating to .NET -- not us.  Pure PHP.  Trying to find the best way/process to deploy stable version of our PHP app.  I've seen an article on Capistrano, but am curious what else is out there.  Aside from the obvious reasons, I'm also looking to add some scripting so that the SVN rev number gets added in there as well.

Much thanks.

[A]
I've used a home-grown script for quite some time. It will (based on an application configuration file):
Run
```
svn export
```
on the repository based on a tag.
Package the export into a tar or zip file, which includes the tag in the name.
Use
```
scp
```
to copy the package to the appropriate server (QA or release).
Connect to the server with
```
ssh
```
to install the package and run post-install scripts.
The application configuration file is part of the project. It can tell the script (at step 2) to strip paths and otherwise process specified files. It also specifies server names and how to handle externals.
I've recently migrated the script to support Git as well as Subversion. I'm also probably going to migrate it to PHP since we're now running in a mixed (Linux and Windows) set up, with Linux now in the minority.
I have plans to automatically call the script with post-commit hooks, but haven't had the need to implement that just yet.


q:
I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error.

And I found the py2exe said:

The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg_resources', 'pywintypes', 'resource', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security']

So how do I solve this problem?

Thanks.

[A]
I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out.
You can explicitly specify modules to include on the py2exe command line:
```
```
python setup.py py2exe -p win32com -i twisted.web.resource
```
```
Something like that. Read up on the options and experiment.


q: I want to write a script which cleans the 'run' dialogue automatically every log off. Where is the history stored?

[A]
```
```
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\RunMRU
```
```


q: I need to encode a 100KB+ string as base64 in VBA. Are there any built-in functions or COM objects available which will do this as a pure VBA approach is either complex or doesn't scale well at these volumes (see links from dbb and marxidad)?

[A]
You can use the MSXML Base64 encoding functionality as described at
www.nonhostile.com/howto-encode-decode-base64-vb6.asp
:
```
```
Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As MSXML2.DOMDocument
  Dim objNode As MSXML2.IXMLDOMElement

  Set objXML = New MSXML2.DOMDocument
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = Replace(objNode.Text, vbLf, "")

  Set objNode = Nothing
  Set objXML = Nothing
End Function
```
```


q:
I want to convert a string into a double and after doing some math on it, convert it back to a string.

How do I do this in Objective-C?

Is there a way to round a double to the nearest integer too?

[A]
You can convert an NSString into a double with
```
```
double myDouble = [myString doubleValue];
```
```
Rounding to the nearest int can then be done as
```
```
int myInt = (int)(myDouble + (myDouble>0 ? 0.5 : -0.5))
```
```
I'm honestly not sure if there's a more streamlined way to convert back into a string than
```
```
NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];
```
```


q:
I'm wondering what's a reasonable size for iPhone Apps. Right now I'm working on an iPhone game, and of course it loads fast into my device since I'm connected directly to it through a USB cable, but I've no idea how long it would actually take to download from the App Store.

In my case it's about 2mb in size, which is reasonable for a desktop or even a flash game, but I've no idea if this is reasonable size for the iPhone.

My other concern is what's the non-wifi download limit of the App Store? Occasionally there are Apps that won't download unless you've got a wifi connection. And personally I've never downloaded such apps, since it gives me a bad impression. So I'd definitely want to stay below that limit.

Also since I'm already asking about app sizes, it would be probably be useful to collect good sizes for other types of apps as well.

Thanks!

[A]
The 3g network is fast.  I wouldn't limit your development based on this - do exactly what you need to do to make your game as good as it can be, and people will download it even if it takes a tiny bit longer.  I've downloaded 10MB+ applications from the store over 3g and it might as well be a slow wi-fi connection, it's just that fast.
Also remember that many people purchase on their computers (hence a fast connection) and then just sync to the iPhone, especially those that are in areas with slower cellular networks.
Bottom line, size won't affect downloads, ratings will.


q:
Per this Adobe KB tech note is there any way around having to place the FLVPlayback skin SWF in same directory as HTML file the container SWF is loaded from?  It pains me to have to put a SWF in my site's root directory.

I think loading the Flash video in an iframe would solve this problem, but is that a good practice?  I generally shy away from using iframes because of padding, margin, and sizing issues between browsers.  Maybe that's not an issue anymore with CSS.

[A]
Well, you can place the skin in another directory as long as you specify the path (relative to the loading HTML) in the "skin" parameter for your FLV playback component in the component inspector. Troubleshooting is very easy if you use the Net panel in Firebug or a similar tool.
Using an iframe works and don't cause rendering problems as long as you take care that there's no margin or padding inside the iframe. However, you will need another HTML file which can make maintaining your site more of a hassle.
If you are publishing a lot of video files, you might find that it's more convenient to use a standalone player such as the
JW Media Player
.


q:
Let's say:

<div>
  pre text
  <div class="remove-just-this">
    <p>child foo</p>
    <p>child bar</p>
    nested text
  </div>
  post text
</div>

to this:

<div>
  pre text
  <p>child foo</p>
  <p>child bar</p>
  nested text
  post text
</div>

I've been figuring out using Mootools, jQuery and even (raw) JavaScript, but couldn't get the idea how to do this.

[A]
Using
jQuery
you can do this:
```
```
var cnt = $(".remove-just-this").contents();
$(".remove-just-this").replaceWith(cnt);
```
```
Quick links to the documentation:
contents
( ) :
jQuery
replaceWith
(
content
: [
String
|
Element
|
jQuery
] ) :
jQuery


q: While Scrum is easy in theory and hard in practice, I wanted to hear your definition of Done; i.e. what are the gates (unit test, code coverage > 80%, code reviews, load tests, perf.test, functional tests, etc.) your product has to go through before you can label the product "Done"

[A]
There are three nice articles by
Mitch Lacey
,
Dhaval Panchal
and
Mayank Gupta
on this on the ScrumAlliance website.
EDIT:
Basically the whole point is that
done is defined on a project-by-project basis by the team
. The basic need is to agree on the definition, not what the definition is.


q:
I'm trying to make things simpler. Here is my code:

    If Threading.Monitor.TryEnter(syncRoot) Then
        Try
            'do something
        Finally
            Threading.Monitor.Exit(syncRoot)
        End Try
    Else
        'do something else
    End If

This is even worse than the ReaderWriterLock in terms of noise.
I can use C# or VB, so answers applying to either will be welcome.

[A]
This is very similar to your
last post
, and I would expect a similar answer. The only significant difference is that you might return "null" from your method if the timeout fails - then the "Dispose()" is not called, and you can easily check the value:
```
```
using(var token = GetLock(syncLock, timeout)) {
  if(token != null) { ... }
}
```
```
The only real glitch is that you don't necessarily want to add an extension method to "object" (or even "T where T : class")...
Jon Skeet
has looked at this in the past -
worth a look
.


q:
 <DataTemplate x:Key="Genre_DataTemplate">
        <RadioButton GroupName="One" Content="{Binding...
 </DataTemplate>

Above code is the ItemTemplate of my ItemsControl, I want all the Radiobuttons instantiated should behave as if it is in a group, I know the reason because the generated RadioButtons are not adjacent in the visualtree.

Any solution or workaround to group them together?. GroupName property also doesn't have any effect here.

[Update] I am trying this in Silverlight

[A]
I think the problem is somewhere else in the control tree. Can you post more details?
Here is a sample xaml code that works as expected:
```
```
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
 <Grid>
    <Grid.Resources>
       <XmlDataProvider x:Key="flickrdata" Source="http://api.flickr.com/services/feeds/photos_public.gne?tags=flower&lang=en-us&format=rss_200">
          <XmlDataProvider.XmlNamespaceManager>
             <XmlNamespaceMappingCollection>
                <XmlNamespaceMapping Prefix="media" Uri="http://search.yahoo.com/mrss/"/>
             </XmlNamespaceMappingCollection>
          </XmlDataProvider.XmlNamespaceManager>
       </XmlDataProvider>
       <DataTemplate x:Key="itemTemplate">
        <RadioButton GroupName="One">
          <Image Width="75" Height="75" Source="{Binding Mode=OneWay, XPath=media:thumbnail/@url}"/>
        </RadioButton>
       </DataTemplate>
       <ControlTemplate x:Key="controlTemplate" TargetType="{x:Type ItemsControl}">
          <WrapPanel IsItemsHost="True" Orientation="Horizontal"/>
       </ControlTemplate>
    </Grid.Resources>
    <ItemsControl
       Width="375"
       ItemsSource="{Binding Mode=Default, Source={StaticResource flickrdata}, XPath=/rss/channel/item}"
       ItemTemplate="{StaticResource itemTemplate}"
       Template="{StaticResource controlTemplate}">
    </ItemsControl>
 </Grid>

</Page>
```
```
P.S.: In order grouping to work elements radio buttons should have same parent (as they usually have when generated from ItemsControl)


q:
SQL Server profiler is great for profiling SQL Server performance for web apps. However, when I'm testing my webapp I'd like a summary of database hits/duration per page.

Does anybody know of any utilities for giving you this kind of information?


q:
What criteria should I use to decide whether I write VBA code like this:

Set xmlDocument = New MSXML2.DOMDocument

or like this:

Set xmlDocument = CreateObject("MSXML2.DOMDocument")

?

[A]
For the former you need to have a reference to the type library in your application.  It will typically use early binding (assuming you declare your variable as MSXML2.DOMDocument rather than as Object, which you probably will), so will generally be faster and will give you intellisense support.
The latter can be used to create an instance of an object using its ProgId without needing the type library.  Typically you will be using late binding.
Normally it's better to use "As New" if you have a type library, and benefit from early binding.


q:
I've gone to http://sourceforge.net/project/showfiles.php?group_id=2435, downloaded the Automated MinGW Installer for MinGW 5.1.4 and at the same time the GNU Source-Level Debugger Release Candidate: GDB 6.8-3. I've then installed MinGW base tools into C:\MinGW. No problem so far.

However when I come to install the gdb debugger it has a lot of files and folders with the same names as some already installed but the files are different to those already installed. e.g C:\MinGW\include\bfd.h is 171 KB but gdb-6.8-mingw-3\include\bfd.h is 184 KB.

How do I add gdb to MinGW without breaking what's already installed?

[A]
The
Current Release
(5.2.1) version of gdb at the
project files page
has always worked for me. The download is a stand-alone .exe, you don't need anything else.
But I'll bet the .exe in the 6.8 package will work, too. I'd try using just the .exe, and then if there are problems, try extracting the other files from the 6.8 package. (Though that may cause problems with the rest of the MinGW installation.)
Update: There seems to be a 7.something version. I haven't tested it thoroughly, but it seems to work, even with gcc 3.


q: Hi are there any pros / cons relating to the speed that a stored procedure executes when using an IF statement or choosing to use a CASE statement instead?

[A]
Have you considered simply validating resource access through an HTTP request to the server after the swf loads?
Where I work we provide online trainings to users through flash but rather than verify the HTTP request itself, we allow the swf's to load first and then make a request to the server to verify that the user should have access to the swf and that they are accessing the swf from within our site and not from another location.
If any step of validation fails (either it fails to find an auth file in the necessary location or the user does not have a valid session or does not have access to the particular training) then they receive an error within flash and none of the important content ever loads.
As another note, if you do decide that you want to strictly limit access to the files so that they can only be loaded by those who should have access, then I would probably suggest using your second option of storing the files in a separate, non-public location and then using a handler script to load the swf.


q:
How do I add the Swedish interactive user,

NT INSTANS\INTERAKTIV

or the English interactive user,

NT AUTHORITY\INTERACTIVE

or any other localised user group with write permissions to a program folder's ACL?

Is this question actually "How do I use secureObject"? I cannot use the LockPermissions Table because I undestand inheritance is removed. secureObject permissions seem to require CreateDirectory rather than Directory...

[A]
There is no way
as such
to add both account names to an ACL since they are one and the same. The name you see corresponds to a SID, and that SID is identical in both the English and Swedish localizations. In the case of the INTERACTIVE group, that SID is
```
S-1-5-4
```
.
I haven't followed WiX in a long while, but I expect there has to be a way to specify SIDs for ACLs instead of account names. You should never, ever rely on the account name for well-known accounts unless there is absolutely no way to avoid it. Here is a
list of well-known SIDs
for reference.
Edit:
This post
seems to provide a solution to your problem using a custom action to translate the SIDs to account names - apparently WiX doesn't out of the box support using SIDs for Permission or PermissionEx objects.
Here is a more authoritative list of well-known SIDs in
Q243330
of the Microsoft Knownledge Base.


q:
I was previously taught today how to set parameters in a SQL query in .NET in this answer (click).

Using parameters with values are fine, but when I try to set a field in the database to null I'm unsuccessful. Either the method thinks I am not setting a valid parameter or not specifying a parameter.

e.g.

Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)

If actLimit.ToLower() = "unlimited" Then
    ' It's not nulling :(
    dc.Parameters.Add(New SqlParameter("Limit", Nothing))
Else
    dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))
End If

Is there something I'm missing? Am I doing it wrong?

[A]
Try setting it to
```
DbNull.Value
```
.


q:
What is the minimal conventional directory structure for a Java web app? What do I need to put in a build.xml file to get ant to build it and make a WAR file?

My goal is to deploy a Wicket app to Tomcat without using an IDE. I want to do it with only ant and my favourite text editor.

[A]
Ours look like this:
```
```
web/
web/WEB-INF/   (sometimes we use a conf/ dir at the top level but this is minimal)
src/
lib/
```
```
The build.xml has three targets:
jsp: copies everything from web/ into the tomcat webapp folder and from lib/ into WEB-INF/lib
compile: compiles everything from src/ into WEB-INF/classes in the webapp
war: runs compile, jsp, and then zips the contents of the tomcat webapp into a warfile
This structure is a little bit informal and you can do it more cleanly by having a separate build directory for the warfile, and/or a separate compile directory, etc. Some people don't like the idea of deploying directly to the webapp instead of building a war first. But to get something up and running quickly, the above will do nicely.


q:
Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups.  However, when inserting one must always check if the first index already exists in the hash. For example:

h = Hash.new
h['x'] = Hash.new if not h.key?('x')
h['x']['y'] = value_to_insert

It would be preferable to do the following where the new Hash is created automatically:

h = Hash.new
h['x']['y'] = value_to_insert

Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error.

looked_up_value = h['w']['z']

One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?

[A]
You can pass the
```
Hash.new
```
function a block that is executed to yield a default value in case the queried value doesn't exist yet:
```
```
h = Hash.new { |h, k| h[k] = Hash.new }
```
```
Of course, this can be done recursively. There's
an article explaining the details
.
For the sake of completeness, here's the solution from the article for arbitrary depth hashes:
```
```
hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)}))
```
```
The person to originally come up with this solution is
Kent Sibilev
.


q:
I am trying to set myself up on a mac to learn Ruby on Rails, however I seem to be having some problems. If I try to run commands such as ./script/server, i get this:

Rails requires RubyGems >= 0.9.4 (you have 0.9.2). Please gem update --system and try again.

When I run "gem update.." I get this:

Updating RubyGems...
  Attempting remote update of rubygems-update
  ERROR:  While executing gem ... (Errno::EACCES)
      Permission denied - /opt/local/lib/ruby/gems/1.8/cache/rubygems-update-1.3.0.gem

[A]
got it.
sudo gem update --system


q:
Is there a mode, some switch or a programmatic way that I can ask MSBuild to display or output it's calculated dependencies for a given build file?

Some background -
I have a large project that requires splitting up to speed up the build time and want to remove the slow changing infrastructure code into it's own release area.  Not all of the information is contained in the build file itself, as some sub-projects are referenced by their vcproj or csproj files.

I'd really like to see what MSBuild thinks needs doing (either worse-case [rebuild all] and perhaps for a make) without actually doing the rebuild.

[A]
The
MSBuild Profiler
project should be able to help you in seeing where time is being taken on the build.  It doesn't directly show dependencies.  With or without build dependencies, just profiling the builds can probably give some insight and help speed up the process.
I did just come across this application, but I have not used it myself yet,
Dependency Visualizer
that looks to have just added MSBuild-compatible project files.  There have also been posts about doing this previously, but no code (see
A
,
B
).


q:
I would like to execute a stored procedure within a stored procedure, e.g.

EXEC SP1

BEGIN

EXEC SP2
END

But I only want SP1 to finish after SP2 has finished running so I need to find a way for SP1 to wait for SP2 to finish before SP1 ends.

SP2 is being executed as part of SP1 so I have something like:

CREATE PROCEDURE SP1
AS
BEGIN

EXECUTE SP2

END

[A]
Thats how it works stored procedures run in order, you don't need begin just something like
```
```
exec dbo.sp1
exec dbo.sp2
```
```


q: I seem to only be able to write to the Apache error log via stderr.  Anyone know of a more structured logging architecture that I could use from my python web project, like commons?

[A]
I've used the builtin
Python logging module
in (non-web) projects in the past, with success - it should work in a web-hosted environment as well.


q:
I'm working on a java web-application, trying to be xml-friendly and writing my jsp files using the jspx/xml syntax. It took me hours of dissecting examples and configuration files to find out that with tomcat 5.5 files using the new syntax should end in .jspx, or tomcat won't translate tag libraries and stuff.

Both file extensions map to the same servlet in tomcat's configuration file, so I thought everything was fine with my .jsp files. Am I missing something?

[A]
There are additional configurations for servlets that can affect behavior.  I haven't tried it, but would assume that you could just override some of the default configurations  for *.jsp to use that of *.jspx.
Try adding a
jsp-property-group
definition for
*.jsp
with
is-xml
set to true:
```
```
<jsp-property-group>
  <url-pattern>*.jsp</url-pattern>
  <is-xml>true</is-xml>
</jsp-property-group>
```
```
Some information on configuring property group
s.


q: On a question of just performance, how does Python 3 compare to Python 2.x?

[A]
I'd say any difference will be below trivial. For example, looping over a list will be the exact same.
The idea behind Python 3 is to clean up the language syntax itself - remove ambigious stuff like
```
except Exception1, Exception2
```
, cleanup the standard modules (no urllib, urllib2, httplib etc).
There really isn't much you can do to improve it's performance, although I imagine stuff like the garbage collection and memory management code  will have had some tweaks, but it's not going to be a "wow, my database statistic generation code completes in half the time!" improvement - that's something you get by improving the code, rather than the language!
Really, performance of the language is irrelevant - all interpreted languages basically function at the same speed.
Why I find Python "faster" is all the built-in moudles, and the nice-to-write syntax - something that
has
been improved in Python3, so I guess in those terms, yes, python3's performance is better then python2.x..


q:
I have found that SP2 doesn't execute from within SP1 when SP1 is executed.

Below is the structure of SP1:

ALTER PROCEDURE SP1 AS BEGIN

Declare c1 cursor....

open c1 fetch next from c1 ...

while @@fetch_status = 0 Begin

...

Fetch Next from c1 end

close c1

deallocate c1

exec sp2

end

I see non of the PRINT statement outputs if they are printed in the 'Output window' in SQL Server 2005 management studio as the 'Output Window'is empty.

[A]
What happens if you run the Stored Procedure code as a single query? If you put a
```
PRINT
```
statement before and after the exec, do you see both outputs?
If you do, then the stored procedure must have been executed. Probably it's not doing what you would like.
If you don't see any print output, then there's something wrong in the cycle
If you don't see the second output but you see the first, there's something wrong in the second Stored Procedure.


q:
Which search engine would you recommend for a Commerce website?

We have millions of products in a catalog and we want it to be as quick as possible.

We would also want to make sure that the marketing driven through the search engine will be fast and effective.

What are your opinions?

[A]
This is only half the answer to your question. I've used it with Java and not .NET. Fast is said to be the better search engine. I don't know. However for Commerce Endeca is considered to be the best. I've used it with a catalog of 5Mil. products and queries are very very fast.
If you use .NET or Java does not matter in the end solution the Search Engine stays the same.
And what search engine to be used is not answered easily. it all depends on what you want/can spend. My experiences with Endeca are very positive.


q:
PHP has a number of opcode caches, which as i understand it are scripts that handle the caching aspects of an application. Is there something similar for classic asp, especially something that does not require component installation?

Regarding the IIS caching behaviour, it seems from reading here that the behaviour is relevant to some sort of pre-compilation step rather than finished pages. please correct me if i am wrong

[A]
Looking at your comments to the answers here so far and at your edit of your question you seem a little confused over caching.
There are two types of caching we could be be talking about.
Opcode or Template caching
Output caching
Opcode or Template caching
is the caching that takes place when a raw script file which is merely a text file is transformed to an in memory set of opcodes that can be executed by the script engine.  PHP has some additional tools which allow such a set of opcodes be reused when the script file is requested subsequently.  Similarly ASP keeps a cache of 'compilied' opcodes in memory and on disk so that it can serve subsequent requests for the same script without going through the whole parsing process again.
Output caching
is where the generated output of script that is sent to a response buffer is cached so that subsequent requests for an identical URL (and possible matching other headers as well) would not re-run the script at all but resend the previously cached output.
ASP has no facility for output caching whereas ASP.NET does.  I'm not familiar enough with PHP or its normal platforms to comment on whether such a facility is available for it.
You can configure ASPs 'opcode' caching (which it calls template caching) in IIS manager (IIS6) open the properties window on the Web Sites node go to home directory tab and click Configuration... then select the cache options tab. By default 500 'compilied' pages will be cached in memory and 2000 will be cached on disk.
In a comment to my original version of this answer you seem to asking whether PHP hosted by IIS would also benefit from template caching.  That would depend how PHP is added to the platform.
I hardly know anything about PHP but I would imagine it is simply another dll which IIS script mapping maps files with the extension PHP to.  That being that case it won't be benefiting from ASPs template caching.
The following is probably fiction but just to try to round out the picture:-
Another unlikely possiblity would be if PHP were some how added as ASP Script language.  In this case files with PHP extension would be mapped to the ASP.DLL and the files would either contain <%@ language="PHP" or the default language in the application configuration would be set to PHP.  In this unlikely set up ASP would build a template that would be cached, however whether that template contains 'compilied' opcode etc would be up to PHP.


q:
I want to experiment with GCC whole program optimizations. To do so I have to pass all C-files at once to the compiler frontend. However, I use makefiles to automate my build process, and I'm not an expert when it comes to makefile magic.

How should I modify the makefile if I want to compile (maybe even link) using just one call to GCC?

For reference - my makefile looks like this:

LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

OBJ = 64bitmath.o    \
      monotone.o     \
      node_sort.o    \
      planesweep.o   \
      triangulate.o  \
      prim_combine.o \
      welding.o      \
      test.o         \
      main.o

%.o : %.c
    gcc -c $(CFLAGS) $< -o $@

test: $(OBJ)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)

[A]
```
```
LIBS  = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall

# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)

test: $(SRC)
    gcc -o $@ $^ $(CFLAGS) $(LIBS)
```
```


q: What's the best way to create a non-NULL constraint in MySQL such that fieldA and fieldB can't both be NULL. I don't care if either one is NULL by itself, just as long as the other field has a non-NULL value. And if they both have non-NULL values, then it's even better.

[A]
I've done something similar in SQL Server, I'm not sure if it will work directly in MySQL, but:
```
```
ALTER TABLE tableName ADD CONSTRAINT constraintName CHECK ( (fieldA IS NOT NULL) OR (fieldB IS NOT NULL) );
```
```
At least I believe that's the syntax.
However, keep in mind that you cannot create check constraints across tables, you can only check the columns within one table.


q:
I want to save the objects I generated in a program. After restart the App should load automaticly all Objects in an Array. I want to write them in a file and parse them after restart. Are the other smarter possibilities than do it by hand?
Thank you

[A]
Yes, the concept you are looking for is called serialization. There's a fine tutorial at Sun
here
.
The idea is that classes you want to persist have to implement the Serializable interface. After that you use java.io.ObjectOutputStream.writeObject() to write the object to a file and java.io.ObjectInputStream.readObject() to read it back.
You can't serialize everything, as there are things that don't make sense to serialize, but you can work around them. Here's a quote about that:
The basic mechanism of Java
  serialization is simple to use, but
  there are some more things to know. As
  mentioned before, only objects marked
  Serializable can be persisted. The
  java.lang.Object class does not
  implement that interface. Therefore,
  not all the objects in Java can be
  persisted automatically. The good news
  is that most of them -- like AWT and
  Swing GUI components, strings, and
  arrays -- are serializable.
On the other hand, certain
  system-level classes such as Thread,
  OutputStream and its subclasses, and
  Socket are not serializable. Indeed,
  it would not make any sense if they
  were. For example, thread running in
  my JVM would be using my system's
  memory. Persisting it and trying to
  run it in your JVM would make no sense
  at all. Another important point about
  java.lang.Object not implementing the
  Serializable interface is that any
  class you create that extends only
  Object (and no other serializable
  classes) is not serializable unless
  you implement the interface yourself
  (as done with the previous example).
That situation presents a problem:
  what if we have a class that contains
  an instance of Thread? In that case,
  can we ever persist objects of that
  type? The answer is yes, as long as we
  tell the serialization mechanism our
  intentions by marking our class's
  Thread object as transient.


q:
This is related to the accepted answer for What’s your #1 way to be careful with a live database?

Suppose you create a temp table for backup purpose and make your changes in the original. The changes break the system and you want to restore the backup. In the meantime some other records have also changed in the original table (it is a live db). Now if you restore the backup, the system will be in an inconsistent state.

Whats the best way to tackle this

[A]
I don't think that's desirable, I'd test harder before putting the table in production, but supposing it happened anyway, you'd have two options:
1.- Create an ON INSERT trigger which updates the temporary backup table with the rows inserted into the new table, massaging the data to fit into the old table
or
2.- Find the difference in the data like this
```
```
SELECT * FROM faultyTable
EXCEPT
SELECT * FROM backupTable
```
```
You'd have to adjust the columns to be selected to the common subset of course. And EXCEPT is called MINUS sometimes too.
After that you can insert the difference into the backed up table and restore the combination. This gets harder and harder the more relationships the table has... depending on the way used to restore the table you might drop the related data, thus you'd have to select it too.


q:
Does anyone have an idea how long it will take before "almost all" widely used Python libraries work with Python 3.0?

I am planning to stay on 2.X for a while because I don't want to start porting stuff over and then find that some library I already rely on or a new library I might start using doesn't work yet with py3k.

My understanding is that the py3k beta process was drawn out specifically to give library developers time to move their stuff over. Has this been happening?

Examples of the sorts of libraries I am talking about would be PIL, numpy/ scipy, SQLAlchemy, BeautifulSoup, CherryPy...

[A]
The examples you have listed will probably be ported very quickly, as they are so widely used.
I would be surprised if BeautifulSoup takes more than a month (In fact, I'm surprised it hasn't been ported already using the py3k betas), more complex things like numpy may take a big longer, especially because 2to3 only works on python sources, not C modules..
It's hard to generalise - some modules may never be ported, some may take days, others may take years. It could end up being a situation along the lines of "well I'm not porting my library to Python3, no one is using it!"/"Well I'm not porting my project to python3, no libraries have been updated yet!", but I hope not!


q:
On some Microsoft Access queries, I get the following message:  Operation must use an updatable query. (Error 3073).  I work around it by using temporary tables, but I'm wondering if there's a better way.  All the tables involved have a primary key. Here's the code:

UPDATE CLOG SET CLOG.NEXTDUE = (
    SELECT H1.paidthru
    FROM CTRHIST as H1
    WHERE H1.ACCT = clog.ACCT AND
    H1.SEQNO = (
        SELECT MAX(SEQNO)
        FROM CTRHIST
        WHERE CTRHIST.ACCT = Clog.ACCT AND
        CTRHIST.AMTPAID > 0 AND
        CTRHIST.DATEPAID < CLOG.UPDATED_ON
    )
)
WHERE CLOG.NEXTDUE IS NULL;

[A]
Since Jet 4, all queries that have a join to a SQL statement that summarizes data will be non-updatable. You aren't using a JOIN, but the WHERE clause is exactly equivalent to a join, and thus, the Jet query optimizer treats it the same way it treats a join.
I'm afraid you're out of luck without a temp table, though maybe somebody with greater Jet SQL knowledge than I can come up with a workaround.
BTW, it might have been updatable in Jet 3.5 (Access 97), as a whole lot of queries were updatable then that became non-updatable when upgraded to Jet 4.
--


q:
I have read on Stack Overflow some people that have converting to C#2.0 to C#3, but is it really worth it?

I have a project that is done at 75% before going in maintenance phase. I am asking to myself if it is worth it to switch to C#3.0?

Update:

The project will have a web interface now so before entering the maintenance phase we have to develop the web part (all was done for internal purposes with Windows Forms). Most parts will be resused (back-end). Most people have said that it wasn't worth it in the past because it was already at 75%... but now do you still think it's not worth it?

What have been done finally

Finally since we are continuing the project with the web interface we will update to 3.5 for the new year. Thank you everybody for all your input.

[A]
Is there any C# 3.5 feature you want badly at this stage? :)
If it is LINQ, you can give
LINQBridge
a try..
With Studio's multi-targeting and LINQBridge, you'll be able to write local (LINQ to Objects) queries using the full power of the C# 3.0 compiler—and yet your programs will require only Framework 2.0.


q: I have a somewhat messily-formatted Objective-C code base. Is there a way to have Xcode reformat an entire project to conform to a coding standard (i.e., properly indent, spaces v. tabs, etc.)? Are there other tools that might accomplish this?

[A]
According to this
blog post
,
bcpp
works with Objective-C.
In addition, the tool indent might help you. It's aimed at plain C but has a gazillion options that could help. I don't know if it comes by default on OS X though.
```
```
NAME
       indent - changes the appearance of a C program by inserting or deleting
       whitespace.

SYNOPSIS
       indent [options] [input-files]

       indent [options] [single-input-file] [-o output-file]

       indent --version

DESCRIPTION
       This man page is generated from the file indent.texinfo.  This is  Ediâ
       tion  of "The indent Manual", for Indent Version , last updated .

       The  indent  program  can  be used to make code easier to read.  It can
       also convert from one style of writing C to another.

       indent understands a substantial amount about the syntax of C,  but  it
       also attempts to cope with incomplete and misformed syntax.
```
```


q:
I am trying to compile my apps (which uses 3rd party libraries) for the x64 platform. However selecting x64 from Build Configuration Manager from my VS2008 Pro doesn't seem to work. The binary does get created but my client wasn't able to get it to run on x64.

I wonder if the 3rd party DLLs could be the cause. Anyone has any idea on this?

[A]
Do you have x64 versions of the third party libraries?  If not you are out of luck.  A process must either be fully x86 or x64, you can't mix and match libraries.  If the libraries are DLLs then you still need the export libraries from an x64 build.
In what way does selecting the x64 configuration in VS not work?
Updated:
If your app is .NET and architecture neutral, then it will be loaded as 64 bit on 64 bit OS'es.  However, if it relies on 32 bit DLLs then this will fail at run time. You can force your exe to always load 32 bit using the
corflags
utility.


q:
This might sound like a little bit of a crazy question, but how can I find out (hopefully via an API/registry key) the install time and date of Windows?

The best I can come up with so far is to look at various files in C:\Windows and try to guess... but that's not exactly a nice solution.

[A]
In
```
regedit.exe
```
go to:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallDate
```
```
It's given as the number of seconds since January 1, 1970. (Note: for Windows 10, this date will be when the last feature update was installed, not the original install date.)
To convert that number into a readable date/time just paste the decimal value in the field "UNIX TimeStamp:" of this
Unix Time Conversion online tool
.


q:
Does anyone know how to resize images proportionally using JavaScript?

I have tried to modify the DOM by adding attributes height and width on the fly, but seems did not work on IE6.

[A]
Instead of modifying the height and width attributes of the image, try modifying the CSS height and width.
```
```
myimg = document.getElementById('myimg');
myimg.style.height = "50px";
myimg.style.width = "50px";
```
```
One common "gotcha" is that the height and width styles are strings that include a unit, like "px" in the example above.
Edit - I think that setting the height and width directly instead of using style.height and style.width should work. It would also have the advantage of already having the original dimensions. Can you post a bit of your code? Are you sure you're in standards mode instead of quirks mode?
This should work:
```
```
myimg = document.getElementById('myimg');
myimg.height = myimg.height * 2;
myimg.width = myimg.width * 2;
```
```


q:
I am developing a collection of plugins on Eclipse 3.4 (official) on both mac and a PC.

At present (I'm aware it is not the best practice) some of my common plugins export all of their packages.

The problem is this: many of the listed packages are empty because subpackages are not,
for example: prefix.core may be empty while prefix.core.model may not be.

Even though I use the same manifest file, having the empty packages listed on one platform raises an error in the manifest file on the other platform. If I omit the packages in that platform, then when I come to the other platform I'm told that the plugin does not export everything.

Any idea what is going on? I have no idea why there would be differences between the PC and the Mac on a non-UI related issue. The only significant difference is that the mac is running Java 5 (still not Eclipse for Java 6) while the PC is running Java 6, but the manifests should have nothing to do with it.

[A]
It's usually a good practice to use the same version of the JVM if you're developing plugins across multiple machines and platforms.
If you are going to build the plugins on a PC and expect them to run on the Mac, you should standardize on Java 5. You can easily install and add additional JREs to Eclipse by going to Window->Preferences->Installed JREs. You can even configure which JRE each project and launch configuration uses, if you don't want the rest of your PC Java coding to use 5.
I wouldn't be surprised if this fixes your manifest problem, as well.


q: That's the question. Give only one reason you think why have OODB failed or why many systems nowadays still use relational databases.

[A] The main reason is SQL. It is very useful to be able to use the data from a database in other contexts outside of the application, and often with object databases the data is stored in a format that can't easily be queried.  With a relational database the data can become part of a data warehouse, for instance, or just queried by sys admins etc.


q:
I've been trying to consider how Row Level Security could be implemented with the Entity Framework.  The idea is to have a database agnostic means that would offer methods to restrict the rows coming from the ObjectContext.

Some of my inital ideas have involved modifying the partial classes created by the EDMGEN tool and that has offered some limited support.  Users are still able to get around this solution by using their own eSQL statements and a QueryObject.

I've been looking for a comprehensive solution that would exist above the database providers so that it would remain agnostic.

[A]
The place where you add security really depends on who you're trying to secure against.
If, for example, you were securing a web site, then adding the filtering at the context level would be sufficient, because the "users" in this case are on the web site. They have no choice but to go through your context, since you would write the application entirely against the context.
In your case, it sounds like the "users" you're trying to secure against are developers. That's quite a bit more difficult. If the developers don't have access to make modifications to the database itself, then you'll have to put the security at the database level. No amount of eSQL access is going to be able to get around the database saying "no".


q:
With Merb 1.0 rapidly approaching, I would like to know what Merb/Rails users recommend?

Is it time to try Merb? What was downside for you when you switched to Merb from Rails?

[A] Everyone, including many from the Merb Core team have been recommended to wait for 1.0.  But if you're at all curious, grab the latest Gem and start toying.  Just don't expect to put it into production and hold off on any production work till 1.0 is out.


q:
We are building a website which will display news headlines and news. It will be a public site initially, but will evolve include portal content like personalized web pages.

The site also needs to build web 2.0 features around the news stories being displayed, and needs to be extensible and highly customizable, allowing the business to change templates in which the stories are defined and use different templates based on business logic etc..

The core business logic is being built using Windows work flow and Windows communication foundation, we are now looking for a suitable UI stack, is WCSF a good choice?

[A]
WCSF might be a good choice, but probably for reasons that have nothing to do with the possible feature needs you've listed.
The best things in my opinion that WCSF has going for it is that it's built on the Model-View-Presenter-[Controller] pattern which gives you the separation of concerns between the view and presenter (just like MVC)... BUT at the same time it's not a total paradigm shift from the "Page Control" model that many .net'ers are used to.  This means you can still use a lot of third party controls like Telerik or Infragistics pretty much like you did before (much more challenging with MVC).
Because the MVP pattern uses a dependency injection container (ObjectBuilder) and inversion of control you get a pretty nice way to write unit tests without a web context (easy to mock objects).  Also the container supports service location, so you can easily write WCSF services that will be shared (and WCF and or the WSSF fit in nicely here).
It's highly modularized from a programatic standpoint and has many extensibility points.
All that being said... it kind of sounds like you're looking for more of a templating, personalization, dynamic framework.  You might check out WSS/SharePoint in this case, because it may get you further down the field out of the box.


q:
I want to use the Date::ABBR_MONTHS constant in my rails application. I see the Ruby stdlib documentation at http://www.ruby-doc.org/stdlib/ which does not seem to have this constant.
However, this constant is there at http://stdlib.rubyonrails.org/

What is the difference between these two libraries?

This constant is working on my unix deployment machine but not on my dev machine on windows. Can anybody explain whats going on?

[A]
```
ABBR_MONTHS
```
is something you get given to you by ActiveSupport and it's just added into the Date class. The first library is for ruby, where the second one is for ruby on rails. The constant may not be working because of different versions of Rails.


q:
Seems to me most of developers completely ignore this features. People prefer handling security exceptions as generic ones relying on standard windows roles and rights instead of learning to use CAS ways of enhancing security - probably because CAS is quite confusing in its logic and naming.

Can anyone suggest any general rule-of-thumb/best practices for using CAS at his best in a clean way?

[A]
See also
this discussion
.
The problem is exacibated because a lot of code (perhaps too much) runs at full trust. And then the only checks that get done are things like PrincipalPermissionAttribute checks - most of the rest are simply bypassed. So in many cases there isn't much point! Unless you are loading in external (untrusted) files [and so need CAS], it simply doesn't add a lot in many cases (and yes, there are plenty of exceptions).
CAS is much more useful for clients running in the sandbox (for example downloaded from the internet). Sliverlight takes this to the extreme, with stricter rules (especially around reflection) than regular .NET.


q:
I'm writing a game in Java, and I want the user to be able to provide input from both the command line and my GUI. Currently, I use this method to get input:

    static String getInput(){
        System.out.println("Your move:");
        Scanner sc = new Scanner(System.in);
        return sc.nextLine();
    }

I want to keep using this, but let a mousePressed event emulate the user actually typing in their input as well.  It's not that efficient of a solution, but it makes sense in my application. So the question is: how do I simulate a user typing to System.in from the code side?

[A]
I made an application once that could run via the command line or using a GUI.
The way I did this was to define an Interface (named IODevice) which defined the following methods:
public String getInput();
public void showOutput(String output);
I then had two classes which implemented this interface - One used the host computer's terminal (as you are doing now) and one used a JTextArea (output) / JOptionPane (input).
Perhaps you could do something similar - To change the input device used, simply change the instance of the IODevice.
Hope this is of some use.


q:
For PHP, what is the default time after which an HTTP request is deemed to have timed out?

I'm using the PECL HTTP extension to make HTTP requests. I can set a timeout limit when making a request, however I'd like to know what the default is if nothing is explicitly specified.

I've hunted through the PHP manual to no avail. I'd appreciate answers supported by evidence, such as a link to the relevant manual page, as opposed to speculative suggestions.

I'm keen to find out what the default timeout actually is not just what it probably is. I can guess it may probably be 30 seconds as this seems a reasonable value, however I can find nothing to confirm or deny this.

[A]
I'm quite sure what you're looking for is the
default_socket_timeout
php.ini option.  It appears the default is 60 seconds.


q:
I notice sometimes with my parent/child objects or many-to-many relationships, I need to call either SaveOrUpdate or Merge. Usually, when I need to call SaveOrUpdate, the exception I get on calling Merge has to do with transient objects not being saved first.

Please explain the difference between the two.

[A]
This is from section
10.7. Automatic state detection
of the Hibernate Reference Documentation:
saveOrUpdate() does the following:
if the object is already persistent in this session, do nothing
if another object associated with the session has the same identifier,
   throw an exception
if the object has no identifier property, save() it
if the object's identifier has the value assigned to a newly
   instantiated object, save() it
if the object is versioned (by a <version> or <timestamp>), and the
   version property value is the same value assigned to a newly
   instantiated object, save() it
otherwise update() the object
and merge() is very different:
if there is a persistent instance with the same identifier currently
   associated with the session, copy the state of the given object onto
   the persistent instance
if there is no persistent instance currently associated with the
   session, try to load it from the database, or create a new persistent
   instance
the persistent instance is returned
the given instance does not become associated with the session, it
   remains detached
You should use Merge() if you are trying to update objects that were at one point detached from the session, especially if there might be persistent instances of those objects currently associated with the session. Otherwise, using SaveOrUpdate() in that case would result in an exception.


q: What is the best method for removing a table row with jQuery?

[A]
Is the following acceptable:
```
```
$('#myTableRow').remove();
```
```


q:
I want to recreate the the update panel postback without using an update panel to do the postback.  What is the generic method for doing this?

For example, on Stackoverflow, when you vote up or down on a question it does a postback to update the database and I would bet they didn't use an update panel.

What do I have?

I have a table with table data.  When I click on the td item as a whole column, I want to do an update to the database and also update a gridview on the page itself.  The gridview shows all the currently clicked items in the table because it was updated via "our method".

Looking for a good generic method I could use for a lot of async postbacks without update panel.

[A]
You can just use a standard AJAX call to accomplish this.  Create a .aspx page which updates the database in its Page_Load method, and displays any desired information (like the current DB value after the update) as XML.  Then make an AJAX call to that page using jQuery.
You can also return an HTML fragment (i.e. an updated GridView), and use jQuery to insert the updated HTML into the current page.
Edit:
Sample 2 on this page should be very close to what you want:
http://www.codeproject.com/KB/ajax/AjaxJQuerySample.aspx


q: Any pointers on how to initiate serial communication with the iphone?  Or any other idea to interact with external hardware?

[A]
It depends on what you want to do. For an SSH terminal connection I reccomend TouchTerm (search the appstore).
I have no experience with electrical connections, but you can find the pinout of the iPod/iPhone connector here:
http://pinouts.ru/PortableDevices/ipod_pinout.shtml
You can then download the iPhone developer kit here:
http://developer.apple.com/iphone/


q:
I'm using jQuery to add an additional row to a table as the last row.

I have done it this way:

$('#myTable').append('<tr><td>my data</td><td>more data</td></tr>');

Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)? Is there a different way to do it?

[A]
The approach you suggest is not guaranteed to give you the result you're looking for - what if you had a
```
tbody
```
for example:
```
```

...

...

```
```
You would end up with the following:
```
```

...

...

...

```
```
I would therefore recommend this approach instead:
```
```
$('#myTable tr:last').after('
...

...
');
```
```
You can include anything within the
```
after()
```
method as long as it's valid HTML, including multiple rows as per the example above.
Update:
Revisiting this answer following recent activity with this question. eyelidlessness makes a good comment that there will always be a
```
tbody
```
in the DOM; this is true, but only if there is at least one row. If you have no rows, there will be no
```
tbody
```
unless you have specified one yourself.
DaRKoN_
suggests
appending to the
```
tbody
```
rather than adding content after the last
```
tr
```
. This gets around the issue of having no rows, but still isn't bulletproof as you could theoretically have multiple
```
tbody
```
elements and the row would get added to each of them.
Weighing everything up, I'm not sure there is a single one-line solution that accounts for every single possible scenario. You will need to make sure the jQuery code tallies with your markup.
I think the safest solution is probably to ensure your
```
table
```
always includes at least one
```
tbody
```
in your markup, even if it has no rows. On this basis, you can use the following which will work however many rows you have (and also account for multiple
```
tbody
```
elements):
```
```
$('#myTable > tbody:last-child').append('
...

...
');
```
```


q:
I need an API that can make menus like Win32API,

But something simpler and better than WinAPI.

That can make GUI, with text zones, buttons etc...like an average Windows program.(Windows GUI Style)

Can anyone recommand on one like it? Thanks.

[A]
wxWidgets
:
wxWidgets lets developers create applications for Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more using one codebase. It can be used from languages such as C++, Python, Perl, and C#/.NET. Unlike other cross-platform toolkits, wxWidgets applications look and feel native. This is because wxWidgets uses the platform's own native controls rather than emulating them. It's also extensive, free, open-source, and mature.


q:
There are several web applications which allow you to send photos from your mobile phone and post them to web site/application. How do these work and what sort of technologies would one use to implement such a feature?  Is it an MMS server or does one need to get into socket programming?  For example, some applications provide you with an email address to email your photos to via mobile phone.  I'm curious to know how these things work.  I can somewhat figure out on my own how they work, but I would like to know this feature is normally implemented.

Thanks

[A]
I think you have three options to support this:
MMS - you would need an
MMS gateway
to recieve MMS messages. This can be software/hardware that you run yourself, or there are services were you pay per message. You would likely need to write your own handling of the message at the application end.
Email - you just provide users with an email address to send picture to and you either interface with the email server via POP/IMAP or with the message store directly.
Web form - you implement a web form specifically designed for mobile devices that lets them upload pictures. In truth I have no idea if and how many devices support
```
<input type="file" />
```
, so this may not actually be an option at all.
You can use whatever server-side technology you prefer for processing each of these.


q:
So is there a way to initialize and start a command line Spring app without writing a main method. It seems like all such main methods have the same form

public static void main(final String[] args) throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("context.xml", Boot.class);
    FooService fooService = (FooService) ctx.getBean("fooService");
    fooService.bar();
}

I suppose that's not complicated, but has someone found a way to provide a way to just specify the context.xml at the command line or, better yet, in a manifest file?

The goal here is to simplify the creation of spring applications as executable jars. I hope that I can specify some utility class as the Main-Class in the manifest. I suppose I would also need to specify the starting point for the app, a bean and a method on it where begins the process.

[A]
I'll try to answer the question as I understand it:
How to package a jar containing a spring configuration such as I just need to use
```
java -jar myjar.jar
```
?
The code snippet you have in your question simply works. You don't have to parameterise the
```
context.xml
```
. You just need to bundle your code and its dependencies (spring, etc.) in a single jar with a proper manifest entry for the main class in a jar file.
I personaly use
maven 2
and here is a
pom.xml
I would use that do just that:
```
```
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.stackoverflow</groupId>
  <artifactId>stackoverflow-autostart-spring-app</artifactId>
  <version>0.1</version>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring</artifactId>
      <version>2.5.2</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.stackoverflow.spring.autostart.Autostart</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
```
```
This is assuming some package name for the java code, the source code being in the
```
src/main/java
```
directory and the file
```
context.xml
```
in the
```
src/main/resources
```
directory.
So in this
```
pom.xml
```
there are several important points:
the spring dependency (speaks for itself I believe)
the configuration of the
maven jar plugin
, that adds the main class as a manifest entry
the
maven shade plugin
, which is the plugin responsible for gathering all the dependencies/classes and packaging them into one single jar.
The executable jar will be available at
```
target\stackoverflow-autostart-spring-app-0.1.jar
```
when running
```
mvn package
```
.
I have this code all working on my box but just realised that I can't attach a zip file here. Anyone know of place I could do so and link here?
I created a
git repository at github
with the code related to this question if you want to check it out.
Hope this helps.


q: I've implemented a basic search for a research project. I'm trying to make the search more efficient by building a suffix tree. I'm interested in a C# implementation of the Ukkonen algorith. I don't want to waste time rolling my own if such implementation exists.

[A]
Hard question.  Here's the closest to match I could find:
http://www.codeproject.com/KB/recipes/ahocorasick.aspx
, which is an implementation of the Aho-Corasick string matching algorithm.  Now, the algorithm uses a suffix-tree-like structure per:
http://en.wikipedia.org/wiki/Aho-Corasick_algorithm
Now, if you want a prefix tree, this article claims to have an implementation for you:
http://www.codeproject.com/KB/recipes/prefixtree.aspx
<
HUMOR
> Now that I did your homework, how about you mow my lawn.  (Reference:
http://flyingmoose.org/tolksarc/homework.htm
) <
/HUMOR
>
Edit
: I found a C# suffix tree implementation that was a port of a C++ one posted on a blog:
http://code.google.com/p/csharsuffixtree/source/browse/#svn/trunk/suffixtree
Edit
: There is a new project at Codeplex that is focused on suffix trees:
http://suffixtree.codeplex.com/


q:
I've always been able to allocate 1400 megabytes for Java SE running on 32-bit Windows XP (Java 1.4, 1.5 and 1.6).

java -Xmx1400m ...

Today I tried the same option on a new Windows XP machine using Java 1.5_16 and 1.6.0_07 and got the error:

Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

Through trial and error it seems 1200 megabytes is the most I can allocate on this machine.

Any ideas why one machine would allow 1400 and another only 1200?

Edit: The machine has 4GB of RAM with about 3.5GB that Windows can recognize.

[A] The JVM needs contiguous memory and depending on what else is running, what was running before, and how windows has managed memory you may be able to get up to 1.4GB of contiguous memory.  I think 64bit Windows will allow larger heaps.


q: Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?

[A]
Well, there's emacs, which is arguably a shell written in lisp :)
Seriously though, are you looking for a reimplementation of an existing shell design in a different language such as Python? Or are you looking for a new implementation of a shell language that looks similar to your language of choice?


q:
How to I get the Fixnum returned by the following:

"abc"[2]

Back into a character?

[A]
This will do it (if n is an integer):
```
```
n.chr
```
```


q:
Is there a way for me to add logging so that entering and exiting methods gets logged along with parameters automatically somehow for tracing purposes? How would I do so?

I am using Log4Net.

[A]
The best way to achieve this sort of thing is by using interception,  There are a couple of ways to do this, though they all tend to be somewhat invasive.  One would be to derive all your objects from ContextBoundObject.
Here
is an example of using this sort of approach.  The other approach would be to use one of the existing AOP libraries to achieve this.  Something like DynamicProxy from the
Castle Project
is at the core of many of these.  Here are a few links:
Spring.Net
PostSharp
Cecil
There are probably several others, and I know
Castle Windsor
, and
Ninject
both provide AOP capabilities on top of the IoC functionality.
Once AOP is in place you would simply write an interceptor class that would write the information about the method calls out to log4net.
I actually wouldn't be surprised if one of the AOP frameworks would give you that sort of functionality out of the box.


q:
I'm trying to Unit Test a class that has many internal functions. These obviously need testing too, but my Tests project is seperate, mainly because it covers many small, related projects. What I have so far is:

FieldInfo[] _fields =
    typeof(ButtonedForm.TitleButton).GetFields(
        BindingFlags.NonPublic | BindingFlags.Instance |
        BindingFlags.DeclaredOnly);
Console.WriteLine("{0} fields:", _fields.Length);
foreach (FieldInfo fi in _fields)
{
    Console.WriteLine(fi.Name);
}

This spits out all the private members nicely, but still doesn't display internals. I know this is possible, because when I was messing around with the autogenerated tests that Visual Studio can produce, it asked about something to do with displaying internals to the Test project. Well, now I'm using NUnit and really liking it, but how can I achieve the same thing with it?

[A]
It would be more appropriate to use the
```
InternalsVisibleTo
```
attribute to grant access to the internal members of the assembly to your unit test assembly.
Here is a link with some helpful additional info and a walk through:
The Wonders Of InternalsVisibleTo
To actually answer your question... Internal and protected are not recognized in the .NET Reflection API.  Here is a quotation from
MSDN
:
The C# keywords protected and internal have no meaning in IL and are not used in the Reflection APIs. The corresponding terms in IL are Family and Assembly. To identify an internal method using Reflection, use the
IsAssembly
property. To identify a protected internal method, use the
IsFamilyOrAssembly
.