Question:
I'm using this XPath to get the value of a field:

//input[@type="hidden"][@name="val"]/@value

I get several results, but I only want the first. Using

//input[@type="hidden"][@name="val"]/@value[1]

Doesn't work. Once I have this, how do I pick up the value in Greasemonkey? I am trying things like:

alert("val " + val.snapshotItem);

But I think that's for the node, rather than the string.

Answer:
For the XPath, try:
```
//input[@type="hidden" and @name="val" and position() = 1]/@value
```
For use in a GreaseMonkey script, do something like this:
```
```
var result = document.evaluate(
  "//input[@type='hidden' and @name='var' and position()=1]/@value",
  document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null
);

var hiddenval = result.snapshotItem(0);

if (hiddenval)
  alert("Found: " + hiddenval.nodeValue);
else
  alert("Not found.");
```
```
Strictly speaking: Using
```
"position()=1"
```
in the XPath filter is not absolutely necessary, because only the first returned result is going to be used anyway (via
```
snapshotItem(0)
```
). But why build a larger result set than you really need.
EDIT: Using an XPath result of the
```
ORDERED_NODE_SNAPSHOT_TYPE
```
type makes sure you get the nodes in
document order
. That means the first node of the result will also be the first node in the document.


Question:
Just looking for the relevant documentation.  An example is not necessary, but would be appreciated.

We have a situation where we are having to create 100s of virtual directories manually, and it seems like automating this would be a good way to make the process more efficient for now.

Perhaps next year we can rework the server environment to allow something more sane, such as URL rewriting (unfortunately this does not seem feasible in the current cycle of the web application).  Isn't it great to inherit crap code?

~ William Riley-Land

Answer:
NOT TESTED (from an old code base and written by a former contractor of mine)
```
```
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.IO;

namespace Common.DirectoryServices
{
    public class IISManager
    {

        private string _webSiteID;

        public string WebSiteID
        {
            get { return _webSiteID; }
            set { _webSiteID = value; }
        }

        private string _strServerName;
        public string ServerName
        {
            get
            {
                return _strServerName;
            }
            set
            {
                _strServerName = value;
            }
        }

        private string _strVDirName;
        public string VDirName
        {
            get
            {
                return _strVDirName;
            }
            set
            {
                _strVDirName = value;
            }
        }

        private string _strPhysicalPath;
        public string PhysicalPath
        {
            get
            {
                return _strPhysicalPath;
            }
            set
            {
                _strPhysicalPath = value;
            }
        }

        private VDirectoryType _directoryType;
        public VDirectoryType DirectoryType
        {
            get
            {
                return _directoryType;
            }
            set
            {
                _directoryType = value;
            }
        }

        public enum VDirectoryType
        {
            FTP_DIR, WEB_IIS_DIR
        };

        public string CreateVDir()
        {
            System.DirectoryServices.DirectoryEntry oDE;
            System.DirectoryServices.DirectoryEntries oDC;
            System.DirectoryServices.DirectoryEntry oVirDir;
            //try
           // {
                //check whether to create FTP or Web IIS Virtual Directory
                if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)
                {
                    oDE = new DirectoryEntry("IIS://" +
                          this._strServerName + "/W3SVC/" + _webSiteID + "/Root");
                }
                else
                {
                    oDE = new DirectoryEntry("IIS://" +
                          this._strServerName + "/MSFTPSVC/1/Root");
                }

                //Get Default Web Site
                oDC = oDE.Children;

                //Add row
                oVirDir = oDC.Add(this._strVDirName,
                          oDE.SchemaClassName.ToString());

                //Commit changes for Schema class File
                oVirDir.CommitChanges();

                //Create physical path if it does not exists
                if (!Directory.Exists(this._strPhysicalPath))
                {
                    Directory.CreateDirectory(this._strPhysicalPath);
                }

                //Set virtual directory to physical path
                oVirDir.Properties["Path"].Value = this._strPhysicalPath;

                //Set read access
                oVirDir.Properties["AccessRead"][0] = true;

                //Create Application for IIS Application (as for ASP.NET)
                if (this.DirectoryType == VDirectoryType.WEB_IIS_DIR)
                {
                    oVirDir.Invoke("AppCreate", true);
                    oVirDir.Properties["AppFriendlyName"][0] = this._strVDirName;
                }

                //Save all the changes
                oVirDir.CommitChanges();

                return null;

           // }
            //catch (Exception exc)
            //{
             //   return exc.Message.ToString();
            //}
        }
    }
}
```
```


Question:
We have simple web-based data entry internal business app.
Now business wants to be able to attach a document to a row in the database that represents business entity. Document can be Word, Excel, PDF.

How can we do that?

I think creating yet another home grown document management system is not a good idea.
Instead we can try to use an third party document management system and integrate tightly form our app.
Ideally all user interface will stay within application, without going to an external system.
Is sharepoint or documentum capable of doing it?
What other options are there?

The application platform is Java/Websphere. We ave both Windows and Unix infrastructure available.

Answer:
I think any document management system can do what you are requesting. At one time we did something similar with Sharepoint. The systems expose an API that allows you to query documents that are stored. Exactly how the integration happens depends on the solution you go for.
You need to consider the platform on which your current system is built when choosing because different solutions support different integration technologies. For instance, if your current system uses .NET then Sharepoint would be easy to integrate.
Many document management systems use a backend database like SQL server and integration could be as easy as querying the backend database from your application.


Question: How do I tell if my application (compiled in Visual Studio 2008 as Any CPU) is running as a 32-bit or 64-bit application?

Answer:
I found this code from
Martijn Boven
that does the trick:
```
```
public static bool Is64BitMode() {
    return System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8;
}
```
```


Question: How do you programmatically obtain a picture of a .Net control?

Answer:
There's a method on every control called
DrawToBitmap
.  You don't need to p/invoke to do this.
```
```
Control c = new TextBox();
System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(c.Width, c.Height);
c.DrawToBitmap(bmp, c.ClientRectangle);
```
```


Question: if A is extension use case (not base use case), can A be directly referenced by the actor?

Answer:
You can make the case that there are two kinds of use cases:
Abstract -- not directly experience by an actor, but extensions ("subclasses") are.
Concrete -- experienced by an actor.


Question:
Can someone post a simple example of starting two (Object Oriented) threads in C++.

I'm looking for actual C++ thread objects that I can extend run methods on (or something similar) as opposed to calling a C-style thread library.

I left out any OS specific requests in the hopes that whoever replied would reply with cross platform libraries to use. I'm just making that explicit now.

Answer:
It largely depends on the library you decide to use. For instance, if you use the
wxWidgets
library, the creation of a thread would look like this:
```
```
class RThread : public wxThread {

public:
    RThread()
        : wxThread(wxTHREAD_JOINABLE){
    }
private:
    RThread(const RThread &copy);

public:
    void *Entry(void){
        //Do...

        return 0;
    }

};

wxThread *CreateThread() {
    //Create thread
    wxThread *_hThread = new RThread();

    //Start thread
    _hThread->Create();
    _hThread->Run();

    return _hThread;
}
```
```
If your main thread calls the CreateThread method, you'll create a new thread that will start executing the code in your "Entry" method. You'll have to keep a reference to the thread in most cases to join or stop it.
More information is in the
wxThread documentation
.


Question:
I'm trying to be responsible with my "DOM" references in this little Flash 8/AS2 project.

What has become increasingly frustrating is obtaining references to other movie clips and objects.  For example, currently my code to access the submit button of a form looks something like this

var b:Button = _level0.instance4.submitBtn;

I was hoping there was an instance-retrieval method for AS2 similar to AS3's MovieClip.getChildByName() or even Javascript's document.getElementById().  Because hard-coding the names of these anonymous instances (like instance4 in the above) just feel really, really dirty.

But, I can't find anything of the sort at this AS2 Reference.

Answer:
If the MovieClip was placed on the stage in the Flash IDE, you can give it a proper instance name in the properties panel.
If it was dynamically added, you can also give it a name, and additionally store a reference:
```
```
var my_MC=createEmptyMovieClip("instanceName", depth);
```
```
In either case, you can then adress them with
```
_parentClip.instanceName
```
or
```
my_MC.
```


Question: Is there a programming language "below" Assembly?

Answer:
Machine code
. Time it was programmers coded in the 1 and 0's of binary. Hex was considered an advance over this. That was before assembly, which uses the code's names and separates the parts of an instruction into its parts.


Question:
It there any article/book that defines upper bounded design limits for WS timeouts? Do you timeout at the server or recommend the client specific timeouts too?

Is there a common best practice like "never design WS that can take longer than 60 seconds, use an asynchronous token pattern"

I am interested in knowing what you do or your opinion too.

Answer:
Take the amount of data you are transfering via your web service an see how long the process takes.
Add 60 secs to that number and test.
If you can get it to timeout on a good connection then add 30 more seconds.
rinse and repeat.


Question: Is there a limit to the length of a GET request?

Answer:
Not in the
RFC
, no, but there are practical limits.
The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they
serve, and SHOULD be able to handle URIs of unbounded length if they
provide GET-based forms that could generate such URIs. A server
SHOULD return 414 (Request-URI Too Long) status if a URI is longer
than the server can handle (see section 10.4.15).
Note: Servers should be cautious about depending on URI lengths
above 255 bytes, because some older client or proxy implementations
may not properly support these lengths.


Question:
Am I safe in casting a C++ bool to a Windows API BOOL via this construct

bool mybool = true;
BOOL apiboolean = mybool ? TRUE : FALSE;

I'd assume this is a yes because I don't see any obvious problems but I wanted to take a moment to ask only because this may be more subtle than it appears.

Thanks to Dima for (gently) pointing out my carelessness in the way I'd originally phrased the question.

Answer:
Do you mean
```
```
bool b;
...
BOOL apiboolean = b ? TRUE : FALSE;
```
```
If so, then yes, this will work.


Question:
A pattern that's started to show up a lot in one of the web apps I'm working are links that used to just be a regular a-tag link now need a popup box asking "are you sure?" before the link will go.  (If the user hits cancel, nothing happens.)

We've got a solution that works, but somehow we're a web app shop without a Javascript expert, so I'm left with this crawling feeling like there's a better way to get the job done.

So, JS experts, what's the most standards-compliant, cross-browser way to get this done?

(For the record, this is already a site that requires JS, so no need to have a "non-JS" version.  But, it does need to work in any and all reasonably modern browsers.)

(Also, for bonus points it would be nice if people with JS turned off didn't have the links  work, rather than bypassing the confirm box.)

Answer:
Here's how we've been doing it:
```
```
Go to new page`

function goThere()
{
   if( confirm("Are you sure?") )
    {
       window.location.href="newPage.aspx";
    }
}
```
```
(EDIT: Code reformatted to avoid horizontal scroll)


Question:
I got a quick question about running a directX application (C++) in a managed environment. I'm attempting to write a MDI tool (in C#) where the background of the parent window would be an embedded render window of directX (C++).

I've read ways that involved writing the C++ into a native dll, however it would be prefered to be able to have the C++ projects included within the solution (I dont even know if that's possible though). Eitherway, if you know of some helpful steps, hints, or if this is a bad idea in general, please let me know. Thanks!

Answer:
First of all writing the C++ part in a different dll file doesn't mean that it couldn't be at the same solution as the C# project.
In order to use native DX to render on a managed window you need to pass the HWND window id (use form.WindowId.ToInt32) to the C++ D3Ddevice c'tor. after that each time you'll render using that device it would render on the .NET window.
To do this you probably need two saparate projects - a C++ dll & .NET project. use COM wrapper or p-invoke to pass the HWND to the C++ dll.


Question:
I have a MS Access form with a Datasheet subform.

Using code, I change the ColumnHidden property of various of its columns.
But, when I close the form, I'm asked whether to save the table layout of the Datasheet's table.

How can I stop the form from asking the user to same the table layout continually?

Do I have no choice but to change the Datasheet to a regular subform?

Answer:
If you are always hiding the same columns - create a query that only has the columns you want displayed and use that as the source of your subform.
If you still need some hidden fields (child keys, etc.) you will have to create a regular form. It's not too bad:
just base it on your table,
drag your columns onto the form (formatting, and placement doesn't matter)
set it to datasheet view
edit labels (these become column headings)
change the tab order (this controls the order the columns are displayed)
view the datasheet and hide the columns you want
save the form
add this form as a subform to the main form


Question: In VIM in command line mode a "%" denotes the current file, "cword" denotes the current word under the cursor. I want to create a shortcut where I need the current line number. What is the symbol which denotes this?

Answer:
. (dot) stands for the current line.
To clarify:
This is meant for stuff like
```
:1,.s/foo/bar/g
```
which will transform every
```
foo
```
to
```
bar
```
from the beginning of the file up to the current line.
I don't know know of a way to get the current line number expanded for a shell command, which is what you are trying to do by doing
```
:!echo .
```
You can find out about the expansions that are done (like
```
%
```
and
```
#
```
for example) in
```
:he cmdline-special
```
.


Question:
I've got a WAR file that I need to add two files to. Currently, I'm doing this:

File war = new File(DIRECTORY, "server.war");
JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war)));

//Add file 1
File file = new File(DIRECTORY, "file1.jar");
InputStream is = new BufferedInputStream(new FileInputStream(file));
ZipEntry e = new ZipEntry("file1.jar");
zos.putNextEntry(e);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf, 0, buf.length)) != -1) {
    zos.write(buf, 0, len);
}
is.close();
zos.closeEntry();

//repeat for file 2

zos.close();

The result is that the previous contents get clobbered: the WAR has only the 2 files I just added in it. Is there some sort of append mode that I'm not using or what?

Answer:
Yeah, there's an extra boolean argument to the
FileOutputStream constructor
which lets you force it to append to the file rather than overwrite it. Change your code to
```
```
JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(war, True)));
```
```
and it should work the way you want.


Question:
We are in a Windows environment and looking to automate this process for non-company machines.  If a vendor comes on site, we'd like to be able to have him/her hit a website that can perform a quick scan of the workstation to determine if they have the proper MS KB patches and if their virus scanner dats are up to date.

I can scan for the KB updates relatively easy, what I'm having a hard time finding is a way to check the virus dat status and since there are so many different engines out there, it seemed to make sense to use the (built into XP at least) proprietary MS security center stuff.

Eventually we'd like to have our routers redirect non-company machines to a website that will force validation, but until that point it will be a manual process.

Any thoughts?

Answer:
In Windows Vista there are some new APIs to interface with the Security Center component status:
http://msdn2.microsoft.com/en-us/library/bb963845(VS.85).aspx
Through WMI, here's a VBS code snippet I checked out on
http://social.msdn.microsoft.com/forums/en-US/windowssecurity/thread/bd97d9e6-75c1-4f58-9573-9009df5de19b/
to dump Antivirus product information:
```
```
Set oWMI = GetObject
("winmgmts:{impersonationLevel=impersonate}!\\.\root\SecurityCenter")
    Set colItems = oWMI.ExecQuery("Select * from AntiVirusProduct")

    For Each objAntiVirusProduct In colItems
    msg = msg & "companyName: " & objAntiVirusProduct.companyName & vbCrLf
    msg = msg & "displayName: " & objAntiVirusProduct.displayName & vbCrLf
    msg = msg & "instanceGuid: " & objAntiVirusProduct.instanceGuid & vbCrLf
    msg = msg & "onAccessScanningEnabled: "
 & objAntiVirusProduct.onAccessScanningEnabled & vbCrLf
    msg = msg & "productUptoDate: " & objAntiVirusProduct.productUptoDate & vbCrLf
    msg = msg & "versionNumber: " & objAntiVirusProduct.versionNumber & vbCrLf
    msg = msg & vbCrLf

    Next

    WScript.Echo msg
```
```


Question:
How would I format the standard RSS pubDate string as something closer to ASP.NET's DateTime?

So, from this:

Wed, 29 Oct 2008 14:14:48 +0000

to this:

10/29/2008 2:14 PM

Answer:
Something close to this should work:
```
```
string orig = "Wed, 29 Oct 2008 14:14:48 +0000";
string newstring = String.Format("{0:MM/dd/yyyy hh:mm tt}", DateTime.Parse(orig.Remove(orig.IndexOf(" +"))));
```
```
Taken from
http://blog.stevex.net/index.php/string-formatting-in-csharp/


Question: I'm using linq to pull back an object (i.e. customer) that might have a collection of other objects(customer.orders).  I would be nice if I can pass this list of customers to the ultragrid and a hierarchical view of customers and thier orders displayed on databind.  When I try this, I just get customers.  Anyone know how to get this to work with non dataset objects?

Answer:
Figured it out.  IList collection works and will create bands for properties of your domain object if it is an
```
IList<T>
```
.  Just make sure that
```
DisplayLayout.ViewStyle                 = ViewStyle.MultiBand
```
.


Question: Are there any drawbacks to using the STL or templates. Are there any situations for which they are inappropriate.

Answer:
First, you should use probably use them if they help you solve your problem.  Templates are a very important part of C++ and have been part of the standard for years.  STL is very powerful and fast at run time and should be supported on all decent compilers, but of course there are issues.
If you have a really old compiler, STL might not be completely supported.
The thread-safety of the STL implementation might be work for your application
Templates can lead to slower compile-times and possibly larger executable, especially with older compilers.
Compilers often produce incomprehensible error messages on code using templates.
just to name a few, but the drawbacks of not using them are likely to be much greater.


Question:
I really like the Flex framework, however I routinely deal with SWF files that are ~ 500KB.

I don't know at what point a file considered to be "too big" to be served on the internet, but I would assume that a 500KB download just to use a web application would certainly annoy some users.

Are there any tips or techniques on reducing the size of compiled SWFS?

As a side note, the 500KB SWF file really isn't that big of application...

Answer:
This answer is a little more general than you're probably looking for (it applies to all web apps, whether Flash/Flex-based or HTML/CSS/JS based or whatever), but...
It depends a lot on the use case for your application. Is it an application that will be loaded all day and pull in updates as necessary (like Gmail) or is it something that will be launched, used, then closed?
If the former, besides reducing resource size, you are probably alright here. It makes more sense to get the downloading all out of the way at once, rather than to expect the user to tolerate delays at every turn.
If the latter, you should lazy-load as much as possible. In other words, for example, instead of embedding all of the application's graphics into the SWF, load them with
```
URLRequest
```
s or whatever method necessary when they are needed. A quicker launch will "feel" faster and more than make up for the increased HTTP requests over a short time.


Question:
I am coding in ColdFusion, but trying to stay in cfscript, so I have a function that allows me to pass in a query to run it with

<cfquery blah >
  #query#
</cfquery>

Somehow though, when I construct my queries with sql = "SELECT * FROM a WHERE b='#c#'"  and pass it in, ColdFusion has replaced the single quotes with 2 single quotes.  so it becomes  WHERE b=''c'' in the final query.

I have tried creating the strings a lot of different ways, but I cannot get it to leave just one quote.  Even doing a string replace has no effect.

Any idea why this is happening?  It is ruining my hopes of living in cfscript for the duration of this project

Answer:
ColdFusion, by design, escapes single quotes when interpolating variables within
```
<cfquery>
```
tags.
To do what you want, you need to use the
```
PreserveSingleQuotes()
```
function.
```
```
<cfquery ...>#PreserveSingleQuotes(query)#</cfquery>
```
```
This doesn't address, however, the danger of SQL injection to which you are exposing yourself.
Using
```
<cfqueryparam>
```
also allows your database to cache the query, which in most cases will improve performance.
It might be helpful to read
an old Ben Forta column
and
a recent post by Brad Wood
for more information about the benefits of using
```
<cfqueryparam>
```
.


Question:
I'm running an application (web service) in tomcat with TLS enabled (with certificates both for the client and the server).

I want that my application will be able to send audit message (logging) when TLS handshake fails. For example I want to log when:

the client certificate is expired,

the client certificate is unknown (not in the server trust store)

any other  handshake failure

Is there any event that I can catch and handle in order to do that?

My application is web service based and is running in tomcat. Tomcat is handling all network and the TLS layers, and the application does not aware of that.

As I don't open any socket myself, where should I catch this Exception?

Answer:
Since I spent the past week debugging Tomcat's SSL configuration, I am pretty sure catching
```
javax.net.ssl.SSLHandshakeException
```
in your code and logging it should take care of all three of those errors.
When you instantiate a new webservice connection in your application, that is when the exception will occur.


Question:
I'm consuming an axis 1.4 web service that returns soap responses that I want to unmarshal into my domain objects using jaxb annotations.  My initial tests worked very well until some of the returned messages had multiRef elements. Objects that were marshalled using multiRef were showing up as null in my client side annotated model objects.

My question is does JAXB support unmarshalling soap responses with multiRef elements?  If so, how? and if not, does anybody know of a better way to unmarshal axis 1.4 soap responses into my domain model in java?

Answer:
In case of web services JAXB doesn't come alone, but as data binding part of ws client framework. So I assume your question is how to use JAXB as data binding within axis 1.4. In general I think there is no easy way to achieve that, have a look at the following thread in axis-user mailing list:
Specify JAXB generated complex types to Axis web service
.
If you can upgrade to consume web service with axis2 then it should be much easier since axis2 comes with pluggable data binding architecture including integrated jaxb implementation.


Question:
How can I check if a file uploaded by a user is a real jpg file in Python (Google App Engine)?

This is how far I got by now:

Script receives image via HTML Form Post and is processed by the following code

...
incomming_image = self.request.get("img")
image = db.Blob(incomming_image)
...

I found mimetypes.guess_type, but it does not work for me.

Answer:
If you need more than looking at extension, one way would be to read the JPEG header, and check that it matches valid data.  The format for this is:
```
```
Start Marker  | JFIF Marker | Header Length | Identifier
0xff, 0xd8    | 0xff, 0xe0  |    2-bytes    | "JFIF\0"
```
```
so a quick recogniser would be:
```
```
def is_jpg(filename):
    data = open(filename,'rb').read(11)
    if data[:4] != '\xff\xd8\xff\xe0': return False
    if data[6:] != 'JFIF\0': return False
    return True
```
```
However this won't catch any bad data in the body.  If you want a more robust check, you could try loading it with
PIL
.  eg:
```
```
from PIL import Image
def is_jpg(filename):
    try:
        i=Image.open(filename)
        return i.format =='JPEG'
    except IOError:
        return False
```
```


Question:
I just realized that in some place in my code I have the return statement inside the lock and sometime outside. Which one is the best?

1)

void example()
{
    lock (mutex)
    {
    //...
    }
    return myData;
}

2)

void example()
{
    lock (mutex)
    {
    //...
    return myData;
    }

}

Which one should I use?

Answer:
It doesn't make any difference; they're both translated to the same thing by the compiler.
To clarify, either is effectively translated to something with the following semantics:
```
```
T myData;
Monitor.Enter(mutex)
try
{
    myData= // something
}
finally
{
    Monitor.Exit(mutex);
}

return myData;
```
```


Question: Is there any way in JavaScript to create a "weak reference" to another object? Here is the wiki page describing what a weak reference is. Here is another article that describes them in Java. Can anyone think of a way to implement this behavior in JavaScript?

Answer:
http://www.jibbering.com/faq/faq_notes/closures.html
ECMAScript uses automatic garbage collection. The specification does not define the details, leaving that to the implementers to sort out, and some implementations are known to give a very low priority to their garbage collection operations. But the general idea is that if an object becomes un-referable (by having no remaining references to it left accessible to executing code) it becomes available for garbage collection and will at some future point be destroyed and any resources it is consuming freed and returned to the system for re-use.
This would normally be the case upon exiting an execution context. The scope chain structure, the Activation/Variable object and any objects created within the execution context, including function objects, would no longer be accessible and so would become available for garbage collection.
Meaning there are no weak ones only ones that no longer become available.


Question:
I'm trying to figure out a way to detect files that are not opened for editing but have nevertheless been modified locally. p4 fstat returns a value headModTime for any given file, but this is the change time in the depot, which should not be equal to the filesystem's stat last modified time.

I'm hoping that there exists a more lightweight operation than backing up the original file, forcing a sync of the file, and then running a diff. Ideas?

Answer:
From:
http://answers.perforce.com/articles/KB/3481/?q=disconnected&l=en_US&fs=Search&pn=1
See step 2 specifically:
2 . Next, open for "edit" any files that have changed:
```
```
p4 diff -se //myclient/... | p4 -x - edit
```
```
p4 diff -se returns the names of depot files whose corresponding client file differs in any way from the clients #have revision.


Question:
I'm trying to submit a form with javascript. Firefox works fine but IE complains that "Object doesn't support this property or method" on the submit line of this function:

function submitPGV(formName, action)
{
    var gvString = "";

    pgVisibilities.each(function(pair) {
        gvString += pair.key + ":" + pair.value + ",";
    });

    $('pgv_input').value = gvString;

    var form = $(formName);
    form.action = action;
    form.submit();
}

Called here:

<a href="javascript:submitPGV('ProductGroupVisibility','config/productgroupvis/save')">

Here's the form:

<form id="ProductGroupVisibility" action="save" method="post">
    <input type="hidden" name="ows_gv..PGV" id="pgv_input" value=""/>
</form>

Any ideas?

Answer:
Are you sure you have your JavaScript library loaded? (jQuery or Prototype)
It worked for me in IE7 with Prototype.
Try:
```
```
alert($('ProductGroupVisibility').id)
```
```
See if you get an error.


Question:
I have a C# class the returns a List, using System.Collections.Generic Lists not F# List

I want to iterate though the list to find a object or not find it.  Here is how I would do it in C#.  How would I accomplish the similar thing in F#

foreach (AperioCaseObj caseObj in CaseList)
{
     if (caseObj.CaseId == "")
     {
     }
     else
     {
     }
}

Answer:
See this example for iterating an integer generic list:
```
```
#light
open System.Collections.Generic

let genList = new List<int>()

genList.Add(1)
genList.Add(2)
genList.Add(3)

for x in genList do
  printf "%d" x
```
```


Question:
Is there any performance reason to declare method parameters final in Java?

As in:

public void foo(int bar) { ... }

Versus:

public void foo(final int bar) { ... }

Assuming that bar is only read and never modified in foo().

Answer:
Compilers that operate after class loading, such as JIT compilers, can take advantage of final methods. Consequently, methods declared final could have some performance benefit.
http://www.javaperformancetuning.com/tips/final.shtml
Oh and another good resource
http://mindprod.com/jgloss/final.html


Question:
I need to see if a string value matches with an object value, but why won't this work?

public int countPacks(String flavour) {
    int counter = 0;
    for(int index = 0; index < packets.size(); index++) {
        if (packets.equals(flavour)) {
           counter ++;
        }
        else {
           System.out.println("You have not entered a correct flavour");
        }
    }
    return counter;
}

Answer:
You probably mean something like
```
```
if (packets.get(index).equals(flavour)) {
   ...
```
```


Question:
Where is the best place to add a method to the integer class in Rails?
I'd like to add a to_meters and to_miles methods.

Answer:
Normally (and logically), integers can't be converted to miles or to meters. It sounds like you may want to create a new class like "Feet" or "inches" that is initialized with an integer, then contains methods like size_in_miles or size_in_meters. For convenience those methods could return decimal or float types, but you might also want to write a miles class or a meters class.
As an alternate method, you might want to create a static method in your new class that would have a signature like this:
```
Float feetToMiles(integer I)
```
that you would call
```
miles = Feet.feetToMiles(5280);
```
and get
```
miles = 1.0
```


Question: I'd like to format a duration in seconds using a pattern like H:MM:SS. The current utilities in java are designed to format a time but not a duration.

Answer:
If you're using a version of Java prior to 8... you can use
Joda Time
and
```
PeriodFormatter
```
. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using
```
Duration
```
for the most part - you can then call
```
toPeriod
```
(specifying whatever
```
PeriodType
```
you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a
```
Period
```
which you can format.
If you're using Java 8 or later: I'd normally suggest using
```
java.time.Duration
```
to represent the duration. You can then call
```
getSeconds()
```
or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a
single
negative sign in the output string. So something like:
```
```
public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}
```
```
Formatting this way is
reasonably
simple, if annoyingly manual. For
parsing
it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.


Question:
I'm conducting experiments regarding e-mail spam. One of these experiments require sending mail thru Tor. Since I'm using Python and smtplib for my experiments, I'm looking for a way to use the Tor proxy (or other method) to perform that mail sending.
Ideas how this can be done?

Answer:
If you're using a version of Java prior to 8... you can use
Joda Time
and
```
PeriodFormatter
```
. If you've really got a duration (i.e. an elapsed amount of time, with no reference to a calendar system) then you should probably be using
```
Duration
```
for the most part - you can then call
```
toPeriod
```
(specifying whatever
```
PeriodType
```
you want to reflect whether 25 hours becomes 1 day and 1 hour or not, etc) to get a
```
Period
```
which you can format.
If you're using Java 8 or later: I'd normally suggest using
```
java.time.Duration
```
to represent the duration. You can then call
```
getSeconds()
```
or the like to obtain an integer for standard string formatting as per bobince's answer if you need to - although you should be careful of the situation where the duration is negative, as you probably want a
single
negative sign in the output string. So something like:
```
```
public static String formatDuration(Duration duration) {
    long seconds = duration.getSeconds();
    long absSeconds = Math.abs(seconds);
    String positive = String.format(
        "%d:%02d:%02d",
        absSeconds / 3600,
        (absSeconds % 3600) / 60,
        absSeconds % 60);
    return seconds < 0 ? "-" + positive : positive;
}
```
```
Formatting this way is
reasonably
simple, if annoyingly manual. For
parsing
it becomes a harder matter in general... You could still use Joda Time even with Java 8 if you want to, of course.


Question:
I'm writing a Rails plugin that includes some partials.  I'd like to test the partials, but I'm having a hard time setting up a test that will render them.  There's no associated controller, so I'm just faking one:

require 'action_controller'
require 'active_support'
require 'action_pack'
require 'action_view'

class MyTest < Test::Unit::TestCase
  def setup
    @renderer = ActionController::Base.new
    @renderer.append_view_path File.expand_path(File.join(File.dirname(__FILE__), '..', 'views'))
  end

  def test_renders_link
    result = @renderer.render(:partial => '/something')
    assert ...
  end
end

But that :render call always blows up.  I've tried using an ActionView::Base instead of an ActionController::Base, but that gets even less far.

Has anyone had any success?

Answer:
checkout ActionView::TestCase -
http://api.rubyonrails.org/classes/ActionView/TestCase.html
You can also use these to test helpers, which I've found extremely helpful.
RSpec also has a way to test views:
http://rspec.info/documentation/rails/writing/views.html
Hope that helps!


Question: I am about 2 minor revisions behind.

Answer:
I'm one of those guys who always upgrade stuff. But have a look at the official
changelog
and see if the many bugfixes and new features are interesting enough to you.
I noticed 1.7.0 is out, and I'm definetly going to upgrade. But I need to test my applications after upgrading, since changes
could
break existing code.


Question:
How can I create an instance of the following annotation (with all fields set to their default value).

    @Retention( RetentionPolicy.RUNTIME )
    public @interface Settings {
            String a() default "AAA";
            String b() default "BBB";
            String c() default "CCC";
    }

I tried new Settings(), but that does not seem to work...

Answer:
If used with a method:
```
```
@Settings
public void myMethod() {
}
```
```
Now your annotation is initialized with default values.


Question:
I am trying to convert a date with individual parts such as 12, 1, 2007 into a datetime in SQL Server 2005. I have tried the following:

CAST(DATEPART(year, DATE)+'-'+ DATEPART(month, DATE) +'-'+ DATEPART(day, DATE) AS DATETIME)

but this results in the wrong date. What is the correct way to turn the three date values into a proper datetime format.

Answer:
Try CONVERT instead of CAST.
CONVERT allows a third parameter indicating the date format.
List of formats is here:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
Update after another answer has been selected as the "correct" answer:
I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.


Question:
We have a Windows Form application which hosts an IE browser control. Our users run the application and open links to documents stored in MOSS. We are trying to set the application up to pass in credentials of a service account so that we can avoid giving all users access to the MOSS site. We have used code found here which seems to work fine if the user is not currently signed on to our domain. However the application will not seem to pass in the service account authentication for any user which is already authenticated to the domain. In this case it just seems to use the authenticated users credentials.

How can we make this work?

Answer:
Would impersonation not help here? You can run that bit of code (the form) under the guise of the service account user you're talking about and the browser control should then run within the same context.
the following links might help;
http://msdn.microsoft.com/en-us/library/b80a7e92.aspx
http://www.buro9.com/blog/2006/10/06/impersonating-a-user-in-c/


Question: I'm trying to save the output of an vector image drawin in Java2D to an SWF file. There are great libraries for saving java2D output as things like SVG (BATIK) and PDF(itext) but I can't find one for SWF.  Any ideas?

Answer:
Flash generally uses SVG as its native format.  You could export to SVG and then write a trivial Flash program to embed and display the image.  But why use Flash at all?  Most browsers are capable of displaying SVG nowadays.
Edit
: I don't know why I was downvoted for a clearly correct answer.  I can understand not being upvoted for not having the best answer (I fully acknowledge that this soltuion isn't ideal), but I really don't think it deserves a downvote.  You can consult the section in the middle of
this page
about embedding SVG in Flex programs.  For those of you who aren't familiar, Flex is an adobe toolkit/library that generates SWF programs that run in the normal Flash player.  Many (all?) of the normal Flash libraries are available to it.  It uses ActionScript.  For you doubters, here's a snippet showing exactly how you do it, copied from a Flex program I wrote.  It should go inside an MXML file.
```
```
<mx:Script><![CDATA[

[Embed(source="../images/down.svg")]
[Bindable]
protected var drillDownImage:Class;

]]></mx:Script>

<mx:HBox width="50%" horizontalAlign="right">
    <mx:Image id="drillDownButton" source="{drillDownImage}" height="20" width="20" click="drillDown();" />
</mx:HBox>
```
```
Now all you need to do is wrap that in an appropriate MXML file, maybe import some controls packages for the HBox and Image tags, and you're good to go.  The example in the link I provided should be sufficient for you to figure it out.


Question:
I'm trying to understand what this method means as I'm reading this and have wondered what uses this may have. I don't quite understand the example given.

Can anyone give another explanation of it. Examples would help.

Thanks

Answer:
The simplest example is a LinkButton. Drop one in a page and look at the HTML it generates. You'll see something like.
```
```
href="javascript:__doPostBack('ctl00$LinkButton1','')"
```
```
GetPostBackEventReference allows you to get that piece of JavaScript, so that you can trigger that postback from elsewhere. However you run that bit of JavaScript, a postback will happen and the OnClick event will fire on the server just as if you'd clicked the LinkButton. The example on MSDN wires up a similar bit of JavaScript to the links to trigger server-side events on the GridView.
The more practical uses are when you want to handle postbacks in a custom control. Your control implements
IPostBackEventHandler
to handle the postbacks on the server, and you use GetPostBackEventReference to get the JavaScript that will trigger those postbacks.


Question: I need to read an Excel 2007 XLSX file in a Java application. Does anyone know of a good API to accomplish this task?

Answer:
I had to do this in .NET and I couldn't find any API's out there.   My solution was to unzip the .xlsx, and dive right into manipulating the XML.   It's not so bad once you create your helper classes and such.
There are some "gotchas" like the nodes all have to be sorted according to the way excel expects them, that I didn't find in the official docs.  Excel has its own date timestamping, so you'll need to make a conversion formula.


Question: Could someone please tell me which objects types can be tested using Regular Expressions in C#?

Answer:
If I understand you correctly and you are asking which object types can be tested against regular expressions then the answer is: strings and only strings.
Thus your test would be:
```
```
if(obj is string){...}
```
```


Question:
I always try to avoid to return string literals, because I fear they aren't defined outside of the function. But I'm not sure if this is the case. Let's take, for example, this function:

const char *
return_a_string(void)
{
    return "blah";
}

Is this correct code? It does work for me, but maybe it only works for my compiler (gcc). So the question is, do (string) literals have a scope or are they present/defined all the time.

Answer:
This code is fine across all platforms.  The string gets compiled into the binary as a static string literal.  If you are on windows for example you can even open your .exe with notepad and search for the string itself.
Since it is a static string literal scope does not matter.
String pooling:
One thing to look out for is that in some cases, identical string literals can be "pooled" to save space in the executable file.  In this case each string literal that was the same could have the same memory address.  You should never assume that it will or will not be the case though.
In most compilers you can set whether or not to use static string pooling for stirng literals.
Maximum size of string literals:
Several compilers have a maximum size for the string literal.  For example with VC++ this is approximately 2,048 bytes.
Modifying a string literal gives undefined behavior:
Modifying a string literal should never be done.  It has an undefined behavior.
```
```
char * sz = "this is a test";
sz[0] = 'T'; //<--- undefined results
```
```
Wide string literals:
All of the above applies equally to wide string literals.
Example: L"this is a wide string literal";
The C++ standard states:
(section lex.string)
1 A  string  literal  is  a  sequence
  of  characters  (as  defined   in
lex.ccon
) surrounded by double quotes, optionally beginning with the
  letter L, as in "..." or L"...".  A string literal that does not begin
  with  L  is  an  ordinary string literal, also referred to as a narrow
  string literal.  An ordinary string literal has type "array of n
  const
  char"  and  static storage duration (
basic.stc
), where n is the
  size
  of the string as defined below, and  is  initialized  with  the  given
  characters.   A string literal that begins with L, such as L"asdf",
  is
  a wide string literal.  A wide string literal has  type  "array  of
  n
  const wchar_t" and has static storage duration, where n is the size
  of
  the string as defined below, and is initialized with the given charac-
  ters.
2 Whether  all  string  literals  are  distinct  (that is, are stored in
    nonoverlapping objects)  is  implementation-defined.   The  effect
  of
   attempting to modify a string literal is undefined.


Question:
I have a site where I use CustomErrors in the web.config to specify a custom error page, and that's working just fine.  The custom 404 page is also specified in the IIS configuration (because if it's not, I don't get my custom 404 page).

But I have some logic that kicks in if a user gets a 404 that looks at their requested URL and make a navigation suggestion, if appropriate.  This logic relies on the aspxerrorpath value.  On my development PC, the aspxerrorpath is correctly appended to the URL, like so:
http://localhost:3092/FileNotFound.aspx?aspxerrorpath=/badpage.aspx, but on my test site, there's no aspxerrorpath appended to the URL, so all of my custom logic is bypassed and my suggestions don't work.  I'm not sure if this is an IIS config issue or something else.  The web server is Windows Server 2008 with IIS 7.

Any thoughts?

Many Thanks.

Answer:
The aspxerrorpath parameter is passed if the error was caught by .NET (and the error page specified in web.config is used). This happens if you're using the development web server, or if IIS is configured not to check that the file exists.
If IIS checks that the file exists, then the custom error configured in IIS is used, and the requested URL is included in the querystring as something like
```
http://example.com/FileNotFound.aspx?404;http://example.com/badpage.aspx
```


Question:
I recently added JQuery's date-picker control to a project. In Internet Exploder, I get the following error message:

Internet Explorer cannot open the
  Internet site

http://localhost/

Operation aborted

What is causing this problem?

Answer:
Found this possibly related blog post:
http://blogs.msdn.com/ie/archive/2008/04/23/what-happened-to-operation-aborted.aspx
Or this:
http://weblogs.asp.net/infinitiesloop/archive/2006/11/02/Dealing-with-IE-_2600_quot_3B00_Operation-Aborted_2600_quot_3B002E00_-Or_2C00_-how-to-Crash-IE.aspx
Seems to be pretty common


Question: In C++ when can a virtual function use static binding? If it is being accessed through a pointer, accessed directly, or never?

Answer: Static binding can only be done when the object's type is totally unambiguous at compile time. I can only think of four places where an abstract object's type is unambiguous: in the constructor, in the destructor, when declared locally and within the same scope as a dynamic allocation. I don't know the standard that well so I couldn't say what it says about those four possibilities (I'd say the first two are statically bound, the third possible statically bound and the last not; although it probably says it's undefined or implementation dependent). Other than those points, the object being accessed through a base class pointer could be pointing to a derived class and the current translation unit has no way of knowing, so static binding is not possible. The function could be called with a pointer to the base class in one instance and a pointer to a derived class in another!


Question:
Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function.  I figured I would just access the control in Javascript using:

var theControl = document.getElementById("txtEditBox");

Then just set the control's Visible property to true/false.  It doesn't seem to be working, I can't seem to figure out how to set "Visible" to true/false.  How can I do that?  Also, is that the best way to hide/show a ASP.NET control from a Javascript function?

Thanks,
Jeff

Answer:
The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.
So, you cannot, technically, set that property of the control.
That said, if the control
is
rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:
```
```
var theControl = document.getElementById("txtEditBox");
theControl.style.display = "none";

// to show it again:
theControl.style.display = "";
```
```
That assumes that the control's
```
id
```
attribute really is "txtEditBox" on the client and that it is already visible.
Also, is that the best way to hide/show a ASP.NET control from a Javascript function?
There is not necessarily a "best" way, although one better approach is to use CSS class definitions:
```
```
.invisible { display: none; }
```
```
When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose
```
display
```
value starts off as
```
block
```
.


Question:
I have a computer at home which I can't access from work.  I'd like to be able to view results from work that my home computer produces.  The best idea I've come up with is an automated script running on my home computer that emails myself the results (from a text file or stderr/out) when complete.

I'm decent with bash (I have a linux machine) and java, so an answer using either or both of those would be ideal, but if there's something easier that's fine too.

I typically use gmail, but also have yahoo mail.

My question is this: what would be the basic steps in solving this problem?  I can do the nitty gritty stuff, but can't really get the big picture of how something like this would work.

Please help.

jbu

Answer:
Traditionaly, with unix systems like Linux, you'd have an MTA, a mail transfer agent, on the computer that deals with sending e-mail.
This could be a full blown e-mail server like exim, or something simple like ssmtp that just sends messages on to a relaying SMTP server such as would be provided by your ISP.
This isn't neccessarily the case anymore, since mail clients like Thunderbird include their own MTA, much like mail clients on Windows do.
However, it is likely that your distro will install some MTA or other by default, if for no other reason than the fact that other things on your system, like cron, want to be able to send e-mail. Generally there will be a command line tool called sendmail (sendmail being the original MTA [citation needed], other MTAs maintain compatability with its interface and it has sort of become the standard) that can be used from a shell script to send an e-mail.


Question:
We need to handle this event in the base form, regardless of which controls currently have focus. We have a couple of global key commands that need to work regardless of control focus.

This works by handling the PreviewKeyDown event in the form normally.  When we add a user control to the form, the event no longer fires.

Am I missing something trivial here?  Or do we need to handle the event in the user control first?

Thanks for your help!

Thanks Factor.  When I get more time :) I'll get it working 'properley'!

Answer:
This is probably not the best way of doing it, but the first way that comes to mind.
In your forms constructor, after you call InitializeComponent(); do something like this:
```
```
foreach (Control control in this.Controls)
            {
                control.PreviewKeyDown += new PreviewKeyDownEventHandler(HandlePreviewKeyDown);
            }
```
```
I THINK that should do the trick. In your HandlePreviewKeyDown method you can then do your work and it should trigger regardless of which control has focus.


Question:
I want to display the current host and database names in a view.

Where can I get these names?

Are there some predefined environment or global variables?

Answer:
You can create a rails configuration object and obtain the necessary information from it:
```
```
config   = Rails::Configuration.new
host     = config.database_configuration[RAILS_ENV]["host"]
database = config.database_configuration[RAILS_ENV]["database"]
```
```
See the
documentation
for Rails::Configuration for details.


Question:
I would like to write an application that will copy MP3 files to a SanDisk Sansa M240.  The SanDisk doesn't have a drive letter and uses MTP for file transfer.
I stumbled through the sample of connecting to the device at : http://blogs.msdn.com/dimeby8/archive/2006/09/27/774259.aspx

but once connected, I can't figure out how to actually copy files / create folders on the device.

I am very surprised that there aren't any .Net wrappers for this COM library.

Answer:
It looks like dimeby8 posted some code that handles data transfers.  Check other posts in his blog, especially:
Sending MTP commands through WPD part 1
Sending MTP commands through WPD part 2
Sending MTP commands through WPD part 3


Question:
It seems if I do something like

$file = fopen($filepath, "w");
$CR = curl_init();
curl_setopt($CR, CURLOPT_URL, $source_path);
curl_setopt($CR, CURLOPT_POST, 1);
curl_setopt($CR, CURLOPT_FAILONERROR, true);
curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($CR, CURLOPT_FILE, $file);
$result = curl_exec( $CR );
$error = curl_error( $CR );
print filesize($filepath);

I get a different result than if I just run

print filesize($filepath);

a second time.  My guess is that curl is still downloading when do a filesize().

Answer:
Note that functions like filesize() cache their result, try adding a call to clearstatcache() above 'print filesize(...);'. Here is an example:
```
```
$file = '/tmp/test12345';
file_put_contents($file, 'hello');
echo filesize($file), "\n";
file_put_contents($file, 'hello world, this is a test');
echo filesize($file), "\n";
clearstatcache();
echo filesize($file), "\n";
```
```
See www.php.net/clearstatcache


Question:
I have some code that looks like:

template<unsigned int A, unsigned int B>
int foo() {
  int v = 1;
  const int x = A - B;
  if (x > 0) {
    v = v << x;
  }
  bar(v);
}

gcc will complain about x being negative for certain instantiations of A, B; however,  I do perform a check to make sure it is non-negative.  What's the best way around this?  I know I can cast x to be unsigned int but that will cause warnings about x being larger than the width of v (since it is casting a negative number to be positive).  I know there is a work-around that involves creating a new templatized shift function, but I'd like to avoid that if possible.

Answer:
Would this work?
```
```
const short unsigned int x = A - B;
```
```
It's cutting off a lot more bits than need to be cut off, but if your values of A - B are small enough...


Question:
I am using getch() and my app crashes instantly. Including when doing:

int main()
{
    getch();
}

I can't find the link but supposedly the problem is that it needs to turn off buffering or something strange along those lines, and I still want cout to work along with cross platform code.

I was told to use std::cin.get(), but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.

Is there any function for this? The code must work under Mac (my os) and Windows.

Linking/compiling is not an issue; I include <curses.h> and link with -lcurses in XCode, while Windows uses <conio.h>.

Answer:
You have not exhibited a
```
```
#include <stdio.h>
```
```
or
```
```
#include <curses.h>
```
```
or similar line. Are you sure that you are linking against a library that
includes
```
getch()
```
?


Question:
After considering the answers to my previous question (One SVN Repository or many?), I've decided to take the 4 or so repositories I have and consolidate them into one. This of course leads to the question, what's the best way to do this?

Is there a way to combine two or more repositories maintaining the version history for both?

Edit: I should also point out that I'm using Assembla.com, which does not provide access to the svnadmin command, AFAIK

Another edit: Does this even matter? If svnadmin works on URLs, then it's no problem then.

Answer:
Yes, using
svnadmin dump
and
svnadmin load
.
Let's assume that you have to repositories, one with HEAD revision 100 and the other with HEAD revision 150.
You dump the first repository and load it in the new one: you end up with the full story of the first repository, from revision 0 to revision 150.
Then you dump the second repository and load it in the new one: it gets loaded with its full history, the only things that change are the actual revision numbers. The history of the second repository will be represented in the new repository from revision 151 to revision 250.
The full history of both repositories is preserver, only the revision numbers change for the repository that is imported for second.
The same of course applies for more than two repositories.
EDIT: I posted while you were editing, so I didn't see your note...


Question:
The Dragon Book includes an exercise on converting integers to roman numerals using a syntax-directed translation scheme.

How can this be completed?

Answer:
I would consider parsing from right-to-left.
First, I would map the units column:
```
```
0 -> ''
1 -> 'I'
2 -> 'II'
3 -> 'III'
4 -> 'IV'
...
9 -> 'IX'
```
```
Then, if there was a second column (e.g. second from the right = tens column), I would use that to map to
```
```
0 -> ''
1 -> 'X'
2 -> 'XX'
...
9 -> 'XC'
```
```
That would need to be prepended to the initial output.
Repeat for next columns (hundreds, thousands) until you run out of letters.
Double-check the number isn't '0' or negative.


Question:
I have a Grid in WPF. The Grid has a transparent background (necessary) and each of the cells potentially has a different colored solid background, or maybe no background. When I put arbitrary content in these cells, when two adjacent cells both have colored backgrounds (same or different color, it doesn't matter) there is often (and unpredictably) a thin transparent line separating them, allowing you to see through the grid at that line.

Does anyone know how this could possibly be fixed?

Edit: Meant to mention it in my question, but I've tried enabling SnapsToDevicePixels anywhere and everywhere I can, to no avail.

Answer:
My answer: Do a simple comparsion of the time taken to perform a simple Get/Edit/Update sequence.  I think you will find that LINQ to SQL is twice as quick.  I did a quick comparsion project when i was investigating the differences.
The results where:
Entity Framework 8,700 milliseconds
LINQ to SQL 3,100 milliseconds
Data-sets 2,000 milliseconds
So for me it was a simple question.  Use DataSets or use Linq-Sql - Entity Framework didn't even factor into it!
link text


Question:
When beginning a new web project, i'm always a bit worried about removing pieces of the web.config.  It seems there are more entries than ever with Net 3.5 SP1.

Which bits of the .config do you delete for the following scenarios:

WCF Web Service, no Javascript support

Simple MVC Website

EDIT
Can someone document a basic list of things left in and taken out of the web.config for a simple website?

Answer:
I usually just delete items from the web.config until things break -- a process of trial and error.
It's astonishing how much of web.config you can remove without affecting anything. It's gotten quite crufty in .NET 3.5.


Question: What is the best option for a windows application that uses SQL server authentication? Should I create a single SQL account and manage the users inside the application (using a users table). Or should I create a SQL server account for each user. What is your experience? Thank you!

Answer:
What about having SQL accounts based on the level of permissions needed for the task. For example you could have a read only account just used for reporting if your system has a lot of reporting. You would also need an account what has write access for people to change their passwords and other user admin tasks.
If you have situations where certain users are only going to have access to certain data I would have separate accounts for that data. The problem with using 1 account is you are saying that there is no SQL injection anywhere in your application. That is something everyone would strive for but sometimes perfect security is not possible, hence the multi-pronged approach.


Question:
For example, if I have a unicode string, I can encode it as an ASCII string like so:

>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'

However, I have e.g. this ASCII string:

'\u003foo\u003e'

... that I want to turn into the same ASCII string as in my first example above:

'<foo/>'

Answer:
It's a little dangerous depending on where the string is coming from, but how about:
```
```
>>> s = '\u003cfoo\u003e'
>>> eval('u"'+s.replace('"', r'\"')+'"').encode('ascii')
'<foo>'
```
```


Question:
I would like to read/write encrypted XML files using LINQ to XML. Does anyone know how to use encryption algorithms built into the .NET Framework to encrypt the Stream used by the XDocument object?

I did try it, but you can't set the CryptoStream to Read/Write access. It only support Read or Write, which causes LINQ to XML to throw an exception.

Update: It would be nice to read/write the document "on the fly", but I am only required to read the encrypted xml file, manipulate it, then write it back out encrypted again.

Answer:
The easiest approach is probably an XDocument.Load(), Linq around, then XDocument.Save(). From a quick test app (go easy on non-disposed resources):
```
```
XDocument writeContacts = new XDocument(
   new XElement("contacts",
      new XElement("contact",
         new XElement("name", "Patrick Hines"),
         new XElement("phone", "206-555-0144",
             new XAttribute("type", "home")),
         new XElement("phone", "425-555-0145",
             new XAttribute("type", "work")),
         new XElement("address",
            new XElement("street1", "123 Main St"),
            new XElement("city", "Mercer Island"),
            new XElement("state", "WA"),
            new XElement("postal", "68042")
         )
      )
   )
);

Rijndael RijndaelAlg = Rijndael.Create();

FileStream writeStream = File.Open("data.xml", FileMode.Create);
CryptoStream cStream = new CryptoStream(writeStream,
    RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV),
    CryptoStreamMode.Write);

StreamWriter writer = new StreamWriter(cStream);

writeContacts.Save(writer);

writer.Flush();
writer.Close();

FileStream readStream = File.OpenRead("data.xml");

cStream = new CryptoStream(readStream,
  RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV),
  CryptoStreamMode.Read);

XmlTextReader reader = new XmlTextReader(cStream);

XDocument readContacts = XDocument.Load(reader);

//manipulate with Linq and Save() when needed
```
```
Swap your favorite ICryptoTransform into the CryptoStream.


Question:
I'm looking for a wrapper that distills zlib to:

OpenZipFile()

GetItemInfo(n)

UnzipItem(n)  // Bonus points for unzipping recursively if item n is a directory.

I see a lot of wrappers around the zlib library on, say, codeproject.com but they are all platform-specific in order to provide the added platform-specific functionality of unzipping to file/memory buffer/pipe.

Answer:
In the zlib source archive, there is a contribution named "minizip".
"minizip" is a set of files you can use to play with .zip files. Basic services you need are already there :
unzOpen
unzLocateFile
unzOpenCurrentFile
unzGetCurrentFileInfo
unzCloseCurrentFile
unzClose
Of course, this is not object oriented (and I'm sure that was not the goal of the creator of minizip), but writing a simple object oriented wrapper should be easy.


Question:
On IBM DB2 v.9 windows, when someone connect to database by Server\Administrator user
DB2 database will automatically accept and grant all the permissions to this user?
But, in some case environment Administrator of server does not need to see every data in the database. So how to prevent Administrator use connect to database?

Answer:
By default, DB2 databases are created with
```
CONNECT
```
authority granted to public.  If you want to restrict some users from connecting, you need to do
```
```
GRANT CONNECT ON DATABASE TO <user1>, <user2>, ...
```
```
Then revoke the CONNECT authority from PUBLIC
```
```
REVOKE CONNECT ON DATABASE FROM PUBLIC
```
```


Question:
I'm having some trouble figuring out how to use more than one left outer join using LINQ to SQL.  I understand how to use one left outer join.  I'm using VB.NET.  Below is my SQL syntax.

T-SQL

SELECT
    o.OrderNumber,
    v.VendorName,
    s.StatusName
FROM
    Orders o
LEFT OUTER JOIN Vendors v ON
    v.Id = o.VendorId
LEFT OUTER JOIN Status s ON
    s.Id = o.StatusId
WHERE
    o.OrderNumber >= 100000 AND
    o.OrderNumber <= 200000

Answer:
I think you should be able to follow the method used in
this
post.  It looks really ugly, but I would think you could do it twice and get the result you want.
I wonder if this is actually a case where you'd be better off using
```
DataContext.ExecuteCommand(...)
```
instead of converting to linq.


Question:
I have two tables that I would like to join but I am getting an error from MySQL

Table: books
bookTagNum ShelfTagNum
book1      1
book2      2
book3      2

Table: shelf
shelfNum   shelfTagNum
1          shelf1
2          shelf2

I want my results to be:

bookTagNum ShelfTagNum shelfNum
book1      shelf1           1
book2      shelf2           2
book3      shelf2           2

but instead I am also getting an extra result:

book1      shelf2           2

I think my query is doing a cross product instead of a join:

SELECT `books`.`bookTagNum` , `books`.`shelfNum` , `shelf`.`shelfTagNum` , `books`.`title`
FROM books, shelf
where `books`.`shelfNum`=`books`.`shelfNum`
ORDER BY `shelf`.`shelfTagNum` ASC
LIMIT 0 , 30

What am I doing wrong?

Answer:
I think you want
```
```
where `books`.`shelfTagNum`=`shelf`.`shelfNum`
```
```
In order to match rows from the
```
books
```
and
```
shelf
```
tables, you need to have terms from each in your
```
where
```
clause - otherwise, you're just performing a no-operation check on the rows of
```
books
```
, since every row's
```
shelfNum
```
will be equal to its
```
shelfNum
```
.
As @fixme.myopenid.com suggests, you could also go the explicit
```
JOIN
```
route, but it's not necessary.


Question: I would like to implement a telnet server in C. How would I proceed with this? Which RFCs should I look at? This is important to me, and I would appreciate any help.

Answer:
For very basic telnet (just telnet to a port and echo bytes), there's not much to do.  Read from a socket, process it (in an echo server, do nothing), spit back a result.  You could implement a simple MUD-style server without knowing anything in any RFCs.
But if you're really concerned about RFCs, RFC 854 might be a starting point.
http://www.faqs.org/rfcs/rfc854.html


Question:
I'd like to know what are the most useful JQuery plugins. I'm particularly interested in  those which are likely to be useful in general UI development, such as Tablesorter, rather than those which serve uncommon needs.

If you could provide a very brief description of the plugin's purpose, that would be really helpful.

Thanks,
Don

Answer:
I'll list one I'm working on...
My jLINQ plugin
is a jQuery version of .NET LINQ. It's made for working with in-memory collections (not talking directly to the server) and let's you use syntax similar to the following.
```
```
var results = $.from(data)
    .ignoreCase()
    .startsWith("firstName","m")
    .or("n")
    .isNot("administrator")
    .orderBy("lastName")
    .select();
```
```
It supports a bunch of other commands that you find in LINQ for ordering and grouping along with most of the selection commands like contains, between, greaterThan, etc...
Here is a demo
-
It's stable, but still in progress
Maybe not must have, but might be useful as it progresses...


Question:
Using jquery how do I focus the first element (edit field, text area, dropdown field, etc)
in the form when the page load?

Something like:

document.forms[0].elements[0].focus();

but using jquery.

Another requirement, don't focus the first element when the form has class="filter".

Answer:
```
```
$('form:not(.filter) :input:visible:enabled:first').focus()
```
```
This will select the first visible input element (
```
<input />
```
,
```
<select>
```
,
```
<textarea>
```
) that doesn't have the class
```
filter
```
in it.


Question:
I have both Fruityloops and Propellerheads Reason software synths on my Windows PC.

Any way I can get at and script these from either Visual Basic or Python? Or at least send Midi messages to the synths from code?

Update : attempts to use something like a "midi-mapper" (thanks for link MusiGenesis) don't seem to work. I don't think Reason or FL Studio act like standard GM Midi synths.

Update 2 : If you're interested in this question, check out this too.

Answer:
I think both FL Studio and Reason can be configured as the default MIDI playback device.  To send MIDI messages to either from VB.NET, you'll need to PInvoke the midiOutOpen, midiOutShortMsg and midiOutClose API calls.  Here's a link to code samples:
http://www.answers.com/topic/midioutopen
They're for VB6, but they should be easy to translate to VB.NET.
I know FL Studio can be "driven" from a plugin authored for FL (or a VSTx plugin), but I think these are always written in C or C++.
Edit:  I just learned that Windows Vista dropped the MIDI Mapper (which would have made setting up FL or Reason as the default MIDI device simple).  Amazing.  Here is a link I found with an alternative solution:
http://akkordwechsel.de/15-windows-vista-und-der-midi-mapper/
I just tried it out (it's just a *.CPL file that you double-click to run) and it appears to work (although the GM Synth is the only option available on my laptop, so I'm not sure if it will pick up FL or Reason as choices).


Question:
Does anyone know how to generate SQL scripts from a query?

For example,

Script some tables.

Do custom action 1.

Script the views.

Do custom action 2.

Etc.

Answer:
It sounds like you want to write a cursor to execute custom SQL.  This is common and easy to do.  What you need to do is specify a few things to help us more completely answer your question:
What type of SQL server are you using? (MSSQL, Oracle, MySQL)
What language are you writing in? (Java, C++, PL/SQL, TSQL)
You can either write code (Java / C++) to generate SQL from a query, or possibly use a cursor to iterate over recordsets (PL/SQL / TSQL).  You can use the results to give you information that can then be executed as SQL via an exec (of some kind depending on the language).


Question:
I am trying to use native windows API with Qt using mingw toolset. There are link problems with some functions. What happens? Is this a bug with mingw name mangling?

#ifdef Q_WS_WIN
    HWND hwnd = QWidget::winId();
    HDC hdcEMF  = CreateEnhMetaFile(NULL, NULL, NULL, NULL ) ;
    Rectangle(hdcEMF,100,100,200,200);
    HENHMETAFILE hemf = CloseEnhMetaFile(hdcEMF);
    OpenClipboard(hwnd);
    EmptyClipboard();
    SetClipboardData(CF_ENHMETAFILE,hemf);
    CloseClipboard();
#else

The errors:

undefined reference to `CreateEnhMetaFileW@16'

undefined reference to `Rectangle@20'

undefined reference to `CloseEnhMetaFile@4'

Answer:
The functions
```
CreateEnhMetaFileW()
```
and
```
CloseEnhMetaFile()
```
are defined in the static library Gdi32.lib, so you have to make sure to link against that.  Try adding
```
-lgdi32
```
to the end of your command line you're using to compile.  If that doesn't work, you might have to specify the full path to Gdi32.lib by adding
```
-L/path/to/folder/containing/the/library -lgdi32
```
instead.


Question: Is it possible to inspect the return value of a function in gdb assuming the return value is not assigned to a variable?

Answer:
Yes, just examine the
```
EAX
```
register by typing
```
print $eax
```
.  For most functions, the return value is stored in that register, even if it's not used.
The exceptions to this are functions returning types larger than 32 bits, specifically 64-bit integers (
```
long long
```
),
```
double
```
s, and
```
structs
```
or
```
classes
```
.
The other exception is if you're not running on an Intel architecture. In that case, you'll have to figure out which register is used, if any.


Question:
This question is regarding the performance issue in Mac OS X

Canvas3D object is embedded in a JPanel; then the panel is integrated with the rest of the Swing-built application. Within that Canvas I am rendering a simple cube by applying
certain transformations. At the initial launch It works fine. But when i try to resize the window or perform some operations on vertical or horizontal split bar buttons.Swing components take certain time to appear on the screen. A flashy white coloured thing appears first then swing components will appear? ( Totally saying flickering kind of stuff will happen). Is there any to solve this issue?

Kindly help me in this regard.

J3DSwinger

Answer:
Yes, just examine the
```
EAX
```
register by typing
```
print $eax
```
.  For most functions, the return value is stored in that register, even if it's not used.
The exceptions to this are functions returning types larger than 32 bits, specifically 64-bit integers (
```
long long
```
),
```
double
```
s, and
```
structs
```
or
```
classes
```
.
The other exception is if you're not running on an Intel architecture. In that case, you'll have to figure out which register is used, if any.


Question:
We're building an C# .NET app which will be running on computers sitting inside trucks.  We need to talk to Digital IO ports on the truck computers which do not exist on our developer machines, so I need to write a dummy library which will be included in our dev builds, but will be replaced with our actual Digital IO library when we do releases.  And I want this library substitution to be automated by the build process.

Coming from a Java background, I can do this easily in maven using build profiles.  Is there a similar way I can do it using MSbuild??  If not, whats the best way to handle this in C# microsoft land.

Answer:
I recently developed something similar where I assumed an interface for communicating with some embedded computers that operated servos.  To write the software that controlled these computers I
used Moq to mock
the interfaces I wrote, and then later
plugged in real classes via StructureMap
that implemented those interfaces.
I also used Moq to write the unit tests for the software controlling the machine using the same interfaces.


Question:
I just recently installed the MVC beta.
However, I assumed because the versioning numbers have changed and because it now uses the GAC instead of the bin folder that it wouldn't break existing applications.

However, it has.

What steps do I need to follow to ensure my existing preview 3 applications use a bin copy of the .dlls and are not broken by the installation of the beta?

Answer:
ASP.NET MVC beta is also bin-deployable, Move the following DLL's from GAC to the bin folder of your app
```
```
* System.Web.Mvc
* System.Web.Routing
* System.Web.Abstractions
```
```
Check this article for more information


Question:
I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'

Currently i am doing this:

SELECT from_days(to_days(my_date))

Is there a proper way of doing this?

Answer:
Yes, use the
date
function:
```
```
SELECT date(my_date)
```
```


Question:
I have a swing application deployed in HTTP Server. Users use the browser to point an URL and install the client using java webstart. Now I need to enable https access to my application deployed on HTTP server. I am using JDK 1.5 as default jdk supported in the jnlp file. For time being I use a self signed certificate to the sign the jars (by default created using Sun's jarsigner, keytool, etc, utils).

Solution/steps would be much appreciated.

Thanks in advance

Ramesh

Answer:
What is the feature of https that you are hoping to leverage?
The signing/server authentication is done by code signing, though you are undermining this using a self-signed certificate.
Does your application code contain secrets that must be hidden from eavesdroppers?
As you say you "need to enable" there must be an underlying reason.
I believe that before you "need https" you need a proper code signing certificate. You might want to rephrase your question so that your underlying problem can be solved instead of the very specific question.


Question:
What is the difference in the accessibility of the following variables in Java?

public class Joe {
    public int a;
    protected int b;
    private int b;
    int c;
}

I'm most interested in what the last one is doing.

Answer:
```
public
```
: read/writable for anyone
```
protected
```
: read/writable for
instances of subclasses
and from within the enclosing package
```
private
```
: read/writable for
any
instance of the class
and inner or outer (enclosing) instance
```
int c
```
:
package-private, read/writable for
all classes inside same package
See the
JLS
for more details
EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for
```
private
```
. I remember now... ;-)


Question:
So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232.  The documementation is sparse and the examples are non-existent.  Can't figure out exactly how to communicate with the device.  The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated.  What code I have so far follows.

#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;

int main()
{
    io_service io;
    serial_port port( io, "COM3" );
    port.set_option( serial_port_base::baud_rate( 19200 ) );

    unsigned char commands[4] = { 1, 128, 240, 0 };

    // write the commands to the device

    return 0;
}

In short: need help with the io part of the serial_port.

Answer:
In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:
```
```
boost::asio::write(port, boost::asio::buffer(commands, 4));
```
```
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here:
Buffers
.


Question:
I'm impressed with the simplicity of Microsoft's Virtual Earth Street Address search service.

My requirement is to type rough address info with no comma separators into a simple text box, press a find button, wait a few seconds and then observe a result picklist.

I mocked up something here using the virtual earth SDK.

Does Google Maps have a similar API?

Which street address search service is better?

Answer:
In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:
```
```
boost::asio::write(port, boost::asio::buffer(commands, 4));
```
```
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here:
Buffers
.


Question:
I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button.

Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?

Answer:
If 'Copystart' is your original rows, and 'Copyend' is where you want to paste them, then using named ranges:
```
```
Sub Copybutton_Click()

Range("Copyend").value = Range("Copystart").value
Range("Copyend").visible = True

End Sub
```
```
If you have multiple named ranges with the same name, then add [Sheetname]. in front of the range, where Sheetname is the name of the sheet that the named range is in that you want to reference.


Question:
Slightly related to my other question: What is the difference between the following:

private class Joe
protected class Joe
public class Joe
class Joe

Once again, the difference between the last 2 is what I'm most interested in.

Answer:
A public class is accessible to a class in any package.
A class with default access (
```
class Joe
```
) is only visible to other classes in the same package.
The private and protected modifiers can only be applied to inner classes.
A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.
A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.


Question:
(Note: This is for MySQL's SQL, not SQL Server.)

I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.

Answer:
Check the
Pattern Matching
and
Regular Expressions
sections of the MySQL Reference Manual.


Question:
Hey, in the Programming Pearls book, there is a source code for setting, clearing and testing a bit of the given index in an array of ints that is actually a set representation.

The code is the following:

#include<stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000

int a[1+ N/BITSPERWORD];

void set(int i)
{
    a[i>>SHIFT] |= (1<<(i & MASK));
}

void clr(int i)
{
    a[i>>SHIFT] &= ~(1<<(i & MASK));
}

int test(int i)
{
    a[i>>SHIFT] & (1<<(i & MASK));
}

Could somebody explain me the reason of the SHIFT and the MASK defines? And what are their purposes in the code?

I've already read the previous related question.

Answer:
From
Here
(General answer to get this thread started)
A bit mask is a value (which may be stored in a variable) that enables you to isolate a specific set of bits within an integer type.
Normally the masked will have the bits you are interested in set to 1 and all the other bits set to 0. The mask then allows you to isolate the value of the bits, clear all the bits or set all the bits or set a new value to the bits.
Masks (particularly multi-bit ones) often have an associated shift value which is the amount the bits need shifting left so that the least significant masked bit is shifted to the least significant bit in the type.
For example using a 16 bit short data type suppose you wanted to be able to mask bits 3, 4 and 5 (LSB is number 0). You mask and shift would look something like
```
```
#define MASK 0x0038
#define SHIFT 3
```
```
Masks are often assigned in hexadecimal because it is easier to work with bits in the data type in that base as opposed to decimal. Historically octal has also been used for bit masks.
If I have a variable, var, that contains data that the mask is relevant to then I can isolate the bits like this
```
```
var & MASK
```
```
I can isolate all the other bits like this
```
```
var & ~MASK
```
```
I can clear the bits like this
```
```
var &= ~MASK;
```
```
I can clear all the other bits like this
```
```
var &= MASK;
```
```
I can set all the bits like this
```
```
var |= MASK;
```
```
I can set all the other bits like this
```
```
var |= ~MASK;
```
```
I can extract the decimal value of the bits like this
```
```
(var & MASK) >> SHIFT
```
```
I can assign a new value to the bits like this
```
```
var &= ~MASK;
var |= (newValue << SHIFT) & MASK;
```
```


Question: I am writing a Rails app that processes data into a graph (using Scruffy).  I am wondering how can I render the graph to a blog/string and then send the blog/string directly to the  the browser to be displayed (without saving it to a file)? Or do I need to render it, save it to a file, then display the saved image file in the browser?

Answer:
I think you will be able to use
send_data
for this purpose:
```
```
send_data data_string, :filename => 'icon.jpg', :type => 'image/jpeg', :disposition => 'inline'
```
```
If you put this in a controller action - say show on a picture controller, then all you need do is include the following in your view (assuming RESTful routes):
```
```
<%= image_tag picture_path(@picture) %>
```
```


Question:
Can anyone please tell me if Certifying Authorities (CAs) are allowed to make modifications to the Certificate Signing Request (CSR) before actually signing the certificate with their own private key?

Specifically, I'd like to know if it's valid for the CA to insert additional fields (such as EKUs) into the cert before adding their signature.

Answer:
I can't speak about CAs in general, but I once ran a Windows Server 2003 network with its own CA, and it's definitely possible to make
```
certreq
```
(through the
```
-attrib
```
option) add additional fields to the CSR before it gets to the CA. Thus, it looks to me like it's possible for the CA itself to do much the same thing.
Your mileage may vary.


Question:
I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)

For example, if an object "parent" has a "children" relation that has
3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to
fetch the parent object with just two children..

How should I do it? By adding an "and" condition to the primaryjoin
parameter of the relation? (e.g. "Children.parent_id == Parent.id and Children.logically_deleted == False", but is it correct to write "and" in this way?)

Edit:

I managed to do it in this way

children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False))

but is there a way to use a string as primaryjoin instead?

Answer:
I'm only currently developing agains 0.4.something, but here's how I'd suggest it:
```
```
db.query(Object).filter(Object.first==value).filter(Object.second==False).all()
```
```
I think that's what you are trying to do, right?
(Note: written in a web browser, not real code!)


Question:
Reading Paul Graham's essays on programming languages one would think that Lisp macros are the only way to go. As a busy developer, working on other platforms, I have not had the privilege of using Lisp macros. As someone who wants to understand the buzz, please explain what makes this feature so powerful.

Please also relate this to something I would understand from the worlds of Python, Java, C# or C development.

Answer:
You will find a comprehensive debate around
lisp macro here
.
An interesting subset of that article:
In most programming languages, syntax is complex.  Macros have to take apart program syntax, analyze it, and reassemble it.  They do not have access to the program's parser, so they have to depend on heuristics and best-guesses.  Sometimes their cut-rate analysis is wrong, and then they break.
But Lisp is different.  Lisp macros
do
have access to the parser, and it is a really simple parser.
A Lisp macro is not handed a string, but a preparsed piece of source code in the form of a list, because the source of a Lisp program is not a string; it is a list.
And Lisp programs are really good at taking apart lists and putting them back together.  They do this reliably, every day.
Here is an extended example.  Lisp has a macro, called "setf", that performs assignment.  The simplest form of setf is
```
```
(setf x whatever)
```
```
which sets the value of the symbol "x" to the value of the expression "whatever".
Lisp also has lists; you can use the "car" and "cdr" functions to get the first element of a list or the rest of the list, respectively.
Now what if you want to replace the first element of a list with a new value?  There is a standard function for doing that, and incredibly, its name is even worse than "car".  It is "rplaca".  But you do not have to remember "rplaca", because you can write
```
```
(setf (car somelist) whatever)
```
```
to set the car of somelist.
What is really happening here is that "setf" is a macro.  At compile time, it examines its arguments, and it sees that the first one has the form (car SOMETHING).  It says to itself "Oh, the programmer is trying to set the car of somthing.  The function to use for that is 'rplaca'."  And it quietly rewrites the code in place to:
```
```
(rplaca somelist whatever)
```
```


Question: What is the best way to configure Tomcat 5.5 or later to authenticate users from Windows Active Directory?

Answer:
From
www.jspwiki.org
See :
ActiveDirectoryIntegration
Try this in the server.xml with your ldap-settings :
```
```
<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
    connectionURL="ldap://youradsserver:389"
    alternateURL="ldap://youradsserver:389"
    userRoleName="member"
    userBase="cn=Users,dc=yourdomain"
    userPattern="cn={0},cn=Users,dc=yourdomain"
    roleBase="cn=Users,dc=yourdomain"
    roleName="cn"
    roleSearch="(member={0})"
    roleSubtree="false"
    userSubtree="true"/>
```
```
And define the role in the tomcat-users.xml and the web.xml of your application
Edit
```
webapp_root/WEB_INF/Web.xml
```
file as follows:
```
```
<security-constraint>
   <display-name>your web app display name</display-name>
   <web-resource-collection>
     <web-resource-name>Protected Area</web-resource-name>
     <url-pattern>*.jsp</url-pattern>
     <url-pattern>*.html</url-pattern>
     <url-pattern>*.xml</url-pattern>
   </web-resource-collection>
   <auth-constraint>
     <role-name>yourrolname(ADS Group)</role-name>
   </auth-constraint>
 </security-constraint>
 <login-config>
   <auth-method>FORM</auth-method>
   <form-login-config>
     <form-login-page>/login.jsp</form-login-page>
     <form-error-page>/error.jsp</form-error-page>
   </form-login-config>
 </login-config>
 <security-role>
   <description>your role description</description>
   <role-name>yourrolename(i.e ADS group)</role-name>
 </security-role>
```
```


Question:
I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?

For example, I have a type that I need to use all over a particular application - should I define it thus:

mytypes.h

typedef int MY_TYPE;

foo.cpp

MY_TYPE myType;

Or use a namespace:

mytypes.h

namespace ns {
typedef int MY_TYPE;
}

foo.cpp

ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;

Which do you prefer?  Are there times when it is acceptable to use the first method?

Answer:
I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project.
The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application.
So, if your
```
MY_TYPE
```
is used throughout your application, put it in the global namespace, otherwise put it in a named namespace.


Question: I'm making my way through the early Data Access Tutorials on Microsoft's ASP.NET website and it occurred to me that this all seems awfully similar to what I have read about separating your logic and presentation code using the MVC pattern. As a newbie I have yet to implement the MVC pattern but I'm curious as to how these two design structures differ and if I should be focusing my attention on one or the other, particularly in the context of web design.

Answer:
The link you've posted for the Data Access Tutorial is implementation of MVC pattern. MVC pattern is a concept, implementation can differ; you have this in ASP.NET whereas in Java there's one framework called
Struts
, which is an implementation MVC.
DAL & BLL patterns differ from the MVC pattern in terms of concepts; but NOT this specific implementation. MVC is actually achieved through usage of DAL, BLL & View Patterns.


Question:
I have two applications under tomcat/webapps folder.

tomcat/webapps/App1
tomcat/webapps/App2

Both applications share the same libraries. Which are stored for example in tomcat/webapps/App1/WEB-INF/lib.

Are both libraries loaded twice in memory?

Should I put these shared libraries in tomcat/server/lib?

Answer:
As you can see
here
, Tomcat creates one class-loader per webapp on your server.
Thus, if you have webapp1 and webapp2 that share the same library, then this library will be indeed loaded twice.
You can eventually place this library in the common directory (tomcat-dir/common/lib) if it is shared by
all
webapps that run on your Tomcat server.


Question:
I have a QGraphicsScene that I want to copy and append to the start of a list.  What is the best method of doing this?

QGraphicsScene* m_scene = new QGraphicsScene();
QGraphicsScene* m_DuplicateScene;

QList<QGraphicsScene *>m_list;

Answer:
Doing this would be very complicated because you don't know anything about the children of
```
m_scene
```
.  Even if you
```
dynamic_cast
```
and create a
```
clone()
```
function for each type of
```
QGraphicsItem
```
, you still need to remember that other people can subclass
```
QGraphicsItem
```
and create their own type of graphics item, making them unclonable by you.
Basically, no, you can't duplicate a
```
QGraphicsScene
```
(cloning all items in the process).  You can't even make references to the children of the original scene's children because a
```
QGraphicsItem
```
can only have one scene.
Unless I'm missing a method call, of course.  Searches for "clone," "copy," and "duplicate" produced no results, though.
On your second question, use
```
QList<T *>::push_front
```
.  Thus,
```
m_list.push_front
```
(
```
m_DuplicateScene
```
);
(Side note: you prepend to the start of a list, and append to the end of a list.)


Question:
Does any one know of an API that would allow me to draw something like this. It would need some interactivity to it

zooming

change second dimension axis angle

I was looking at JFreeChart but I don't see any example of doing 2D overlap chart.

Thanks

Answer:
May be
Chart3D
might be what you are after (not free though)
A more simple and free solution might be a
SpiceChart 3D line
.


Question: Is there anyway to decompile java webstart application?

Answer: Start the application, then fetch the JAR(s) from the webstart cache. Proceed to decompile like with any other Java application.


Question:
Is there anything that has features of TFS(Like Source Control, Debug, Testing,...) that we can use in a workgroup with a small team(say 1-6 persons)?

BTW: we are using VS 2008 Team Suit

Answer:
Do you particularly need it all in one package? Various open source projects only do one thing, but integrate nicely with others. For instance:
Subversion
for source control
Trac
for bug tracking
Cruise Control .NET
for continuous builds
NAnt
for build management


Question:
The install instructions are:

$ python setup.py build
$ sudo python setup.py install # or su first

This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?

Thanks!

Answer:
From the
EasyInstall
doc, command line options:
--always-unzip, -Z
Don't install any packages as zip files, even if the packages are marked as safe for running as a zipfile.
Can you use
easyinstall
instead of calling setup.py ?
calling
```
easy_install -Z mysql_python
```
from the command prompt, finds the egg on the net and installs it.