q:
I have one applicationContext.xml file, and it has two org.springframework.orm.jpa.JpaTransactionManager (each with its own persistence unit, different databases) configured in a Spring middleware custom application.

I want to use annotation based transactions (@Transactional), to not mess around with TransactionStatus commit, save, and rollback.

A coworker mentioned that something gets confused doing this when there are multiple transaction managers, even though the context file is set configured correctly (the references go to the correct persistence unit.
Anyone ever see an issue?

In your config, would you have two transaction managers?
Would you have txManager1 and txManager2?

That's what I have with JPA, two different Spring beans that are transaction managers.

[A]
I guess you have 2 choices
If your use-cases never require updates to both databases within the same transaction, then you can use two JpaTransactionManagers, but I'm not sure you will be able to use the @Transactional approach? In this case, you would need to fallback on the older mechanism of using a simple
TransactionProxyFactoryBean
to define transaction boundaries, eg:
```
```
<bean id="firstRealService" class="com.acme.FirstServiceImpl"/>
<bean id="firstService"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager" ref="firstJpaTm"/>
    <property name="target" ref="firstRealService"/>
    <property name="transactionAttributes">
        <props>
           <prop key="insert*">PROPAGATION_REQUIRED</prop>
           <prop key="update*">PROPAGATION_REQUIRED</prop>
           <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
        </props>
    </property>
</bean>
<!-- similar for your second service -->
```
```
If you are require a transaction spanning both databases, then you will need to use a JTA transaction manager. The
API
states:
This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access. JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. Note that you need to configure your JPA provider accordingly in order to make it participate in JTA transactions.
What this means is that you will need to provide a JTA transaction manager. In our application, we use config similar to the following:
```
```
<tx:annotation-driven transaction-manager="txManager"/>

<bean id="txManager"
    class="org.springframework.transaction.jta.JtaTransactionManager">
    <property name="transactionManagerName" value="appserver/jndi/path" />
</bean>
```
```
If you are deploying within an appserver, then the spring JtaTransactionManager needs to do a lookup to the real XA-compliant JTA transaction manager provided by the appserver. However, you can also use a standalone JTA transaction manager (but I haven't tried this myself yet)
As for configuring the Jpa persistence provider, I'm not that familiar. What JPA persistence provider are you using?
The code above is based on our approach, where we were using native Hibernate as opposed to Hibernate's JPA implementation. In this case, we were able to get rid of the two HibernateTransactionManager beans, and simply ensure that both SessionFactories were injected with the same JTA TM, and then use the tx:annotation-driven element.
Hope this helps


q: Let's say I write a DLL in C++, and declare a global object of a class with a non-trivial destructor.  Will the destructor be called when the DLL is unloaded?

[A]
It should be called when either the application ends or the DLL is unloaded, whichever comes first.  Note that this is somewhat dependent on the actual runtime you're compiling against.
Also, beware non-trivial destructors as there are both timing and ordering issues. Your DLL may be unloaded
after
a DLL your destructor relies on, which would obviously cause issues.

s: huggingface

c: devops

d: intermediate


q:
I have searched for various techniques on how to read/write dBase III (dbf) files using OLEDB or ODBC with C#/.NET.  I have tried almost all of the tecniques posted, but without success.  Can someone point me in the right direction?

Thanks for your time.

[A]
FoxPro 2.0 files were exactly the same as dBase III files with an extra bit for any field that was of type "memo" (not sure the exact name, it's been a while). That means that if you just use a
FoxPro 2.x method
for accessing the files, it should work.


q:
In C#, if I want to deterministically clean up non-managed resources, I can use the "using" keyword.  But for multiple dependent objects, this ends up nesting further and further:

using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
{
    using (BufferedStream bs = new BufferedStream(fs))
    {
        using (StreamReader sr = new StreamReader(bs))
        {
            // use sr, and have everything cleaned up when done.
        }
    }
}

In C++, I'm used to being able to use destructors to do it like this:

{
    FileStream fs("c:\file.txt", FileMode.Open);
    BufferedStream bs(fs);
    StreamReader sr(bs);
    // use sr, and have everything cleaned up when done.
}

Is there a better way in C# to do this?  Or am I stuck with the multiple levels of nesting?

[A]
The using statement is syntactic sugar that converts to:
```
```
try
   {
      obj declaration
      ...
   }
   finally
   {
      obj.Dispose();
   }
```
```
You can explicitly call Dispose on your objects, but it won't be as safe, since if one of them throws an exception, the resources won't be freed properly.


q: I've seen numerous people mentions that you shouldn't use widths and padding or margins on the same element with CSS. Why is that?

[A]
Because some browsers treat the width as the total width of the element including the padding and the margins, and others treat the width as the base width to which the padding and margins are added.  As a result your design will look different in different browsers.
For more information, see the
W3C page on Box Model
and
quirksmode's take
.


q: What's the best way to implement the enum idiom in Ruby? I'm looking for something which I can use (almost) like the Java/C# enums.

[A]
Most people use symbols (that's the
```
:foo_bar
```
syntax). They're sort of unique opaque values. Symbols don't belong to any enum-style type so they're not really a faithful representation of C's enum type but this is pretty much as good as it gets.


q: 1.exe doesn't give enough time for me to launch the IDE and attach 1.exe to the debugger to break into.

[A]
I assume you have the source to 1.exe (if you're debugging it), then just insert a statement near the beginning that will cause it to hang around long enough to attach a debugger.  ( getch() if you're desperate and it's not interactive. )
After the attach, just skip to the next statement and let it go.


q:
I assumed that the C# margin property had a meaning like in CSS - the spacing around the outside of the control. But Margin values seem to be ignored to matter what values I enter.

Then I read on the SDK:

Setting the Margin property on a
  docked control has no effect on the
  distance of the control from the the
  edges of its container.

Given that I'm placing controls on forms, and perhaps docking them, what does the Margin property get me?

[A]
The margin property is used by whatever layout engine your control host (Panel, for example) is using, in whatever way that layout engine sees fit.   However, it is best used for spacing just as you assume.   Just read the documentation for that specific layout engine.
It can be very handy when using a FlowLayoutPanel or TableLayoutPanel, for example - to either reduce the default padding or space things out a bit.   Obviously, if you write a  custom layout provider, you can use Margin however you see fit.


q:
Is there any complete guidance on doing AppBar docking (such as locking to the screen edge) in WPF? I understand there are InterOp calls that need to be made, but I'm looking for either a proof of concept based on a simple WPF form, or a componentized version that can be consumed.

Related resources:

http://www.codeproject.com/KB/dotnet/AppBar.aspx

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/05c73c9c-e85d-4ecd-b9b6-4c714a65e72b/

[A]
Please Note:
This question gathered a good amount of feedback, and some people below have made great points or fixes.  Therefore, while I'll keep the code here (and possibly update it), I've also
created a
WpfAppBar project on github
.  Feel free to send pull requests.
That same project also builds to a
WpfAppBar nuget package
I took the code from the first link provided in the question (
http://www.codeproject.com/KB/dotnet/AppBar.aspx
) and modified it to do two things:
Work with WPF
Be "standalone" - if you put this single file in your project, you can call AppBarFunctions.SetAppBar(...) without any further modification to the window.
This approach doesn't create a base class.
To use, just call this code from anywhere within a normal wpf window (say a button click or the initialize).   Note that you can not call this until AFTER the window is initialized, if the HWND hasn't been created yet (like in the constructor), an error will occur.
Make the window an appbar:
```
```
AppBarFunctions.SetAppBar( this, ABEdge.Right );
```
```
Restore the window to a normal window:
```
```
AppBarFunctions.SetAppBar( this, ABEdge.None );
```
```
Here's the full code to the file -
note
you'll want to change the namespace on line 7 to something apropriate.
```
```
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Threading;

namespace AppBarApplication
{
    public enum ABEdge : int
    {
        Left = 0,
        Top,
        Right,
        Bottom,
        None
    }

    internal static class AppBarFunctions
    {
        [StructLayout(LayoutKind.Sequential)]
        private struct RECT
        {
            public int left;
            public int top;
            public int right;
            public int bottom;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct APPBARDATA
        {
            public int cbSize;
            public IntPtr hWnd;
            public int uCallbackMessage;
            public int uEdge;
            public RECT rc;
            public IntPtr lParam;
        }

        private enum ABMsg : int
        {
            ABM_NEW = 0,
            ABM_REMOVE,
            ABM_QUERYPOS,
            ABM_SETPOS,
            ABM_GETSTATE,
            ABM_GETTASKBARPOS,
            ABM_ACTIVATE,
            ABM_GETAUTOHIDEBAR,
            ABM_SETAUTOHIDEBAR,
            ABM_WINDOWPOSCHANGED,
            ABM_SETSTATE
        }
        private enum ABNotify : int
        {
            ABN_STATECHANGE = 0,
            ABN_POSCHANGED,
            ABN_FULLSCREENAPP,
            ABN_WINDOWARRANGE
        }

        [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
        private static extern uint SHAppBarMessage(int dwMessage, ref APPBARDATA pData);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern int RegisterWindowMessage(string msg);

        private class RegisterInfo
        {
            public int CallbackId { get; set; }
            public bool IsRegistered { get; set; }
            public Window Window { get; set; }
            public ABEdge Edge { get; set; }
            public WindowStyle OriginalStyle { get; set; }
            public Point OriginalPosition { get; set; }
            public Size OriginalSize { get; set; }
            public ResizeMode OriginalResizeMode { get; set; }

            public IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam,
                                    IntPtr lParam, ref bool handled)
            {
                if (msg == CallbackId)
                {
                    if (wParam.ToInt32() == (int)ABNotify.ABN_POSCHANGED)
                    {
                        ABSetPos(Edge, Window);
                        handled = true;
                    }
                }
                return IntPtr.Zero;
            }

        }
        private static Dictionary<Window, RegisterInfo> s_RegisteredWindowInfo
            = new Dictionary<Window, RegisterInfo>();
        private static RegisterInfo GetRegisterInfo(Window appbarWindow)
        {
            RegisterInfo reg;
            if( s_RegisteredWindowInfo.ContainsKey(appbarWindow))
            {
                reg = s_RegisteredWindowInfo[appbarWindow];
            }
            else
            {
                reg = new RegisterInfo()
                    {
                        CallbackId = 0,
                        Window = appbarWindow,
                        IsRegistered = false,
                        Edge = ABEdge.Top,
                        OriginalStyle = appbarWindow.WindowStyle,
                        OriginalPosition =new Point( appbarWindow.Left, appbarWindow.Top),
                        OriginalSize =
                            new Size( appbarWindow.ActualWidth, appbarWindow.ActualHeight),
                        OriginalResizeMode = appbarWindow.ResizeMode,
                    };
                s_RegisteredWindowInfo.Add(appbarWindow, reg);
            }
            return reg;
        }

        private static void RestoreWindow(Window appbarWindow)
        {
            RegisterInfo info = GetRegisterInfo(appbarWindow);

            appbarWindow.WindowStyle = info.OriginalStyle;
            appbarWindow.ResizeMode = info.OriginalResizeMode;
            appbarWindow.Topmost = false;

            Rect rect = new Rect(info.OriginalPosition.X, info.OriginalPosition.Y,
                info.OriginalSize.Width, info.OriginalSize.Height);
            appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                    new ResizeDelegate(DoResize), appbarWindow, rect);

        }

        public static void SetAppBar(Window appbarWindow, ABEdge edge)
        {
            RegisterInfo info = GetRegisterInfo(appbarWindow);
            info.Edge = edge;

            APPBARDATA abd = new APPBARDATA();
            abd.cbSize = Marshal.SizeOf(abd);
            abd.hWnd = new WindowInteropHelper(appbarWindow).Handle;

            if( edge == ABEdge.None)
            {
                if( info.IsRegistered)
                {
                    SHAppBarMessage((int)ABMsg.ABM_REMOVE, ref abd);
                    info.IsRegistered = false;
                }
                RestoreWindow(appbarWindow);
                return;
            }

            if (!info.IsRegistered)
            {
                info.IsRegistered = true;
                info.CallbackId = RegisterWindowMessage("AppBarMessage");
                abd.uCallbackMessage = info.CallbackId;

                uint ret = SHAppBarMessage((int)ABMsg.ABM_NEW, ref abd);

                HwndSource source = HwndSource.FromHwnd(abd.hWnd);
                source.AddHook(new HwndSourceHook(info.WndProc));
            }

            appbarWindow.WindowStyle = WindowStyle.None;
            appbarWindow.ResizeMode = ResizeMode.NoResize;
            appbarWindow.Topmost = true;

            ABSetPos(info.Edge, appbarWindow);
        }

        private delegate void ResizeDelegate(Window appbarWindow, Rect rect);
        private static void DoResize(Window appbarWindow, Rect rect)
        {
            appbarWindow.Width = rect.Width;
            appbarWindow.Height = rect.Height;
            appbarWindow.Top = rect.Top;
            appbarWindow.Left = rect.Left;
        }

        private static void ABSetPos(ABEdge edge, Window appbarWindow)
        {
            APPBARDATA barData = new APPBARDATA();
            barData.cbSize = Marshal.SizeOf(barData);
            barData.hWnd = new WindowInteropHelper(appbarWindow).Handle;
            barData.uEdge = (int)edge;

            if (barData.uEdge == (int)ABEdge.Left || barData.uEdge == (int)ABEdge.Right)
            {
                barData.rc.top = 0;
                barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;
                if (barData.uEdge == (int)ABEdge.Left)
                {
                    barData.rc.left = 0;
                    barData.rc.right = (int)Math.Round(appbarWindow.ActualWidth);
                }
                else
                {
                    barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;
                    barData.rc.left = barData.rc.right - (int)Math.Round(appbarWindow.ActualWidth);
                }
            }
            else
            {
                barData.rc.left = 0;
                barData.rc.right = (int)SystemParameters.PrimaryScreenWidth;
                if (barData.uEdge == (int)ABEdge.Top)
                {
                    barData.rc.top = 0;
                    barData.rc.bottom = (int)Math.Round(appbarWindow.ActualHeight);
                }
                else
                {
                    barData.rc.bottom = (int)SystemParameters.PrimaryScreenHeight;
                    barData.rc.top = barData.rc.bottom - (int)Math.Round(appbarWindow.ActualHeight);
                }
            }

            SHAppBarMessage((int)ABMsg.ABM_QUERYPOS, ref barData);
            SHAppBarMessage((int)ABMsg.ABM_SETPOS, ref barData);

            Rect rect = new Rect((double)barData.rc.left, (double)barData.rc.top,
                (double)(barData.rc.right - barData.rc.left), (double)(barData.rc.bottom - barData.rc.top));
            //This is done async, because WPF will send a resize after a new appbar is added.
            //if we size right away, WPFs resize comes last and overrides us.
            appbarWindow.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle,
                new ResizeDelegate(DoResize), appbarWindow, rect);
        }
    }
}
```
```


q:
I'm wondering if there's such a thing as Django-like ease of web app development combined with good deployment, debugging and other tools?

Django is a very productive framework for building content-heavy sites; the best I've tried and a breath of fresh air compared to some of the Java monstrosities out there. However it's written in Python which means there's little real support in the way of deployment/packaging, debugging, profilers and other tools that make building and maintaining applications much easier.

Ruby has similar issues and although I do like Ruby much better than I like Python, I get the impression that Rails is roughly in the same boat at Django when it comes to managing/supporting the app.

Has anyone here tried both Django and Grails (or other web frameworks) for non-trivial projects? How did they compare?

[A]
cakephp.org
Cakephp is really good, really close to ruby on rails (1.2).  It is in php, works very well on shared hosts and is easy to implement.
The only downside is that the documentation is somewhat lacking, but you quickly get it and quickly start doing cool stuff.
I totally recommend cakephp.


q:
All the docs for SQLAlchemy give INSERT and UPDATE examples using the local table instance (e.g. tablename.update()... )

Doing this seems difficult with the declarative syntax, I need to reference Base.metadata.tables["tablename"] to get the table reference.

Am I supposed to do this another way?   Is there a different syntax for INSERT and UPDATE recommended when using the declarative syntax?  Should I just switch to the old way?

[A]
via the
```
__table__
```
attribute on your declarative class


q:
I'm trying to insert a Spry accordion into an already existing JSF page using Dreamweaver. Is this possible?

I've already tried several things, and only the labels show up.

[A]
I'm not a Dreamweaver expert, but all Spry Accordian requires is the correct HTML structure. E.g.:
```
```

Panel 1

                    Panel 1 Content

                    Panel 1 Content

                    Panel 1 Content

```
```
Provided you have the
JavaScript
library loaded correctly, that should pretty much be all you need to do.


q: As a part of database maintenance we are thinking of taking daily backups onto an external/firewire drives. Are there any specific recommended drives for the frequent read/write operations from sql server 2000 to take backups?

[A] Whatever you do, just don't use USB 1.1.


q: This may be a no-brainer for the WPF cognoscenti, but I'd like to know if there's a simple way to put text on the WPF ProgressBar. To me, an empty progress bar looks naked. That's screen real estate that could carry a message about what is in progress, or even just add numbers to the representation. Now, WPF is all about containers and extensions and I'm slowly wrapping my mind around that, but since I don't see a "Text" or "Content" property, I'm thinking I'm going to have to add something to the container that is my progress bar. Is there a technique or two out there that is more natural than my original WinForms impulses will be? What's the best, most WPF-natural way to add text to that progress bar?

[A]
If you are needing to have a reusable method for adding text, you can create a new Style/ControlTemplate that has an additional TextBlock to display the text.  You can hijack the TextSearch.Text attached property to set the text on a progress bar.
If it doesn't need to be reusable, simply put the progress bar in a Grid and add a TextBlock to the grid.  Since WPF can compose elements together, this will work nicely.
If you want, you can create a UserControl that exposes the ProgressBar and TextBlock as public properties, so it would be less work than creating a custom ControlTemplate.


q:
I'm working on a web page where I'm making an AJAX call that returns a chunk of HTML like:

<div>
  <!-- some html -->
  <script type="text/javascript">
    /** some javascript */
  </script>
</div>

I'm inserting the whole thing into the DOM, but the JavaScript isn't being run.  Is there a way to run it?

Some details: I can't control what's in the script block (so I can't change it to a function that could be called), I just need the whole block to be executed.  I can't call eval on the response because the JavaScript is within a larger block of HTML.  I could do some kind of regex to separate out the JavaScript and then call eval on it, but that's pretty yucky.  Anyone know a better way?

[A]
You don't have to use regex if you are using the response to fill a div or something. You can use getElementsByTagName.
```
```
div.innerHTML = response;
var scripts = div.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
    eval(scripts[ix].text);
}
```
```


q: In a .NET Win console application, I would like to access an App.config file in a location different from the console application binary. For example, how can C:\bin\Text.exe get its settings from C:\Test.exe.config?

[A]
Use the following (remember to include System.Configuration assembly)
```
```
ConfigurationManager.OpenExeConfiguration(exePath)
```
```


q:
I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:

mysql> source script.sql

How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.

I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.

[A]
Like this:
```
```
set @department := 'Engineering';
```
```
Then, reference
```
@department
```
wherever you need to in script.sql:
```
```
update employee set salary = salary + 10000 where department = @department;
```
```


q: I have a couple old services that I want to completely uninstall. How can I do this?

[A]
Click
Start
|
Run
and type
```
regedit
```
in the Open: line. Click OK.
Navigate to
```
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
```
Scroll down the left pane, locate the service name, right click it and
select Delete
.
Reboot the system.


q:
I am trying to solve numerically a set of partial differential equations in three dimensions. In each of the equations the next value of the unknown in a point depends on the current value of each unknown in the closest points.

To write an efficient code I need to keep the points close in the three dimensions close in the (one-dimensional) memory space, so that each value is called from memory just once.

I was thinking of using octtrees, but I was wondering if someone knows a better method.

[A]
Octtrees are the way to go.  You subdivide the array into 8 octants:
```
1 2
3 4

---

5 6
7 8
```
And then lay them out in memory in the order 1, 2, 3, 4, 5, 6, 7, 8 as above.  You repeat this recursively within each octant until you get down to some base size, probably around 128 bytes or so (this is just a guess -- make sure to profile to determine the optimal cutoff point).  This has much, much better cache coherency and locality of reference than the naive layout.


q: can anyone please suggest a good code example of vb.net/c# code to put the application in system tray when minized.

[A]
Add a NotifyIcon control to your form, then use the following code:
```
```
private void frm_main_Resize(object sender, EventArgs e)
    {
        if (this.WindowState == FormWindowState.Minimized)
        {
           this.ShowInTaskbar = false;
           this.Hide();
           notifyIcon1.Visible = true;
        }
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        this.Show();
        this.WindowState = FormWindowState.Normal;
        this.ShowInTaskbar = true;
        notifyIcon1.Visible = false;
    }
```
```
You may not need to set the ShowInTaskbar property.


q:
I'm trying to keep dependencies to a minimum for a program I contribute to, it's a small text editor.

GTK Textview doesn't seem to come with a built-in undo function. Is there any reference implementation I've been missing on so far? Is everyone writing their own undo function for their TextView widgets?

I'll be happy about any sample code - most happy about python sample code, as our project is in python.

[A]
As far as I know, GTK TextView doesn't include an undo function. So while I am not familiar with Python's GTK library, I would think it doesn't have one.
The Ruby-GNOME2 project has a
sample text editor
that has undo/redo functionality. Basically they are connecting to the insert_text and delete_range signals of the TextView widget and recording the events and associated data in a list.


q:
I have 4 2D points in screen-space, and I need to reverse-project them back into 3D space. I know that each of the 4 points is a corner of a 3D-rotated rigid rectangle, and I know the size of the rectangle. How can I get 3D coordinates from this?

I am not using any particular API, and I do not have an existing projection matrix. I'm just looking for basic math to do this. Of course there isn't enough data to convert a single 2D point to 3D with no other reference, but I imagine that if you have 4 points, you know that they're all at right-angles to each other on the same plane, and you know the distance between them, you should be able to figure it out from there. Unfortunately I can't quite work out how though.

This might fall under the umbrella of photogrammetry, but google searches for that haven't led me to any helpful information.

[A]
Assuming that the points are indeed part of a rectangle, I'm giving a generic idea :
Find two points with max inter-distance: these most probably define a diagonal (exception: special cases where the rectangle is almost paralell to the YZ plane, left for the student). Call them A, C. Calculate the BAD, BCD angles. These, compared to right angles, give you orientation in 3d space. To find out about z distance, you need to correlate the projected sides to the known sides, and then, based on the 3d projection method (is it 1/z?) you're on the right track to know distances.


q: Does anybody have experience of a decent J2SE (preferably at least Java JDK 1.5-level) Java Virtual Machine for Windows Mobile 6? If you know of any CLDC VMs, I'm also interested because even that would be better than what we currently have for the platform.

[A]
Honestly I searched a while and there no decent JVM for windows mobile. The best bet I think is this :
http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html
but it's JDK 1.3 compliant the last time I checked.


q:
I've only been able to find two thus far, namely TinyRadius, which itself discourages production use and AXL, which is pay-only.

JRadius seems tied to FreeRADIUS, which isn't a library and will need a lot of cajoling to function like one.

[A]
List from
http://freeradius.org/related/opensource.html
(not copying the descriptions because the page says it's copyright
rolleyes
):
Cistron -
http://www.radius.cistron.nl/
GNU Radius -
http://www.gnu.org/software/radius/
FreeRADIUS -
http://freeradius.org/
JRadius -
http://www.coova.org/JRadius
ICRADIUS -
http://www.icradius.org/
OpenRADIUS -
http://www.openradius.net/
XtRADIUS -
http://xtradius.sourceforge.net/
YARD RADIUS -
http://sourceforge.net/projects/yardradius


q:
In my SWT Java app I often want to return information from inside a Display.syncExec() call.  The best way I've found so far to do this is:

final ArrayList<Integer> result = new ArrayList<Integer>();
GUI.display().syncExec(new Runnable(){ public void run() {
   MessageBox mb = /* ... */;
    /* set up messagebox */
   result.add(mb.open());
}});
if (SWT.OK == result.get(0)) { /* ... */ }

I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?

[A]
ArrayList is
not
thread-safe. From the relevant
Javadoc
:
Note that this implementation is not
  synchronized. If multiple threads
  access an ArrayList instance
  concurrently, and at least one of the
  threads modifies the list
  structurally, it must be synchronized
  externally.
If you need a thread-safe implementation of List, there are (at least) two provided in the JDK: CopyOnWriteArrayList and Vector.


q: PHP5 has a "magic method" __call()that can be defined on any class that is invoked when an undefined method is called -- it is roughly equivalent to Ruby's method_missing or Perl's AUTOLOAD. Is it possible to do something like this in older versions of PHP?

[A]
I recall using it, and a little bit of googling suggests that
```
```
function __call($method_name, $parameters, &$return)
{
  $return_value = "You called ${method_name}!";
}
```
```
as a member function will do the job.


q:
Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in C (not C++, I know that template magic is available there)?

I generally use GCC and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...).

I'm looking for how to do this in GCC (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.


q:
I just got surprised by something in TSQL.  I thought that if xact_abort was on, calling something like

raiserror('Something bad happened', 16, 1);

would stop execution of the stored procedure (or any batch).

But my ADO.NET error message just proved the opposite.  I got both the raiserror error message in the exception message, plus the next thing that broke after that.

This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary:

if @somethingBadHappened
    begin;
        raiserror('Something bad happened', 16, 1);
        return;
    end;

The docs say this:

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.

Does that mean I must be using an explicit transaction?

[A]
This is By Design
TM
, as you can see on
Connect
by the SQL Server team's response to a similar question:
Thank you for your feedback. By design, the XACT_ABORT set option does not impact the behavior of the RAISERROR statement. We will consider your feedback to modify this behavior for a future release of SQL Server.
Yes, this is a bit of an issue for some who hoped
```
RAISERROR
```
with a high severity (like
```
16
```
) would be the same as an SQL execution error - it's not.
Your workaround is just about what you need to do, and using an explicit transaction doesn't have any effect on the behavior you want to change.


q:
Does ADOdb do data sanitation or escaping within the same functionality by default? Or am I just confusing it with Code Igniter's built-in processes?

Does binding variables to parameters in ADOdb for PHP prevent SQL injection in any way?

[A]
yes, you pass the array of parameters.
```
```
$rs = $db->Execute('select * from table where val=?', array('10'));
```
```
Rest of their docs can be found
here
:


q:
In what domains do each of these software architectures shine or fail?

Which key requirements would prompt you to choose one over the other?

Please assume that you have developers available who can do good object oriented code as well as good database development.

Also, please avoid holy wars :) all three technologies have pros and cons, I'm interested in where is most appropriate to use which.

[A]
I agree that there are pros and cons to everything and a lot depends on your architecture. That being said, I try to use ORM's where it makes sense. A lot of the functionality is already there and usually they help prevent SQL Injection (plus it helps avoid re-inventing the wheel).
Please see these other two posts on the topic (dynamic SQL vs
stored procedures vs ORM) for more information
Dynamic SQL vs. stored procedures
Which is better: Ad hoc queries, or stored procedures?
ORMs vs. stored procedures
Why is parameterized SQL generated by NHibernate just as fast as a stored procedure?


q:
I have a SQL Insert query inside a stored proc, for inserting rows into a linked server table.

Since the stored proc is getting called within a parent transaction, this Insert statement tries to use a DTC for inserting rows into the linked server.

I would like to avoid DTC from getting involved.

Is there any way I can do that (like a hint) for the Insert SQL statement to ignore transactional scope?

[A]
My suggestion is that you store whatever you want to insert into a staging table, and once the procedure is over run the cross server insert.  To my knowledge there is no way of ignoring the transaction you are in once you are within the SProc execution.
In contrast, if you use .NET 2.0's System.Transaction namespace, you can tell specific statements not to participate in any parent scope transaction.  This would require you to write some of your logic in code rather than stored procedures, but would work.
Here's a
relevant link
.
Good luck,
Alan.


q:
How can I create a regular expression that will grab delimited text from a string?  For example, given a string like

text ###token1### text text ###token2### text text

I want a regex that will pull out ###token1###.  Yes, I do want the delimiter as well.  By adding another group, I can get both:

(###(.+?)###)

[A]
```
```
/###(.+?)###/
```
```
if you want the ###'s  then you need
```
```
/(###.+?###)/
```
```
the
?
means non greedy, if you didn't have the
?
, then it would grab too much.
e.g.
```
'###token1### text text ###token2###'
```
would all get grabbed.
My initial answer had a * instead of a +.  * means 0 or more.  + means 1 or more.  * was wrong because that would allow ###### as a valid thing to find.
For playing around with regular expressions. I highly recommend
http://www.weitz.de/regex-coach/
for windows.  You can type in the string you want and your regular expression and see what it's actually doing.
Your selected text will be stored in \1   or $1 depending on where you are using your regular expression.


q:
In C#.NET I am trying to programmatically change the color of the border in a group box.

Update:  This question was asked when I was working on a winforms system before we switched to .NET.

[A]
I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmatically using:
```
```
GroupBox box = new GroupBox();
[...]
box.Paint += delegate(object o, PaintEventArgs p)
{
    p.Graphics.Clear(someColorHere);
};
```
```
Cheers!


q: I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting.  I have a control that currently uses a Repeater control with templates.  Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties?


q: Is there a way in Ruby to find the version of a file, specifically a .dll file?

[A]
For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to find out what version the file is.  There is no API or common method to determine a file version in Ruby.
Note that it would be easier if the file version were in the file name.


q:
I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code:

cat tmp.log -encoding UTF8 > new.log

The resulting file is still in UCS-2 Little Endian.  Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?

[A]
I would do it like this:
```
```
get-content tmp.log -encoding Unicode | set-content new.log -encoding UTF8
```
```
My understanding is that the -encoding option selects the encdoing that the file should be read or written in.


q: Can't find anything relevant about Entity Framework/MySQL on Google so I'm hoping someone knows about it.

[A]
You would need a mapping provider for MySQL. That is an extra thing the Entity Framework needs to make the magic happen.
This blog
talks about other mapping providers besides the one Microsoft is supplying. I haven't found any mentionings of MySQL.


q: Under what circumstances - if any - does adding programmers to a team actually speed development of an already late project?

[A]
If the existing programmers are totally incompetent, then adding competent programmers may help.
I can imagine a situation where you had a very modular system, and the existing programmer(s) hadn't even
started
on a very isolated module.  In that case, assigning just that portion of the project to a new programmer might help.
Basically the Mythical Man Month references are correct, except in contrived cases like the one I made up.  Mr. Brooks did solid research to demonstrate that after a certain point, the networking and communication costs of adding new programmers to a project will outweigh any benefits you gain from their productivity.


q:
All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it.

I know I could just use an image; I'd rather not do that if I can help it.

[A]
```
```

test

```
```
the big problem with this method is the extra markup. (the span tag)


q:
In JavaScript, using the Prototype library, the following functional construction is possible:

var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"];
words.pluck('length');
//-> [7, 8, 5, 16, 4]

Note that this example code is equivalent to

words.map( function(word) { return word.length; } );

I wondered if something similar is possible in F#:

let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"]
//val words: string list
List.pluck 'Length' words
//int list = [7; 8; 5; 16; 4]

without having to write:

List.map (fun (s:string) -> s.Length) words

This would seem quite useful to me because then you don't have to write functions for every property to access them.

[A]
Prototype's
```
pluck
```
takes advantage of that in Javascript
```
object.method()
```
is the same as
```
object[method]
```
.
Unfortunately you can't call
```
String.Length
```
either because it's not a static method. You can however use:
```
```
#r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Compatibility
words |> List.map String.length
```
```
http://research.microsoft.com/fsharp/manual/FSharp.PowerPack/Microsoft.FSharp.Compatibility.String.html
However, using
```
Compatibility
```
will probably make things more confusing to people looking at your code.


q:
There's an MSDN article here, but I'm not getting very far:

p = 139;
g = 5;

CRYPT_DATA_BLOB pblob;
pblob.cbData = sizeof( ULONG );
pblob.pbData = ( LPBYTE ) &p;

CRYPT_DATA_BLOB gblob;
gblob.cbData = sizeof( ULONG );
gblob.pbData = ( LPBYTE ) &g;

HCRYPTKEY hKey;
if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF,
                    CRYPT_PREGEN, &hKey ) )
{
    ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 );

Fails here with NTE_BAD_DATA.  I'm using MS_DEF_DSS_DH_PROV.   What gives?

[A]
It looks to me that
```
KP_P
```
,
```
KP_G
```
,
```
KP_Q
```
are for DSS keys (Digital Signature Standard?). For Diffie-Hellman it looks like you're supposed to use
```
KP_PUB_PARAMS
```
and pass a
```
DATA_BLOB
```
that points to a
```
DHPUBKEY_VER3
```
structure.
Note that the article you're pointing to is from the Windows Mobile/Windows CE SDK. It wouldn't be the first time that CE worked differently from the desktop/server.
EDIT: CE does not implement
```
KP_PUB_PARAMS
```
. To use this structure on the desktop, see
Diffie-Hellman Version 3 Public Key BLOBs
.


q:
I'm trying to load test data into a test DB during a maven build for integration testing. persistence.xml is being copied to target/test-classes/META-INF/ correctly, but I get this exception when the test is run.

javax.persistence.PersistenceException:
  No Persistence provider for
  EntityManager named aimDatabase

It looks like it's not finding or loading persistence.xml.

[A]
If this is on windows, you can use sysinternal's procmon to find out if it's checking the right path.
Just filter by path -> contains -> persistence.xml.  Procmon will pick up any attempts to open a file named persistenc.xml, and you can check to see the path or paths that get tried.
See here for more detail on procmon:
http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx


q:
Is there a way to have a 64 bit enum in C++?  Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.

For some reason I thought the following might work:

enum MY_ENUM : unsigned __int64
{
    LARGE_VALUE = 0x1000000000000000,
};

[A]
An enum in C++ can be any integral type. You can, for example, have an enum of chars. IE:
```
```
enum MY_ENUM
{
   CHAR_VALUE = 'c',
};
```
```
I would
assume
this includes __int64. Try just
```
```
enum MY_ENUM
{
   LARGE_VALUE = 0x1000000000000000,
};
```
```
According to my commenter, sixlettervariables, in C the base type will be an int always, while in C++ the base type is whatever is large enough to fit the largest included value. So both enums above should work.


q: I would like to call my unmanaged C++ libraries from my C# code. What are the potential pitfalls and precautions that need to be taken? Thank you for your time.

[A]
There are a couple routes you can go with this - one, you can update your unmanaged C++ libraries to have a managed C++ extensions wrapper around them and have C# utilize those classes directly.  This is a bit time-consuming, but it provides a nice bridge to legacy unmanaged code.  But be aware that managed C++ extensions are sometimes a bit hard to navigate themselves as the syntax is similar to unmanaged C++, but close enough that a very trained eye will be able to see the differences.
The other route to go is have your umnanaged C++ implement COM classes and have C# utilize it via an autogenerated interop assembly.  This way is easier if you know your way around COM well enough.
Hope this helps.


q: Where may one find references on implementing an algorithm for calculating a "dirty rectangle" for minimizing frame buffer updates?  A display model that permits arbitrary edits and computes the minimal set of "bit blit" operations required to update the display.

[A]
To build the smallest rectangle that contains all the areas that need to be repainted:
Start with a blank area (perhaps a rectangle set to 0,0,0,0 - something you can detect as 'no update required')
For each dirty area added:
Normalize the new area (i.e. ensure that left is less than right, top less than bottom)
If the dirty rectangle is currently empty, set it to the supplied area
Otherwise, set the left and top co-ordinates of the dirty rectangle to the smallest of {dirty,new}, and the right and bottom co-ordinates to the largest of {dirty,new}.
Windows, at least, maintains an
update region
of the changes that it's been informed of, and any repainting that needs to be done due to the window being obscured and revealed. A
region
is an object that is made up of many possibly discontinuous rectangles, polygons and ellipses. You tell Windows about a part of the screen that needs to be repainted by calling InvalidateRect - there is also an InvalidateRgn function for more complicated areas. If you choose to do some painting before the next WM_PAINT message arrives, and you want to exclude that from the dirty area, there are ValidateRect and ValidateRgn functions.
When you start painting with BeginPaint, you supply a PAINTSTRUCT that Windows fills with information about what needs to be painted. One of the members is the smallest rectangle that contains the invalid region. You can get the region itself using GetUpdateRgn (you must call this before BeginPaint, because BeginPaint marks the whole window as valid) if you want to minimize drawing when there are multiple small invalid areas.
I would assume that, as minimizing drawing was important on the Mac and on X when those environments were originally written, there are equivalent mechanisms for maintaining an update region.


q:
I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; messages (id, body) and messages_read (user_id, message_id).

Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?

Thanks!

[A]
Well, you could use
```
```
SELECT id FROM messages m WHERE m.id NOT IN(
    SELECT message_id FROM messages_read WHERE user_id = ?)
```
```
Where ? is passed in by your app.


q: I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.

[A]
```
```
SELECT id, datefield, count(*) FROM tablename GROUP BY datefield
  HAVING count(*) > 1
```
```


q:
How cheap can MySQL be compared to MS SQL when you have tons of data (and joins/search)? Consider a site like  stackoverflow full of Q&As already and after getting dugg.

My ASP.NET sites are currently on SQL Server Express so I don't have any idea how cost compares in the long run. Although after a quick research, I'm starting to envy the savings MySQL folks get.

[A]
I know that stackoverflow has had problems with deadlocks from reads/writes coming at odd intervals but they're claiming their architecture (MSSQL) is holding up fine.  This was before the public beta of course and according to Jeff's twitter earlier today:
the range of top 32 newest/modified
  questions was about 20 minutes in the
  private beta; now it's about 2
  minutes.
That the site hasn't crashed yet is a testament to the database (as well as good coding and testing).
But why not post some specific numbers about your site?


q: What factors determine which approach is more appropriate?

[A] Not nearly enough information here. It depends if your language even supports the construct "Thing.something" or equivalent (ie. it's an OO language). If so, it's far more appropriate because that's the OO paradigm (members should be associated with the object they act on). In a procedural style, of course, DoSomethingtoThing() is your only choice... or ThingDoSomething()


q: What's the best library to use to generate RSS for a webserver written in Common Lisp?

[A]
xml-emitter
says it has an RSS 2.0 emitter built in.


q: How can I set the protected DoubleBuffered property of the controls on a form that are suffering from flicker?

[A]
```
```
public void EnableDoubleBuffering()
{
   this.SetStyle(ControlStyles.DoubleBuffer |
      ControlStyles.UserPaint |
      ControlStyles.AllPaintingInWmPaint,
      true);
   this.UpdateStyles();
}
```
```


q:
I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.

My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using gcc).

I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?

[A]
```
```
ulimit -c unlimited
```
```
is a system variable, wich will allow to create a core dump after your application crashes. In this case an unlimited amount. Look for a file called core in the very same directory. Make sure you compiled your code with debugging informations enabled!
regards


q: I would like to display multiple colors (and potentially shapes and sizes) of data points in a Google Chart scatter chart. Does anyone have an example of how to do so?

[A]
You can only use one dataset in a scatter plot, thus only one color.
http://code.google.com/apis/chart/#scatter_plot
From the API description:
Scatter plots use multiple data sets differently than other chart types. You can only show one data set in a scatter plot.


q:
I've used the MIT Continuous testing plugin in the past, but it has long since passed out of date and is no longer compatible with anything approaching a modern release of Eclipse.

Does anyone have a good replacement? Free, naturally, is preferred.

[A]
There is a list in this Ben Rady article at Object Mentor:
Continuous Testing Explained
.  Unfortunately the only Eclipse tool appears to be
CT-Eclipse
which is not currently maintained either.
There is also
Fireworks
for IntelliJ and
Infinitest
which is not IDE specific but also has some IntelliJ integration.


q:
I will be moving our production SQL2005 application to SQL2008 soon. Any things to lookout for before/after the move? Any warnings, advices?

Thank you!

[A]
The upgrade adviser can also help.
Look at the execution plans with production data in the database.
Though my best advice is to test, test, test.
When people started moving from 2000 to 2005 it wasn't the breaking features that were show stoppers it was the change in how queries performed with the new optimizer.
Queries that were heavily optimized for 2000 now performed poorly or even worse erratically leading people to chase down non-problems and generally lowering the confidence of the end users.


q: What is the easiest way to capitalize the first letter in each word of a string?

[A]
Take a look at the
ucfirst
function.
```
```
$line = join " ", map {ucfirst} split " ", $line;
```
```


q:
Can I persuade operator>> in C++ to read both a hex value AND and a decimal value?  The following program demonstrates how reading hex goes wrong.  I'd like the same istringstream to be able to read both hex and decimal.

#include <iostream>
#include <sstream>

int main(int argc, char** argv)
{
    int result = 0;
    // std::istringstream is("5"); // this works
    std::istringstream is("0x5"); // this fails

    while ( is.good() ) {
        if ( is.peek() != EOF )
            is >> result;
        else
            break;
    }

    if ( is.fail() )
        std::cout << "failed to read string" << std::endl;
    else
        std::cout << "successfully read string" << std::endl;

    std::cout << "result: " << result << std::endl;
}

[A]
You need to tell C++ what your base is going to be.
Want to parse a hex number?  Change your "is >> result" line to:
```
```
is >> std::hex >> result;
```
```
Putting a std::dec indicates decimal numbers, std::oct indicates octal.


q:
I would like to keep the overhead at a minimum. Right now I have:

// Launch a Message Box with advice to the user
DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation);

// The test will only be launched if the user has selected Yes on the Message Box
if(result == DialogResult::Yes)
{
    // Execute code
}

Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.

[A]
You can use "OK" and "Cancel"
By substituting
```
MessageBoxButtons::YesNo
```
with
```
MessageBoxButtons::OKCancel
```
MessageBoxButtons Enum
Short of that you would have to create a new form, as I don't believe the Enum can be extended.


q:
In the Java collections framework, the Collection interface declares the following method:

<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?

[A]
```
```
Array.newInstance(Class componentType, int length)
```
```


q:
Suppose I have a vector that is nested in a dataframe one or two levels.  Is there a quick and dirty way to access the last value, without using the length() function?  Something ala PERL's $# special var?

So I would like something like:

dat$vec1$vec2[$#]

instead of

dat$vec1$vec2[length(dat$vec1$vec2)]

[A]
If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck.  The standard idiom is
```
```
x[length(x)]
```
```
but it's easy enough to write a function to do this:
```
```
last <- function(x) { return( x[length(x)] ) }
```
```
This missing feature in R annoys me too!


q:
GDB has severe issues when debugging with multiple threads (pthreads).
Are there any other good multi-threaded debuggers for C/C++ on *nix?

[A] From my search, I have not found any good multi-thread debuggers for *nix. GDB seems to be getting better, and the last time I had to debug a multi-threaded application on FreeBSD (7.0-RELEASE) it behaved fairly well, letting me find where the error was.


q:
I want to write a raw byte/byte stream to a position in a file.
This is what I have currently:

$fpr = fopen($out, 'r+');
fseek($fpr, 1); //seek to second byte
fwrite($fpr, 0x63);
fclose($fpr);

This currently writes the actually string value of "99" starting at byte offset 1.  IE, it writes bytes "9" and "9".  I just want to write the actual one byte value 0x63 which happens to represent number 99.

Thanks for your time.

[A]
```
fwrite()
```
takes strings. Try
```
chr(0x63)
```
if you want to write a
```
0x63
```
byte to the file.


q:
I have an application written in java, and I want to add a flash front end to it. The flash front end will run on the same computer as the java app in the stand alone flash player. I need two way communication between the two parts, and have no idea how to even start going about this. I suppose I could open a  socket between the two programs, but I feel that there must be an easier way. Is there a nice part of the api in actionscript 3.0 that will allow me to access java methods directly, or will I have to resort to sockets? I am relatively new to flash, by the way, so any good guides would be much appreciated!

Thanks

[A]
AMF
is a messaging protocol commonly used to talk between flash and a backend system. There're several Java implementations, but I haven't used any of them so can't tell you which is best.
Blaze DS
Red5
Granite DS
Flash can also talk plain old XML, SOAP or REST to the backend, so depending on your codebase that might be easier.


q:
I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script.

My goal is to use phpunit with Selenium RC in CruiseControl & phpUnderControl. This is what the test looks like:

require_once 'PHPUnit/Extensions/SeleniumTestCase.php';

class WebTest extends PHPUnit_Extensions_SeleniumTestCase
{
    protected function setUp()
    {
        $this->setBrowser('*firefox');
        $this->setBrowserUrl('http://www.example.com/');
    }

    public function testTitle()
    {
        $this->open('http://www.example.com/');
        $this->assertTitleEquals('Example Web Page');
    }
}

I also got PEAR in the include_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem.

Any help would be very much appreciated.

Thanks, Remy

[A]
Have a look at one of the comments in the require_once entry in the php manual..
http://ie.php.net/manual/en/function.require-once.php#62838
"require_once (and include_once for that matters) is slow
Furthermore, if you plan on using unit tests and mock objects (i.e. including mock classes before the real ones are included in the class you want to test), it will not work as require() loads a file and not a class."


q:
This is not "exactly" a programming question, but it's highly related.  We are writing an app that sends out email invitations for a client (no, it's not spam).  Their designer gave us an HTML and CSS template to use which is fine.  The problem is that it looks like crap in Outlook 2007 because Microsoft decided to use Word (of all things!) as the rendering engine for HTML in Outlook 2007.  I want the client to understand that they should design a "compatible" look and would love to be able to show some kind of statistics about what email clients are being used out there, namely that Outlook 2007 is growing in use.

Has anyone run across any white papers, web sites, studies that even come close to providing a view on this?  I don't expect census level accuracy, but something fairly credible would be good.  Thanks for any help.

[A]
you should look at
ReturnPath
- they somewhat specialize in that.
Clients you likely need to consider (aside from Outlook):
AOL
Gmail
(Google)
Yahoo Mail
(Yahoo)
Hotmail
/
Live
/
MSN
/
Outlook
(Microsoft)
Lotus Notes (IBM)
Thunderbird
(Mozilla)


q: I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?

[A]
Tk does not natively support windows bitmap files. However, the "Img" extension does and is freely available on just about every platform. You do not need to read the data in, you can create the image straight from the file on disk. In plain tcl/tk your code might look something like this:
```
```
package require Img
set image [image create photo -file /path/to/image.bmp]
label .l -image $image
pack .l
```
```
a little more information can be found at
http://wiki.tcl.tk/6165


q: How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that use strict; isn't sufficient for this purpose.

[A]
Include this:
```
```
use Carp ();
```
```
Then include
one
of these lines at the top of your source file:
```
```
local $SIG{__WARN__} = \&Carp::confess;
local $SIG{__WARN__} = \&Carp::cluck;
```
```
The
```
confess
```
line will give a stack trace, and the
```
cluck
```
line is much more terse.


q:
I recently came across a ASP 1.1 web application that put a whole heap of stuff in the session variable - including all the DB data objects and even the DB connection object. It ends up being huge. When the web session times out (four hours after the user has finished using the application) sometimes their database transactions get rolled back. I'm assuming this is because the DB connection is not being closed properly when IIS kills the session.

Anyway, my question is what should be in the session variable? Clearly some things need to be in there. The user selects which plan they want to edit on the main screen, so the plan id goes into the session variable. Is it better to try and reduce the load on the DB by storing all the details about the user (and their manager etc.) and the plan they are editing in the session variable or should I try to minimise the stuff in the session variable and query the DB for everything I need in the Page_Load event?

[A]
This is pretty hard to answer because it's so application-specific, but here are a few guidelines I use:
Put as little as possible in the session.
User-specific selections that should only last during a given visit are a good choice
often, variables that need to be accessible to multiple pages throughout the user's visit to your site (to avoid passing them from page to page) are also good to put in the session.
From what little you've said about your application, I'd probably select your data from the db and try to find ways to minimize the impact of those queries instead of loading down the session.


q: How can I dismiss dialog in Cocoa application when user presses Esc or Enter key? I have OK button, is it possible to make it default button?

[A]
If you present the alert panel using the
```
NSAlert
```
class or,
```
NSRunAlertPanel
```
family of functions, or the
```
NSBeginAlertSheet
```
family of functions, you will get support for default and cancel buttons automatically.
If you're presenting a sheet that needs OK/Cancel buttons, and you're not using any of the above, you should be able to assign your buttons appropriate keyboard equivalents in Interface Builder using the attributes inspector.  (Just highlight the
Key Equiv.
area and press the key you want to be equivalent to pressing that button.)
If you're presenting a dialog that's not either an alert or a document/window-modal sheet — don't. :)  Document-modal alerts aren't Mac-like, and shouldn't be used for things like preferences windows.


q: Is it possible to create custom events in C++?  For example, say I have the variable X, and the variable Y.  Whenever X changes, I would like to execute a function that sets Y equal to 3X.  Is there a way to create such a trigger/event?  (triggers are common in some databases)

[A]
Think you should read a little about
Design Patterns
, specifically the
Observer Pattern
.
Qt from
Trolltech
have implemented a nice solutions they call
Signals and Slots
.


q: I do work in theoretical chemistry on a high performance cluster, often involving molecular dynamics simulations.  One of the problems my work addresses involves a static field of N-dimensional (typically N = 2-5) hyper-spheres, that a test particle may collide with.  I'm looking to optimize (read: overhaul) the the data structure I use for representing the field of spheres so I can do rapid collision detection.  Currently I use a dead simple array of pointers to an N-membered struct (doubles for each coordinate of the center) and a nearest-neighbor list.  I've heard of oct- and quad- trees but haven't found a clear explanation of how they work, how to efficiently implement one, or how to then do fast collision detection with one.  Given the size of my simulations, memory is (almost) no object, but cycles are.

[A]
A Quad tree is a 2 dimensional tree, in which at each level a node has 4 children, each of which covers 1/4 of the area of the parent node.
An Oct tree is a 3 dimensional tree, in which at each level a node has 8 children, each of which contains 1/8th of the volume of the parent node.  Here is picture to help you visualize it:
http://en.wikipedia.org/wiki/Octree
If you're doing N dimensional intersection tests, you could generalize this to an N tree.
Intersection algorithms work by starting at the top of the tree and recursively traversing into any child nodes that intersect the object being tested, at some point you get to leaf nodes, which contain the actual objects.


q: I would like to have some suggestions about which third-part controls can we use in our Visual C++ MFC application?

[A]
If you don't mind paying, there's FarPoint Spread:
http://www.componentsource.com/selec/products/farpoint-spread/summary.html


q: What is the best/fastest way to sort Alphanumeric fields?

[A]
You will find that most development libraries ship with an implementation of the quicksort algorithm, which is often the fastest sorting algorithm.  Check out the
Wikipedia link here
.


q:
In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).

Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?

Edit to add: Thanks for the great answers. But what if you're not using locks; what if you're using barriers for example? Or code that uses primitives such as compare-and-swap to directly and atomically modify a shared variable...

[A]
Volatile means that we have to go to memory to get or set this value. If you don't set volatile, the compiled code might store the data in a register for a long time.
What this means is that you should mark variables that you share between threads as volatile so that you don't have situations where one thread starts modifying the value but doesn't write its result before a second thread comes along and tries to read the value.
Volatile is a compiler hint that disables certain optimizations. The output assembly of the compiler might have been safe without it but you should always use it for shared values.
This is especially important if you are NOT using the expensive thread sync objects provided by your system - you might for example have a data structure where you can keep it valid with a series of atomic changes. Many stacks that do not allocate memory are examples of such data structures, because you can add a value to the stack then move the end pointer or remove a value from the stack after moving the end pointer. When implementing such a structure, volatile becomes crucial to ensure that your atomic instructions are actually atomic.


q: If I am given a MemoryStream that I know has been populated with a String, how do I get a String back out?

[A]
use a
StreamReader
, then you can use the
ReadToEnd
method that returns a string.


q:
My employer just asked me to run a timed batch process in a Java EE WebSphere application they have running. It's supposed to run a certain class at 11:30 pm everyday.

I'm not very familiar with Java EE nor WebSphere server (or tomcat, in the development environment), and I've been digging around but all I've found is about the java timer class but not how to set it or invoke it.

It seems that editing the web.xml file is required as well.

Any help will be appreciated!

[A]
You should look at the open-source
Quartz library
from OpenSymphony. Very easy to use and perfect for this kind of thing.
TimerTasks are best suited for running something in a short time in the future. But for a repeated execution in a large timeframe such as this, Quartz excels. You can even keep your list of upcoming tasks in persistent storage such as a file or database, so upcoming timed jobs are not lost if your application is restarted.
Also, there's a fantastic abstraction for Quartz in the Spring framework.


q: I am just getting started with flex and am using the SDK (not Flex Builder). I was wondering what's the best way to compile a mxml file from an ant build script.

[A]
The Flex SDK ships with a set of ant tasks. More info at:
http://livedocs.adobe.com/flex/3/html/help.html?content=anttasks_1.html
Here is an example of compiling Flex SWCs with ant:
http://www.mikechambers.com/blog/2006/05/19/example-using-ant-with-compc-to-compile-swcs/
mike chambers


q: The two connection limit can be particularly troublesome when you have multiple tabs open simultaneously.  Besides "ignore the problem," what coping mechanisms have you seen used to get multiple tabs both doing heavily interactive Ajax despite the two connection limit?

[A]
The two connection limit is a "suggestion" and this
article
describes how to get around it where possible.  Other Firefox configuration is discussed on this about the
about:config
capability in Firefox.
Also, if you own the website, you can tweak the performance of the site using suggestions form this
book
from the Chief Performance Yahoo.


q:
I installed both the Delphi 2009 trial and actual release via the web installer when I received them and experienced the same errors when installing both.

Both times it appears that the core web installer failed when it went to spawn the additional install packages for boost, documentation and dbtools.  (It brought up a findfile dialog asking for a setup.msi that didn't exist on my machine).  When cancelling out of this, the installer reported a fatal error.

The uninstaller did not appear in my program list, and would did not launch from the installation folder.

Future attempts to bring up the installer had it in a state where it thought Delphi 2009 was already installed and it wouldn't correct or repair or uninstall it.

[A]
The problems seem to originate with the web installer not having all the files needed.
Download the 2009 ISO:
http://cc.codegear.com/item/26049
Mounted it using this free tool from Microsoft:
http://download.microsoft.com/download/7/b/6/7b6abd84-7841-4978-96f5-bd58df02efa2/winxpvirtualcdcontrolpanel_21.exe
(You can burn it to a DVD too)
Then reran the installer.  At this point, both the repair and uninstall worked.


q: How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.

[A]
Use sub references, and closures. A good perlish example of this
```
```
sort { lc($a) cmp lc($b) } @items
```
```


q:
What are some reasons why PHP would force errors to show, no matter what you tell it to disable?

I have tried

error_reporting(0);
ini_set('display_errors', 0);

with no luck.

[A]
Note the caveat in the manual at
http://uk.php.net/error_reporting
:
Most of E_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error_reporting is enhanced to include E_STRICT errors (and vice versa).
If your underlying system is configured to report E_STRICT errors, these may be output before your code is even considered. Don't forget, error_reporting/ini_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects.
Based on your comment that your error is...
Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public_html/dev.php on line 11
Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered.
Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place...
php_value error_reporting 0
in a .htaccess file to suppress them all, but this is system configuration dependent.
Pragmatically, don't write files with syntax errors :)


q:
I'm toying with my first remoting project and I need to create a RemotableType DLL. I know I can compile it by hand with csc, but I wonder if there are some facilities in place on Visual Studio to handle the Remoting case, or, more specificly, to tell it that a specific file should be compiled as a .dll without having to add another project to a solution exclusively to compile a class or two into DLLs.

NOTE: I know I should toy with my first WCF project, but this has to run on 2.0.


q:
I've been running into a peculiar issue with certain Java applications in the HP-UX environment.

The heap is set to -mx512, yet, looking at the memory regions for this java process using gpm, it shows it using upwards of 1.6GBs of RSS memory, with 1.1GB allocated to the DATA region.  Grows quite rapidly over a 24-48hour period and then slows down substantially, still growing 2MB every few hours. However, the Java heap shows no sign of leakage.

Curious how this was possible I researched a bit and found this HP write-up on memory leaks in java heap and c heap: http://docs.hp.com/en/JAVAPERFTUNE/Memory-Management.pdf

My question is what determines what is ran in the C heap vs the java heap, and for things that do not run through the java heap, how would you identify those objects being run on the C heap? Additionally does the java heap sit inside the C heap?

[A]
My only guess with the figures you have given is a memory leak in the Java VM.  You might want to try one of the other VMs they listed in the paper you referred.  Another (much more difficult) alternative might be to compile the open java on the HP platform.
Sun's Java isn't 100% open yet, they are working on it, but I believe that there is one in sourceforge that is.
Java also thrashes memory by the way.  Sometimes it confuses OS memory management a little (you see it when windows runs out of memory and asks Java to free some up, Java touches all it's objects causing them to be loaded in from the swapfile, windows screams in agony and dies), but I don't think that's what you are seeing.


q:
Our application commonly used an ActiveX control to download and install our client on IE (XP and prior), however as our user base has drifted towards more Vista boxes with "Protected Mode" on, we are required to investigate.

So going forward, is it worth the headache of trying to use the protected mode API?  Is this going to result in a deluge of dialog boxes and admin rights to do the things our app needs to do (write to some local file places, access some other applications, etc)?

I'm half bent on just adding a non-browser based installer app that will do the dirty work of downloading and installing the client, if need be... this would only need to be installed once and in large corporate structures it could be pushed out by IT.

Are there some other ideas I'm missing?

[A]
Have you checked out Microsoft's
ClickOnce Deployment
?
If I remember correctly you can embed a manifests which would help with dealing with protected modes automatically, saving you those headaches with the APIs.
I believe ClickOnce is geared for the same thing your ActiveX installer was designed to do.
Since you say your IT dept could push this out, I assume you could use this kind of technology as well.
Even though you might not be writing applications on the .NET CLR, you can use Visual Studio to generate those manifest and installers for you.


q:
I would like to replicate this in python:

gvimdiff <(hg cat file.txt) file.txt

(hg cat file.txt outputs the most recently committed version of file.txt)

I know how to pipe the file to gvimdiff, but it won't accept another file:

$ hg cat file.txt | gvimdiff file.txt -
Too many edit arguments: "-"

Getting to the python part...

# hgdiff.py
import subprocess
import sys
file = sys.argv[1]
subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file])

When subprocess is called it merely passes <(hg cat file) onto gvimdiff as a filename.

So, is there any way to redirect a command as bash does?
For simplicity's sake just cat a file and redirect it to diff:

diff <(cat file.txt) file.txt

[A]
There is also the commands module:
```
```
import commands

status, output = commands.getstatusoutput("gvimdiff <(hg cat file.txt) file.txt")
```
```
There is also the popen set of functions, if you want to actually grok the data from a command as it is running.


q: How to create a DOM from a User's input in PHP5?

[A]
I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object with
```
```
$dom = new DOMDocument();
$dom->loadXML($xml);
```
```
Manipulate it with the rest of the DOM API, defined at
http://uk.php.net/DOM


q:
What are the steps to estimating using function points?

Is there a quick-reference guide of some sort out there?

[A]
I took a conference session on Function Point Analysis a few years back.  There is a lot too it.  You can check out the
Free Function Point Training Manual
online, the
Fundamentals of Function Points
, or I suspect you can get a book on it at a computer store.
You might also check out the
International Function Point Users Group
and see if they have some resources or a local meeting for you.


q:
How can I find out the date a MS SQL Server 2000 object was last modified?

I need to get a list of all the views, procs, functions etc that were modified since Aug 15th.  In sysObjects I can see the date objects were created but I need to know when they were last altered.

NB: this is an SQL 2000 database.

[A]
Note that SQL Server actually does
not
record the last modification date. It does not exist in any system tables.
The Schema Changes History report is actually constructed from the
Default Trace
. Since many admins (and web hosts) turn that off, it may not work for you.
Buck Woody had a good explanation of how this report works
here
. The data is also temporary.
For this reason, you should never RELY on the Schema Changes History report. Alternatives:
Use
DDL Triggers
to log all schema modification to a table of your choosing.
Enforce a protocol where views and procs are never altered, they are only dropped and recreated. This means the created date will also be the last updated date (this does not work with tables obviously).
Vigilantly version your SQL objects and schema in source control.
--
Edit: saw that this is SQL 2000. That rules out Default Trace and DDL Triggers. You're left with one of the more tedious options I listed above.


q: Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?

[A]
I suppose you could step through the string and check if there are any
```
.
```
characters in it.  That's just the first thing that popped into my head though, so I'm sure there are other (better) ways to be more certain.


q:
I'd like to be able to open a TDataSet asynchronously in its own thread so that the main VCL thread can continue until that's done, and then have the main VCL thread read from that TDataSet afterwards. I've done some experimenting and have gotten into some very weird situations, so I'm wondering if anyone has done this before.

I've seen some sample apps where a TDataSet is created in a separate thread, it's opened and then data is read from it, but that's all done in the separate thread. I'm wondering if it's safe to read from the TDataSet from the main VCL thread after the other thread opens the data source.

I'm doing Win32 programming in Delphi 7, using TmySQLQuery from DAC for MySQL as my TDataSet descendant.

[A]
I have seen it done with other implementations of TDataSet, namely in the
Asta
components.  These would contact the server, return immediately, and then fire an event once the data had been loaded.
However, I believe it depends very much on the component.  For example, those same Asta components could not be opened in a synchronous manner from anything other than the main VCL thread.
So in short, I don't believe it is a limitation of TDataSet per se, but rather something that is implementation specific, and I don't have access to the components you've mentioned.


q: How can I get a ASP.NET (inc MVC) application talking to a Flex UI over AMF.  I am wanting to push approx 100+ records around at a time and AMF would appear to be the way forward, but there doesn't appear to be anything obvious.

[A]
If you're pressed for time, you can just use the RemoteObject to hit a compiled DLL  (like WebORB - its free for .NET, but you need a VS copy above Express to compile your classes that you want to expose to Flex)
and Retrieve the object that way...
Obviously your objects should have a DAL in place or be generated so you can communicate with your database.
But i suggest using Cairngorm for any data intensive Flex application. It isn't simple and development won't feel as fast, but once you understand it, things go alot smoother and it just feels right. I could go into the details, but there are people that are much smarter than I am that have already explained it, in depth. Someone like yourself should be able to grasp the concepts pretty quickly.
here are the links to learning WebORB and Cairngorm:
weborb :
http://www.themidnightcoders.com/weborb/
cairngorm :
http://opensource.adobe.com/wiki/display/cairngorm/Cairngorm
learning Cairngorm :
http://www.adobe.com/devnet/flex/articles/cairngorm_pt1.html


q:
I'm looking for a good 3D Mesh library

Should be able to read popular formats (OFF, OBJ...)

Should support both half-edge structure and a triangle soup

Should be tolerant to faults and illegal meshes.

Basic geometric operations - intersections, normal calculation, etc'

Most importantly - Should not be convoluted with endless template and inheritance hierarchies.

I've tried both CGAL and OpenMesh but both fail miserably in the last point.

Specifically CGAL which is impossible to follow even with the most advanced code analysis tools.

So far I'm seriously considering to pull my own.

My preference is C++ but I'm open to other options.

[A]
May I ask why the last point is a requirement?
Libraries written for public consumption are designed to be as generic as possible so that it is usable by the widest possible audience.  In C++, this is often best done using templates.  It would suck tremendously if found a good library, only to discover it was useless for your purposes because it used floats instead of doubles.
CGAL, for example, appears to have adopted the well-known and well-tested STL paradigm of writing generic and extensible C++ libraries.  This does indeed make it difficult to follow with code analysis tools; I doubt they're much good at following STL headers either.
But are you trying to use the library or modify it?  Either way, they seem to have some extremely high-quality documentation (e.g.
Kernel Manual
) that should make it relatively simple to figure out what you need to do, without having to resort to reading their code.
Disclaimer:  I know this isn't what you're asking for.  But I don't think what you're looking for exists.  It is
extraordinarily
rare to find open source code with documentation as good as what I've seen scanning through CGAL.  I would strongly suggest that you take another look at it.


q:
I'm using KVM to run a Windows virtual machine on my Linux box. Networking is accomplished through a tap device, hooked into a bridged Ethernet device, which allows the Windows VM to basically appear like a separate physical computer on my network. This is pretty nice.

However, my understanding is that most, if not all, wireless drivers can't support bridging. I'd really like to be able to roam a little more freely while I'm working -- does anyone know of an effective workaround?

User-mode networking won't work, as I have to use some Windows VPN software that wants lower-level networking access.

[A]
I assume that you could configure your Windows guest to use the host as its default gateway, and set up NAT via the wireless interface on the host. So the signal flow would look like this:
Windows software opens connections to a host on the internets.
Windows routes the packet via the default gateway, i.e. the host Linux system.
Linux does NAT magic and routes the packet via its normal routing table (which should use a default gateway via the wireless interface).
I have never tried this in combination with bridging though.


q: Does any know of a good calendar (not datepicker, but a BIG browsable calendar) plugin for one of the major javascript frameworks.  I'd prefer jQuery.

[A]
You might want to send the guys at
jCalendar
a note. They were working on a Google Calendar-like jQuery plugin.  Project seems to have moved on, but they may be able to point you in the right direction.
From their site:
Coming soon will be v1.0, which will allow for not only visually selecting dates but also for displaying them in both mini and full page calendar views, similar to that of Google Calendar.


q: How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.

[A]
The following function should do the trick:
```
```
Function SetLandscape()
   Application.Printer.Orientation = acPRORLandscape
End Function
```
```
Should be able to call this from the autoexec function to ensure it always runs.


q:
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?

I have code that looks something like this:

class DownloadThread:
    def foo(self):
        pass

class DownloadManager():
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadThread())

But now I'm wondering if there's a situation where nesting would be better. Something like:

class DownloadManager():
    class DownloadThread:
        def foo(self):
            pass
    def __init__(self):
        dwld_threads = []
    def create_new_thread():
        dwld_threads.append(DownloadManager.DownloadThread())

[A]
You might want to do this when the "inner" class is a one-off, which will never be used outside the
definition
of the outer class. For example to use a metaclass, it's sometimes handy to do
```
```
class Foo(object):
    class __metaclass__(type):
        ....
```
```
instead of defining a metaclass separately, if you're only using it once.
The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together:
```
```
class Group(object):
    class cls1(object):
       ...

    class cls2(object):
       ...
```
```
Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.


q: Is there an effective tool to convert C# code to Java code?

[A]
They don't convert directly, but it allows for interoperability between .NET and J2EE.
http://www.mainsoft.com/products/index.aspx


q: How do you use gen_udp in Erlang to do multicasting? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.

[A]
Multicast is specified by IP Address
It's the same in erlang as for all languages.  The IP addresses 224.0.0.0 through 239.255.255.255 are multicast addresses.
Pick an address in that range, check that you're not overlapping an already assigned address, and you are good to go.
http://www.iana.org/assignments/multicast-addresses


q:
In SQL Server 2005, a snapshot of a database can be created that allows read-only access to a database, even when the database is in "recovery pending" mode.   One use case for this capability is in creating a reporting database that references a copy of a production database, which is kept current through log-shipping.

In this scenario, how can I implement security on the "snapshot" database that is different from the "production" source database?

For example, in the production database, all access to data is through stored procedures, while in the snapshot database users are allowed to select from table in the database for reporting purposes.    The problem the I see is that security for the snapshot database is inherited from the source database, and can not be changed because snapshots are strictly read-only.

[A]
Are you able to manage permissions on this database?  Would adding a separate user who only has read access to a database be sufficient for this type of scenario?  This could be a read-only user on the main database, but is only effectively used on the snapshot db.
i.e. Add a new user, readerMan5000 who is only given select access, to the database in question.  Then require users to authenticate through that new credential.
Note to future commenters, you may want to read:
http://www.simple-talk.com/sql/database-administration/sql-server-2005-snapshots/
or
http://msdn.microsoft.com/en-us/library/ms187054(SQL.90).aspx
before you open your big mouth like me. :)


q:
ASP.NET 1.1 - I have a DataGrid on an ASPX page that is databound and displays a value within a textbox. The user is able to change this value, then click on a button where the code behind basically iterates through each DataGridItem in the grid, does a FindControl for the ID of the textbox then assigns the .Text value to a variable which is then used to update the database. The DataGrid is rebound with the new values.

The issue I'm having is that when assigning the .Text value to the variable, the value being retrieved is the original databound value and not the newly entered user value. Any ideas as to what may be causing this behaviour?

Code sample:

foreach(DataGridItem dgi in exGrid.Items)
{
    TextBox Text1 = (TextBox)dgi.FindControl("TextID");
    string exValue = Text1.Text; //This is retrieving the original bound value not the newly entered value
    // do stuff with the new value
}


q:
I have an image (mx) and i want to get the uint of the pixel that was clicked.

Any ideas?

[A]
A few minutes on the
BitmapData LiveDoc Page
will take you where you need to go.  Once you have your image loaded into a Bitmap variable, you can access its BitmapData property.  Add a
Mouse Click Event
Listener to the image and then use
BitmapData::getPixel
.  The example for getPixel shows how to convert the uint response to an rgb hex code.
Here's a modification of the Example given on the BitmapData page that worked for me (using mxmlc - YMMV):
```
```
package {
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.display.Loader;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.net.URLRequest;

    public class BitmapDataExample extends Sprite {
        private var url:String = "santa-drunk1.jpg";
        private var size:uint = 200;
        private var image:Bitmap;

        public function BitmapDataExample() {
            configureAssets();
        }

        private function configureAssets():void {
            var loader:Loader = new Loader();
            loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);

            var request:URLRequest = new URLRequest(url);
            loader.load(request);
            addChild(loader);
        }

        private function completeHandler(event:Event):void {
            var loader:Loader = Loader(event.target.loader);
            this.image = Bitmap(loader.content);

            this.addEventListener(MouseEvent.CLICK, this.clickListener);
        }

        private function clickListener(event:MouseEvent):void {
            var pixelValue:uint = this.image.bitmapData.getPixel(event.localX, event.localY)
            trace(pixelValue.toString(16));
        }
    }
}
```
```


q: What is the difference between publishing a website with visual studio and just copying the files over to the server?  Is the only difference that the publish files are pre-compiled?

[A]
I believe you are correct in your assumption. It has been my experience that the only difference is that published files are compiled.
Visual Studio® 2008 Web Deployment Projects
is a nice enhancement for customizing your build scripts for both your Websites and Web Applications.


q:
I have an xslt sheet with some text similar to below:

<xsl:text>I am some text, and I want to be bold</xsl:text>

I would like some text to be bold, but this doesn't work.

<xsl:text>I am some text, and I want to be <strong>bold<strong></xsl:text>

The deprecated b tag doesn't work either. How do I format text within an xsl:text tag?

[A]
Try this:
```
```
<fo:inline font-weight="bold"><xsl:text>Bold text</xsl:text></fo:inline>
```
```
XSL-FO Tutoria: Inline Text
Formatting
XSL-FO inline Object


q:
More specifically I am trying to make the mailto component show within my template; the same way as an article does.

By default the mailto component opens in a new window. So far I changed the code so it opens on the same window, but that way the whole template is gone.

Any suggestions?

[A]
I'm afraid I can't entirely follow your question - do you want to have a sign up form for membership or email notifications shown as an article? If so, then the easiest way is to install 'm2c' - the 'module to component' component. Then you can put any module (ie the sign up box) in the centre content area.
The m2c component can be found here:
http://joomla.focalizaisso.com.br/en/componentes/index.php


q:
What is the single most effective practice to prevent arithmetic overflow and underflow?

Some examples that come to mind are:

testing based on valid input ranges

validation using formal methods

use of invariants

detection at runtime using language features or libraries (this does not prevent it)

[A]
One possibility is to use a language that has arbitrarily sized integers that never overflow / underflow.
Otherwise, if this is something you're really concerned about, and if your language allows it, write a wrapper class that acts like an integer, but checks every operation for overflow.  You could even have it do the check on debug builds, and leave things optimized for release builds.  In a language like C++, you could do this, and it would behave almost exactly like an integer for release builds, but for debug builds you'd get full run-time checking.
```
```
class CheckedInt
{
private:
    int Value;

public:
    // Constructor
    CheckedInt(int src) : Value(src) {}

    // Conversions back to int
    operator int&() { return Value; }
    operator const int &() const { return Value; }

    // Operators
    CheckedInt operator+(CheckedInt rhs) const
    {
        if (rhs.Value < 0 && rhs.Value + Value > Value)
            throw OverflowException();
        if (rhs.Value > 0 && rhs.Value + Value < Value)
            throw OverflowException();
        return CheckedInt(rhs.Value + Value);
    }

    // Lots more operators...
};
```
```
Edit:
Turns out someone is
doing this already for C++
- the current implementation is focused for Visual Studio, but it looks like they're getting support for gcc as well.


q:
I have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email.

It is working for me, except sometimes the rule fails and Outlook deactivates it.

Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day.

I would love to fix this once and for all.

[A]
have written a message handler function in Outlook's Visual Basic (we're using Outlook 2003 and Exchange Server) to help me sort out incoming email. It is working for me, except sometimes the rule fails and Outlook deactivates it. Then I turn the rule back on and manually run it on my Inbox to catch up. The rule spontaneously fails and deactivates several times a day. I would love to fix this once and for all.
Here is the code stripped of the functionality, but giving you an idea of how it looks:
```
```
Public WithEvents myOlItems As Outlook.Items

   Public Sub Application_Startup()
       ' Reference the items in the Inbox. Because myOlItems is declared
       ' "WithEvents" the ItemAdd event will fire below.
       ' Set myOlItems = Outlook.Session.GetDefaultFolder(olFolderInbox).Items
       Set myOlItems = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox).Items
   End Sub

   Private Sub myOlItems_ItemAdd(ByVal Item As Object)
       On Error Resume Next
       If TypeName(Item) = "MailItem" Then
           MyMessageHandler Item
       End If
   End Sub

   Public Sub MyMessageHandler(ByRef Item As MailItem)
       Dim strSender As String
       Dim strSubject As String

       If TypeName(Item) <> "MailItem" Then
           Exit Sub
       End If

       strSender = LCase(Item.SenderEmailAddress)
       strSubject = Item.Subject

       rem do stuff
       rem do stuff
       rem do stuff
   End Sub
```
```
One error I get is "Type Mismatch" calling MyMessageHandler where VB complains that Item is not a MailItem. Okay, but TypeName(Item) returns "MailItem", so how come Item is not a MailItem?
Another one I get is where an email with an empty subject comes along. The line
```
```
strSubject = Item.Subject
```
```
gives me an error. I know Item.Subject should be blank, but why is that an error?
Thanks.


q:
I have the following HTML <select> element:

<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>

Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?

[A]
You can use this function:
```
```
function selectElement(id, valueToSelect) {
    let element = document.getElementById(id);
    element.value = valueToSelect;
}

selectElement('leaveCode', '11');
```
```
```
```
<select id="leaveCode" name="leaveCode">
  <option value="10">Annual Leave</option>
  <option value="11">Medical Leave</option>
  <option value="14">Long Service</option>
  <option value="17">Leave Without Pay</option>
</select>
```
```
Optionally if you want to trigger onchange event also, you can use :
```
```
element.dispatchEvent(new Event('change'))
```
```


q:
I've written a control that inherits from the System.Web.UI.WebControls.DropDownList and so I don't have any code in front for this control, but I still want to set the OutputCache directive.  I there any way to set this in the C# code, say with an attribute or something like that?

I'm particularly hoping to be able to replicate the VaryByParam property

[A]
```
```
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);
```
```