Question:
According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().

Answer:
Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $_GET/$_POST/$_COOKIES/$_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.
The PHP
man page on magic quotes
agrees:
"This feature has been DEPRECATED as
  of PHP 5.3.0 and REMOVED as of PHP
  5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a
  process that automagically escapes
  incoming data to the PHP script. It's
  preferred to code with magic quotes
  off and to instead escape the data at
  runtime, as needed."


Question:
I'm trying to make a triangle (isosceles triangle) to move around the screen and at the same time slightly rotate it when a user presses a directional key (like right or left).

I would like the nose (top point) of the triangle to lead the triangle at all times. (Like that old asteroids game).

My problem is with the maths behind this. At every X time interval, I want the triangle to move in "some direction", I need help finding this direction (x and y increments/decrements).

I can find the center point (Centroid) of the triangle, and I have the top most x an y points, so I have a line vector to work with, but not a clue as to "how" to work with it.

I think it has something to do with the old Sin and Cos methods and the amount (angle) that the triangle has been rotated, but I'm a bit rusty on that stuff.

Any help is greatly appreciated.

Answer:
The arctangent (inverse tangent) of vy/vx, where vx and vy are the components of your (centroid->tip) vector, gives you the angle the vector is facing.
The classical arctangent gives you an angle normalized to -90° < r < +90° degrees, however, so you have to add or subtract 90 degrees from the result depending on the sign of the result and the sign of vx.
Luckily, your standard library should proive an atan2() function that takes vx and vy seperately as parameters, and returns you an angle between 0° and 360°, or -180° and +180° degrees. It will also deal with the special case where vx=0, which would result in a division by zero if you were not careful.
See
http://www.arctangent.net/atan.html
or just search for "arctangent".
Edit: I've used degrees in my post for clarity, but Java and many other languages/libraries work in radians where 180° = π.
You can also just add vx and vy to the triangle's points to make it move in the "forward" direction, but make sure that the vector is normalized (vx² + vy² = 1), else the speed will depend on your triangle's size.


Question: How would I be able to programmatically search and replace some text in a large number of PDF files?  I would like to remove a URL that has been added to a set of files.  I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains.  I have seen recommendations to use text touchup, which works manually, but I don't want to modify 1300 files manually.

Answer:
Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file.  That said,
CAM::PDF
has some search-replace capabilities and heuristics.  Give
changepagestring.pl
a try and see if it works on your PDFs.
To install:
```
```
$ cpan install CAM::PDF
 # start a new terminal if this is your first cpan module
 $ changepagestring.pl input.pdf oldtext newtext output.pdf
```
```


Question:
I have an application which I have made a 256 x 256 Windows Vista icon for.

I was wondering how I would be able to use a 256x256 PNG file in the ico file used as the application icon and show it in a picture box on a form.

I am using VB.NET, but answers in C# are fine. I'm thinking I may have to use reflection.

I am not sure if this is even possible in Windows XP and may need Windows Vista APIs

Answer:
Found info
here
.  To get the large Vista icon, you need to use Shell32's SHGetFileInfo method.  I've copied the relevant text below, of course you'll want to replace the filename variable with "Assembly.GetExecutingAssembly().Location".
```
```
using System.Runtime.InteropServices;
```
```
A bunch of constants we will use in the call to SHGetFileInfo() to specify the size of the icon we wish to retrieve:
```
```
// Constants that we need in the function call
private const int SHGFI_ICON = 0x100;
private const int SHGFI_SMALLICON = 0x1;
private const int SHGFI_LARGEICON = 0x0;
```
```
The SHFILEINFO structure is very important as it will be our handle to various file information, among which is the graphic icon.
```
```
// This structure will contain information about the file
public struct SHFILEINFO
{
    // Handle to the icon representing the file
    public IntPtr hIcon;
    // Index of the icon within the image list
    public int iIcon;
    // Various attributes of the file
    public uint dwAttributes;
    // Path to the file
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    public string szDisplayName;
    // File type
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
};
```
```
The final preparation for the unmanaged code is to define the signature of SHGetFileInfo, which is located inside the popular Shell32.dll:
```
```
// The signature of SHGetFileInfo (located in Shell32.dll)
[DllImport("Shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);
```
```
Now that we have everything prepared, it's time to make the call to the function and display the icon that we retrieved. The object that will be retrieved is an Icon type (System.Drawing.Icon) but we want to display it in a PictureBox so we'll convert the Icon to a Bitmap using the ToBitmap() method.
But first of all there are 3 controls you need to add to the form, a Button btnExtract that has "Extract Icon" for its Text property, picIconSmall which is a PictureBox and a picIconLarge which is also a PictureBox. That's because we will get two icons sizes. Now double click btnExtract in Visual Studio's Design view and you'll get to its Click event. Inside it is the rest of the code:
```
```
private void btnExtract_Click(object sender, EventArgs e)
{
    // Will store a handle to the small icon
    IntPtr hImgSmall;
    // Will store a handle to the large icon
    IntPtr hImgLarge;

    SHFILEINFO shinfo = new SHFILEINFO();

    // Open the file that we wish to extract the icon from
    if(openFile.ShowDialog() == DialogResult.OK)
    {
        // Store the file name
        string FileName = openFile.FileName;
        // Sore the icon in this myIcon object
        System.Drawing.Icon myIcon;

        // Get a handle to the small icon
        hImgSmall = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON);
        // Get the small icon from the handle
        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
        // Display the small icon
        picIconSmall.Image = myIcon.ToBitmap();

        // Get a handle to the large icon
        hImgLarge = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);
        // Get the large icon from the handle
        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
        // Display the large icon
        picIconLarge.Image = myIcon.ToBitmap();

    }
}
```
```
UPDATE: found even more info
here
.


Question:
Does anyone knows how to detect printable characters in java?

After a while ( trial/error ) I get to this method:

    public boolean isPrintableChar( char c ) {
        Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
        return (!Character.isISOControl(c)) &&
                c != KeyEvent.CHAR_UNDEFINED &&
                block != null &&
                block != Character.UnicodeBlock.SPECIALS;
    }

I'm getting the input via KeyListener and come Ctr-'key' printed an square. With this function seems fairly enough.

Am I missing some char here?

Answer:
I'm not perfectly sure whether I understand your problem. But if you want detect if character can be drawn to Graphics object, and if not print some placeholder char you might find usefull:
```
```
Font.canDisplay(int)
```
```
It will check whether font can display specific codepoint (it is more that check whether font is displayable at all -- since there are chars that are displayable - like ą - but some fonts cant display them.


Question:
I am changing document template macros. The one thing I can't find out how to do is to customize error messages. For example an error message in a document is

"Error! No table of figures entries found"

I would like to change this to display something else. Is it possible to do this with Word VBA or VBScript?

Answer:
If you want to trap a specific error type in VBA, one method is to use On Error Resume Next then test for an error message on the line following the action to trap, e.g.:
```
```
On Error Resume Next
' try action
If Err.Number <> 0 Then
  ' handle w/ custom message
  Err.Clear
End If
```
```
If you know the exact error number (
```
If Err.Number = N Then
```
), that would be better of course.


Question: As above. Usually at work someone else does the database design, and when I do personal projects they're small enough to not really require more than five or six tables, but I'm about to start a personal project that I think will probably require around eleven or twelve tables and I'd like something to help me design it neatly and keep track of it.

Answer:
MySQL Workbench
, while a little buggy, has been invaluable to me since I discovered it.
Visio
has a good visual database designer, but it can't export the result to a MySQL database and is windows only.
phpMyAdmin
also has a
designer tool
which can be used if you correctly configure the
pma database
.


Question:
I'm calling a web service that returns an array of objects in JSON.  I want to take those objects and populate a div with HTML.  Let's say each object contains a url and a name.

If I wanted to generate the following HTML for each object:

<div><img src="the url" />the name</div>

Is there a best practice for this? I can see a few ways of doing it:

Concatenate strings

Create elements

Use a templating plugin

Generate the html on the server, then serve up via JSON.

Answer:
Either of the first two options is both common and acceptable.
I'll give examples of each one in
Prototype
.
```
```
// assuming JSON looks like this:
// { 'src': 'foo/bar.jpg', 'name': 'Lorem ipsum' }
```
```
Approach #1:
```
```
var html = "
 #{name}
".interpolate(json);
$('container').insert(html); // inserts at bottom
```
```
Approach #2:
```
```
var div = new Element('div');
div.insert( new Element('img', { src: json.src }) );
div.insert(" " + json.name);
$('container').insert(div); // inserts at bottom
```
```


Question:
How do I write the getDB() function and use it properly?

Here is a code snippet of my App Object:

public class MyApp extends UiApplication {

    private static PersistentObject m_oStore;
    private static MyBigObjectOfStorage m_oDB;

    static {
        store = PersistentStore.getPersistentObject(0xa1a569278238dad2L);
    }

    public static void main(String[] args) {
        MyApp theApp = new MyApp();
        theApp.enterEventDispatcher();
    }
    public MyApp() {
        pushScreen(new MyMainScreen());
    }

    // Is this correct?  Will it return a copy of m_oDB or a reference of m_oDB?
    public MyBigObjectOfStorage getDB() {
        return m_oDB;  // returns a reference
    }

}

Answer:
```
```
public MyBigObjectOfStorage getDB() {
    Object o = store.getContents();
    if ( o instanceof MyBigObjectOfStorage ) {
        return (MyBigObjectOfStorage) o;
    } else {
        return null;
    }
}
```
```


Question:
If I make two iPhone applications, how can/should I share custom data (not contacts and stuff like that) among them?

Thanks!

Answer:
There are two different ways you might go about this.
1) The data you need to share is non-persistent. In other words you need to launch one application with a piece of data that it can do something with. In this case you would register a special URL scheme per application.
You can find out more information about URL schemes via Craig Hockenberry in his
[redacted] blog post
.
2) The data you need to share is persistent. In other words you need something like a data file that both applications can read and write too. As far as I know there isn't a safe way to do this other than storing your data on a remote server. If you need the data accessible without a data connection then you would need to figure out a way to sync data between the individual apps and the remote server.


Question: I teach a C++ course using Visual Studio.  One of my students has a Mac and was looking for an IDE to use on his machine. What would be good to recommend?

Answer:
Xcode
which is part of the MacOS Developer Tools is a great IDE. There's also
NetBeans
and
Eclipse
that can be configured to build and compile C++ projects.
Clion
from JetBrains, also is available now, and uses Cmake as project model.


Question:
Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused.

And now that we're here, how do they differ from a regular function?

Answer:
Not all closures are lambdas and not all lambdas are closures. Both are functions, but not necessarily in the manner we're used to knowing.
A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.
A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.
In an object-oriented language, closures are normally provided through objects. However, some OO languages (e.g. C#) implement special functionality that is closer to the definition of closures provided by purely
functional languages
(such as lisp) that do not have objects to enclose state.
What's interesting is that the introduction of Lambdas and Closures in C# brings functional programming closer to mainstream usage.


Question:
I've been searching around for a Continuous Integration solution for Ruby on Rails, but haven't been too pleased with the results.  I came from a .NET shop that used CruiseControl.NET and was really spoiled with its ease of use and rich status/reporting.

Ideally I'm looking for:

The obvious Git/SVN and Test::Unit
integration

Integration with Rake and/or
Capistrano

A web interface showing the status
of the build

Email notification of failed builds.

Desktop notification (potentially
through Growl)

REST API for build statuses

Plugin framework for running other code analysis tools and reporting results in the UI

Answer:
How about
CruiseControl.rb
?
Same crowd that did
```
CruiseControl
```
(thoughtworks) and written in
```
Ruby
```
. Very easy to use
```
Rake
```
to integrate your other tools, and can use the
ruby-growl
gem for your notifications.


Question:
What would be the most efficient data type to store a UUID/GUID in databases that do not have a native UUID/GUID data type? 2 BIGINTs?

And what would be the most efficient code (C# preferred) to convert to and from a GUID to that type?

Thanks.

Answer:
Looking at the
.NET guid class
, there are a couple ways to initialize a guid:
Guid(Int32, Int16, Int16, Byte, Byte, Byte, Byte, Byte, Byte, Byte, Byte)
Guid(string)
While it may be more efficient, in theory, to store the integer in a database (you could use bit shifting to really store 4 32-bit integers.. but you'd have to calculate this out when loading and saving every time. Additionally, it would take 4 fields in the database.. I would imagine it would end up being less efficient.
Add in the impossibility of reading this directly in your database for debugging/testing purposes, and I'd say hands-down that it's best to store a string. It's only a 32-character field (36 if you include the dashes), and it's very easy to convert. guid.
ToString()
and
new Guid(stringValue);


Question:
I am trying to use set.insert (key) as a conditional, where if the key is inserted correctly (meaning that the key does NOT already exist in the set ) then it should go on and perform some kind of code. For example, something like:

if (set.insert( key )) {
    // some kind of code
}

Is this allowed? Because the compiler is throwing this error:

conditional expression of type 'std::_Tree<_Traits>::iterator' is illegal

Answer:
set::insert returns a pair, try this:
```
```
if( set.insert( key ).second ) {
    // some kind of code
}
```
```


Question:
I need a serviceable shell for MSYS.  This is my current dilemma:

The default rxvt.exe has a scroll bar and copy and paste, but doesn't send control characters or arrow keys to a running program in the shell (like interpreters/debuggers).  This is a real thorn when using the Haskell interpreter ghci.

The other shell sh.exe handles control characters (or at least some of them), but has no scroll bar or copy and paste.

rxvt also has (relatively) more issues with output buffering

What are my options?  Does the replacement shell need to be msys aware?  All I want is a sane environment to work with Haskell (ghc), C++ (gcc), and the basic tool chain (make and what not).  I'm willing to compile a shell if it doesn't involve crazy shenanigans.

Answer:
You are confusing "shell" and "terminal emulator".
```
sh.exe
```
is the former; rxvt is the latter. (mind you, under Windows you can do without a terminal emulator because Windows creates one (a "console window") for any console program (such as sh.exe) if it's not already running inside one)


Question:
I have a DataTable that has a boolean column called [Invalid]. I need to divide this data up by this Invalid column - valid rows can be edited, invalid rows cannot. My original plan was to use two BindingSources and set the Filter property ([Invalid] = 'false', for instance), which plays right into my hands because I have two DataGridViews and so I need two BindingSources anyway.

This doesn't work: the BindingSources set the Filter property associated with the DataTable, so both BindingSources hold the same data. Am I going to have to do two fetches from the database, or can I do what I want with the objects I have?

Answer:
I think you need to do another join to get ab's max val for each a.id first.
Something like this:
```
```
select a.*
from a
left join (
    select aid, max(val) as val
    from ab
    group by aid
) abmax on abmax.aid=a.id
inner join ab on ab.aid=abmax.aid and ab.val=abmax.val
inner join b on b.id=ab.bid
where b.val='foo'
```
```


Question:
What is the memory model for concurrency in C++03?

(And, does C++11 change the memory model to support concurrency better?)

Answer:
Unfortunately in C++ there is no "Standard Memory Model" like that of Java. The actual implementation is left up to the compiler, runtime libraries and processors.
Thus the C++ memory model == chaotic mix-mash of models, which means you always have to try to write safe code that doesn't depend on a specific memory model, and that goes for threaded programming as well, because the compiler can do any optimization it wants to outside of a critical section, even out of order processing!


Question:
What are some of the better AJAX Treeviews out there that support asynchronous JSON loading.

YUI TreeView seems nice, but bloated with tables, etc.

Answer:
jQuery TreeView plugin
it's really good and it haves very nice
asynchronous
JSON
loading capabilities...
ExtJS TreeView Component
, also great, multi-level asynchronous loading, excelent for large trees.


Question: I wrote a simple javascript image rotator which picks a random image on each page load.  The issue is that if i use a default image, that default image will show up for a second before the javascript loads and replaces it. Obviously if someone has javascript disabled i want them to see an image. How can i have a default image without a flickering of the default image.

Answer:
If you hide the default image as the first thing you do when the page loads, there probably won't be a chance for the users to see the image. You can then install an onload handler on the image and change its source to your random image. When the image loads, you can unhide the image.
```
```
window.onload = function () {
    var img = document.getElementById("rotating_image");

    // Hide the default image that's shown to people with no JS
    img.style.visibility = "hidden";

    // We'll unhide it when our new image loads
    img.onload = function () {
        img.style.visibility = "visible";
    };

    // Load a random image
    img.src = "http://example.com/random" + Math.floor(Math.random() * 5) + ".jpg";

};
```
```


Question:
I have several branches in TFS (dev, test, stage) and when I merge changes into the test branch I want the automated build and deploy script to find all the updated SQL files and deploy them to the test database.

I thought I could do this by finding all the changesets associated with the build since the last good build, finding all the sql files in the changesets and deploying them. However I don't seem to be having the changeset associated with the build for some reason so my question is twofold:

1) How do I ensure that a changeset is associated with a particular build?

2) How can I get a list of files that have changed in the branch since the last good build? I have the last successfully built build but I'm unsure how to get the files without checking the changesets (which as mentioned above are not associated with the build!)

Answer:
So I can understand the intuitive appeal of this approach, but I don't think it's the right way to go.
For one thing it's going to be difficult. But the second problem is that TFS doesn't have a good way to record deployment data.
For the first question, I'm not sure what that means. For the second question you can use the build labels and tf history today list of the changed files.
As an alternative, you could reconsider how you want to manage SQL changes. I use a low-tech method of keeping the current pending changes in one directory, and then after deploying moving the files to a different directory. This method can be enhanced by keeping a deployment history table in the database. You may also want to look into vsts DB addition, the current
CTP
has a lot of new features around managing database changes. I also hear that
Red Gate
has nice database management tools as well.


Question:
I have an application running on multiple IIS servers that need to parse a CSV file that is placed on a common network drive.  If I use the System.IO.FileSystemWatcher Created event to be notified of the event when the file is available, how can I ensure only one server parses the file?  If all servers are notified of this change, all will try to parse it.  Should the first server copy this locally and then parse it?  Would this cause errors on the other servers? Should I set the remote directory access to only allow one server read access?

The file contains records that needs to be inserted into a shared database, but there is no unique key for the records.  Therefore, if more than one server grabs the file at the same time and inserts the records, there will be duplicates in the database.

Answer:
Key question is: Does something bad happen when all of them try and parse the file at roughly the same time? Multiple read access is basically allowed on the file system level, so this fact alone would not necessarily break anything.
I would probably try the method of creating a lock file on first file access and make servers look for the lock file before accessing the file. Delete the lock file when you're done.
You could also place an exclusive lock on the file, only one server will be able to do that at a time. The others will fail trying:
```
```
FileStream fs = new FileStream(
  FilePath,
  FileMode.Open,
  FileAccess.ReadWrite,
  FileShare.None
);
```
```


Question:
If I have the string .....ZZ..ZZ..... or .Z.1.Z.23Z.4.Z55,

Is there an easy way of shifting all Zcharacters in the string one space right of the current position?

Some additional test strings are:

.Z

Z.

ZZ.

.ZZ

Z

ZZ

ZZZ

I think a few of the higher voted answers to this question (including the currently accepted one) do not work on these tests.

Answer:
Just iterate through the text and swap characters:
```
```
int main ()
{
    char text[] = "...Z.Z.Z...", temp;
    int text_len = strlen (text), i;
    for (i = text_len - 1; i >= 0; i--)
    {
        if (text[i] == 'Z')
        {
                temp = text[i+1];
                text[i+1] = text[i];
                text[i] = temp;
        }
    }
    printf ("%s\n", text);
    return 0;
}
```
```
Produces:
```
```
[~]$ gcc zshift.c && ./a.out
....Z.Z.Z..
```
```
There's a lot of discussion in the comments about a possible off-by-1 error in the above code. However, simple testing / stepping through is enough to show that this is not the case.
```
```
zshift "Z." -> ".Z"
zshift ".Z" -> "."
zshift "Z" -> ""
```
```
I think the behavior of "dropping" trailing Zs when shifting off the end of the string is sensible. After all, if you shift the bits of an integer, bits that end up outside the bounds of the integer are dropped.
If another behavior is desired -- for example, shifting only within the string -- the change to the algorithm is minimal:
```
```
temp = text[i+1];
if (temp == 0) continue;
text[i+1] = text[i];
text[i] = temp;
```
```


Question: Do you think ASP.NET MVC is able to develop RESTful web services and which approach you would use for it?

Answer:
I would seriously look at ADO.NET Dataservices. (formaly code named Astoria) There's some really nice tooling for Restful services in there!
http://msdn.microsoft.com/en-us/data/bb931106.aspx


Question:
Our groups legacy ASP 3.0 web apps were able to take advantage of a global error file by setting up a custom error file within IIS's Custom Error's tab.  I'm unable to find a similar solution for ASP.NET apps.

Does anyone know if there is a way to have a centralized "Error.aspx" page (for example) that will trap errors for an entire application pool?  The objective is to avoid adding custom code to each app's Global error handler ....

Any guidance is greatly appreciated!

Answer:
You can add the
```
<customErrors defaultRedirect="[url]"></customErrors>
```
tag to your web.config or even up to your machine.config to redirect to a custom error page.  The custom errors tag also suppors multiple  subelements that can be used to define custom errors.
Just remember when editing the machine.config file, it will affect all the applications on that machine.


Question:
What is the best way to deal with XML documents, XSD etc in C# 2.0?

Which classes to use etc. What are the best practices of parsing and making XML documents etc.

EDIT: .Net 3.5 suggestions are also welcome.

Answer:
It depends on the size; for small to mid size xml, a DOM such as
XmlDocument
(any C#/.NET versions) or
XDocument
(.NET 3.5/C# 3.0) is the obvious winner. For using xsd, You can load xml using an
XmlReader
, and an XmlReader accepts (to
Create
) an
XmlReaderSettings
. The XmlReaderSettings objects has a
Schemas
property that can be used to perform xsd (or dtd) validation.
For writing xml, the same things apply, noting that it is a little easier to lay out content with LINQ-to-XML (XDocument) than the older XmlDocument.
However, for huge xml, a DOM may chomp too much memory, in which case you might need to use XmlReader/XmlWriter directly.
Finally, for manipulating xml you may wish to use
XslCompiledTransform
(an xslt layer).
The alternative to working with xml is to work with an object model; you can use
xsd.exe
to create classes that represent an xsd-compliant model, and simply load the xml
as objects
, manipulate it with OO, and then serialize those objects again; you do this with
XmlSerializer
.


Question:
In Ruby I have often written a number of small classes, and had a main class organize the little guys to get work done. I do this by writing

require "converter.rb"
require "screenFixer.rb"
.
.
.

at the top of the main class. How do I do this in Java? Is it "import?"

Also, could someone please come up with a better title for this question?

Answer:
```
```
public class Example {
   public Example(IConverter converter, IScreenFixer screenFixer) {

   }
}
```
```
http://en.wikipedia.org/wiki/Facade_pattern
?


Question:
I have a COM SDK written in C++ and I'd like to create documentation for my product.  I understand that most people will probably not use C++ for integration with this COM component, but many will.

Which method is best to describe the API, without losing details that a C++ developer would need to know.

Answer:
```
```
public class Example {
   public Example(IConverter converter, IScreenFixer screenFixer) {

   }
}
```
```
http://en.wikipedia.org/wiki/Facade_pattern
?


Question: I am writing one web chat program using AJAX (a little bit). It is working when both users open a chat page, but I want to open a window when one user send data to others.

Answer:
Sounds like you need to write some javascript to open a new window when a message is received.  How are you sending the message -
reverse Ajax
?
Presumably both users will need to have your chat applications web page open so that you have somewhere to put the reverse ajax hook code.


Question: How does reverse proxy server work? Is it used to secure the main server? Is it used as a firewall? What are the reasons for using a proxy server? Could someone give a real world example?

Answer:
Typically a normal proxy server looks at requests going from an internal network out to the internet and caches them so that if another client requests the same page, the proxy can give it to them much quicker than a brand new request to a remote server.
A reverse proxy works in the opposite way.
Generally a reverse proxy will be installed in front of a web server, so that the second time a client requests a page from that server, the proxy will give it back to the remote client without bothering the web server at all.
In many cases the reverse proxy and the web server are the same machine.  This is often done because the work the reverse proxy does is much, much simpler than going through a complete web server transaction.
Apache, lighthttpd and many other web servers can also function as reverse proxies.
Check
Wikipedia
for more info.


Question:
Where can I find a free, lightweight YUI-like compressor for PHP?

I am sure it will decrease the file size but will compressing PHP code boost its performance?

Is this the same thing as an obfuscator?

Answer:
There is a product called PHP Encoder by ionCube (
http://www.ioncube.com/sa_encoder.php
) which is enterprise grade compression and obfuscater.
PHP Encoder is a PHP extension to create and run compiled bytecodes for accelerated runtime performance and maximum security.
It will shrink the file size, and speed up runtime because the code is already partially compiled


Question: If I'm using Visual Studio 2008 targeted to ASP.NET 2.0, then which version of the Ajax Control Toolkit should I be using?

Answer:
You need the Toolkit version
1.0.20229.20821
,
AjaxControlToolkit.zip
the dll's are targeted to .NET 2.0 and you need also the
ASP.NET AJAX Extensions 1.0 for .NET 2.0
.


Question:
Greenspunning. We've all had occasion to hack around a language's missing features to get what we need. Implementing pseudo-monadic patterns in Java,  Y Combinators in Javascript, variable immutability in C...

What do you consider your most impressive workaround in search of greater functionality? In hindsight, was it worth the hack? Even better: did it, like Ruby's string#to_proc, become an accepted feature of a later version of the language?

Answer:
You need the Toolkit version
1.0.20229.20821
,
AjaxControlToolkit.zip
the dll's are targeted to .NET 2.0 and you need also the
ASP.NET AJAX Extensions 1.0 for .NET 2.0
.


Question: Can anyone point to live examples of SOAP or REST web services? How do you use or test an existing web service with a client?

Answer:
A SOAP webservice which converts the temperature Celsius to Fahrenheit and other way around
http://www.w3schools.com/webservices/tempconvert.asmx
A description and source code is here
http://www.w3schools.com/webservices/ws_example.asp


Question: How to put underline for first letter for access key for  ?

Answer:
Tried the AccessKey attribute?
```
```
<asp:button id="Button1" runat="server" Text="Print" AccessKey="P" />
```
```
If it is really underlined is out of your control. The user agent (e.g. browser) is deciding that.


Question:
So from what little I understand about packaging for Macs, I see that the actual program that launches is the one defined under the CFBundleExecutable key in Info.plist.

<key>CFBundleExecutable</key>
<string>JavaApplicationStub</string>

Now, my app doesnt work if /APP/Content/MacOS/JavaApplicationStub is not chmodded +x (It just fails silently without doing anything, which is a pain!).
Fair enough, its not executable I guess. But its a big problem if you are copying the app from somewhere that dosent support +x properties on files; such as windows, fat32 USB keys, CDROMs, websites, zip files, etc...

What can I do in these instances to make the app able to run?  Manually setting the execute bit is not an option.

There's got to be people who run Mac apps off CD, at the very least!

Answer:
An alternative would be to create an audit log that might look like this:
```
```
AuditLog table
    EntityName varchar(2000),
    Action varchar(255),
    EntityId int,
    OccuranceDate datetime
```
```
where EntityName is the name of the table (eg: Contries, Provinces), the Action is the audit action (eg: Created, Removed etc) and the EntityId is the primary key of the modified row in the original table.
The table would need to be kept synchronized on each action performed to the tables. There are a couple of ways to do this:
1) Make triggers on each table that will add rows to AuditTable
2) From your application add rows in AuditTable each time a change is made to the repectivetables
Using this solution is very simple to get a list of logs in audit.
If you need to get columns from original table is also possible using joins like this:
```
```
select *
from
    Contries C
    join AuditLog L on C.Id = L.EntityId and EntityName = 'Contries'
```
```


Question:
Currently when I build my site I have to manually open validate it at the 3wbc site (means when opera pops up, press ctr+alt+shft+u) for every page.
Is it possible to automatically validate every page whenever I build my pages?

P.s.: This page doesn't validate ;)

Answer:
You can download and install your own copy of the validator -
http://validator.w3.org/source/
- and invoke it locally instead of trekking out to w3.org for each page. Still, this requires piggybacking over a web server through plain HTTP or the API. For a simpler solution you may prefer to download the SP library -
http://www.jclark.com/sp/index.htm
or
http://openjade.sourceforge.net/
- on which the W3 validator is based, then invoke the command 'nsgmls' from the command line.
There are of course also many desktop HTML validators that can process a batch of HTML pages at once, which may not be automated, but would certainly be much easier than manually checking each page. For example
http://arealvalidator.com/
(Windows),
http://www.webthing.com/software/validator-lite/install.html
(Unix).


Question:
In this sentence:

myCommand.ExecuteReader(CommandBehavior.CloseConnection)

does it close connection in case of exception?

Answer:
There are plenty of ways that the command can go wrong.
Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.
If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.
In case of an exception, I wouldn't trust it to close the connection.


Question: I have a Java service which now will execute in a batch mode. Multi threaded support is added to the service so for every batch request a thread pool will be dedicated to execute the batch. The question is how do I test this? I have functional tests that pass under the threaded version of the service but, somehow, I feel there must be an idiom for testing this.

Answer:
There really isn't a "good" way to do this.  The best thing I can suggest would be TestNG, which allows you to annotate your test methods and cause them to be executed in
n
threads concurrently.  For example:
```
```
@Test(invocationCount=10, threadPool=10)
public void testSomethingConcurrently() {
    ...
}
```
```
My TestNG knowledge is rusty at best, but AFAIK that should invoke the
```
testSomethingConcurrently
```
method 10 times concurrently.  This is a nice and declarative way to run multi-threaded tests against your code.
You can of course do something similar in JUnit by spawning threads manually in a loop, but that's insanely ugly and difficult to work with.  I had to do this once for a project I was working on; those tests were a nightmare to deal with since their failures weren't always repeatable.
Concurrency testing is difficult and prone to frustration, due to its non-deterministic nature.  This is part of why there is such a big push these days to use better concurrency abstractions, ones which are easier to "reason about" and convince one's self of correctness.


Question:
Could anyone provide any example of NAnt script for C++ project build automation?

Thanks!

Answer:
If the project is in Visual Studio then you can use the
```
<Solution>
```
task, I think.  That's the simplest/ugliest way of doing it.
edit:
Just realised that SO filtered out my little XML tag there.


Question:
How can i find out this information?

Ie,

I can install boost 1.35 with a command like

sudo port install boost

only to get boost 1.36 via port i would do something like this?

sudo port install boost-1.36

Hope that clears up my question

Answer:
If the project is in Visual Studio then you can use the
```
<Solution>
```
task, I think.  That's the simplest/ugliest way of doing it.
edit:
Just realised that SO filtered out my little XML tag there.


Question:
How can I extract information from a website (http://tv.yahoo.com/listings)  and then create an XML file out of it? I want to save it so  to parse later and display information using JavaScript?

I am quite new to Perl and I have no idea about how to do it.

Answer:
Of course. The easiest way would be the
Web::Scraper
module. What it does is it lets you define scraper objects that consist of
hash key names,
XPath expressions that locate elements of interest,
and code to extract bits of data from them.
Scraper objects take a URL and return a hash of the extracted data. The extractor code for each key can itself be another scraper object, if necessary, so that you can define how to scrape repeated compound page elements: provide the XPath to find the compound element in an outer scraper, then provide a bunch more XPaths to pull out its individual bits in an inner scraper. The result is then automatically a nested data structure.
In short, you can very elegantly suck data from all over a page into a Perl data structure. In doing so, the full power of XPath + Perl is available for use against any page. Since the page is parsed with HTML::TreeBuilder, it does not matter how nasty a tagsoup it is. The resulting scraper scripts are much easier to maintain and far more tolerant of minor markup variations than regex-based scrapers.
Bad news: as yet, its documentation is almost non-existent, so you have to get by with googling for something like [
miyagawa web::scraper
] to find example scripts posted by the module’s author.


Question:
My company has developed (and still continues to develope) a large ASP.NET business application. Our platform is ASP.NET 2.0 using some ASP.NET Ajax. We're extensively using third-party components, like webgrids, comboboxes, treeviews, calendar and scheduling controls etc.

Now, I don't know a lot of ASP.NET MVC and I'd like to know if there is a way to use these third-party-controls in the ASP.NET MVC model. Or do vendors have to rewrite their products in order to make them suitable for ASP.NET MVC?

Answer:
If they use the ASP.NET Control Model (That will be about 99,9% of controls written by ASP.NET Control vendors), they have to rewrite their controls. How much work there is in that, is very different depending of there arhitecture of their controls - the more ajax they already use, the more posible it is that they easily can change it to MVC.
ASP.NET AJAX Control toolkit for exsample can work with MVC. You can see how to do this in a video on WWW.ASP.NET:
http://www.asp.net/learn/mvc-videos/video-373.aspx


Question:
I'm new to Flex, although not new to programming. I want to write a generic event handler that will be called by all my textinput boxes when they receive focus.  When they have focus, I want to change the colour of the textinput box.  When they lose focus, I want to restore the "inactive" color profile. I could write an ActionScript event handler for each textinput box, but we all know that's lame.  :o)  What I need, then, is a way to access the object which is calling the event handler.

In Delphi, I'd have written a function which passes in the Sender object, allowing me to access the calling object's properties.  I'm guessing ActionScript/Flex has a completely different architecture, which is why I'm having difficulty doing this.

Thanks in anticipation!

Answer:
I hope I'm understanding what you're asking for... are you talking about event delegation?
This worked for me:
```
```
// 'focusOut' for blur
stage.addEventListener('focusIn', function(e:Event):void {
    // The focused control is e.target
});
```
```


Question: How do I declare a private function in Fortran?

Answer:
I've never written a line of FORTRAN, but
this thread about "Private module procedures"
seems to be topical, at least I hope so. Seems to contain answers, at least.
jaredor
summary:
The public/private attribute exists within modules in Fortran 90 and later. Fortran 77 and earlier--you're out of luck.


Question:
In my Spring MVC based applications i use Freemarker and i like it very much, but it's lacking advantages provided by Composite View pattern.

I'm thinking of trying to use Tiles2 together with Freemarker - does anyone know where do i find a simple example of SpringMVC together with Tiles2+Freemarker?

Answer:
nevermind, i've solved it. i just had to specify freemarker templates in tiles definitions file
```
```
<definition name="template" template="/WEB-INF/ftl/main.ftl">
```
```
and add freemarker servlet/maping to web.xml
```
```
<servlet>
    <servlet-name>freemarker</servlet-name>
    <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>

    <!-- FreemarkerServlet settings: -->
    <init-param>
        <param-name>TemplatePath</param-name>
        <param-value>/</param-value>
    </init-param>
    <init-param>
        <param-name>NoCache</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>ContentType</param-name>
        <param-value>text/html</param-value>
    </init-param>

    <!-- FreeMarker settings: -->
    <init-param>
        <param-name>template_update_delay</param-name>
        <param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
    </init-param>
    <init-param>
        <param-name>default_encoding</param-name>
        <param-value>ISO-8859-1</param-value>
    </init-param>
    <init-param>
        <param-name>number_format</param-name>
        <param-value>0.##########</param-value>
    </init-param>

    <load-on-startup>5</load-on-startup>
</servlet>

 <servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.ftl</url-pattern>
 </servlet-mapping>
```
```
in spring configuration specify tiles as my primary view engine
```
```
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/defs/definitions.xml</value>
            </list>
        </property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView"/>
</bean>
```
```


Question:
How can I access Ethernet statistics from C/C++ code like netstat -e?

Interface Statistics

                       Received            Sent

Bytes                      21010071        15425579
Unicast packets               95512           94166
Non-unicast packets           12510               7
Discards                          0               0
Errors                            0               3
Unknown protocols                 0

Answer:
Szia,
from
http://en.wikipedia.org/wiki/Netstat
On the Windows platform, netstat
  information can be retrieved by
  calling the GetTcpTable and
  GetUdpTable functions in the IP Helper
  API, or IPHLPAPI.DLL. Information
  returned includes local and remote IP
  addresses, local and remote ports, and
  (for GetTcpTable) TCP status codes. In
  addition to the command-line
  netstat.exe tool that ships with
  Windows, there are GUI-based netstat
  programs available.
  On the Windows platform, this command
  is available only if the Internet
  Protocol (TCP/IP) protocol is
  installed as a component in the
  properties of a network adapter in
  Network Connections.
MFC sample at CodeProject:
http://www.codeproject.com/KB/applications/wnetstat.aspx


Question: How can I compile/run C or C++ code in a Unix console or a Mac terminal?

Answer:
Assuming the current directory is not in the path, the syntax is
```
./[name of the program]
```
.
For example
```
./a.out
```


Question:
I have a page, with some code in js and jQuery and it works very well. But unfortunately, all my site is very very old, and uses frames. So when I loaded my page inside a frame, $(document).ready() doesn't fire up.

My frameset looks like:

<frameset rows="79,*" frameBorder="1" frameSpacing="1" bordercolor="#5996BF" noresize>
    <frame name="header" src="Operations.aspx?main='Info.aspx'" marginwidth="0" marginheight="0" scrolling="no" noresize frameborder="0">
    <frame name="main" src="Info.aspx" marginwidth="0" marginheight="0" scrolling="auto" noresize frameborder="0">
</frameset>

My page is loaded into the main frame. What should I do?

Answer:
There is no reason for
```
$(document).ready()
```
not to be called.
Be sure your page contains an include to
```
jquery.js
```
. Try to do a simple test with an empty HTML page and just an alert to see if there is another problem.
If you are trying to use this inside the HTML page that contains the frame's definition, keep in mind that there is no document there, you will have to use the


Question:
I have table employee like,

employee
(
emp_id int primary key,
emp_name varchar(50),
mngr_id int)

and here mngr_id would either null or contain valid emp_id. This way it form the hierarchy of employees in the organization.

In order to traverse the entire hierarchy I had to write the recursive stored procedure. (in Oracle it's easy by using CONNECT BY .. START WITH)

So the question is that what is the performance impact of such stored procedure given that the level of hierarchy would not go beyond 10 levels !

Is there any other way to achieve the same ?

Answer:
Regarding the last question: There are a few nice options at
"What is the most efficient/elegant way to parse a flat table into a tree?"
You should also consider caching the result of the recursion in an intermediate table. If you change that only on update to your hierarchy table, the recursion performance hit will be negligible.
EDIT:
Personally I would do the recursion in the presentation layer of my app, for example on the web server. This provides greater flexibility compared to what can be achieved in SQL, and you can also use session or application level caching. (Using a pre-constructed DB table that is kept up to date with a trigger never leaves you with an outdated cache, though.)


Question:
In Visual Studio, when you compile foo.idl, MIDL generates the proxy information in foo_p.c.

Unfortunately, for Win32 and x64 files, it uses the same filename. For Win32, the file starts with:

#if !defined(_M_IA64) && !defined(_M_AMD64)

For x64, the file starts with:

#if defined(_M_AMD64)

When you build for Win32 and then immediately build for x64, it doesn't replace the foo_p.c file, meaning that the project fails to link.

I tried having a pre-build event that deletes the foo_p.c file if it's for the wrong architecture, but VS doesn't even bother to run that step.

How should I get it so that I can build one configuration and then the other?

Answer:
You could modify the compiler settings for your IDL file to specify a different file name for the output proxy file according to the target platform. (Select Properties on the IDL file, then Configuration Properties / MIDL / Output).
For Win32 builds, use
```
foo_p_w32.c
```
For x64 builds, use
```
foo_p_x64.c
```
Then, in your Win32 project settings, exclude the file
```
foo_p_x64.c
```
and vice versa for the x64 project.
You need to do the same for the _i.c file, otherwise Visual Studio doesn't seem to rebuild the IDL at all.


Question:
What is the simplest way of copying symbolic links on the Mac?

A python or perl solution would be preferred, but any solution would be a help.

I am copying frameworks for an installation package, and need the links to be maintained

Answer:
In python you can use
os.readlink
and
os.symlink
to perform this action. You should check if what you operate on is actually a symbolic link with
os.lstat
and
stat.S_ISLNK
```
```
import os, stat
if stat.S_ISLNK(os.lstat('foo').st_mode):
    src = os.readlink('source')
    os.symlink(src, 'destination')
```
```
You could do it with the
-R option of cp
. This works because cp by default does not follow symbolic links but barks at copying non-files without specifying -R which means recursion.
```
```
cp -R source destination
```
```
In python that would be with the
subprocess.call
```
```
from subprocess import call
call(['cp', '-R', 'source', 'destination'])
```
```
Note that a
macosx alias
is not a symbolic link and therefore symbolic link specific treatment will fail on it.


Question:
I'm trying to do XHTML DOM parsing with JTidy, and it seems to be rather counterintuitive task. In particular, there's a method to parse HTML:

Node Tidy.parse(Reader, Writer)

And to get the <body /> of that Node, I assume, I should use

Node Node.findBody(TagTable)

Where should I get an instance of that TagTable? (Constructor is protected, and I haven't found a factory to produce it.)

I use JTidy 8.0-SNAPSHOT.

Answer:
You could use the
```
parseDOM
```
method instead, which would give you a
```
org.w3c.dom.Document
```
back:
```
```
Document document = Tidy.parseDOM(reader, writer);
Node body = document.getElementsByTagName("body").item(0);
```
```


Question: How do I convert text between multi-byte text strings, for example Simplified Chinese GB 2312, into UTF8 using c++ ?

Answer:
On unix systems you'd best use the iconv library.
See
iconv_open
,
iconv
,
iconv_close
You'd have to know the character encoding of course (EUC-CN, HZ).
If not on a unix system, search for some support in the OS, doing character conversions by hand is very hard to get right.


Question: What'd also interest me is which have more or less dependencies.

Answer:
Google is our friend
...
First hit:
http://syntax.rubyforge.org/chapter-1.html#s1


Question:
For a file containing the given class, SomeCoolClass, what would be the proper or standard filename?

 1. somecoolclass.rb
 2. some_cool_class.rb
 3. some-cool-class.rb
 4. SomeCoolClass.rb

or some other variation?

I noticed in the Ruby stdlib, versions 1, 2 and 3 are used.

Answer:
With just
Ruby
(i.e. not Rails), naming is only a convention.  In
Rails
the
convention
of using underscores is necessary (almost).
I think convention #2
```
lowercase_and_underscore.rb
```
is more common and looks pretty good, though an article
Here
says
```
lowercasenounderscore.rb
```
is the Ruby convention.
Pick either
which ever convention is more common or which ever one you like more.  The most important thing is to
be consistent within a project
.


Question: What is the arrow operator (->) a synonym for?

Answer:
The following two expressions are equivalent:
```
```
a->b

(*a).b
```
```
(subject to operator overloading, as Konrad mentions, but that's unusual).


Question:
If I have a folder structure set up like this:

~/Projects
    emacs
        package1
            package1-helpers
        package2
            package2-helpers
            package2-more-helpers
        package3
            package3-helpers

How do I add these folders:

~/Projects/emacs

~/Projects/emacs/package1

~/Projects/emacs/package2

~/Projects/emacs/package3

...to the load-path from my .emacs file?

I basically need a short automated  version of this code:

(add-to-list 'load-path "~/Projects/emacs")
(add-to-list 'load-path "~/Projects/emacs/package1")
(add-to-list 'load-path "~/Projects/emacs/package2")
(add-to-list 'load-path "~/Projects/emacs/package3")

Answer:
```
```
(let ((base "~/Projects/emacs"))
  (add-to-list 'load-path base)
  (dolist (f (directory-files base))
    (let ((name (concat base "/" f)))
      (when (and (file-directory-p name)
                 (not (equal f ".."))
                 (not (equal f ".")))
        (add-to-list 'load-path name)))))
```
```


Question:
Is there an easy way with LINQ to flatten an XML file?

I can see a number of ways with XSLT but wondered what the best option with LINQ would be?

I cant put the xml structure up exactly as stackoverflow seems to filter chevron chars. But its something like this

nodeA

--nodeA1

--nodeA2

NodeB

I want to end up with

nodeA

nodeA1

nodeA2

NodeB

Answer:
OK; it depends on the output you want - with XElement you'd need to do a bit of work to remove all the descendent nodes etc. However, it is actually quite simple with XmlDocument:
```
```
string xml = @"<xml><nodeA><nodeA1/><nodeA2/></nodeA><NodeB/></xml>";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);

XmlDocument clone = new XmlDocument();
XmlElement root = (XmlElement) clone.AppendChild(clone.CreateElement("xml"));
foreach(XmlElement el in doc.SelectNodes("//*")) {
    root.AppendChild(clone.ImportNode(el, false));
}
Console.WriteLine(clone.OuterXml);
```
```
Outputs:
```
```
<xml><xml /><nodeA /><nodeA1 /><nodeA2 /><NodeB /></xml>
```
```
[was]
Care to define "flatten" in this context? i.e. "before" and "after"?
XDocument has Descendants() and DescendantNodes() which might do the job...


Question:
Sometimes, when we're doing small changes to our web apps, e.g. bug fixes, we don't build a whole new WAR-file each time, but merely replace just the affected class files in the exploded web app directory under WEB-INF/classes and restart the app.

Is that okay?

Answer:
I'd say that probably isn't a best practice, because of versioning: how do you know which version of the application you've got deployed? If you deploy a .war file your build process can take care of updating a build number (from source control, or separately, whatever - as long as each build has a different number it's OK).
If you're using continuous integration (and it's definitely a good idea to be) then your build process should be kicking out an 'artifact' (war file) each time you make changes in source code. also perhaps tagging the code in version control with the build number.
So, when you deploy your web app, you know exactly which version is running and which source code makes up that version.
Making small incremental changes by updating individual .class files I'd say is probably not a good idea for anything other than local developer testing.


Question:
I need to include a copyright statement at the top of every Python source file I produce:

#   Copyright: © 2008 etc.

However, when I then run such a file I get this message:

SyntaxError: Non-ASCII character '\xa9' in file MyFile.py on line 3, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details.

Apparently Python isn't happy about the copyright symbol because it assumes the source file is all in ASCII. Either I need to make my first line be:

# -*- coding: iso-8859-1 -*-

to tell Python I'm using Latin encoding, or I can change the copyright statement to:

#   Copyright: \xa9 2008 etc.

which just possibly doesn't have the same legal standing.

Is there a more elegant solution?

Answer:
The copyright symbol in ASCII is spelled
```
(c)
```
or "
```
Copyright
```
".
See circular 61,
Copyright Registration for Computer Programs
.
While it's true that the legal formalism (see Circular 1,
Copyright Basics
) is
The symbol © (the letter C in a
  circle), or the word “Copyright,” or
  the abbreviation “Copr.”; and...
And it's also true that
To guarantee protection for a
  copyrighted work in all UCC member
  countries, the notice must consist of
  the symbol © (the word “Copyright” or
  the abbreviation is not acceptable)
You can dig through circular
3
and
38a
.
This has, however, already been tested in court.  It isn't an interesting issue.  If you do a search for "(c) acceptable for c-in-a-circle", you'll find that lawyers all agree that (c) is an acceptable substitute.  See Perle and Williams.  See Scott on Information Technology Law.


Question:
I appreciate that there are now many mechanisms in dotnet to deal with XML in a myriad of ways...

Suppose I have a string containing the XML....

<?xml version="1.0" encoding="utf-8" ?>
<root>
    <Element1>
        <Element1_1>
            SomeData
        </Element1_1>
    </Element1>
    <Element2>
        Some More Data
    </Element2>
</root>

What is the simplest (most readable) way of removing Element1_1?

Update... I can use any .Net API available in .Net 3.5 :D

Answer:
Which APIs are you able to use? Can you use .NET 3.5 and LINQ to XML, for instance? If so,
XNode.Remove
is your friend - just select Element1_1 (in any of the many ways which are easy with LINQ to XML) and call Remove() on it.
Examples of how to select the element:
```
```
XElement element = doc.XPathSelectElement("/root/Element1/Element1_1");
element.Remove();
```
```
Or:
```
```
XElement element = doc.Descendants("Element1_1").Single().Remove();
```
```


Question: Is it okay to run Hibernate applications configured with hbm2ddl.auto=update to update the database schema in a production environment?

Answer:
No, it's unsafe.
Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates
in production
. Write your own patches, review them with DBA, test them, then apply them manually.
Theoretically, if
hbm2ddl update
worked in development, it should work in production too. But in reality, it's not always the case.
Even if it worked OK, it may be sub-optimal. DBAs are paid that much for a reason.


Question: I would like to trim long sequences of the same value from a binary file in python. A simple way of doing it is simply reading in the file and using re.sub to replace the unwanted sequence. This will of course not work on large binary files. Can it be done in something like numpy?

Answer:
If two copies fit in memory, then you can easily make a copy.  The second copy is the compressed version.  Sure, you can use numpy, but you can also use the
array
package.  Additionally, you can treat your big binary object as a string of bytes and manipulate it directly.
It sounds like your file may be
REALLY
large, and you can't fit two copies into memory.  (You didn't provide a lot of details, so this is just a guess.) You'll have to do your compression in chunks.  You'll read in a chunk, do some processing on that chunk and write it out.  Again, numpy, array or simple string of bytes will work fine.


Question: I need a way to check for Wi-Fi routers/access points on my DS homebrew. I'm using PAlib.

Answer:
i used the code from ds_wifi_test (which comes with the original dswifi library) when i tried to implement this. Basically, access points are scanned internally when you invoke
```
Wifi_ScanMode()
```
. You can then have the number of AP identified with
```
Wifi_GetNumAP()
```
and retrieve the information for the ith access point with
```
Wifi_GetAPData(i,&data);
```
```
```
nbitems=Wifi_GetNumAP();
Wifi_AccessPoint ap;

for (int i=0;i<nbitems; i++) {
   if(Wifi_GetAPData(i+scrolltop,&ap)==WIFI_RETURN_OK)
      do_whatever_with(&ap);
}
```
```
I'm not aware of any "helper" functions through the PALib in this regards. All the PALib seems to have is a few "wrappers" to ease common tasks once a WFC setting has been defined (
see day#20 tutorial
)


Question:
I'm opening a new browser window from my site for some of the members. However, some may later close it, or it might have initially failed to open.

Is there a snippet of fairly plain Javascript that can be run on each page to confirm if another browser window is open, and if not, to provide a link to re-open it?

[clarification:] The code to check is a window is open would be run on other pages - not just in the same window and URL that opened it.  Imagine a user logging in, the window (tries to) open, and then they surf around in the same tab/window (or others) for some time before they close the 2nd window (or it never opened) - I want to be able to notice the window has been closed some time after the initial attempt at opening/after it's closed, so I'm not sure that checking the javascript's return from window.open() (with popup_window_handle.closed) is easily used, or indeed possible.

Answer:
```
```
var myWin = window.open(...);

if (myWin.closed)
{
    myWin = window.open(...);
}
```
```


Question:
How can I put up a "File Open" dialog from some VBA running in Excel?

I'm using Excel 2003.

Answer:
Add a reference to ComDLG32.OCX and then something like...
```
```
Sub PromptForFile()
Dim d As New MSComDlg.CommonDialog

d.Filter = "xls"
d.Filename = "*.xls"
d.ShowOpen

Excel.Workbooks.Open d.Filename

Set d = Nothing
End Sub
```
```


Question: I have a customer who needs to send some direct mailing to his contacts which is being collected from trade shows etc. I am thinking about providing a web based solution for them on sending direct mailing material- however this kind of solution always face a major difficulty on having the server blacklisted. I would like to know if there is any suggestions on how to maintain such SMTP server?

Answer: Aside from the server (just set up exim or postfix and a web interface to send newsletters from, and do this on a server with an IP address that is different from your own personal mail server (maybe even a different network)), you will want to get your terms and conditions of use nice and tight so that you can remove access to the systems from any customer that has complaints made about emailing. Indeed you can mandate that all emails sent must be lawful (e.g., unsubscription option that works, etc).


Question:
Control.TabIndex

Only allows me to overide the Tab order of controls in a given container.

Is there a way to specify this across all the controls in, for example a UserControl, regardless of the contains used to arrange the controls.

Cheers,

Jan

Answer:
I'm not sure that there is a particularly good way of doing what you are asking, but check out
Changing WPF focus in code
.
That uses
```
KeyboardNavigation.TabNavigation
```
to set how the various containers take and give up the Focus on tabbing, and also sets the
```
TabIndex
```
properties for each control. Look at the example code with the
```
TabNavigation
```
set to "Continue".
If your tabbing problems are simple, you should be able to find a solution here, if they are complex of need to be generalised, then it might take some more work.


Question:
My stomach churns when I see this kind of output.

http://www.freeimagehosting.net/uploads/e1097a5a10.jpg

and this was my command
as suggested by Best way to convert pdf files to tiff files

gswin32c.exe -q -dNOPAUSE -sDEVICE=tiffg4 -sOutputFile=a.tif a.pdf -c quit

What am I doing wrong?

(commercial products will not be considered)

Answer:
tiffg4 is a black&white output device.
You should use tiff24nc or tiff12nc as the output device colour PDFs - see
ghostscript output devices
.
These will be uncompressed but you could put the resulting TIFFs through imagemagick or similar to resave as compressed TIFF.


Question:
In LinqToSql, it is lovely easy to load a row, change a column, and submit the changes to the database:

using (MyDataContext wdc = new MyDataContext())
{
  Article article = wdc.Article.First(p => p.ID == id);
  article.ItemsInStock = itemsinstock;
  wdc.SubmitChanges();
}

The only drawback: Article is huge. To load the entire article, just to update one column is way overkill and slows down my app significantly.

Is there a way to update a single column using LINQ, without having to load the entire row?

Right now I revert to using ExecuteCommand where speed is of essence, but this is ugly and error prone:

wdc.ExecuteCommand("UPDATE Article SET ItemsInStock = @1 WHERE ID = @2", itemsinstock,id);

Answer:
You need to set UpdateCheck on all properties of the Article class except the primary key (click on the class property in LINQ2SQL designer and switch to Properties Tool Window) to Never (not sure about WhenChanged, maybe that works too - go ahead and experiment with it!).
This will force LINQ2SQL to use
```
```
UPDATE ... SET ... WHERE ID = @2
```
```
instead of the long version with all columns in the WHERE-clause:
```
```
UPDATE ... SET ... WHERE ID = @2 AND ItemsInStock = @1 AND SomeOtherColumn = @3 AND...
```
```
Now you can use code like
```
```
context.Articles.Attach(article /* article with updated values */, new Article { ID = articleID, ItemsInStock = -1 } /* pretend that this is the original article */);
context.SubmitChanges();
```
```
Basically you indicate that only ItemsInStock property has changed - other props should have the same default value, articleID of course being the same.
NOTE: you don't need to fetch the article prior to that.


Question:
After update, old Eclipse plugins remain in "plugins" folder (there are also leftovers in "features" folder).

Is there a way to remove those automatically?

Answer:
Eclipse allows you to revert back to any previous configuration (go to the Help menu, then "Software Updates"). My guess is that Eclipse won't remove these old versions, or this functionality would no longer work.
If when you restart Eclipse you provide the "-clean" argument, it performs various cleanup operations, but for reasons stated above I don't think it will remove old plugins/features.


Question:
I'm comparing the results produced when i use the 'Make .exe' compared to when i run the exact same process using the exact same variables though the IDE vb 6 debugger.

I've tried an array of different compiler options but to no avail.

So my question is why would i get a difference between the debugger and the 'Make .exe'?
have you ever come arross something similar and if so did you find a fix?

the program takes a large file of counts of cars in a timeperiod and averages them into 15 minute timeperiods for the day over a month for each route.
It elminates certain records depending on if there outside the standard deviation and other statistical algorithms To eliminate values.
its a bit to much code to post unfortunately...

Answer:
```
Debug.Assert
```
and
```
Debug.Print
```
Statement are not compiled into the binary. I sometimes use this to detect whether I am in the IDE or a compiled binary:
```
On Error Resume Next
Debug.Print 1/0
If Err=0 then
  'Compiled Binary
else
  'in the IDE
End if
```
Be careful with statements like this:
```
```
Debug.Assert( DoSomeThingImportend() )
```
```
In the compiled version this statement will not be executed.


Question:
Suppose, objects of type A are stored in DB. Here's the way I load specific one from DB using hibernate:

org.hibernate.Session session = ...;
long id = 1;
A obj = session.load(A.class, id);

If object with id=1 doesn't exist I will get ObjectNotFoundException. But is there a way to check if such object exists without having to catch the exception? What I would like to have is smth like:

org.hibernate.Session session = ...;
long id = 1;
boolean exists = session.exists(A.class, id);
if(exists){
 // do smth.....
}

Couldn't find it hibernate docs...

Answer:
You can use
```
session.get
```
:
```
```
public Object get(Class clazz,
                  Serializable id)
           throws HibernateException
```
```
It will return null if the object does not exist in the database. You can find more information in
Hibernate API Documentation
.


Question:
The following Code does not compile

Dim BasicGroups As String() = New String() {"Node1", "Node2"}
Dim NodesToRemove = From Element In SchemaDoc.Root.<Group> _
                    Where Element.@Name not in BasicGroups
For Each XNode In NodesToRemove
    XNode.Remove()
Next

It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is Not listed in the BasicGroups StringArray.

What is the correct syntax for this task?

Answer:
You probably want to move the 'not' part. Eg (psuedo code)
```
```
where (not (list.Contains(foo))
```
```


Question:
I've seen this in a few places

function fn() {
    return +new Date;
}

And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.

Can anyone explain?

Answer:
JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:
http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html
http://www.jibbering.com/faq/faq_notes/type_convert.html
Other examples:
```
```
>>> +new Date()
1224589625406
>>> +"3"
3
>>> +true
1
>>> 3 == "3"
true
```
```


Question:
Is there a way in SWT to get a monospaced font simply, that works across various operating systems?

For example. this works on Linux, but not Windows:

Font mono = new Font(parent.getDisplay(), "Mono", 10, SWT.NONE);

or do I need to have a method that tries loading varying fonts (Consolas, Terminal, Monaco, Mono) until one isn't null? Alternatively I could specify it in a properties file on startup.

I tried getting the system font from Display, but that wasn't monospaced.

Answer:
According to the section on
Font Configuration Files
in the JDK documentation of
Internationalization Support
-related APIs, the concept of
Logical Font
s is used to define certain platform-independent fonts which are mapped to physical fonts in the default font configuration files:
The Java Platform defines five logical font names that every implementation must support: Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical font names are mapped to physical fonts in implementation dependent ways.
So in your case, I'd try
```
Font mono = new Font(parent.getDisplay(), "Monospaced", 10, SWT.NONE);
```
to get a handle to the physical monospaced font of the current platform your code is running on.
Edit
: It seems that SWT doesn't know anything about logical fonts (
Bug 48055
on eclipse.org describes this in detail). In this bug report a hackish workaround was suggested, where the name of the physical font may be retrieved from an AWT font...


Question: I'd like them to be easy to bundle, with few dependencies and easy to use.

Answer:
http://sourceforge.net/projects/jintilla/
http://syntax.jedit.org/


Question:
I have some products that belongs to the some category.

Each category can have different properties.

For example,

category cars has properties color,
power, ...

category pets have properties  weight, age, ...

Number of categories is about 10-15.
Number of properties in each category is 3-15.
Number of products is very big.

Main requirement for this app is very good search. We will select category, and enter criteria for each property in this category.

Have to design database for this scenario. (SQL Server 2005)

Answer:
If the user of the application
has
to select a category before they can search, I would separate your products into different database tables by category.  This solution is also indicated by the fact that the categories themselves have so little in common.  Breaking it down by category will also make each search much faster, since time won't be wasted searching through cars when your user is looking for a pet.
Once you have the products split up in to categories, it should be easy to create the tables using the common properties of the products in each category.  The user interface of your application should be dynamic (I'm thinking of a web form), in that the properties the user can choose from should change when the user selects a category.
Please note that if you have products that you want listed in multiple categories, this solution will result in duplicate data in your tables.  There is a trade-off between speed and normalization when designing a database.  If you
don't
have products that fit in multiple categories, then I think this will be the fastest solution (in terms of search speed).


Question:
I am building an ObjectQuery like this:

        string query = "select value obj from Entities.Class as obj " +
                       "where obj.Property = @Value";

        ObjectQuery<Class> oQuery = new ObjectQuery<Class>(query, EntityContext.Instance);
        oQuery.Parameters.Add(new ObjectParameter("Value", someVariable));

I can now assign this object as a DataSource for a control, or iterate with a foreach loop or even force a materialization to a List, however, I can I count the number of objects that will be returned, without forcing a materialization?

Do I need to create a companion query that will execute a count() or is there a function that will do that for me somewhere?

Thank you.

Answer:
```
ObjectQuery<T>
```
implements
```
IQueryable<T>
```
, so can't you simply use the extension method:
```
```
int count = oQuery.Count();
```
```
What happens if you execute this? I would have expected the overall query to just do a Count()... (not that I've done much EF...).


Question:
I'm thinking about using BlogEngine.NET to launch my blog. I'm a C# programmer and was wondering was BlogEngine.NET has in the belly.

Does it scale well? Is it caching properly? Is it memory intensive? Can you easily add/remove functionality?

I also accept any hosting recommendation :)

Answer:
I'm running BlogEngine.Net. I don't know about scaling because my weblog isn't that popular (yet). I'm very happy with it.
I tried subtext before and I had some stability problems with it, it logged exceptions that I found hard to debug. I got an error exporting the database to BlogML and it messed up the order of my blogposts. BlogEngine.Net seems a lot more stable.
I'm running on a virtualized server hosted by a friend of mine. I have seen no performance issues but that might be because of the massive 15 visitors per day peak load. I've have some trouble where Live Writer posts blog entries twice, but I suspect this is Live Writer's fault.
I really like the extension model and the way you can drag and drop extensions on the design of your blog. There aren't much themes that support this yet but I created my own look and feel by changing the standard theme in about three hours.


Question:
For a certain Hibernate entity we have a requirement to store its creation time and the last time it was updated.  How would you design this?

What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)?  Will the data types be timezone-aware?

What data types would you use in Java (Date, Calendar, long, ...)?

Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?

What annotations would you use for the mapping (e.g. @Temporal)?

I'm not only looking for a working solution, but for a safe and well-designed solution.

Answer:
A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.
For the creation date, you simply keep a
java.util.Date
property. Be sure, to always initialize it with
new Date()
.
For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).


Question:
I have a c++ application which logs to some file using log4cxx (RollingFile appender). I want to log into the same file, at the same time, from another module written in c#; so i configured log4net to use the same file, but i can't get the new messages in. If i deactivate the c++ logging, i can see c# messages. So i think it is a locking issue, and looked for a configuration option to tell log4cxx not to lock the file. I came into MinimalLock model for log4net, but couldn't find anything in log4cxx... does anybody know if it could be done, and how?

thanks in advance,

Ernesto Cullen

Answer:
I think that you might run into concurrency and contention problems no matter what configuration you use as long as you are attempting to have two different processes log to the same file.
You should look into sending log events from both processes to a third, centralized location - take a look at
RemotingAppender
in log4net, I assume log4cxx has something similar.


Question: Enterprise Architect has a way to generate the documentation in HTML/RTF/etc. that you could publish, but you have to use its GUI to do that manually. When you have your *.eap files in a CVS/Subversion server, it would be useful to have a script that would check out daily the latest version and publish it in a web server. As long as I know, EA doesn't have a command line utility for this purpose. I found that you can automate almost anything using its COM interface, but that means it's necessary to write a small program to do that. Any ideas about the easiest/cleanest way to do that (without having to write code, if possible)?

Answer:
I think that you might run into concurrency and contention problems no matter what configuration you use as long as you are attempting to have two different processes log to the same file.
You should look into sending log events from both processes to a third, centralized location - take a look at
RemotingAppender
in log4net, I assume log4cxx has something similar.


Question:
I want to make a generic class that accepts only serializable classes, can it be done with the where constraint?

The concept I'm looking for is this:

public class MyClass<T> where T : //[is serializable/has the serializable attribute]

Answer:
Nope, I'm afraid not. The only things you can do with constraints are:
```
where T : class
```
- T must be a reference type
```
where T : struct
```
- T must be a non-nullable value type
```
where T : SomeClass
```
- T must be SomeClass or derive from it
```
where T : ISomeInterface
```
- T must be ISomeInterface or implement it
```
where T : new()
```
- T must have a public parameterless constructor
Various combinations are feasible, but not all. Nothing about attributes.


Question:
This might be a old question: Why does IEnumerable<T> inherit from IEnumerable?

This is how .NET do, but it brings a little trouble. Every time I write a class implements IEumerable<T>, I have to write two GetEnumerator() functions, one for IEnumerable<T> and the other for IEnumerable.

And, IList<T> doesn't inherit from IList.

I don't know why IEnumerable<T> is designed in other way.

Answer:
The answer for
```
IEnumerable
```
is: "because it can without affecting type safety".
```
IEnumerable
```
is a "readonly" interface - so it doesn't matter that the generic form is more specific than the nongeneric form. You don't break anything by implementing both.
```
IEnumerator.Current
```
returns
```
object
```
, whereas
```
IEnumerator<T>.Current
```
returns
```
T
```
- that's okay, as you can always legitimately convert to
```
object
```
, although it may mean boxing.
Compare this with
```
IList<T>
```
and
```
IList
```
- you can call
```
Add(object)
```
on an
```
IList
```
, whereas that may well be invalid for any particular
```
IList<T>
```
(anything other than
```
IList<object>
```
in fact).
Brad Abram's
blogged with Anders' answer
about this very question.


Question: I've been searching a lot but couldn't find a solution. How do you deal with a DateTime that should be able to contain an uninitialized value (equivalent to null)? I have a class which might have a DateTime property value set or not. I was thinking of initializing the property holder to DateTime.MinValue, which then could easily be checked. I guess this is a quite common question, how do you do that?

Answer:
For normal DateTimes,  if you don't initialize them at all then they will match
```
DateTime.MinValue
```
, because it is a value type rather than a reference type.
You can also use a nullable DateTime, like this:
```
```
DateTime? MyNullableDate;
```
```
Or the longer form:
```
```
Nullable<DateTime> MyNullableDate;
```
```
And, finally, there's a built in way to reference the default of any type.  This returns
```
null
```
for reference types, but for our DateTime example it will return the same as
```
DateTime.MinValue
```
:
```
```
default(DateTime)
```
```
or, in more recent versions of C#,
```
```
default
```
```


Question: I have a MySQL database of keywords that are presently mixed-case. However, I want to convert them all to lowercase. Is there an easy command to do this, either using MySQL or MySQL and PHP?

Answer:
```
SELECT LOWER(foo) AS foo FROM bar
```


Question:
I want to learn MSBuild, was wondering if someone could get me started with a simple build script to filter out my vs.net 2008 project of all files with the .cs extension.

how do I run the build?

where do you usually store the build also?

Answer:
```
```
C:\projects\_Play\SimpleIpService>type \\sysrdswbld1\public\bin\mrb-vs2008.cmd
@echo off

call "c:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"

echo %0 %*
echo %0 %* >> %MrB-LOG%
cd
if not ""=="%~dp1" pushd %~dp1
cd
if exist %~nx1 (
        echo VS2008 build of '%~nx1'.
        echo VS2008 build of '%~nx1'. >> %MrB-LOG%
        set MrB-BUILDLOG=%MrB-BASE%\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log
        msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release > %MrB-BUILDLOG%
        findstr /r /c:"[1-9][0-9]* Error(s)" %MrB-BUILDLOG%
        if not errorlevel 1 (
                echo ERROR: sending notification email for build errors in '%~nx1'.
                echo ERROR: sending notification email for build errors in '%~nx1'. >> %MrB-LOG%
                call mrb-email "Mr Build isn't happy about build errors in '%~nx1'" %MrB-BUILDLOG%
        ) else (
                findstr /r /c:"[1-9][0-9]* Warning(s)" %MrB-BUILDLOG%
                if not errorlevel 1 (
                        echo ERROR: sending notification email for build warnings in '%~nx1'.
                        echo ERROR: sending notification email for build warnings in '%~nx1'. >> %MrB-LOG%
                        call mrb-email "Mr Build isn't happy about build warnings in '%~nx1'" %MrB-BUILDLOG%
                ) else (
                        echo Successful build of '%~nx1'.
                        echo Successful build of '%~nx1'. >> %MrB-LOG%
                )
        )
) else (
        echo ERROR '%1' doesn't exist.
        echo ERROR '%1' doesn't exist. >> %MrB-LOG%
)
popd
```
```


Question:
I'm familiar with Sybase / SQL server, where I can create a temp. table like this:

SELECT *
INTO   #temp
FROM   tab1 ,
       tab2
WHERE  tab1.key = tab2.fkey

SELECT *
FROM   #temp
WHERE  field1 = 'value'

#temp only exists for the duration of this session, and can only be seen by me.

I would like to do a similar thing in Oracle, but I'm reading about "global temporary tables", which don't sound like the same thing.

How can I do the same thing in Oracle as I'm doing in Sybase?

Thanks :)

Answer:
I believe
global temporary
tables are the same. They will give you private access to a temporary table that dies when the session ends:
The data in a global temporary table is private, such that data inserted by a session can only be accessed by that session. The session-specific rows in a global temporary table can be preserved for the whole session, or just for the current transaction. The ON COMMIT DELETE ROWS clause indicates that the data should be deleted at the end of the transaction.
After reading the question a few more times I believe it the main difference, and maybe your issue is that the temporary tables persist between sessions. So the exact equivalent is not possible as you would imagine in Oracle it would be something like:
```
```
CREATE GLOBAL TEMPORARY TABLE my_temp_table ON COMMIT DELETE ROWS select * from other table;
```
```
That table will live until it is dropped even through sessions although the data in it does not. Instead you would need to create the temporary table in advance.


Question:
Basically I'm converting local dates stored in the database into UTC. But I've read somewhere that daylight saving rules have changed in 2007. So does the Date.ToUniversalTime() function still work correctly. Basically the dates before 2007(when the new rules came into effect) would be converted correctly but the dates after that would be not. Am I right here? Or would .Net take care of the conversion internally i.e. depending upon the different daylight saving rules?

EDIT: Dates are stored in DB as local times. I am converting it into UTC. So a date such as '9 March 2005' should be converted using day light rules of 2005 instead of today's rules. The rules changed in the US in 2007. So the date is coming out wrong by one hour.

Answer:
I would expect
```
ToUniversalTime()
```
to take that into account. Have you tried and checked the result with dates from before and after the DST change?
EDIT
If you
know
the timezone offset of all the dates in your DB, I definitively recommend you to convert them to UTC at the table level. You get rid of a whole lot of headaches that way. Converting to local time for display purposes is easier.


Question:
I have two BufferedImages I loaded in from pngs. The first contains an image, the second an alpha mask for the image.

I want to create a combined image from the two, by applying the alpha mask. My google-fu fails me.

I know how to load/save the images, I just need the bit where I go from two BufferedImages to one BufferedImage with the right alpha channel.

Answer:
Actually, I've figured it out. This is probably not a
fast
way of doing it, but it works:
```
```
for (int y = 0; y < image.getHeight(); y++) {
    for (int x = 0; x < image.getWidth(); x++) {
        Color c = new Color(image.getRGB(x, y));
        Color maskC = new Color(mask.getRGB(x, y));
        Color maskedColor = new Color(c.getRed(), c.getGreen(), c.getBlue(),
            maskC.getRed());
        resultImg.setRGB(x, y, maskedColor.getRGB());
    }
}
```
```


Question: I have heard that this is what JavaRebel does but is there any other good way to deploy a new version of an EAR while allowing users to remain active on the previous version?  We use JBoss for the application server...

Answer:
It's not what JavaRebel does. JavaRebel (according to description) hot-replaces the classes in memory. It's not acceptable in the case of existing connections to the system, since the updated classes may break the client's logic.
Once a company I was working for had a similar problem, and it was solved this way:
a smart router was used as a load-balancer
the new version was deployed to 50% of the nodes of the (new) cluster
new connections were delivered strictly to these updated nodes, old ones were balanced between old nodes
old nodes were took off-line (one-by-one, to keep number of clients per node within limits)
at the same time, new version was deployed to off-line "old" nodes and they were brought up as new nodes
due to EJB clustering, the sessions and beans were picked up by other old nodes
eventually (in a few hours), only one old node left, having a single instance of old version and all clients using old version were connected to it
when the last old client got disconnected, that node was too brought down
Now, I'm not a networking guy, and cannot give you many details (like what was the router hardware and such). My understanding this can be set up pretty easy, except, if I remember right, we had to setup an additional Weblogic domain to deploy new versions of the application (otherwise it would be conflicting with the old one on JNDI names).
Hope that helps.
P.S. Ichorus provided a comment saying that the app is deployed on clients' servers. So the router trick may be not feasible. Now, I see only one viable solution right now ( it's 21:52 now, I may overlook things :) ) --
Develop new version with "versioned" JNDI names; e.g. if Customer bean was under ejb/Customer in version 1, in version 2 it would be under ejb/Customer2
Have a business facade in the application with a stable basic interface (Factory-style) which, when asked for Customer bean, tries to find the highest-versioned JNDI name (not on every call, of course, can cache for a hour or so). That facade could (and should) be deployed as a separate application -- and never or very rarely updated
Now every new client would get access to the latest application deployed, and the applications won't conflict.
This approach takes a careful planning and testing, but should work IMHO.
I recently modified a few applications in a similar way to let them coexist in the same domain (before they used the same JNDI name for different data sources).


Question:
Is there a way to write an enumeration that can be extended.  I have several methods that I would like to always have available for my enumerations.  For example I use an enumeration for my database fields.  I include the actual field name in the database.

public enum ORDERFIELDS
        {
            OrderID("Order_ID");
            private String FieldName;

            private ORDERFIELDS(String fname)
                {
                    this.FieldName = fname;
                }

            public String getFieldName()
                {
                    return FieldName;
                }
        }

Answer:
All enums implicitly extend
```
java.lang.Enum
```
. Since Java does not support multiple inheritance, an enum cannot extend anything else.


Question: Do the clients need something else than a proper jdk and javafx compliant browser to visit javafx applets?

Answer:
GetAdaptersInfo() is the official method, it enumerates all adapters even ones that are disconnected.
See this post for example code
codeguru


Question:
I am getting a warning when trying to include the .net 3.5 sp1 prerequisite for my setup project.  The warning states Prerequisite could not found for bootstrapping.

Any suggestions?

Thanks

Answer:
I followed the directions in 2.3.1.1 Enable Samesite for the .NET Framework 3.5 SP1 bootstrapper package  and now everything works perfect.
Thanks


Question:
What is the prefered method for creating a byte array from an input stream?

Here is my current solution with .NET 3.5.

Stream s;
byte[] b;

using (BinaryReader br = new BinaryReader(s))
{
    b = br.ReadBytes((int)s.Length);
}

Is it still a better idea to read and write chunks of the stream?

Answer:
It really depends on whether or not you can trust
```
s.Length
```
. For many streams, you just don't know how much data there will be. In such cases - and before .NET 4 - I'd use code like this:
```
```
public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}
```
```
With .NET 4 and above, I'd use
```
Stream.CopyTo
```
, which is basically equivalent to the loop in my code - create the
```
MemoryStream
```
, call
```
stream.CopyTo(ms)
```
and then return
```
ms.ToArray()
```
. Job done.
I should perhaps explain why my answer is longer than the others.
```
Stream.Read
```
doesn't guarantee that it will read everything it's asked for. If you're reading from a network stream, for example, it may read one packet's worth and then return, even if there will be more data soon.
```
BinaryReader.Read
```
will keep going until the end of the stream or your specified size, but you still have to know the size to start with.
The above method will keep reading (and copying into a
```
MemoryStream
```
) until it runs out of data. It then asks the
```
MemoryStream
```
to return a copy of the data in an array. If you know the size to start with - or
think
you know the size, without being sure - you can construct the
```
MemoryStream
```
to be that size to start with. Likewise you can put a check at the end, and if the length of the stream is the same size as the buffer (returned by
```
MemoryStream.GetBuffer
```
) then you can just return the buffer. So the above code isn't quite optimised, but will at least be correct. It doesn't assume any responsibility for closing the stream - the caller should do that.
See
this article
for more info (and an alternative implementation).


Question:
I want to provide silverlight app to my customer while hosting the app at my own site for streamlined maintenance.

my Silverlight .xap  is hosted in, let say,  domain me-supplier.com

i want to embed it in, let say, domain my-customer.com

It works perfectly for http://my-customer.com, not for https://my-customer.com

i have added the (me-supplier.com hosted) cross domain silverlight policy file to allow my-customer.com

i have configured the mime types for .xap

the silverlight app needs html dom access so the iframe approach is not viable i believe.

this works for javascript code, so why not for silverlight ? any idea, workaround ?

Answer:
The short story is that it isn't
easily
accomplished. That code is added to the header by the menu during the prerender phase.
A possible workaround might be overriding the menu's onprerender in a custom menu control and don't call base. You could then replace the default menu control with your own using
tagMappings
.
I'd suggest you stay clear of the menu control if you can.


Question:
Possible Duplicate:

  ASP.NET MVC Performance

I know there is a learning curve, but what about performance? It seems to me that web forms would be less performant, but I havent tried MVC yet to know for sure. What is everyone else experiencing?

Answer:
This is almost a duplicate question. Here are some similar discussions:
ASP.NET MVC Performance
What are the key differences between ASP.NET webforms and MVC
Biggest advantage to using ASP.Net MVC vs web forms


Question:
What tools are there that I can test out a WCF service?

I am expecting allot of load so I want to have an idea how much a single server can handle.

Answer:
Start with this:
http://www.codeplex.com/WCFLoadTest
It doesn't do everything possible with WCF, but it is the best tool to start with. Worse comes to worse, it's not that hard to write manual invocation code with web services. They are much easier to load test than web sites.


Question:
I am creating an application in java which will be the part of an external application. My application contains a viewport which shows some polygons and stuff like that. The external application needs to get the image of the viewport in gif format. For that it calls a method in an interface (implemented by my application) and my application returns the image. The external application needs to store the image in database (or something related to it which I dont need to worry about).

My question is:- What should be the data container type of the image when my application send it to the external application? I mean what should be the return type of the method?
Currently my gif encoder class returns a byte array. Is there any other 'better' option?

Answer:
A byte array could be appropriate if you expect the GIFs to be small, but you might consider using an
```
OutputStream
```
so you can stream bits more efficiently.
Even if today you just return a fully-populated
```
ByteArrayOutputStream
```
, this would allow you to change your implementation in future without affecting cilent code.


Question: Pretty much what the title says. Is there a way to add files to a vsnet project from inside Vim? I work in a group of devs, and all of our code has solutions and projects as you would expect. I would like to use Vim, and was hoping for a way to maintain those project files when I added or removed files without having to go into vsnet.

Answer:
The project and solution files are in xml and are hand-edittable.  (I often have to during an SVN merge.)  However, HUGE DISCLAIMER AHOY, adding stuff from scratch is a lot more dubious than an svn merge.  I get to see the lines and just move them in (or not) here or there.  To be confident that you're not destroying the proj and sln files, you would have to experiment with visual studio a little bit to make sure what has to be added.
There are more IDEs than visual studio... perhaps there's some clues in their guts.