Question:
I'm doing some small changes to C++ MFC project. I'm .NET developer so Windows programming is new to me.

I need to launch some method right after CDialog is completely shown (painted) for the first time, but only once.

How can I do this? In .NET I would handle Form.Shown event.

Do I need to handle some message? Which?
Do I need to override some CDialog method?
Or is there no easy way? I'm thinking of handling WM_ACTIVATE and then using a flag to ensure I call another method only once.

Answer:
Found the answer here:
Waiting until the dialog box is displayed before doing something
```
```
Short story:
INT_PTR CALLBACK
DlgProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
  switch (uiMsg) {

  case WM_INITDIALOG:
    return TRUE;

  case WM_WINDOWPOSCHANGED:
    if ((((WINDOWPOS*)lParam)->flags & SWP_SHOWWINDOW) &&
        !g_fShown) {
      g_fShown = TRUE;
      PostMessage(hwnd, WM_APP, 0, 0);
    }
    break;

  case WM_APP:
      MessageBox(hwnd,
                 IsWindowVisible(hwnd) ? TEXT("Visible")
                                       : TEXT("Not Visible"),
                 TEXT("Title"), MB_OK);
      break;

  case WM_CLOSE:
   EndDialog(hwnd, 0);
   break;
  }

  return FALSE;
}
```
```
If you're using MFC like I am you'll need to map WM_WINDOWPOSCHANGED and then use ON_MESSAGE to map WM_APP. See
this CodeProject article
for more details.


Question: How can we find out that how many applications are there in a database?

Answer: Do you mean stored procedures? You can have multiple applications using the same login credentials accessing a given database from the same web server, so you can't simply count databases or tables to get that number.


Question:
There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:

Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.

Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.

What are the benefits, costs, and consequences of each? Are there other alternatives?

I see this debate come up on a regular basis, but I don't think it's been asked on
Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it.

Answer:
The difference is typically expressed as the difference between "is a" and "has a". Inheritance, the "is a" relationship, is summed up nicely in the
Liskov Substitution Principle
. Aggregation, the "has a" relationship, is just that - it shows that the aggregating object
has
one of the aggregated objects.
Further distinctions exist as well - private inheritance in C++ indicates a "is implemented in terms of" relationship, which can also be modeled by the aggregation of (non-exposed) member objects as well.


Question: Why is the generic.list slower than array?

Answer:
A generic list is slightly slower than an array, but not so you'd notice in most cases.  Mostly it has to do with the lookup being slightly more complex: List is said to use an array "under the hood", but it's not not guaranteed to keep nodes in adjacent memory in the same way in array is.
However, I saw some benchmarks way back in 2005 (can't find the link now) and difference is
very
small.
Also, the list has a number of important advantages over an array: mainly that it's trivial to add or remove items.  It's much easier to use a list when you don't know how many items you will need, or when that number will vary.  In those cases (and honestly, that's
most of the time
), you probably should
not
use an array.


Question: I want to work with versioned ActiveRecord associations. E.g., I want to find the object that another object belongs_to as of a certain past date, or the one that it belonged to before that. Does there already exist a library subclassing Rails' ActiveRecord to provide versioned relations? Or some other Ruby library which provides persistable versioned relations?

Answer:
Supporting historical state in a transactional application is a good way to massively expand complexity, slow DB performance and make life difficult for yourself.  If you only need to display or report on historical state and do not need it up to the minute consider building a star schema with
Type-II slowly changing dimensions
and  a periodic process that updates it.
This will be substantially less complex than building an application with systemic ad-hoc history tracking running through the code base.  If this approach will do what you require of the application you will probably be better off doing it.  It also means that the application database will play nicely with the vanilla database access mechanisms that come with the system.
If you need reasonably frequent refresh you can implement a changed-data capture system on the database, which is relatively simple if the application only has to be concerned with current state.  With a CDC mechanism the load process only has to update based on changes and will run relatively quickly.


Question:
I've got a Page class in my .edmx ADO.NET Entity Data Model file with with Parent and Children properties.  It's for a hierarchy of Pages.

removed dead ImageShack link - ADO.NET Entity Framework Hierarchical Page Class

This is handled in my SQL database with a ParentId foreign key in the Page table bound to the Id primary key of that same Page table.

How do I display this hierarchy in a WPF TreeView?

Answer:
I got this working with help from
Abe Heidebrecht
.  Much thanks to him.
Here's my XAML...
```
```
<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:PageManager"
    Title="Window1" Height="300" Width="300" Name="Window1">
    <Grid>
        <TreeView Margin="12" Name="TreeViewPages" ItemsSource="{Binding}" TreeViewItem.Expanded="TreeViewPages_Expanded">
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:Page}" ItemsSource="{Binding Children}">
                    <TextBlock Text="{Binding Path=ShortTitle}" />
                </HierarchicalDataTemplate>
            </TreeView.Resources>
        </TreeView>
    </Grid>
</Window>
```
```
Here's my Visual Basic code...
```
```
Class Window1

    Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
        Dim db As New PageEntities
        Dim RootPage = From p In db.Page.Include("Children") _
                       Where (p.Parent Is Nothing) _
                       Select p
        TreeViewPages.ItemsSource = RootPage
    End Sub

    Private Sub TreeViewPages_Expanded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim ExpandedTreeViewItem As TreeViewItem = DirectCast(e.OriginalSource, TreeViewItem)
        Dim PageId As Guid = DirectCast(ExpandedTreeViewItem.DataContext, Page).Id
        Dim db As New PageEntities
        Dim ChildPages = From p In db.Page.Include("Children") _
                         Where p.Parent.Id = PageId _
                         Select p
        ExpandedTreeViewItem.ItemsSource = ChildPages
    End Sub
End Class
```
```
When the window loads, the root node and its children are queried from the database and inserted into the tree.
Each time a node is expanded, that node's children and grandchildren are queried from the database and inserted into the tree.


Question:
With the jQuery datepicker, how does one change the year range that is displayed?  On the jQuery UI site it says the default is "10 years before and after the current year are shown".  I want to use this for a birthday selection and 10 years before today is no good.  Can this be done with the jQuery datepicker or will I have to use a different solution?

link to datepicker demo: http://jqueryui.com/demos/datepicker/#dropdown-month-year

Answer:
If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "
```
Year dropdown shows last 20 years
```
" demo , and hit view source:
```
```
$("#restricting").datepicker({
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both",
    buttonImage: "templates/images/calendar.gif",
    buttonImageOnly: true
});
```
```
You'll want to do the same (obviously changing
```
-20
```
to
```
-100
```
or something).


Question:
In Python map() works on any data that follows the sequence protocol.  It does The Right Thing^TM whether I feed it a string or a list or even a tuple.

Can't I have my cake in OCaml too?  Do I really have no other choice but to look at the collection type I'm using and find a corresponding List.map or an Array.map or a Buffer.map or a String.map?  Some of these don't even exist!  Is what I'm asking for unusual?  I must be missing something.

Answer:
The closest you will get to this is the module
```
Enum
```
in
OCaml Batteries Included
(formerly of
Extlib
).
```
Enum
```
defines maps and folds over
```
Enum.t
```
; you just have to use a conversion to/from
```
Enum.t
```
for your datatype. The conversions can be fairly light-weight, because
```
Enum.t
```
is lazy.
What you really want is Haskell-style
type classes
, like
```
Foldable
```
and
```
Functor
```
(which generalizes "maps"). The Haskell libraries define instances of
```
Foldable
```
and
```
Functor
```
for lists, arrays, and trees. Another relevant technique is the
"Scrap Your Boilerplate" approach
to generic programming. Since OCaml doesn't support type classes or
higher-kinded polymorphism
, I don't think you'd be able to express patterns like these in its type system.


Question: What combination of CSS or attributes are needed?

Answer:
Hide the actual control
Made a DIV with the controls and styling you want on top of it
The button is not a standard HTML control.
See:
http://www.quirksmode.org/dom/inputfile.html


Question:
I'm looking to convert a small .NET console application into a Windows Service.  I'd like to build two versions, one using .NET 2.0 and another with .NET 3.5 .

Are there radically different approaches that need to be taken, or will the 2.0 version be roughly equivalent to the 3.5 version?  Where's a good source of information (i.e. a web-based guide) that can walk me through the steps of setting up the service?

Thanks!
P.A.

Answer:
The thing to remember is that .NET 3.5 is a set of additional libraries on top of .NET 2.0, so, unless you are planning on taking advantage of any additional features provided by .NET 3.5 (or .NET 3.0) like LINQ or WCF the code would be identical.
Try looking at the documentation for
ServiceBase
, which is the base class that you will need to inherit, to get things started.


Question:
I've got an MS access database and I would need to create an SQL query that allows me to select all the not distinct entries in one column while still keeping all the values.

In this case more than ever an example is worth thousands of words:

Table:

A B C
1 x q
2 y w
3 y e
4 z r
5 z t
6 z y

SQL magic

Result:

B C
y w
y e
z r
z t
z y

Basically it removes all unique values of column B but keeps the multiple rows of the
data kept. I can "group by b" and then "count>1" to get the not distinct but the result will only list one row of B not the 2 or more that I need.

Any help?

Thanks.

Answer:
```
```
select
  *
from
  my_table t1,
  my_table t2
where
  t1.B = t2.B
and
  t1.C != t2.C

-- apparently you need to use <> instead of != in Access
-- Thanks, Dave!
```
```
Something like that?


Question:
I am rather new to complex CSS, and have a question- I have a page which positions a floating element along the bottom of the page. It does so by setting the Bottom: 0, and Position: Absolute.

When the user resizes their browser to a very-small size, this element covers up other content on the page.

Ideally, The element would continue to float at the bottom of the browser at normal and large sizes, but if the browser window were to be shrunk too small, the browser would force a scrollbar, instead of moving the floating element any further.

Essentially, I want to tell the browser- No matter how small the window is, never render the page smaller than 800x600.

Answer:
You could set
```
html, body { min-width: 800px; min-height: 600px; }
```
YMMV in different browsers though.


Question:
I want to alert the user in a Swing application of certain events with an old fashioned PC Speaker beep (NOT the soundcard), since not on every PC there is a soundcard with an attached speaker, or volume might be turned to zero, or a headphone might be connected... How can I do this?

UPDATE:
java.awt.Toolkit.getDefaultToolkit().beep() seems usually to generate a sound on the soundcard. It only uses the speaker if there is no active soundcard.
To print an ASCII value 7 works only if the application is launched in a terminal, which at least a Swing app usually isn't.
So the question is still open.

Answer:
```
Toolkit.getDefaultToolkit().beep();
```


Question: I am trying to use a malloc hook to create a custom function my_malloc(). In my main program when I call malloc() I want it to call my_malloc() can someone please give me an example on how to do this in C

Answer:
```
```
#undef malloc
#define malloc my_malloc
```
```
Just put that at the top of any of the files you need to do it for.


Question:
Either for comparisons or initialization of a new variable, does it make a difference which one of these you use?

I know that BigDecimal.ZERO is a 1.5 feature, so that's a concern, but assuming I'm using 1.5 does it matter?

Thanks.

Answer:
```
BigDecimal.ZERO
```
is a predefined constant and therefore doesn't have to be evaluated from a string at runtime as
```
BigDecimal("0")
```
would be. It will be faster and won't require creation of a new object.
If your code needs to run on pre-1.5, then you can use the (much maligned) Singleton pattern to create an object equivalent to
```
BigDecimal.ZERO
```
. The first time it is used, it would call
```
BigDecimal("0")
```
to create a zero object, and return that object on subsequent calls. Otherwise, if your code is running on a 1.5 system, your singleton object can just return
```
BigDecimal.ZERO
```
with no runtime penalty.


Question:
As a web developer, a number of the projects I work on fall under government umbrellas and hence are subject to 508 Accessibility laws, and sometimes W3C accessibility guidelines. To what extent can Flash be used while still meeting these requirements?

For using javascript, the mantra is "Degrade gracefully" by providing the same content and function, just on different pages, or in a less interactive/dynamic way. This allows non-javascript browsers/users still use the site, as well as allowing search engine bots to access all of the content. Users of screen reading software, such as JAWS and Orca also are still able to fully use the site.

With flash, is there a similar way to gracefully fall back for non-flash users? If not, how accessible is flash-based content to search engine bots? And also, how do screen readers handle flash-based content?

Answer:
I'm visually impaired to the point where I use magnification tools and TTS for convenience but not as a necessity. I can tell you that Flash just doesn't work with the majority of accessibility tools out there.  I believe JAWS (the market leader for Windows but not overwhelmingly dominant by any means) says it has Flash support, but most Flash developers don't seem to put in the work necessary to allow JAWS to grok the textual content of the Flash movie.  And many visually impaired users just don't even have flash installed because for 95%+ of the time it's simply useless to them.
Another consideration is that the built-in Text-to-speech that Mac OS X provides also can't do anything with most Flash movies.
IMO 'degrading' or offering a link to an HTML version of your content is probably the only practical means of ensuring your site is accessible.  If you are starting from scratch I would strongly consider JavaScript / JQuery over Flash if at all possible.


Question:
I have a clock feature in a VB.NET program that displays the time including the seconds. I currently have a timer constantly polling using NOW. I have to poll the system clock quite often because I need to have the second update in sync with the system clock.

Is there a more direct to access the time only when the seconds change?

Is there a more efficient way to write this code?

If you need more info let me know.

Answer:
Why not use the timer component?  This assumes that you are using a GUI and not building a service.
You could call a synchronization routine that performed the polling to get the timer very close to the seconds changing, then delegate to the timer.  You could call the sync routine once a minute or so to make sure that you aren't getting any OS drift.
That being said, I'm sure there is a way to detect the seconds changing event, I just don't know how to do it.
Update:
This link
has an implementation similar to what I was envisioning.  Just modify it so that you are not permanently stuck in a loop and voila!  You have your sync routine.
Update 2:
Based on feedback from Shog9, I think this might be a better approach than polling:
```
```
Public Class Form1
   Private WithEvents clockTimer As New Timer
   Private currentTime As DateTime = DateTime.MinValue

   Private Sub ClockTick(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles clockTimer.Tick

      UpdateTimer()
      DisplayTimer()
   End Sub

   Private Sub UpdateTimer()
      currentTime = DateTime.Now

      clockTimer.Stop()
      clockTimer.Interval = 1000 - currentTime.Millisecond
      clockTimer.Start()
   End Sub

   Private Sub DisplayTimer()
      lblTime.Text = currentTime.ToString("T")
   End Sub

   Private Sub Form1_Load(ByVal sender As System.Object, _
      ByVal e As System.EventArgs) Handles MyBase.Load

      UpdateTimer()
      DisplayTimer()
   End Sub
End Class
```
```
Now, based on my preliminary tests, there is some sort of drift with each Tick event.  On my machine, it varied between 12 and 20 milliseconds.  If anyone has an idea on how to reliably correct the drift, I would be interested in learning.


Question:
I have an app with the following basic architecture:

A windows service (Service) that registers a .NET type (RemoteObject) for remote access (.NET Remoting). RemoteObject creates non-ThreadPool threads that use the ThreadPool to do IO processing. The size of the ThreadPool must be restricted to a limit  for a particular reason. A GUI app uses .NET Remoting to access RemoteObject.

I've noticed that if the size of the ThreadPool is too low, the GUI app will hang when making a call to RemoteObject.

My question is, how can I figure out why this is hanging, and why would the RemoteObject thread be affected by the ThreadPool?

This is driving me crazy; thank you for your help!

Answer:
This may not be exceptionally helpful but I will toss it out there anyways.
When debugging services and clients that talk through remoting, I will usually always run two instances of the debugger: one for the client and one for the service.  Just to be clear, I am running two copies of visual studio.  For the service you can use the attach command or you can alter the main and call start directly (bypassing all the service code).
Here is how I typically enable debugging by altering the main, you'll have to and the DebugService call to the service, it really is just a entry point that calls start.  Once I have this I just enable service debug by definine
```
SERVICE_DEBUG
```
or changing the
```
#if
```
by adding a '
```
!'
```
.  Now you basically have converted your service to a console app.
```
```
#if SERVICE_DEBUG
            ServiceHost s = new ServiceHost();
            s.DebugService();
            Thread.Sleep( 300000000 );

#else
            ServiceBase.Run( ServicesToRun );
#endif
```
```
Once you have both setup and running you can step through the client, when the remoting calls hit the service you can step through the service code, allowing you to debug both at the same time.
Out of curiosity
are you calling the remote object directly from the GUI thread?  If so, the GUI thread will block until the remoting call completes.  This will lock up the whole GUI and make it unresponsive.  This isn't the solution to the problem, but if it is the case and your service thread isn't returning, it'll cause the GUI to hang as well.


Question: According to Wikipedia when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round(-3.5) returns -3. Can someone please explain this?

Answer:
According to the
javadoc
Returns the closest long to the
  argument. The result is rounded to an
  integer by adding 1/2, taking the
  floor of the result, and casting the
  result to type long. In other words,
  the result is equal to the value of
  the expression:
```
(long)Math.floor(a + 0.5d)
```
Conceptually, you round
up
. In other words, to the next integer
greater
than the value and -3 is greater than -3.5, while -4 is less.


Question:
I'm setting up a solution to deploy, driven by a batch file so it's reproducible
- I've got a binding file that works but I've now added on my MSMQ adapters
- works on my local machine, but I've found I have to add a userid and password to get it to work on the actual server
   - it's in the domain, my virtual dev machine is just workgroup

Is there someway to add the userid and password to the file ?
  - seems unlikely as that'd have the password in clear text, but what's the solution
  - I sort of think something w.r.t. SSO, but that is an area I've not been near

Answer:
For security reasons, when you export
  bindings, BizTalk Server removes the
  passwords for the bindings from the
  file. After importing the bindings,
  you must reconfigure passwords for
  send ports and receive locations
  before they will function. You
  configure passwords in the Transport
  Properties dialog box of the BizTalk
  Server Administration console for the
  send port or receive location. For
  instructions, see How to Create a Send
  Port. See also How to Create a Receive
  Location.
From
http://msdn.microsoft.com/en-us/library/aa558708.aspx
If you however open the biding file and scroll down to the line with the properties for the MSMQ Adapter you'll find the empty nodes. All you then have to do is to fill these out and the right values and they will be used the next time you import the binding file.
Of course you'll have to remember to redo this every time you export a new binding ...


Question:
I am using a custom item renderer in a combobox to display a custom drawing instead of the default text label.

This works fine for the dropdown list but the displayed item ( when the list is closed) is still the textual representation of my object.

Is there a way to have the displayed item rendered the same way as the one in the dropdown?

Answer:
By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.
```
```
package
{
    import mx.controls.ComboBox;
    import mx.core.UIComponent;

    public class ComboBox2 extends ComboBox
    {
        public function ComboBox2()
        {
            super();
        }

        protected var textInputReplacement:UIComponent;

        override protected function createChildren():void {
            super.createChildren();

            if ( !textInputReplacement ) {
                if ( itemRenderer != null ) {
                    //remove the default textInput
                    removeChild(textInput);

                    //create a new itemRenderer to use in place of the text input
                    textInputReplacement = itemRenderer.newInstance();
                    addChild(textInputReplacement);
                }
            }
        }

        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            if ( textInputReplacement ) {
                textInputReplacement.width = unscaledWidth;
                textInputReplacement.height = unscaledHeight;
            }
        }
    }
}
```
```


Question:
I've got a solution which I setup / cleanup using batch files ...
- there are a pair of MSMQ ports, send and receive, with another application on the end of the queues

I'm finding I can't properly stop the orchestration in the batch file ... the error is the send port is unenlisted
 - I'm using the StopOrch.vbs script from the SDK samples

But I can go into BizTalk Admin Console and manually stop the orchestration with Full Terminate Ok

The setup / cleanup works Ok if I don't actually push any messages down the MSMQ queues

Answer:
By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.
```
```
package
{
    import mx.controls.ComboBox;
    import mx.core.UIComponent;

    public class ComboBox2 extends ComboBox
    {
        public function ComboBox2()
        {
            super();
        }

        protected var textInputReplacement:UIComponent;

        override protected function createChildren():void {
            super.createChildren();

            if ( !textInputReplacement ) {
                if ( itemRenderer != null ) {
                    //remove the default textInput
                    removeChild(textInput);

                    //create a new itemRenderer to use in place of the text input
                    textInputReplacement = itemRenderer.newInstance();
                    addChild(textInputReplacement);
                }
            }
        }

        override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
            super.updateDisplayList(unscaledWidth, unscaledHeight);

            if ( textInputReplacement ) {
                textInputReplacement.width = unscaledWidth;
                textInputReplacement.height = unscaledHeight;
            }
        }
    }
}
```
```


Question:
How can I deploy a custom authentication provider in MOSS 2007?

Is there any provided functionality to do this (like a Sharepoint feature)?

Or do I have to install it in the GAC on each box in the farm manually?

Answer:
The usual approach for installing extensions like this is to use a feature, yes. However, you won't be using any specialized XML as this kind of extension is not catered for explicitly. So how can you do it? By using an essentially empty feature project that contains an Event Receiver assembly. The event receiver assembly is called automatically by sharepoint for 4 different events: install, uninstall, activate and deactivate. I suggest you hook the install and uninstall events to deploy your provider.
http://msdn.microsoft.com/en-us/library/bb862634.aspx
Make sense?
-Oisin


Question:
There are all sorts of advantages to using Emacs, but for someone comfortable with the usual Win32 applications it comes with a wall-like learning curve. With most other editors it’s possible to just start using them and then learn about their other features and enhancements as you go along.

How to just get on with using Emacs straight away, with the aim of reaching that point where you actually prefer to use Emacs over other editors or applications?

Edit - To try and clarify the question: I’ve done the tutorial, read some docs, etc. then soon after when I’ve wanted to quickly edit some text it’s been easier to just use another editor, that I already know. What do I need to do so that not only I don’t just go for another easier editor, but that I actually prefer to use Emacs, and how to get here as quickly as possible? What if any are the training wheels for Emacs?

Answer:
spend 20 minutes running the tutorial
ctrl-h t
That will get you to the point where you can be productive (and that "meta" key that you will read about is probably either Escape or alt).


Question:
So odd situation that I ran into today with OrderBy:

Func<SomeClass, int> orderByNumber =
  currentClass =>
   currentClass.SomeNumber;

Then:

someCollection.OrderBy(orderByNumber);

This is fine, but I was going to create a method instead because it might be usable somewhere else other than an orderBy.

private int ReturnNumber(SomeClass currentClass)
{
  return currentClass.SomeNumber;
}

Now when I try to plug that into the OrderBy:

someCollection.OrderBy(ReturnNumber);

It can't infer the type like it can if I use a Func.  Seems like to me they should be the same since the method itself is "strongly typed" like the Func.

Side Note: I realize I can do this:

Func<SomeClass, int> orderByNumber = ReturnNumber;

Answer:
I believe you still have to enable the tooltip, even though you are replacing the builtin.
```
```
EnableToolTips(TRUE);
```
```
Well, since that did not work for you and since no-one more expert has offered any help, here a few more suggestions from me.  Although they are lame, they might get you moving again:
Make sure your OnCreate() rotine is actually being executed.
Enable the tool tip BEFORE you replace it.
The code I use to do this looks like this. ( I confess I do not understand all the details, I copied it from some sample code, it worked and so I never looked at it any more. )
// Enable the standard tooltip
EnableToolTips(TRUE);
// Disable the builtin tooltip
CToolTipCtrl* pToolTipCtrl = (CToolTipCtrl*)CWnd::FromHandle((HWND)::SendMessage(m_hWnd, LVM_GETTOOLTIPS, 0, 0L));


Question:
If I do this:

// In header
class Foo {
void foo(bar*);
};

// In cpp
void Foo::foo(bar* const pBar) {
//Stuff
}

The compiler does not complain that the signatures for Foo::foo do not match. However if I had:

void foo(const bar*); //In header
void Foo::foo(bar*) {} //In cpp

The code will fail to compile.

What is going on?
I'm using gcc 4.1.x

Answer:
In the first, you've promised the compiler, but not other users of the class that you will not edit the variable.
In your second example, you've promised other users of the class that you will not edit their variable, but failed to uphold that promise.
I should also note that there is a distinct difference between
```
```
bar* const variable
```
```
and
```
```
const bar* variable
```
```
and
```
```
const bar* const variable
```
```
In the first form, the pointer will never change, but you can edit the object that is pointed to.  In the second form, you can edit the pointer(point it to another object), but never the variable that it points to.  In the final form, you will neither edit the pointer, nor the object it points to.
Reference
To add a bit more of a clarification to the question stated, you can always promise MORE const than less.  Given a class:
```
```
class Foo {
    void func1 (int x);
    void func2 (int *x);
}
```
```
You can compile the following implementation:
```
```
Foo::func1(const int x) {}
Foo::func2(const int *x) {}
```
```
or:
```
```
Foo::func1(const int x) {}
Foo::func2(const int* const x) {}
```
```
without any problems.  You've told your users that you may possibly edit their variables.  In your implementation, you've told the compiler that this particular implementation will not edit those variables, even though the told the users you might.  You haven't broken a promise to the user, and so the code compiles.


Question:
As already discussed in "Lua as a general-purpose scripting language?" Lua currently probably isn't the best scripting language for the desktop environment.

But what do you think about the future? Will Lua get so popular that there will soon be enough libraries to be able to use it like Python, Ruby or something similar?

Or will it simply stay in it's WoW niche and that's it?

Answer:
I really like it as an embedded language. It's small, very easy to use and embed and mostly does what I need right out of the box. It's also similar enough to most languages that it has never really been an issue for me. I also like how easy it is to redefine and add base functions and keywords to the language to suit whatever needs my application has.
I have used it in the WoW area but I've also found it useful as a generic scripting language for a number of different applications I've worked on, including as a type of database trigger. I like Ruby and Python and other more full-featured scripting languages but they're not nearly as convenient for embedding in small applications to give users more options for customizing their environments.


Question:
I wrote a managed C++ class that has the following function:

void EndPointsMappingWrapper::GetLastError(char* strErrorMessage)
{
    strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer();
}

As you can see, this is a simple method to copy the managed string of the last error to the unmanaged world (char*).

From my unmanaged class I call the method like this:

char err[1000];
ofer->GetLastError(err);

Putting a breakpoint at the managed C++ method shows that the string is successfully translated into the char*. However, once I return to the unmanaged class, the content of err[1000] is lost and it's empty again.

Answer:
We use the following C++ Class to do the conversions for us and it works fine. You should be able to modify your method to use it.
H File
```
```
public ref class  ManagedStringConverter
{
public:
  ManagedStringConverter( System::String^ pString );
  ~ManagedStringConverter();

  property char* PrimitiveString
  {
     char* get() { return m_pString; }
  }

  /// <summary>
  /// Converts a System::String to a char * string.  You must release this with FreeString.
  /// </summary>
  static const char* StringToChar( System::String^ str );

  /// <summary>
  /// Converts a System::String to a __wchar_t * string.  You must release this with FreeString.
  /// </summary>
  static const __wchar_t * StringToWChar( System::String^ str );

  /// <summary>
  /// Frees memory allocated in StringToChar()
  /// </summary>
  static void FreeString( const char * pszStr );

private:
  char* m_pString;
};
```
```
CPP File
```
```
ManagedStringConverter::ManagedStringConverter( System::String^ pString )
{
  m_pString = const_cast<char*>( ManagedStringConverter::StringToChar( pString ) );
}

ManagedStringConverter::~ManagedStringConverter()
{
  ManagedStringConverter::FreeString( m_pString );
}

// static
const char * ManagedStringConverter::StringToChar( System::String^ str )
{
  IntPtr^ ip = Marshal::StringToHGlobalAnsi( str );
  if ( ip != IntPtr::Zero )
  {
     return reinterpret_cast<const char *>( ip->ToPointer() );
  }
  else
  {
     return nullptr;
  }
}

// static
const __wchar_t * ManagedStringConverter::StringToWChar( System::String^ str )
{
  IntPtr^ ip = Marshal::StringToHGlobalUni( str );
  if ( ip != IntPtr::Zero )
  {
     return reinterpret_cast<const __wchar_t *>( ip->ToPointer() );
  }
  else
  {
     return nullptr;
  }
}

// static
void ManagedStringConverter::FreeString( const char * pszStr )
{
  IntPtr ip = IntPtr( (void *)pszStr );
  Marshal::FreeHGlobal( ip );
}
```
```


Question: Is there a way to run a one-liner in sas, or do I have to create a file?  I'm looking for something like the -e flag in perl.

Answer:
Never having used sas, what I might try is something like:
```
```
echo <insert sas code here> | sas --execute-file -
```
```
Oftentimes applications will let you specify '-' as a file to have it read from STDIN. And 'echo' just prints its arguments out, and the | connects them together.


Question:
I'm constructing a simple form in ERB but the HTML produced by the text_field tag makes the for attribute in the label tag invalid.

<div>
  <p><%= label_tag "email[name]", "Name" %></p>
  <%= text_field :email, :name, :class => "text_field" %>
</div>

Produces the HTML

<div>
  <p><label for="email[name]">Name</label></p>
  <input class="text_field" id="email_name" name="email[name]" size="30" type="text" />
</div>

Which results in the error

character "[" is not allowed in the
  value of attribute "for".

How do I generate the text with without the nested parameter name email[name] to change the label tag for attribute? Is there an alternative approach that produces valid HTML?

Answer:
Never having used sas, what I might try is something like:
```
```
echo <insert sas code here> | sas --execute-file -
```
```
Oftentimes applications will let you specify '-' as a file to have it read from STDIN. And 'echo' just prints its arguments out, and the | connects them together.


Question: Does anyone have any strategies/tips/traps for moving to Team System? Should it be done in baby steps, or all at once? Should we migrate our SourceSafe library over, or draw a line in the sand and move forward? Is it worth brining SharePoint into the mix? Any thoughts are appreciated.

Answer:
I've never had to migrate to TFS, but have used it pretty extensively for the past couple of years.
Regarding your question on Sharepoint, we've found it pretty useful in conjunction with TFS. We use it primarily for documentation management and for storing other "non-technical" artifacts related to the project. Some dev teams advocate keeping documentation in source control alongside source code, which is OK, but in my experience our project stakeholders have an easier time accessing relevent project documentation via the Sharepoint portal than they would having to interface with source control.
I basically was able to distribute the URL to the sharepoint site associated with our TFS team project to the concerned non-technical team members and have been able to avoid constantly e-mailing documents around, so it's been great for us.


Question: I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?

Answer:
If a thread has to be able to execute some bit of code (usually in the form of a delegate) posted to it by another thread, it will have to basically be waiting for those instructions. What else is your main thread doing? It's not that hard to build an equivalent of the event loop (basically you'd have a producer/consumer queue of delegates) but you need to be aware that you can't just interrupt the main thread and say "do this now".
Why does this have to execute on the main thread?


Question:
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)

Class ReportClass
{
 public string ReportName {get; set;}
}

Then it was used as follows in code:

displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())

That is about the simplest form example I can give you.
Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?

EDIT: I'm referring to the inplace assignment. Which I wasn't aware of until today

Answer:
Seems fine to me. It is probably compiled with C# 3.0 and that allows
C# automatic properties
.


Question: I'm writing a small agent in java that will play a game against other agents. I want to keep a small amount of state (probably approx. 1kb at most) around between runs of the program so that I can try to tweak the performance of the agent based upon past successes. Essentially, I will be reading a small amount of data at the beginning of each game and writing a small amount at the end. It seems like I have 2 options, file I/O or derby. Is there a speed advantage to either? Or does it not really matter for such a small amount of data?

Answer:
Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark.  Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).
Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit.  Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.
But since it's a small amount of data, I would say it won't matter.


Question:
I have to pass parameters between two rails apps. In one side (sender) I have an array of hashes. I have a code like the following to send the data:

   http = Net::HTTP.new('localhost', '3030')
   result = http.post('/processar_lotes', my_array_of_hashes)

Some questions

Is there any (kind of) serialize or something like this that I can pass to the other app?

At the other side, how can I de-serialize the information?

Is there a limit to the size of what I pass as a parameter?

Answer:
Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark.  Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).
Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit.  Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.
But since it's a small amount of data, I would say it won't matter.


Question:
I am trying to create a report in SSRS2000 that will query an ORACLE database and pass one parameter, I am getting the following error message:

ORA-01036: illegal variable name/number
But have been unable to find much help elsewhere on the web with this error code

I was hoping that this would be fairly simple to do, does anyone have any idea how to accomplish this task?

Answer:
Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark.  Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).
Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit.  Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.
But since it's a small amount of data, I would say it won't matter.


Question:
I've read a bunch of tutorials involving XNA (and it's various versions) and I still am a little confused on drawing primitives.  Everything seems to be really convoluted.

Can someone show me, using code, the simplest XNA implementation of drawing one or two lines on to the screen?  Perhaps with a brief explanation (including the boilerplate)?

I'm not a games programmer and I have little XNA experience.  My ultimate goal is to draw some lines onto the screen which I will eventually transform with rotations, etc (by hand).  However, for this first step.. I need to simply draw the lines!  I remember back in my ancient OpenGL days it was fairly straightforward when drawing a line with a few method calls.  Should I simply revert to using unmanaged directx calls?

Answer:
When working with XNA, everything (even 2d primitives) have to be expressed in a way that a 3d card can understand, which means that a line is just a set of vertices.
MSDN has a pretty good walkthrough here:
http://msdn.microsoft.com/en-us/library/bb196414.aspx#ID2EEF
You'll find that it takes more code to render a primitive line than it would take to just setup a textured quad and rotate that, since in essence, your doing the same thing when rendering a line.


Question:
I have these 3 tables + data:

items: itemId, itemName

data: 1, my item one

categories: catId, catName

data: 1, my cat one. 2, my cat two

map: mapId, itemId, catId

When you include item "my item one" in category "my cat one", you insert [1, 1, 1] into the map. When you add "my item one" to "my cat two", you insert [2, 1, 2] into the map. Now let's say we change our mind and only want the item in "my cat two". This means we need to know what categories the item is no longer in and delete the associations from the map. What's the most efficient sequence of steps to take to do so? (I'm looking for a solution that will scale beyond this trivial example.)

Answer:
Assuming you've already got the category ID for "my cat two" and the item ID for "my item 1":
```
```
DELETE FROM MAP WHERE ItemID = @MyItem1Id
                AND CatID <> @MyCat2Id
```
```
If you have a set of categories you want to keep the item in, you could either:
Delete everything from the map for that item and then re-add the set
Use a query like the above but with "AND CatID NOT IN [ ... ]"


Question:
Is it possible to create an attribute that can be initialized with a variable number of arguments?

For example:

[MyCustomAttribute(new int[3,4,5])]  // this doesn't work
public MyClass ...

Answer:
Yes, but you need to initialize the array that you are passing in. Here is an example from a row test in our unit tests that tests a variable number of command line options;
```
```
[Row( new[] { "-l", "/port:13102", "-lfsw" } )]
public void MyTest( string[] args ) { //... }
```
```


Question:
I have 4 databases with similar schema's, and I'm trying to create a query to return just the table, column pairs that exist ONLY in database 1 and do not exist in database 2, 3, or 4.

Currently I can return the symmetric difference between database 1 and 2 via the following query...

select table_name, column_name from (
        select table_name, column_name from [Database1].information_schema.columns
        union all
        select table_name, column_name from [Database2].information_schema.columns) as tmp
        group by table_name, column_name having count(*) = 1

However, in trying to isolate just those columns in database 1, and doing the same across all 4 databases, things are getting complicated. What is the cleanest solution for this query?

Answer:
Yes, but you need to initialize the array that you are passing in. Here is an example from a row test in our unit tests that tests a variable number of command line options;
```
```
[Row( new[] { "-l", "/port:13102", "-lfsw" } )]
public void MyTest( string[] args ) { //... }
```
```


Question:
I know the file needs to be where the getClass().getResource(filename) can find it, but I don't know where that is.

I'm interested both in where to put the files on the filesystem itself, and how to go about using Eclipse's functionality to set up the resources.

Answer:
You can either put them in the src folder alongside your classes, or you can create a new source folder for the purpose (usually called
resources
), although you'll locate them identically from code.
Then you get at them using
```
getResource("/com/x/y/foo.png")
```
.


Question:
Let's imagine I got this:

index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php

<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>

Script.php:

Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.

Is there a way to do this?

Answer:
i may be missing something in your question, but the
```
$_POST
```
variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
```
```
print_r($_POST);

// contains:

array
(
  [1] => 1
  [24] => 2233
  [55] => 231321
)

// example access:

foreach($_POST as $name => $value) {
  print "Name: {$name} Value: {$value} <br />";
}
```
```


Question: I'm looking to update our project's jaxb version from 1 to 2.  Has anyone tried doing this on their projects and are there any tips that anyone wanting to do this?  I understand that each project is unique, I'm just looking for general tips.

Answer:
JAXB2 will generate enum classes for simpletype restrictions.  Any Java code which relies on setting string values for uses of these types will require you to use the appropriate enum instead.  I think this is great, since you get the typechecking when compiling rather than a validation warning at runtime.
JABX2 uses typed lists instead of untyped lists, so you can remove a lot of casting from your java code.
Date support is greatly improved.  IIRC, most of the date types in JAXB1 generate Calendar, whereas in JAXB2 they generate XMLGregorianCalendar.


Question:
I have a page with a GridView on it that launches a popup, using Javascript. The user then selects an item, that updates the data connected to the GridView and closes the popup.

How do I refresh the first (ie the Calling page) so that I can refresh the data shown in my Gridview?

Answer:
Try this inside your popup:
```
```
<script>
window.opener.location.reload()
</script>
```
```
That should refresh the page that opened the pop-up


Question:
I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression to calculate a fibonacci number :

var fib : Func<int32, int32>;
fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n);
fib(3);

When I run this code I get a nullreferenceexception. Any ideas as to what I'm doing wrong?

Answer:
You aren't doing anything wrong. If anything, the compiler should warn you about using fib, an unassigned variable, inside the body of the lambda.
However the compiler ought to be capturing fib as a location, so that when the assignment completes and the delegate is later invoked, fib is properly assigned and recursion should work as expected.
The most obvious possible reason for the failure is that Prism isn't capturing locations, but values, which would be grossly unintuitive and at odds with every other closure implementation in non-pure languages.
For example, try this code in JavaScript (contrary to Craig's assertion in the comments to this post, JavaScript also captures locations, not values):
```
```
<html>
<head>
<script language='javascript'>
function main()
{
    var x = 1;
    var f = function() { return x; };
    alert(f());
    x = 2;
    alert(f());
}
</script>
</head>
<body>
<input type=button onclick="javascript:main()"></input>
</body>
</html>
```
```
The alert boxes after you click on the button show 1 and 2 respectively, while following Prism/Oxygene semantics they would show 1 both times.


Question:
Related to https://stackoverflow.com/questions/139944/where-can-one-find-free-software-icons-images

I have a need for free weather-related icons. Specifically, I need icons that you might see in a ten-day forecast (clear day/night, rainy day/night, etc.)  Where might I find such images?

Requirements: Like the author of the question linked above, I would prefer to not rip anyone's intellectual property off.

Answer:
Well a quick Google for
"weather icons"
produced good results.  Or places like
deviantART
(
2nd link
) are a good bet.


Question: Using VB.NET, how do I add the values from an XML file into an SQL Server database with a similar schema?

Answer:
Well a quick Google for
"weather icons"
produced good results.  Or places like
deviantART
(
2nd link
) are a good bet.


Question:
A colleague recently asked me how to deep-clone a Map and I realized that I probably have never used the clone() method- which worries me.

What are the most common scenarios you have found where you need to clone an object?

Answer:
Most commonly, when I have to return a mutable object to a caller that I'm worried the caller might muck with, often in a thread-unfriendly way.  Lists and Date are the ones that I do this to most.  If the caller is likely to want to iterate over a List and I've got threads possibly updating it, it's safer to return a clone or copy of it.
Actually, that brings up something I'm going to have to open up another question for: copy constructors or clone?  When I did C++, we ALWAYS did a copy constructor and implemented clone with it, but FindBugs does not like it if you implement your clone using a copy constructor.


Question: I learned about Microsoft BizSpark the other day and started the sign up process.  Has anyone else heard about it or had success with it?

Answer:
I can't speak for BizSpark specifically (it's so new), but Microsoft has had the similar
Empower
program in place for 5 or so years. When our company was originally getting started, we joined the program (and participated for two years) and it was an excellent program.
The main benefit, of course, is that you get access to MSDN Subscriptions at such a low cost. Aside from that, though, it put us in touch with the local Microsoft office and gave us a clear path to working toward the typical ISV Partner relationship. You also get some technical support incidents, which are handy when/if you need to escalate an issue you're running into.
The requirements for Empower were/are pretty straightforward... basically commit to releasing a commercial software product based on the current Microsoft stack within two years.
Hope that helps... I look forward to hearing more about how BizSpark is different - or if it's simply the next evolution of Empower.


Question:
I'm implementing my app as a drag source. When I call DoDragDrop (Win32 call, not MFC) it enters into a modal loop and I don't get repaint messages in my main window until DoDragDrop returns. Unfortunately if I do a drop in the shell (a file) and the filename is already there the shell asks if I want to replace the file. But since me app is blocked because DoDragDrop  hasn't returned it isn't repainting and looks 'frozen'.

Any clues ?

Answer:
I suggest running the drag-and-drop operation on a different thread.  That way, DoDragDrop() will block the message loop in the new thread rather than the message loop in your UI thread.  If you take this approach, you should also consider (off the top of my head):
Any code that might be run from both your main thread and your drag-and-drop thread will need to be re-entrant.  As a corollary, you will need to protect any data structures used by both your main thread and your drag-and-drop thread.  If your application is already multi-threaded, you should be familiar with these concerns.
You should think about what happens if your user never responds to the shell's dialog box.  Can he continue to interact with your UI?  Can he invalidate the data that would have been 'dropped' in the pending operation?  Can he quit your application?


Question:
I'm getting this error:

javax.servlet.ServletException: bean not found within scope

on a page with this at the top.

<jsp:useBean id="bean" type="com.example.Bean" scope="request" />

The class exists in the classpath, it worked this morning, and I don't get what not found within scope means.

How is this caused and how can I solve it?

Answer:
You must add
```
```
<jsp:useBean id="givingFormBean" type="some.packg.GivingForm" scope="request" />
```
```
Because by default the bean is
looked on the
page
scope


Question: Is there a way to compile multiple java source directories in a single maven project?

Answer:
This worked for me
```
```
<build>
    <sourceDirectory>.</sourceDirectory>
    <plugins>
        <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
        <includes>
            <include>src/main/java/**/*.java</include>
            <include>src/main2/java/**/*.java</include>
        </includes>
        </configuration>
        </plugin>
    </plugins>
</build>
```
```


Question: I'm all for language diversity, but Objective C is insane. So I'm curious: is it possible to code iPhone apps with C++ while using the Cocoa API, etc?

Answer:
Short answer, yes, sort of. You can use Objective-C++, which you can read about at
Apple Developer Connection.
If you know C++ already, learning Objective-C would be pretty simple, if you decided to give that a try. More info on that topic is at the ADC as well.


Question: Can anyone please let me know the procedure to perform silent installation of SQL Server Express 2005 and the way to specify the installation parameters.

Answer:
Get the MSI and do
```
```
string InstallFile = "SSCERuntime-ENU-x86.msi"
string LogFile = "C:\Install.log"

Process proc;
proc = Process.Start("msiexec", "/l " + LogFile + " /quiet /i " + InstallFile);
```
```


Question:
I need two divs to look a bit like this:

    |               |
 ---|    LOGO       |------------------------
|   |_______________|  LINKS                |
|             CONTENT                       |

What's the neatest/most elegant way of making them overlap neatly? The logo will have a fixed height and width and will be touching the top edge of the page.

Answer:
With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:
```
```
div#logo {
  position: absolute;
  left: 100px; // or whatever
}
```
```
Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.


Question:
I have a form with a textbox and a button. IE is the only browser that will not submit the form when Enter is pressed (works in FF, Opera, Safari, Chrome, etc.).  I found this javascript function to try to coax IE into behaving; but no avail:

function checkEnter(e){
    var characterCode
    if (e && e.which) {
        e = e
        characterCode = e.which
    } else {
        e = event
        characterCode = e.keyCode
    }
    if (characterCode == 13) {
        document.forms[0].submit()
        return false
    } else {
        return true
    }
}

Implementation:

searchbox.Attributes("OnKeyUp") = "checkEnter(event)"

Any advice?

EDIT: This page on CodeProject outlines what Dillie was saying, and it works perfectly.

Answer:
```
```
// Use the following Javascript in your HTML view
// put it somewhere between <head> and </head>

    <script language="JavaScript" type="text/javascript"><!--
    function KeyDownHandler(btn)
    {
      if (event.keyCode == 13)
      {
        event.returnValue=false;
        event.cancel = true;
        btn.click();
      }
    }
    // -->
    </script>

    // Put this in your TextBox(es) aka inside <asp:textbox ... >
    onkeydown="KeyDownHandler(ButtonID)"
```
```


Question:
Can any one tell me how to convert an legacy application  which is vb6 ( COM dll's ocx and exes) to use Regfree COM .

I tried opening the dlls in visual studio and created manifest file, but some of the dlls it is giving error.

Is there any tools out there which will help me to do this process?

I tried a tool from codeproject which is called regsvr42, which is not creating the manifest fully.

I used tools like PE explorer where I get all the typelib information , but converting them into manifest files is too difficult.

We have started migrating that to .NET, for some months we have to deploy it, it will easier if it is xcopy based deployment.

Answer:
To create manifest files you can try to use Make My Manifest from
http://mmm4vb6.atom5.com/
.
EDIT
The MMM website is down. I see
here
that the author was having trouble with their hosting and has provided another location to get Make My Manifest -
download it here
.
If you can control creation of objects you can use DirectCOM from
http://www.thecommon.net/10.html
Keep in mind that if one of used DLLs or OCXs is creating other COM objects dynamically with CreateObject calls, that reference will not be stored in vbp project file and you won't get full manifest file. Probably you will have to catch object creations while the application is running. Depends.exe application can profile running application and report all used dlls. I don't know if there is tool that can find additional COM related information.


Question:
I've got an arbitrary list of .NET assemblies.

I need to programmatically check if each DLL was built for x86 (as opposed to x64 or Any CPU). Is this possible?

Answer:
You can use the
CorFlags
CLI
tool (for instance, C:\Program Files\Microsoft SDKs\Windows\v7.0\Bin\CorFlags.exe) to determine the status of an assembly, based on its output and opening an assembly as a binary asset you should be able to determine where you need to seek to determine if the 32BIT flag is set to 1 (
x86
) or 0 (
Any CPU
or
x64
, depending on
```
PE
```
):
```
```
Option    | PE    | 32BIT
----------|-------|---------
x86       | PE32  | 1
Any CPU   | PE32  | 0
x64       | PE32+ | 0
```
```
The blog post
x64 Development with .NET
has some information about
```
corflags
```
.
Even better, you can
use
```
Module.GetPEKind
```
to determine whether an assembly is
```
PortableExecutableKinds
```
value
```
PE32Plus
```
(64-bit),
```
Required32Bit
```
(32-bit and
WoW
), or
```
ILOnly
```
(any CPU) along with other attributes.


Question:
class AbstractQuery {
    virtual bool isCanBeExecuted()=0;
public:
    AbstractQuery() {}
    virtual bool Execute()=0;
};

class DropTableQuery: public AbstractQuery {
    vector< std::pair< string, string> > QueryContent;
    QueryValidate qv;
public:
    explicit DropTableQuery(const string& qr): AbstractQuery(), qv(qr) {}
    bool Execute();
};

Is it necessary to call base contructor in derived class constructor?

Answer:
No, in fact for it is unnecessary for the base class to have an explicitly defined constructor (though make sure you have a virtual destructor).
So for a typical interface you could have something like this:
```
```
class MyInterface {
public:
    virtual ~MyInterface() {}
    virtual void execute() = 0;
};
```
```
EDIT: Here's a reason why you should have a virtual destructor:
```
```
MyInterface* iface = GetMeSomeThingThatSupportsInterface();
delete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor
```
```


Question:
I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.

I am wrapping everything in this div:

#scroll {
    height:400px;
    overflow:scroll;
}

Is there a way to keep it scrolled to the bottom by default using JS?

Is there a way to keep it scrolled to the bottom after an ajax request?

Answer:
Here's what I use on my site:
```
```
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
```
```


Question:
Im having trouble using a .NET COM in vb6, It compiles ok and I use regasm to register it, add a reference to it in the vb6 project, it even has intellisense. But when I try to make make an instance it gives me an 'Automation Error'. Any one can help?

Thanks in advance.

Answer:
You probably need to make sure your .NET assemblies are in the VB6 application's directory, or if debugging in the VB6 IDE that they are in the VB6.exe's directory.
It is possible to make COM interop with .NET assemblies work more like COM dlls (see the codebase option of
regasm
) but by default, .NET assemblies are searched for in the usual way - ie in the GAC or application directory - even when used via COM interop.
A really simple way to get insight into where your assembly should be is by using sysinternals
filemon
utility.


Question:
I can use VS08's MFC/ActiveX template to create a C++ ActiveX object that I can load into a HTML page and script with Javascript. But I can't figure out how to create an interface that allows me to call custom methods on my component with Javascript.

Could you please tell me how to accomplish that? I have spent over two hours on google with no luck.

Thanks.

Answer:
I'm not extremely familiar with the MFC ActiveX wrapper, but I can answer the question in the general sense:
A COM object with an interface which is derived from IDispatch can be called through automation languages (eg: Javascript). The methods must also be "automation-compatible", which means that the parameters are convertible to the VARIANT type, or are explicitly of type VARIANT. Note that for in/out parameters, the type must be VARIANT* for the automation "hookup" to work.
I don't know how to make the ActiveX object accessible in the client script (eg: embed it into the page), but if it has a single interface derived from IDispatch, that makes it callable from Javascript (and other automation languages). I hope that helps...


Question:
We have many WIDE html grids which scroll horizontally within a DIV in our web application.

I would like to find the best strategy for printing these grids on a portrait A4 page.

What I would like to know is what is the best way to present/display grids/data like this.

This question is not HTML specific, I am looking for design strategies and not CSS @page directives.

Answer:
I guess it really depends on what your purpose is.
In a book format
: I usually try span two facing pages.
For a conference or poster
: Find an extra wide printer and print it out on a large sheet of paper.
Something more informal
: Span regular pages and tape them together.
Powerpoint
: Don't show the whole chart, they'll not be able to read the details anyways, just show the relevant information.


Question:
I'd like my .NET Compact Framework app to delete itself after it finishes executing.  What's the best way to do this?

On a Windows machine it's possible to do this using a .bat file, but that's not an option on mobile devices.

Answer:
One idea is you could use wceload:
http://msdn.microsoft.com/en-us/library/bb158700.aspx
Write a cab file that has a custom step (I think you might need to create a setup.dll) that will delete your application.
Get your application to call wceload when it exits to run this cab, passing the argument for wce load to delete the cab after it's finished running.
Not very slick I know.


Question:
How do you invoke a tkinter event from a separate object?

I'm looking for something like wxWidgets wx.CallAfter.  For example, If I create an object, and pass to it my Tk root instance, and then try to call a method of that root window from my object, my app locks up.

The best I can come up with is to use the the after method and check the status from my separate object, but that seems wasteful.

Answer:
To answer your specific question of "How do you invoke a TkInter event from a separate object", use the
```
event_generate
```
command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism.
For example:
```
```
from tkinter import *

def doFoo(*args):
    print("Hello, world")

root = Tk()
root.bind("<<Foo>>", doFoo)

# some time later, inject the "<<Foo>>" virtual event at the
# tail of the event queue
root.event_generate("<<Foo>>", when="tail")
```
```
Note that the
```
event_generate
```
call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will
freeze the GUI
.
I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code.
Here's an example of successfully accessing methods on a root window from some other object:
```
```
from tkinter import *

class myClass:
    def __init__(self, root):
        print("root background is %s" % root.cget("background"))

root = Tk()
newObj = myClass(root)
```
```


Question:
I'm looking at building basic CMS functionality into our web product and am researching tips and design ideas for versioning content. I'm specifically looking for database schemas in use today.

What are you using for content versioning? What patterns apply if you have different types of content that need versions stored? How is question versioning handled on Stack Overflow?

Thanks

Answer:
My gut instinct is that the best thing for this is (in order of bestitude):
A ready version control system.
A nice list here.
Storing diffs.
What is a diff here.
I guess the obvious database solution of having a "ContentVersion" table, where you have multiple "Versions" per unique "Content".


Question:
I've generated a pdf using iTextSharp and I can preview it very well in ASP.Net but I need to send it directly to printer without a preview. I want the user to click the print button and automatically the document prints.

I know that a page can be sent directly to printer using the javascript window.print() but I don't know how to make it for a PDF.

Edit: it is not embedded, I generate it like this;

                ...
                FileStream stream = new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create);
                Document pdf = new Document(PageSize.LETTER);
                PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
                pdf.Open();
                pdf.Add(new Paragraph(member.ToString()));
                pdf.Close();

                Response.Redirect("~1.pdf");
                ...

And here I am.

Answer:
Is the pdf embedded in the page with embedd-tag or just opened in a frame or how are you showing it?
If its embedded, just make sure that the object is selected and then do a print().
Get the ref to the embedded document.
```
```
var x = document.getElementById("mypdfembeddobject");
x.click();
x.setActive();
x.focus();
x.print();
```
```


Question: How do I access specific sections of man pages?

Answer:
Put the section number in front of the item you want to reference. For example, to access the sysctl function from the library section, you can write:
```
```
man 3 sysctl
```
```
and to access the sysctl tool from the system administrator's section, you would write:
```
```
man 8 sysctl
```
```


Question:
I have a char array buffer that I am using to store characters that the user will input one by one.  My code below works but has a few glitches that I can't figure out:

when I execute a printf to see what's in Buffer, it does fill up but I get garbage characters at the end

it won't stop at 8 characters despite being declared as char Buffer[8];

Can somebody please explain to me what is going on and perhaps how I could fix this? Thanks.

char Buffer[8]; //holds the byte stream
int i=0;

if (/* user input event has occurred */)
{
        Buffer[i] = charInput;
        i++;

        // Display a response to input
        printf("Buffer is %s!\n", Buffer);

}

Output:

tagBuffer is 1┬┬w!
tagBuffer is 12┬w!
tagBuffer is 123w!
tagBuffer is 1234!
tagBuffer is 12345!
tagBuffer is 123456=!
tagBuffer is 1234567!
tagBuffer is 12345678!

tagBuffer is 123456789!

Answer:
You have to end the string with a
```
\0
```
character. That's why they are called zero terminated strings.
It is also wise to allocate 1 extra char to hold the
```
\0
```
.


Question:
I'm checking out the Delphi 2009 Trial, but run into problems with the generics stuff right away.

The following code does not compile, and I haven't the slightest idea why it's giving me E2015 for the Equals() method:

type
  TPrimaryKey<T> = class(TObject)
  strict private
    fValue: T;
  public
    constructor Create(AValue: T);
    function Equals(Obj: TObject): boolean; override;
    function GetValue: T;
  end;

constructor TPrimaryKey<T>.Create(AValue: T);
begin
  inherited Create;
  fValue := AValue;
end;

function TPrimaryKey<T>.Equals(Obj: TObject): boolean;
begin
  Result := (Obj <> nil) and (Obj is TPrimaryKey<T>)
    and (TPrimaryKey<T>(Obj).GetValue = fValue);
end;

function TPrimaryKey<T>.GetValue: T;
begin
  Result := fValue;
end;

Why does the compiler think that fValue and the result of GetValue() can not be compared?

Answer:
You can't use operators with untyped generics. See
here
for a discussion.
It compiles if you change it to:
```
```
TPrimaryKey<T: class> = class(TObject)
```
```


Question:
In Joel's article for Inc. entitled How Hard Could It Be?: The Unproven Path, he wrote:

...it turns out that Jeff and his
  programmers were so good that they
  built a site that could serve 80,000
  visitors a day (roughly 755,000 page
  views)

How would I go about figuring out the maximum load my server(s) can handle?

Answer:
Apache has a tool called
```
ab
```
that you can use to benchmark a server. It can simulate loads requests and concurrency situations for you.


Question:
I have multiple Network Interface Cards on my computer, each with its own IP address.

When I use gethostbyname(gethostname()) from Python's (built-in) socket module, it will only return one of them.  How do I get the others?

Answer:
You should directly obtain all IP configured IP addresses, e.g. by running ifconfig and parsing its output (it's also possible to do what
ifconfig does directly in Python
,
see how it is done in C
). If you want host names, use gethostbyaddr.


Question:
I have several server processes that once in a while respond to messages from the clients and perform read-only transactions.

After about a few days that the servers are running, they stop working correctly and when I check it turns out that there's a whole bunch of messages about the connection being closed.

When I checked it out, it turned out that hibernate by default works in some sort of development mode where connections are dropped after a few hours, and I started using c3po for connection pooling.

However, even with c3po, I get that problem about 24 hours or so after the servers are started.

Has anyone encountered that problem and knows how to address it? I'm not familiar enough with the intricacies of configuring hibernate.

Answer:
The MySQL JDBC driver times out after 8 hours of inactivity and drops the connection.
You can set
```
autoReconnect=true
```
in your JDBC URL, and this causes the driver to reconnect if you try to query after it has disconnected.  But this has side effects; for instance session state and transactions cannot be maintained over a new connection.
If you use
```
autoReconnect
```
, the JDBC connection is reestablished, but it doesn't automatically re-execute your query that got the exception.  So you do need to catch
```
SQLException
```
in your application and retry queries.
Read
http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
for more details.


Question:
cmd /C "myshortcut1.lnk"
cmd /C "myshortcut2.lnk"

Works, but gives me a pop-up DOS window which, when closed, kills my two loaded programs.  Same is true for this:

start /B cmd /C "1.lnk"
start /B cmd /C "2.lnk"
start /B cmd /C "3.lnk"
start /B cmd /C "4.lnk"

Answer:
The MySQL JDBC driver times out after 8 hours of inactivity and drops the connection.
You can set
```
autoReconnect=true
```
in your JDBC URL, and this causes the driver to reconnect if you try to query after it has disconnected.  But this has side effects; for instance session state and transactions cannot be maintained over a new connection.
If you use
```
autoReconnect
```
, the JDBC connection is reestablished, but it doesn't automatically re-execute your query that got the exception.  So you do need to catch
```
SQLException
```
in your application and retry queries.
Read
http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html
for more details.


Question:
So we are sure that we will be taking our product internationally and will eventually need to internationalize it. How much internationalizing would you recommend we do as we go along?

I guess in other words, is there any internationalization that is easy now but can be much worse if we let the code base mature and that won't slow us down very much if we choose to start doing it now?

Tech used: C#, WPF, WinForms

Answer:
Prepare it now, before you write all the strings in the codebase itself.
Everything after now will be too late. It's now or never!
It's true that it is a bit of extra effort to prepare well now, but not doing it will end up being a lot more expensive.
If you won't follow all the guidelines in the links below, at least heed points 1,2 and 7 of the summary which are very cheap to do now and which cause the most pain afterwards in my experience.
Check these guidelines and see for yourself why it's better to start now and get everything prepared.
Developing world ready applications
Best practices for developing world ready applications
Little extract:
Move all localizable resources to separate resource-only DLLs. Localizable resources include user interface elements such as strings, error messages, dialog boxes, menus, and embedded object resources.
(Moving the resources to a DLL afterwards will be a pain)
Do not hardcode strings or user interface resources.
(If you don't prepare, you know you will hardcode strings)
Do not put nonlocalizable resources into the resource-only DLLs. This causes confusion for translators.
Do not use composite strings that are built at run time from concatenated phrases. Composite strings are difficult to localize because they often assume an English grammatical order that does not apply to all languages.
(After the interface design, changing phrases gets harder)
Avoid ambiguous constructs such as "Empty Folder" where the strings can be translated differently depending on the grammatical roles of the strings' components. For example, "empty" can be either a verb or an adjective, and this can lead to different translations in languages such as Italian or French.
(Same issue)
Avoid using images and icons that contain text in your application. They are expensive to localize.
(Use text rendered over the image)
Allow plenty of room for the length of strings to expand in the user interface. In some languages, phrases can require 50-75 percent more space.
(Same issue, if you don't plan for it now, redesign is more expensive)
Use the System.Resources.ResourceManager class to retrieve resources based on culture.
Use Microsoft Visual Studio .NET to create Windows Forms dialog boxes, so they can be localized using the Windows Forms Resource Editor (Winres.exe). Do not code Windows Forms dialog boxes by hand.


Question:
I have a DataTrigger defined in my XAML which I want to use in several places. Is it possible to define it as a resource and then share it?

Here's my trigger:

<TextBlock.Style>
    <Style>
        <Style.Triggers>
            <DataTrigger Binding="{Binding HasCurrentTest}" Value="True">
                <Setter Property="TextBlock.Visibility" Value="Hidden" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</TextBlock.Style>

While I can define this in my Window.Resources and give it a key, how do I refer to it in the rest of my XAML?

Answer:
If the style is in the Windows.Resources with a key, each element can add it to their own style like this.
```
```
<Window.Resources>
    <Style x:Key="YourStyleKey">
        <!-- Your Style -->
    </Style>
</Window.Resources>

<TextBox Text="SomeText" Style="{StaticResource YourStyleKey}"/>
<TextBox Text="SomeOtherText" Style="{StaticResource YourStyleKey}"/>
```
```


Question: I've been doing some socket programming to transmit information across the wire.  I've run into a problem with DataOutputStream.writeUTF().  It seems to allow strings of up to 64k but I have a few situations where I can run over this.  Are there any good alternatives that support larger strings or do I need to roll my own?

Answer:
You should be able to use
OutputStreamWriter
with the UTF-8 encoding.  There's no explicit writeUTF method, but you can set the charset in the constructor.  Try
```
```
Writer osw = new OutputStreamWriter(out, "UTF-8");
```
```
where
```
out
```
is whatever OutputStream you're wrapping now.


Question:
This fails:

my @a = ("a", "b", "c", "d", "e");
my %h = map { "prefix-$_" => 1 } @a;

with this error:

Not enough arguments for map at foo.pl line 4, near "} @a"

but this works:

my @a = ("a", "b", "c", "d", "e");
my %h = map { "prefix-" . $_ => 1 } @a;

why?

Answer:
Because Perl is guessing an EXPR (a hash reference, for example) instead of a BLOCK. This should work (note the '+' symbol):
```
```
my @a = ("a", "b", "c", "d", "e");
my %h = map { +"prefix-$_" => 1 } @a;
```
```
See
http://perldoc.perl.org/functions/map.html
.


Question: I know it is a good practice to declare virtual destructors for base classes in C++, but is it always important to declare virtual destructors even for abstract classes that function as interfaces? Please provide some reasons and examples why.

Answer:
It's even more important for an interface. Any user of your class will probably hold a pointer to the interface, not a pointer to the concrete implementation. When they come to delete it, if the destructor is non-virtual, they will call the interface's destructor (or the compiler-provided default, if you didn't specify one), not the derived class's destructor. Instant memory leak.
For example
```
```
class Interface
{
   virtual void doSomething() = 0;
};

class Derived : public Interface
{
   Derived();
   ~Derived()
   {
      // Do some important cleanup...
   }
};

void myFunc(void)
{
   Interface* p = new Derived();
   // The behaviour of the next line is undefined. It probably
   // calls Interface::~Interface, not Derived::~Derived
   delete p;
}
```
```


Question:
I would like to create a batch script, to go through 20,000 links in a DB, and weed out all the 404s and such. How would I get the HTTP status code for a remote url?

Preferably not using curl, since I dont have it installed.

Answer:
CURL would be perfect but since you don't have it, you'll have to get down and dirty with sockets. The technique is:
Open a socket to the server.
Send an HTTP HEAD request.
Parse the response.
Here is a quick example:
```
```
<?php

$url = parse_url('http://www.example.com/index.html');

$host = $url['host'];
$port = $url['port'];
$path = $url['path'];
$query = $url['query'];
if(!$port)
    $port = 80;

$request = "HEAD $path?$query HTTP/1.1\r\n"
          ."Host: $host\r\n"
          ."Connection: close\r\n"
          ."\r\n";

$address = gethostbyname($host);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $address, $port);

socket_write($socket, $request, strlen($request));

$response = split(' ', socket_read($socket, 1024));

print "
Response: ". $response[1] ."
\r\n";

socket_close($socket);

?>
```
```
UPDATE: I've added a few lines to parse the URL


Question:
I am looking for an example of how to do the following in VB.net with Parallel Extensions.

Dim T As Thread = New Thread(AddressOf functiontodowork)
T1.Start(InputValueforWork)

Where I'm getting stuck is on how to pass into the task my parameter InputValueforWork

Dim T As Tasks.Task = Tasks.Task.Create(AddressOf functiontodowork)

Any suggests and possibly a coding example would be welcome.

Andrew

Answer:
Not necessarily the most helpful answer I know, but in C# you could do this with a closure:
```
```
var T = Tasks.Task.Create( () => functionToDoWork(SomeParameter) )
```
```


Question:
I've been reading a text about an extension to C# and at one point it says that "An attribute decoration X may only be applied to fields of type Y."

I haven't been able to find a definition for attribute decoration, and I'm not making much sense out of this by exchanging the two.

Answer:
Not necessarily the most helpful answer I know, but in C# you could do this with a closure:
```
```
var T = Tasks.Task.Create( () => functionToDoWork(SomeParameter) )
```
```


Question:
We have a .NET web service API. Currently, people use the SOAP definition to consume the API, because we require authentication through a custom Authentication element in the SOAP header. Works perfectly. fine.

SOAP requires the request to be a POST. We want to allow the users to use a the GET verb (so it can be cacheable).

So, what's the best way to offer a simple GET API (doesn't have to be a webservice!) that also offers authentication?

example API route:

http://www.blah.com/api/Search?query=Foo

Is this an acceptable and common practice?

http://www.blah.com/api/Search?query=Foo&Key=<some guid>

NOTE: I also don't want to implement SSL nor install extra software or plugins in IIS, etc. etc.

Answer:
If the web service needs to be secured, and I'm assuming that it does since you currently have an Authentication header, then you should reconsider using GET and not using SSL, at least for the authentication piece.  At a minimum I would POST the authorization request via SSL to the web service/application.  If you don't want to provide authentication on every request, then you will need to accept back (and generate in the service) an authorization cookie that the consumer can use for subsequent requests.
I would avoid using authentication in the URL for exactly the reason that you want to support GET -- if the URL can be cached, then the credentials will be cached as well.  This breaks the security of the web service since anyone can reuse the cached credentials.


Question: What is a doubly linked list's remove method?

Answer:
The general algorithm is as follows:
Find the node to remove.
node.previous.next = node.next
node.next.previous = node.previous
node.previous = null
node.next = null
Dispose of node if you're in a non-GC environment
You have to check the previous and next nodes for null to see if you're removing the head or the tail, but those are the easy cases.


Question: I have a migration in Rails that inserts a record into the database. The Category model depends on this record. Since RSpec clears the database before each example, this record is lost and furthermore never seems to be created since RSpec does not seem to generate the  database from migrations. What is the best way to create/recreate this record in the database? Would it be using before(:all)?

Answer:
It's not that RSpec clears the database, it's that Rails's rake:db:prepare task copies the
schema
(but not the contents) of your dev database into your *_test db.
Yes, you can use
```
before(:all)
```
, as transactions are wrapped around each individual example - but a simple fixture file would also do the same job.
(There's a more complicated general solution to this issue: moving to a service-oriented architecture, where your 'dev' and 'test' services are going to be completely separate instances.  You can then point your test db config to the development database in your test service, disable rake:db:prepare, and build your test service from migrations as you regenerate it.  Then you can test your migrations and data transformations.)


Question:
I'm pretty new to the C++ build flow, and I'm thinking of switching to use partial linking for my libraries instead of creating ar archives. I'm hoping to reduce link time in an inevitable final compilation step that I have, and I figure partial linking some libraries once could save me time over linking everything in that final step.

Is what I'm describing possible? I figure it should be something along the lines ld -Ur -o mylib.o [components]. Are there important build considerations that I'm not taking into account?

Answer:
You lose an important effect of having the object files in an
```
ar
```
archive, which is that only the referenced objects will be linked in.
If you have both
```
foo.o
```
with the symbol
```
foo
```
and bar.o with the symbol
```
bar
```
in an
```
ar
```
archive, and only reference the
```
foo
```
symbol, only
```
foo.o
```
would be linked in. If you instead do a partial link, the contents of both will end up in the executable, even if
```
bar
```
is never referenced anywhere.
You could also try a faster linker, like
gold
.


Question:
I'm looking for an open-source web search library that does not use a search index file.
Do you know any?

Thanks,
Kenneth

Answer:
The original poster clarified in a comment to this reply that what he is looking for is essentially "greplike search but through HTTP", and mentioned that he is looking for something that uses little disk as he's working with an embedded system.
I am not aware of any related projects, but you might want to look at html parsers and xquery implementations in your language of choice. You should be able to take care of "real-life" messiness of html with the former, and write a search that's almost as detailed as you might desire with the latter.
I assume that you will be working with a set of urls that will either be provided, or already stored locally, since the idea of actually crawling the whole web, discovering links, etc, in an embedded device is thoroughly unrealistic.
Although with a good html/xquery implementation, you do have the tools to extract all the links..
My original answer, which was really a request for clarification
:
Not sure what you mean.  How do you picture a search working without an index? Crawling the web for every query? Piping through to google?  Or are you referring to a specific kind of search index file that you are trying to avoid?


Question:
I've recently seen occasional problems with stored procedures on a legacy system which displays error messages like this:

Server Message:  Number  10901, Severity 17:
  This query requires X auxiliary scan
  descriptors but currently there are
  only Y auxiliary scan descriptors
  available. Either raise the value of
  the 'number of aux scan descriptors'
  configuration parameter or try your
  query later.

where X is slightly lower than Y. The Sybase manual usefully tells me that I should redesign my table to use less auxiliary scan descriptors (how?!), or increase the number available on the system. The weird thing is, it's been working fine for years and the only thing that's changed is that we amended the data types of a couple of columns and added an index. Can anyone shed any light on this?

Answer:
You don't say what version of Sybase you are on but the following is good for ASE 12.5 onwards.
I suspect that it's the addition of the new index that's thrown out the query plan for that stored procedure. Have you tried running
```
```
update statistics *table_name*
```
```
on it? If that fails you can find out how many scan descriptors you have by running
```
```
sp_monitorconfig "aux scan descriptors"
```
```
and then increase that by running
```
```
sp_configure "aux scan descriptors", x
```
```
where x is the number of scan descriptors you require.
If you wish to reduce the number of scan descriptors that the store procedure is using then according to
here
you have to
Rewrite the query, or break it into steps using temporary tables. For data-only-locked tables, consider adding indexes if there are many table scans.
but without seeing a query plan it's impossible to give more specific advice.


Question:
My application needs to store the users email address in a cookie so that I can pre-populate a login form (username == email address). I set the cookie value in JavaScript. If I read it from JavaScript, I get foo@bar.com. If I look at it in the cookie viewer in Firefox I get foo@bar.com.

When I try to read it on the server-side in Java however, I only get foo.

Do I need to do some sort of encoding/decoding here? If so, how do I do it in a way that can be decoded by both JavaScript and Java?

Thanks in advance!
-Michael

Answer:
You need to escape the value part of your cookie.
```
```
document.cookie = name + "=" +escape( value )
    + ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" )
    + ( ( path ) ? ";path=" + path : "" )
    + ( ( domain ) ? ";domain=" + domain : "" )
    + ( ( secure ) ? ";secure" : "" );
```
```


Question:
I would like to to try Emacs, and want to give it the best chance possible.

To do this, it seems like having a good .emacs file is important.

I primarily use Mac OS X (so I have looked at Aquamacs), and I mainly do Python programming, so anything specifically for that would be great.

Answer:
The most important configuration change that I have found is not one for your .emacs, but for your OS.  In the "Keyboard & Mouse" system preferences, in the "Keyboard" tab, click "Modifier Keys..." at the bottom and then change "Caps Lock" to behave like "Control."  Then train yourself to use the caps lock key (to the left of the "A") instead of the control key down in the corner.  This will make the whole experience both far more productive and far more comfortable.
see:
Emacs on Mac OS X Leopard key bindings


Question:
Is there a way to pass a password to ssh automatically. I would like to automatically ssh to a server without using public key authentication or expect scripts, by somehow getting ssh to read the password from stdin or a file.

The reason it has to be that way is that I would like to backup my files to a server using rsync/ssh running as a cron job. This server mounts my home directory after it authenticates me, so using public key authentication does not work since ~/.ssh isn't available until after the login is successful. expect(1) is out of the question because I would like to run it as a cron job, and since cron jobs don't run under a terminal the combination of expect/ssh just doesn't work. I do not have root access to that server, and it would be difficult to get the admins to make any changes to the way things work there.

Answer:
Rather than passing your password use a public/private key system.  Add the public key for a machine to the authorized keys list on all the machines you want to connect to. Using this method SSH can validate the keys automatically and no password is required.
You can find instructions here:
http://linuxproblem.org/art_9.html
Since I just read the question more carefully, you might want to look around for a different SSH client that supports password authentication without user interaction.  I quick google search hinted that they exist (
http://www.derkeiler.com/Newsgroups/comp.security.ssh/2004-12/0134.html
)
Related Stackoverflow questions:
How do I setup Public-Key Authentication?
Provide password using Shell script
How can I automate running commands remotely over SSH?


Question:
I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class?

For instance

class Any {
    static int one = 1;
    static int two = 2;
    static int three = 3;

    public static void main( String [] args ) {
          for( int i : magicMethod( Any.class ) ){
              System.out.println( i );
          }
    }
 }

Output

 1
 2
 3

Thanks.

Answer:
Hey.. it was very easy.  :P
```
```
Field [] constants = Main.class.getFields();
      Object some = new Main();
      for( Field field : constants ){
          if(Modifier.isStatic(field.getModifiers() ) &&
             field.getType() == int.class  ) {
                    System.out.println( field.getInt( some  ) );
          }
      }
```
```


Question:
Given a UTC time string like this:

2005-11-01T00:00:00-04:00

What is the best way to convert it to a DateTime using a Crystal Reports formula?

My best solution is posted below.

I hope someone out there can blow me away with a one-liner...

Answer:
Here is my best solution, with comments:
```
```
//assume a date stored as a string in this format:
//2005-11-01T00:00:00-04:00
//return a DateTime value
StringVar fieldValue;
StringVar datePortion;
StringVar timePortion;
NumberVar yearPortion;
NumberVar monthPortion;
NumberVar dayPortion;
NumberVar hourPortion;
NumberVar minutePortion;
NumberVar secondPortion;

//store the field locally so i can easily copy-paste into another formula
//(where the field name will be different)
//Crystal formulas do not use a powerful language.
fieldValue := {PACT.ReferralDate};

//break up the date & time parts.
//ignore the -04:00 offset part of the time.
datePortion := Split (fieldValue,"T")[1];
timePortion := Split(Split (fieldValue,"T")[2],"-")[1];

yearPortion := ToNumber(Split(datePortion,"-")[1]);
monthPortion := ToNumber(Split(datePortion,"-")[2]);
dayPortion := ToNumber(Split(datePortion,"-")[3]);

hourPortion := ToNumber(Split(timePortion,":")[1]);
minutePortion := ToNumber(Split(timePortion,":")[2]);
secondPortion := ToNumber(Split(timePortion,":")[3]);

//finally, return the result as a date-time
DateTime(yearPortion,monthPortion,dayPortion,hourPortion,minutePortion,secondPortion);
```
```


Question:
how do i check if an item is selected or not in my listbox?
so i have a button remove, but i only want that button to execute if an item is selected in the list box. im using asp.net code behind C#. I'd prefer if this validation occurred on the server side.

cheers..

Answer:
On the callback for the button click, just check if the selected index of the list box is greater than or equal to zero.
```
```
protected void removeButton_Click( object sender, EventArgs e )
{
    if (listBox.SelectedIndex >= 0)
    {
        listBox.Items.RemoveAt( listBox.SelectedIndex );
    }
}
```
```


Question: In adobe Flex datagrid height is equally to fix height . I want to make datagrid height is depend data .

Answer: You can set each row of the datagrid to fit based on the contents of a particular column of that row by setting the "variableRowHeight" attribute to true on the datagrid and setting the "wordWrap" attribute to true on the dataGridColumn that will contain the variable height content.


Question: Is there a built-in way to know if a given session variable is a serialized object? Say I retrieve a value like $_SESSION['foo'], but I don't know if it was originally a string or if it is a serialized object. Is there some way to check, or once serialized does PHP just see a string as a string as a string?

Answer:
A string is a string is a string. I think the best you'll be able to do is just try to unserialize it, and if it works, it works. If it doesn't, it doesn't.
The only other option would be to use a regex to see if it "looks" like a serialized object. Just running
```
unserialize()
```
on it might be easier though.