q:
Ok, so I'm building bread crumbs and depending on the value of the breadcrumb an image will be the seperator. So "HOME" will have one image and "SEARCH" will have another.

I know I can do this programatically (at least I ASSUME) but is there an easier way to do this? Can I link an image to a node based on the value of the node? Can I do it with PathSeparatorTemplate?

Thank you.

[A]
You can put an
```
```
<asp:Image ... />
```
```
into the PathSerparatorTemplate but you still have to set the image url from code.


q:
After many years of using make, I've just started using jam (actually ftjam) for my projects.

In my project workspaces, I have two directories:

src where I build executables and libraries

test where my test programs are

I'm trying to set up a dependency on test programs so that each time I compile them, the libraries will be recompiled as well (if they need to).

Any suggestion on how to do it?

[A]
Ok this seems to be not an as easy question as I thought so I worked out a solution on my own. It uses a script to achieve the end result so I still hope that a Jam guru will have a jam-only solution.
Create a Jamrules in the root directory of the project with the common definitions.
Create a Jamfile in the root directory of the project with the following content:
```
SubDir . ;
    SubInclude . src ;
    SubInclude . test ;
```
Create a Jamfile in the src directory
```
SubDir .. src ;
    Library mylib : mylib.c ;
```
Create a Jamfile in the test directory
```
SubDir .. test ;
    Main mytest : mytest.c ;
    Depends mytest :  mylib$(SUFLIB) ;
```
With this setting, as long as I am in the root directory, whenever I try to build mytest the library will also be recompiled (if needed). I found an old message on the jammer mailing list describing it.
Alas this doesn't work if I'm in the test subdirectory since jam can only look
down
into subdirectories.
So, I created a simple script called
```
jmk
```
and put it together with the
```
jam
```
executable (so that both are in the path):
```
```
if [ "$JMKROOT" = "" ] ; then
   JMKROOT=`pwd`
   export JMKROOT
fi
cd $JMKROOT
jam $*
```
```
and I set the JMKROOT environment variable to the root of my project.
For when I compile in a Windows shell (that's why I want to use Jam) I simply use this small
```
jmk.bat
```
batch file:
```
```
@echo off
if "%JMKROOT%" EQU "" set JMKROOT=%CD%

set OLDCD=%CD%
cd %JMKROOT%
jam %1 %2 %3 %4 %5 %6 %7 %8 %9

cd %OLDCD%
```
```

s: huggingface

c: devops

d: intermediate


q: I know there are tools to get text files to resource files for Visual Studio.  But I want to get the text from my resource files to a text file so they can be translated.  Or is there a better way to do this?

[A]
You could use
Resx Editor
, a small translation-oriented file editor.
Target audience: translators.
Supported file format: Microsoft RESX 2.0
Here is a link to Joannès Vermoel's (the author of the free tool)
weblog entry
about it.


q:
I am using Visual Studio 2005 to make an install.  The application has a dependency on a DLL that was built with MFC 7.1 (from Visual Studio 2003).

Are there merge modules for MFC 7.1 or other redistributables like there are for MFC 8?  Where could they be found?

[A]
I would expect the merge modules for MFC 7.1 to be in
```
%ProgramFiles%\Microsoft Visual Studio .NET 2003\redist
```
, assuming that you have Visual Studio 2003 installed. (However, I can't verify that because I don't have Visual Studio on this PC.)


q: How can I find out if SP1 has been installed on a server which has .NET 3.5?

[A]
Look at
```
HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\
```
. One of these must be true:
The
```
Version
```
value in that key should be
3.5.30729.01
Or the
```
SP
```
value in the same key should be
1
In C# (taken from the first comment), you could do something along these lines:
```
```
const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();
```
```


q:
I have two users Bob and Alice in Oracle, both created by running the following commands as sysdba from sqlplus:

   create user $blah identified by $password;
   grant resource, connect, create view to $blah;

I want Bob to have complete access to Alice's schema (that is, all tables), but I'm not sure what grant to run, and whether to run it as sysdba or as Alice.

Happy to hear about any good pointers to reference material as well -- don't seem to be able to get a good answer to this from either the Internet or "Oracle Database 10g The Complete Reference", which is sitting on my desk.

[A]
AFAIK you need to do the grants object one at a time.
Typically you'd use a script to do this, something along the lines of:
```
```
SELECT 'GRANT ALL ON '||table_name||' TO BOB;'
FROM   ALL_TABLES
WHERE  OWNER = 'ALICE';
```
```
And similar for other db objects.
You could put a package in each schema that you need to issue the grant from which will go through all call each GRANT statement via an EXECUTE IMMEDIATE.
e.g.
```
```
PROCEDURE GRANT_TABLES
   IS
   BEGIN

      FOR tab IN (SELECT table_name
                  FROM   all_tables
                  WHERE  owner = this_user) LOOP
         EXECUTE IMMEDIATE 'GRANT SELECT, INSERT, UPDATE, DELETE ON '||tab.table_name||' TO other_user';
      END LOOP;
   END;
```
```


q: I have a fairly simple const struct in some C code that simply holds a few pointers and would like to initialize it statically if possible. Can I and, if so, how?

[A]
You can, if the pointers point to global objects:
```
```
// In global scope
int x, y;
const struct {int *px, *py; } s = {&x, &y};
```
```


q:
My goal is to recognize simple gestures from accelerometers mounted on a sun spot. A gesture could be as simple as rotating the device or moving the device in several different motions. The device currently only has accelerometers but we are considering adding gyroscopes if it would make it easier/more accurate.

Does anyone have recommendations for how to do this? Any available libraries in Java? Sample projects you recommend I check out? Papers you recommend?

The sun spot is a Java platform to help you make quick prototypes of systems. It is programmed using Java and can relay commands back to a base station attached to a computer. If I need to explain how the hardware works more leave a comment.

[A]
The accelerometers will be registering a constant acceleration due to gravity, plus any acceleration the device is subjected to by the user, plus noise.
You will need to low pass filter the samples to get rid of as much irrelevant noise as you can. The worst of the noise will generally be higher frequency than any possible human-induced acceleration.
Realise that when the device is not being accelerated by the user, the only force is due to gravity, and therefore you can
deduce its attitude
in space. Moreover, when the total acceleration varies greatly from 1g, it must be due to the user accelerating the device; by subtracting last known estimate of gravity, you can roughly estimate in what direction and by how much the user is accelerating the device, and so obtain data you can begin to match against a list of known gestures.
With a single three-axis accelerometer you can detect the current pitch and roll, and also acceleration of the device in a straight line. Integrating acceleration minus gravity will give you an estimate of current velocity, but the estimate will rapidly drift away from reality due to noise; you will have to make assumptions about the user's behaviour before /  between / during gestures, and guide them through your UI, to provide points where the device is not being accelerated and you can reset your estimates and reliably estimate the direction of gravity. Integrating again to find position is unlikely to provide usable results over any useful length of time at all.
If you have two three-axis accelerometers some distance apart, or one and some gyros, you can also detect rotation of the device (by comparing the acceleration vectors, or from the gyros directly); integrating angular momentum over a couple of seconds will give you an estimate of current yaw relative to that when you started integrating, but again this will drift out of true rapidly.


q:
I'm in need of a lightweight library for 2d & 3d vectors and 3x3 & 4x4 matrices. In basic C.
Just so I don't reinvent the wheel suboptimally.

Any suggestions?

[A]
Assuming you're coding for x86, you might look into Intel's
Integrated Performance Primitives
(IPP) and
Math Kernel Library
(MKL).  These provide super-duper-fast libraries (probably faster than anyone else could write, since they're optimized for non-public microarchitecture details) for lots of common operations, including vectors and matrices.


q:
It seems like Microsoft had a great idea with the ObservableCollection.  They are great for binding, and are super fast on the UI.

However, requiring a context switch to the Dispatcher Thread every time you want to tweak it seems like a bit much.  Does anyone know the best practices for using them?  Is it simply to populate an ICollection as a message object in the business layer, then create the ObservableCollection in the UI layer?  How do you then handle updates to the collection on the UI?

[A] Is updating the ObservableCollection on the UI thread really causing that much of a bottleneck for your application? If not, stick with updating it on the UI thread. Remember, it's not really a context switch that's happening when you run something with the Dispatcher - instead, you're simply submitting a job to the UI thread, which is an already running thread, which the OS will context switch to at some point anyway. The UI thread pulls your submitted job off of an internal queue and executes it. You're not forcing the context switch yourself.


q:
I'm looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.

Main purpose is to filter out XSS and similar nasties that may be entered via web forms.  Secondary purpose is to limit breakage of HTML content entered by non-technical users e.g. via WYSIWYG editor that has an HTML view.

I'm considering using HTML Purifier, or rolling my own by using an HTML DOM parser to go through a process like HTML(dirty)->DOM(dirty)->filter->DOM(clean)->HTML(clean).

Can you describe successes with these or any easier strategies that are also effective?  Any pitfalls to watch out for?

[A]
User-submitted HTML isn't always valid, or indeed complete. Browsers will interpret a wide range of invalid HTML and you should make sure you can catch it.
Also be aware of the valid-looking:
```
```

```
```
and
```
```
click
```
```


q: What is the difference between these three heavily related fields? Is there one specific whole they are all a part of (aside from CS)?

[A]
Machine Learning
could
be considered a part of AI, however I would classify Machine Learning as the study of creation of semantic models and adaptive behavior with AI being the overall science of systems that intelligent-seeming behavior.
Most of what goes as "AI" is rather simplistic, but highly effective, such as heuristics and the like.
Soft Computing doesn't fell like it has many ML and AI components as it is more about analysis of complex systems.  I could be wrong though.  As with most things in computer science, the deeper you dig, the more you discover that it's all related.


q:
I've got a file whose format I'm altering via a python script.  I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word".

My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?

[A]
You could try:
```
```
>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")
'Word Word Word'
```
```


q:
I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it.

Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like:

var jsArray = new {key: 'test test', value: 'value value'},
              new {key: 'test 2', value: 'value 2'};

and accessed like:

value = jsArray[key]

Can someone remind me?


q:
Is it possible to play video from data that has been embedded in a swf at compile time (with the [Embed] metatag)?

The "Import Video->Embed" feature provided by Flash CS3 etc. is not acceptable because it has many severe limitations (including sound synchronization issues, a maximum number of frames, and other caveats)

I'm interested in being able to bundle flv video data in a swf (along with other assets), which will be played by an AIR application.

I don't think it can be done. Anyone disagree?

[A]
You can import a flv into a swf file using the Flash IDE - I've done that before. You can drop it onto the timeline of a MovieClip just like a sound and then drop that movieclip onto the stage for it to play. In Flash CS3 do File>Import>Import Video and select the flv. Choose the video and then on the next stop of the wizard choose "Embed ..... ", Here is a link to an
Adobe Developer center article on embedding flvs into swfs
.
I have not done so myself, but I can see no reason why you could access the flv from the library of a loaded swf.
FYI: It looks like this was a bug that was deferred. It doesn't look like Adobe currently allows embedding using the Embed meta tag. Here is a
forum post
on the issue and a link to the
bug tracker
.


q: Looking for a toolkit/SDK for general Blackberry development or application toolkits. Anything like an MVC framework?

[A]
My understanding is that blackberry's OS is Java ME - based, and that there's a decent development kit for them.  I presume you have already
looked over everything here
... you can find a lot of information, including the development kit download link.
Regarding model-view-controller, there's no particular framework to my knowledge, but I don't see why you wouldn't be able to take MVC as an approach in the paradigmatic sense.  Google has resources out there on java developers working with MVC.


q: Looking at MVC framework, it seems we require more of classic ASP knowledge then ASP.NET postbacks and Viewstates. Are we moving backwards to complex UI + code logic in the actual frontend HTML markup?

[A]
This is funny that you mention this ... I was having the same conversation with a co-worker today.
Is it a step moving backwards?  I don't think so ... while in classic asp you had a some complex logic in the UI, from what I can see with MVC, the complex logic should still be in your business objects, and any complex interaction with the object should be done via the Controller.
The goal, again, from what I can see, is to keep the UI trim and fit when it comes to actual business logic.  Any additional bloat would be caused by making the UI more user friendly, with the likes of AJAX and JQuery.
This is just my initial observation regarding MVC.  It is a very cool technology, especially with how it sits on top of REST, makes it very easy to work with from other technologies.
I'm looking forward to trying it out in a couple of future projects!


q:
A similar question was asked here, but it was specific to .NET 3.5. Specifically, I'm looking for the following:

What is the correct way to determine which .NET Framework versions and service packs are installed?

Is there a list of registry keys that can be used?

Are there any dependencies between Framework versions?

[A]
Enumerate the subkeys of
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP
```
. Each subkey is a
.NET
version. It should have
```
Install=1
```
value if it's present on the machine, an SP value that shows the service pack and an
```
MSI=1
```
value if it was installed using an MSI. (.NET 2.0 on Windows Vista doesn't have the last one for example, as it is part of the OS.)


q:
I'm using $.post() to call a servlet using Ajax and then using the resulting HTML fragment to replace a div element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the div element with the contents of the login page, forcing the user's eyes to witness a rare scene indeed.

How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?

[A]
Use the low-level
```
$.ajax()
```
call:
```
```
$.ajax({
  url: "/yourservlet",
  data: { },
  complete: function(xmlHttp) {
    // xmlHttp is a XMLHttpRquest object
    alert(xmlHttp.status);
  }
});
```
```
Try this for a redirect:
```
```
if (xmlHttp.code != 200) {
  top.location.href = '/some/other/page';
}
```
```


q:
I have a BasePage which inherits from System.Web.UI.Page, and every page that inherits the BasePage will have the same master page.

How do I cast the Page.Master of the BasePage to the specific master page so I can access properties on it?

[A]
In VB.Net
```
```
MasterPageVariable = Ctype(page.MasterPage, MasterPageClass)
```
```


q:
I dont know if I should use the httpcontext caching or the Enterprise Library Caching Application Block. Also, what is the best pattern for the caching Strategy when deleting or updating an entity that is part of a cached list?

Should I remove all of a list from the cache or only remove the item from the cached list?
If I update it will I remove the list from the cache or update the entity in it.

[A]
There are several approaches to implement caching,httpcontext being the easiest one, but it's not necessarily the worst. Take a look at
memcached
or
MS Velocity
, both of which can be used as backends for the ASP.NET Cache. Especially memcached has a reputation of doing a really good job.
As for caching policy: you have to decide what works best for you.I personally would remove the complete list from the cache upon update/delete  rather than trying to find out whether the entity is in the list, since it takes a non-trivial amount of time and you need to take concurrency issues into account (locking the list, since somebody might do an update/delete of another entity).
Sometimes it does make sense to update an entity in place (if you have a complete object with all data you need), sometimes it's a waste of time, because due to some state change the entity should move somewhere else (e.g. when you sort by LastChangedDate etc.)
Don't forget to optimize your DB code too so that it does not take too much time to refresh the flushed list.


q:
I'm trying to link a Qt application with its libraries and the linker (MinGW) spews hundreds of lines like the following, and I am unsure how to proceed.

 cpp: undefined reference to `_Unwind_SjLj_Register'
 c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x29d):qcoreapplication_win.
 cpp: undefined reference to `_Unwind_SjLj_Unregister'
 c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x38c):qcoreapplication_win.
 cpp: undefined reference to `_Unwind_SjLj_Resume'
 c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x4ce):qcoreapplication_win.
 cpp: undefined reference to `_Unwind_SjLj_Register'
 c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x53e):qcoreapplication_win.
 cpp: undefined reference to `_Unwind_SjLj_Unregister'
 c:/qt/lib/libQtCore.a(qcoreapplication_win.o)(.text+0x635):qcoreapplication_win.
 cpp: undefined reference to `_Unwind_SjLj_Resume'

[A]
It's been a while since I did any Qt development, but there were only a couple instances that I remember spewing out huge numbers of messages like this.
Include files for Qt were a
different version than the shared
libraries ... this happened when I
upgraded and for some reason, you
had to manually upgrade the include
files.
The Qt libraries were missing altogether ... I vaguely remember the compiler working, but the linker failing when I first started.
I was doing Qt development targeted at an ARM processor, so I had extra oddities involved when cross-compiling.


q: we have users in each region of the world.  I would like to create an environment picker that shows up a map on the form and has a link for each region.  So if i was in NY i would click NY and would get the NY environment.  Any ideas of doing this dynamically in winforms as opposed to having a static map image.

[A]
I may be misreading the question, but it sounds like you want something akin to how the old-school
Windows time zone picker
worked. The rest of this is based on that assumption, so if I'm wrong, feel free to disregard.
You are, in effect, dealing with an image of a world (or national, or regional, etc.) map, with clickable "hotspots." Given that, you need some form of image to start with. :)
Now you have two choices: You can embed a bitmap image of your map in the application, or you can draw it yourself using GDI+ primitives. Either way, you would display it on the form, and wire up the MouseUp event for the various hotspots. (The MouseUp event, I believe, includes the X,Y coordinates of where the user clicked.)
If you wanted to get really fancy, you could change the mouse pointer on the MouseOver event if the user is in the defined hotspots.
Either way, it's a great UI -- very visual, very in tune with how people think -- but it will be time-intensive to code correctly.


q: The only thing I can get python omnicomplete to work with are system modules. I get nothing for help with modules in my site-packages or modules that I'm currently working on.

[A]
Just ran across this on Python reddit tonight:
PySmell
. Looks like what you're looking for.
PySmell is a python IDE completion helper.
It tries to statically analyze Python source code, without executing it, and generates information about a project’s structure that IDE tools can use.


q: I'm working on a program that is form based but I have been asked to add some command line support, this works fine apart from the form flashes up and closes down when running from the command line. Is there anyway to hide the form whilst the command line is running? Some code does refer to controls so the gui would need to be accessible but not visible, is this workable?

[A]
In your Main method you can create the form such as:
```
```
main = new MainForm();
```
```
then do any command line processing required.
When not in command line mode simply call:
```
```
Application.Run(main);
```
```


q:
How do I check if a number is a palindrome?

Any language. Any algorithm. (except the algorithm of making the number a string and then reversing the string).

[A]
This is
one of the Project Euler problems
.  When I solved it in Haskell I did exactly what you suggest, convert the number to a String.  It's then trivial to check that the string is a pallindrome.  If it performs well enough, then why bother making it more complex?  Being a pallindrome is a lexical property rather than a mathematical one.


q:
I've seen several responses to questions asking for IDEs where text editors were suggested and vice-versa. That makes me think that people treat them as the same thing, where I draw clear distinctions.

How do you define "text editor" and "IDE"?

Do you see a difference between the two tools?

Note that I accepted an answer which I think best addressed the concepts of "text editor" and "IDE". However, it's just my personal opinion of what best addresses the question and I will continue to check in on this question from time to time to see if there's a better answer and I will accept that one.

[A]
The confusion arises from the fact that a text editor is a core component of every IDE. But, an IDE has much more than just a text editor; it also has interfaces to compilers, debuggers, profilers, reference material, and more.
Many text editors have plugins or other flexible extension mechanisms, often including the ability to "wrap" external tools like those I mentioned above. The key difference, IMHO, is the "I" in IDE - integrated. An IDE is (again, IMHO) something that's purposefully designed to support a specific set of tools, one of which is a text editor.


q:
I'm writing a lightweight XML editor, and in cases where the user's input is not well formed, I would like to indicate to the user where the problem is, or at least where the first problem is.  Does anyone know of an existing algorithm for this?  If looking at code helps, if I could fill in the FindIndexOfInvalidXml method (or something like it), this would answer my question.

using System;

namespace TempConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string text = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
            int index = FindIndexOfInvalidXml(text);
            Console.WriteLine(index);
        }

        private static int FindIndexOfInvalidXml(string theString)
        {
            int index = -1;

            //Some logic

            return index;
        }
    }
}

[A]
Unless this is an academic exercise, I think that writing your own XML parser is probably not the best way to go about this.  I would probably check out the
XmlDocument class
within the System.Xml namespace and try/catch
exceptions
for the Load() or LoadXml() methods.  The exception's message property should contain info on where the error occurred (row/col numbers) and I suspect it'd be easier to use a regular expression to extract those error messages and the related positional info.


q:
How can I make xargs execute the command exactly once for each line of input given?
It's default behavior is to chunk the lines and execute the command once, passing multiple lines to each instance.

From http://en.wikipedia.org/wiki/Xargs:

find /path -type f -print0 | xargs -0 rm

In this example, find feeds the input of xargs with a long list of file names. xargs then splits this list into sublists and calls rm once for every sublist. This is more efficient than this functionally equivalent version:

find /path -type f -exec rm '{}' \;

I know that find has the "exec" flag.  I am just quoting an illustrative example from another resource.

[A]
The following will only work if you do not have spaces in your input:
```
```
xargs -L 1
xargs --max-lines=1 # synonym for the -L option
```
```
from the man page:
```
```
-L max-lines
          Use at most max-lines nonblank input lines per command line.
          Trailing blanks cause an input line to be logically continued  on
          the next input line.  Implies -x.
```
```


q:
I've got a number of batch processes that run behind the scenes for a Linux/PHP website. They are starting to grow in number and complexity, so I want to bring a small amount of process to bear on them.

My source tree has a bunch of cpp files and scripts, organized with development but not deployment in mind. After compiling all the executables, I need to put various scripts and binaries on a cluster of machines. Different machines need different executables, scripts, and config files for their batch processes. I also have a few of tools that I've written that belong on every machine. At the moment, this deployment process is manual and error prone.

I'm guessing I'm just going to end up with a script that runs at the root of the source tree and builds a smaller tree of everything necessary for any of the machines. Then, I'll just rsync that to the appropriate machines. But I'm curious how other people are managing this type of problem. Any ideas?

[A]
Create your own packages in the format your distribution uses, e.g. Debian packages (.deb).  These can either be copied to each machine and installed manually, or you can set up your own repository, and add it to your list of sources.
Your packages should be set up so that the scripts they contain consult a configuration file, which is different on each host, depending on what scripts need to be run on each.
To tie it all together, you can create a meta package that just depends on each of the other packages you create.  That way, when you set up a new server, you install that one meta package, and the other packages are brought in as dependencies.
Although this process sounds a bit complicated, if you have many scripts and many hosts to deploy them to, it can really pay off in the long run.


q: What is the best way to write data to the text console at arbitrary locations on the screen and with custom fore/background colors?

[A]
Console.SetCursorPosition, Console.BackgroundColor, Console.ForegroundColor, and Console.ResetColor.
Note these were added to the .NET Framework in version 2.0. Prior to that you would have needed PInvoke.


q:
How would I print a spinning curser in a utility that runs in a terminal using standard C?

I'm looking for something that prints: \ | / - over and over in the same position on the screen?

Thanks

[A]
You could use the backspace character (
```
\b
```
) like this:
```
```
printf("processing... |");
fflush(stdout);
// do something
printf("\b/");
fflush(stdout);
// do some more
printf("\b-");
fflush(stdout);
```
```
etc. You need the
```
fflush(stdout)
```
because normally stdout is buffered until you output a newline.


q:
I have an application used by pretty tech-savey people and they want small island of programmability so I've used embedded Iron Python.

However, since IronPython 2.0 Eval() doesn't work any more. Specifically I can't both load modules and inject local variables.

There is a work around where I can still call Execute(), print out my answer and listen to StandardOut, but then it comes out as a string and I've lost the type.

Not a disaster for a long, but a huge pain for more complex objects.

Does anyone know how to get Eval() working again in 2.0 like it did in 1.x?

Cheers,
Jan

[A]
Could you be a little more specific about the problem, and maybe provide a code example?  The "eval"-style functionality is definitely still present, though as you've noticed, the hosting interface has changed considerably since 1.0.
This works in beta 5:
```
```
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromString("2 + 5", SourceCodeKind.Expression);
int result = source.Execute<int>();
```
```
By the way, using the right
```
SourceCodeKind
```
is critical here.


q:
I Have one entity [Project] that contains a collection of other entities [Questions].

I have mapped the relation with a cascade attribute of "all-delete-orphan".

In my DB the relation is mapped with a project_id (FK) field on the questions table. this field cannot be null since I don't want a Question without a Project.

When I do session.delete(project) it throws an exception saying that project_id cant be null, but if I remove the not-null constraint to that field, the deletion works nice.

Anyone knows how to solve this?

[A]
The delete is occurring on the Project first and cascading to the Question, but the Project delete includes a nulling of the project_id in the Questions (for referential integrity.  You're not getting an exception on the deletion of the Question object, but because the cascade is trying to null the FK in the Question(s).
Looking at "
Java Persistence with Hibernate
", I think that what you really want a cascade type of delete or remove, not delete-orphans.


q: Now that Silverlight 2.0 has been officially released I was wondering if anyone was using it for any line of business apps, for example POS, Vertical Market apps etc. If so how were your experiences compared to an old WinForms app or Web app?

[A]
I think Silverlight is going to be huge for business applications. This is some bullet points highlighting strengths of Silverlight as a LOB platform inside the browser. It's something i wrote to help a colleague out who was comparing ASP.NET vs. Silverlight, but hopefully it includes some hints.
Extra Silverlight Functionality
You can do off line caching of static data using Isolated Storage today - Just serialize your data to JSON or XML and save it locally.
Stronger tool support for UX - With jQuery you will be writing all the extra UX by hand. Don't know if this is a big deal, as jQuery is really  sleek.
C# over JavaScript - Better debugging and developer experience.
Support for multiple threads, cross domain networking and sockets.
Support for local file access - Say you want to do a CSV-file import without having to roundtrip to the server. In Silverlight you can use the FileOpenDialog and read the file content locally.
Easy portabiliy to WPF
Extra Silverlight Controls
First batch of out-of-band Silverlight controls will be available at the PDC, and include the following controls:
  DockPanel, WrapPanel, ViewBox, Label, HeaderedContentControl, Expander, TreeView, NumericUpDown, AutoComplete, Accordion.
Scott Gu have hinted that over time Silverlight might get 100+ controls if you count the out-of-band controls released on CodePlex.
Read more at
http://blogs.msdn.com/sburke/archive/2008/09/17/control-freak.aspx
WPF portability
There are some major differences. The non-UI code should be fairly simple to port to WPF.
If you don't get too creative with your styling most of the controls ports directly as well. One of the major differences is that Silverlight uses the VisualStateManager instead of Trigger for styling of controls. There is a community project available to add VSM support to WPF to make it easier to port applications. The VSM will be added to a future WPF release to make the two more in-pair.
You will be able to reuse ALOT of knowledge, design assets and code.
I did a blog post about porting my Dive Log app (a small one, but highlights some of the issues) to WPF:
http://jonas.follesoe.no/PortingTheSilverlightDiveLogApplicationToWPF.aspx
(did it in a couple of hours).
Data Entry UX
Silverlight will make it easier to implement more complex client-side validation rules, making your data entry forms more responsive with less round-back to the server. You can do this using AJAX, but it takes more effort.
With Silverlight you can get creative and enhance your data entry forms and add nice effects when enabling/disabling parts of your form based on selections earlier in the form.
You can create cool widgets for your data entry. Ref. the way you set the Air-In/Air-Out in the dive log application by changing the air level in a air tank, instead of just typing a value in a text box.
Visualizations
You can do a lot of cool things with the jQuery animation API - but Silverlight makes it alot easier to do rich UI's with animations, nice scalable vector graphics etc. For plain ASP.NET you probably have more third-party controls/components to pick from, but for plain charting the Visifire charts are great.
Copy/paste/select text
I don't like that it's hard to make text selectable/copyable.
The out-of-box print experience in Silverlight is limiting as well. It will simply print what's on screen. I'm working on a blog post showing how to generate HTML behind the Silverlight component and use CSS for printing.
Search Engine Optimization
Guess it depends on your customers requirement. If your data should be searchable you can get around it by having ASPX pages that render the data as HTML behind the Silverlight page when it's first loaded. So your site would be something like ShowCustomer.aspx?CustomerID=10 - Silverlight will show customer 10 in the form, and behind the Silverlight component there is HTML representing the same information. Then you would also provide a sitemap file so that Google knows how to index/find the content of your page. But it would be doable.
If your application is very "application like" it might not make sense as it's hard to create URL's to the different states of your application.


q:
What is the main difference between int.Parse() and Convert.ToInt32()?

Which one is to be preferred

[A]
No difference as such.
```
Convert.ToInt32()
```
calls
```
int.Parse()
```
internally
Except for one thing
```
Convert.ToInt32()
```
returns
```
0
```
when argument is
```
null
```
Otherwise both work the same way


q:
This is the constraint I have on the Customers table.

ALTER TABLE Customers
    ADD CONSTRAINT CN_CustomerPhone
    CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')

Why does this fail?

INSERT INTO Customers
(CustomerName, Address, City, State, Zip, Phone)
VALUES
('Some Name','An Address', 'City goes here', 'WI', 12345, '(800) 555-1212')

With this error message.

Msg 547, Level 16, State 0, Line 1 The
  INSERT statement conflicted with the
  CHECK constraint "CN_CustomerPhoneNo".
  The conflict occurred in database
  "Accounting", table "dbo.Customers",
  column 'Phone'. The statement has been
  terminated.

I'm sure I'm missing something really simple, but I can't find it.

I've tried simplifying the constraint to only 'Phone LIKE '[0-9]'' and inserting a single digit, but it still fails. WTF?

[A]
Check the length of the Phone field.
Is it 15 or more characters?
Using your code with a temp table here
```
```
create table #temp
(phone varchar(15))

ALTER TABLE #temp
    ADD CONSTRAINT CN_CustomerPhone
    CHECK (Phone LIKE '([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]')

INSERT INTO #temp
(Phone)
VALUES
('(800) 555-1212')

select * from #temp

drop table #temp
```
```


q:
I'm just getting started working with foreign keys for the first time and I'm wondering if there's a standard naming scheme to use for them?

Given these tables:

task (id, userid, title)
note (id, taskid, userid, note);
user (id, name)

Where Tasks have Notes, Tasks are owned by Users, and Users author Notes.

How would the three foreign keys be named in this situation? Or alternatively, does it even matter at all?

Update: This question is about foreign key names, not field names!

[A]
How about
```
FK_TABLENAME_COLUMNNAME
```
?
K
eep
I
t
S
imple
S
tupid whenever possible.


q: Is it possible to show other processes in progress on an Oracle database?  Something like Sybases sp_who

[A]
After looking at sp_who, Oracle does not have that ability per se.  Oracle has at least 8 processes running which run the db. Like RMON etc.
You can ask the DB which queries are running as that just a table query.  Look at the V$ tables.
Quick Example:
```
```
SELECT sid,
       opname,
       sofar,
       totalwork,
       units,
       elapsed_seconds,
       time_remaining
FROM v$session_longops
WHERE sofar != totalwork;
```
```


q: $0 is the variable for the top level Ruby program, but is there one for the current method?

[A]
From
http://snippets.dzone.com/posts/show/2785
:
```
```
module Kernel
private
    def this_method_name
      caller[0] =~ /`([^']*)'/ and $1
    end
end

class Foo
  def test_method
    this_method_name
  end
end

puts Foo.new.test_method    # => test_method
```
```


q:
I know how to program Console application with parameters, example : myProgram.exe param1 param2.

My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?

[A]
You need to use
```
Console.Read()
```
and
```
Console.ReadLine()
```
as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).
Edit:
A simple
```
cat
```
style program:
```
```
class Program
{
    static void Main(string[] args)
    {
        string s;
        while ((s = Console.ReadLine()) != null)
        {
            Console.WriteLine(s);
        }

    }
}
```
```
And when run, as expected, the output:
```
C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe
"Foo bar baz"

C:\...\ConsoleApplication1\bin\Debug>
```


q:
Newish to Oracle programming (from Sybase and MS SQL Server).  What is the "Oracle way" to avoid filling the trans log with large updates?

In my specific case, I'm doing an update of potentially a very large number of rows.  Here's my approach:

UPDATE my_table
SET a_col = null
WHERE my_table_id IN
(SELECT my_table_id FROM my_table WHERE some_col < some_val and rownum < 1000)

...where I execute this inside a loop until the updated row count is zero,

Is this the best approach?

Thanks,

[A]
Any UPDATE is going to generate redo.  Realistically, a single UPDATE that updates all the rows is going to generate the smallest total amount of redo and run for the shortest period of time.
Assuming you are updating the vast majority of the rows in the table, if there are any indexes that use A_COL, you may be better off disabling those indexes before the update and then doing a rebuild of those indexes with NOLOGGING specified after the massive UPDATE statement.  In addition, if there are any triggers or foreign keys that would need to be fired/ validated as a result of the update, getting rid of those temporarily might be helpful.


q:
I have been thinking about starting a side project at home to exercise my brain a bit.  Reversi looks like a simply game, where mobility has a profound effect on game play.
It is at least a  step up from tic tac toe.  This would be a  single player against an AI of some sort.

I am thinking to try this in C++ on a PC.

What issues am I likely to run into?

What graphics library would you recommend?

What questions am I not smart enough to ask myself?

[A]
Issues...
Well, just be sure when writing the strategy part of the game, not to simply do the move that gives you the most pieces.  You must also give weight to board position.  For example, given the opportunity to place a piece in a board corner should take priority over any other move (besides winning the game) as that piece can never be turned back over.  And, placing a piece adjacent to a corner spot is just about the worst move you can ever make (if the corner space is open).
Hope this helps!


q:
I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency.

What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?

[A]
Using an automated tool to "port" the web application will almost certainly guarantee that future programming efficiency will be minimised -- not improved.
A good scripting language can help programming efficiency when used by good programmers who understand good coding practices in that language.  Automated tools are usually not designed to output code that is elegent or well-written, only code that works.
You'll only get an improvement in programming efficiency after you've put in the effort to re-implement the web app -- which, due to the time required for the reimplementation, may or may not result in an improvement overall.


q:
So far I've figured out how to pass Unicode strings, bSTRs, to and from a Euphoria DLL using a Typelib. What I can't figure out, thus far, is how to create and pass back an array of BSTRs.

The code I have thus far (along with includes for EuCOM itself and parts of Win32lib):

global function REALARR()
  sequence seq
  atom psa
  atom var
  seq = { "cat","cow","wolverine" }
  psa = create_safearray( seq, VT_BSTR )
  make_variant( var, VT_ARRAY + VT_BSTR, psa )
  return var
end function

Part of the typelib is:

  [
     helpstring("get an array of strings"),
     entry("REALARR")
  ]
  void __stdcall REALARR( [out,retval] VARIANT* res );

And the test code, in VB6 is:

...
Dim v() as String
V = REALARR()
...

So far all I've managed to get is an error '0' from the DLL. Any ideas? Anyone?

[A]
I've been in touch with the Euphoria people via their
forum
, and have gotten this far. The routine is failing on the the make_variant line. I haven't figured it out any further than that and neither have they.
```
```
global function REALARR()
  atom psa
  atom var
  atom bounds_ptr
  atom dim
  atom bstr
  object void

  dim = 1
  bounds_ptr = allocate( 8 * dim ) -- now figure out which part is Extent and which is LBound
  poke4( bounds_ptr, { 3, 0 } ) -- assuming Extent and LBound in that order

  psa = c_func( SafeArrayCreate, { VT_BSTR, 1, bounds_ptr } )

  bstr = alloc_bstr( "cat" )
  poke4( bounds_ptr, 0 )
  void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr})
  free_bstr( bstr )

  bstr = alloc_bstr( "cow" )
  poke4( bounds_ptr, 1 )
  void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr})
  free_bstr( bstr )

  bstr = alloc_bstr( "wolverine" )
  poke4( bounds_ptr, 2 )
  void = c_func( SafeArrayPutElement, {psa, bounds_ptr, bstr})
  free_bstr( bstr )

  make_variant( var, VT_ARRAY + VT_BSTR, psa )
  return var
end function
```
```


q:
We have recently implemented Transparent Data Encryption in SQL Server 2008 for local databases on our developers laptops to keep them protected in the case a laptop is stolen or lost. This works fine.

Now we are trying to figure out a way to have the certificate expire everyday, forcing an automated process (a script at logon maybe) to go out to a network path and grab a new certificate with an expiration for a day later. This would ensure that if something unforeseen happened, the data would not be usable the next day.

I also looked into using a Cryptographic provider but there doesn't appear to be any "providers" out there. Maybe I'm wrong.

I am open to suggestions. If there is a better way please let me know. Thanks!

[A]
Short answer: No
Long answer:  Once a message (piece of data) is encrypted, that same key will decrypt the same encrypted message, regardless of what time the decryption algorithm is applied.  If the key is changed every day, the data must be decrypted with the old key and re-encrypted with the new.  If this process doesn't occur (i.e. someone stops the piece of code that performs the re encryption from running), the old key will still work.  Even if you do create a cryptographic provider to check the date, someone else can create a new provider to perform the decryption without first checking the date.


q: Is there a .NET Framework compiler for the Ruby language? I've heard of the DLR (Dynamic Language Runtime), is this going to enable Ruby to be used with .NET development?

[A]
Yep, the Ruby.NET project
.  Note, it hasn't been updated since November 2007, so I'm not sure what the support's like now.
Edit: As others have pointed out, IronRuby is supported by Microsoft, so it's probably a better idea


q:
I'm looking for a generic "Row Picker" for JQuery.

We've all seen the cool "Picker" tools like date pickers, color pickers, time pickers, etc, where you click in a text box and a little calendar or color palate or clock or something comes up.  You select something (like a date) and the text box is then populated with a value.

I really need an all-purpose "row picker" where you can populate something (a table, divs, etc) with some rows of data (say a list of timezones).  This would be linked to a text field and would pop up when the user clicks in the field.

They would click a row (say a timezone), and the timezone id would be passed back to the field.

Anyone know of anything that does this?

Thanks!

[A]
I don't know about totally generic though you can certainly achieve a row selector fairly easily in jQuery.
```
```

45	GMT

47	CST

```
```
This adds a click to each row, finds the tagged id within the row which would then allow you to do something with it.  Obviously you would need to target this to your data table and filter based on the contents.  JQuery can then be used to populate the result of the click into the target field.  You can then come up with some convention where all your data tables work the same which would allow you to generalise this into a generic picker for your application.


q:
I have only a basic knowledge of css, is it possible to inherit a property from one style into another style. So for instance I could inherit the font size specified in my default paragrah tag settings into my hyperlink tags.

The reason I want to do this is to make it easier to maintain multiple styles.

[A]
You can define common styles for two elements at once like so:
```
```
p, a {
    font-size: 1em;
}
```
```
And then extend each one with their individual properties as you want:
```
```
p {
   color: red;
}

a {
   font-weight: bold;
}
```
```
Keep in mind:
Styles defined later in a style sheet generally override properties defined earlier.
Extra:
If you haven't already, I recommend getting the
Firebug
Firefox extension so you can see what styles the elements on your page are receiving and where they are inherited from.


q:
I found a wonderful open source Java program that I'm translating into C#. The built-in translator in Visual Studio got me started and I've now spent about a month translating the rest manually line by line. I've completed over 15,000 lines of translation and the only thing that remains is trying to figure out how to convert their MemoryImageSource stuff into C#/.NET.

What's the .NET equivalent way of implementing this stuff? Is there a native .NET library already?

[A]
The standard .NET
```
System.Drawing.
```
```
Bitmap
```
class in the
```
System.Drawing.dll
```
assembly comes close to what I know of the
```
MemoryImageSource
```
(i.e., an image represented as an array of pixels that you can manipulate).
For better performance, you can use the
```
ImageTraverser
```
class from CodeProject, which accessses the array through unmanaged pointers.


q:
I have a swf that is run from C:/ in the browser instead of a server (long story) and that swf loads a video that it located at ../../videos/video in relation to that swf.

Problem is, When I run it in Flex, everything is cool.  Running locally, it can't find the file (not a security error) and is throwing a connectionError.

Any ideas?

NOTE: This seems to be a Windows specific problem, it's running on my mac with the same security settings just fine.

[A]
Flex Builder has a file that it adds all of your bin directories to in order to allow the debug player to get around the local security restrictions.
Here's a
blog post on the subject
.
Essentially Flexbuilder tells Flash that it should trust the bin folder... if you do a search on your development machine for the file flexbuilder_plugin.cfg, you should find it in a folder called FlashPlayerTrust in roughly the same area you normally find SharedObject files. If you open this file in a text editor, you should see pretty much every path to every bin folder for every flex project you have ever worked on. And suddenly everything gets so much clearer.
You can do as fenomas suggests and add any directory to your trusted list. You can also follow the advice from the above blog post.
So I created a new file and placed it next to this flexbuilder_plugin.cfg file, and called it MyProggy.cfg. Flash is configured to read in all files in this folder and parse all paths out of it, and any applications run from these paths will be considered "localTrusted" and will act as they would when run from Flexbuilder. Inside this text file I put one line: "c:\program files\my proggy" and saved it. I then had to restart Firefox for the change to take effect. I also had added a text label to my application and bound the text property to {Security.sandboxType}.


q:
Note: This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).

We're building a web API that's programmatically generated from a C# class. The class has method GetFooBar(int a, int b) and the API has a method GetFooBar taking query params like &a=foo &b=bar.

The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?

[A]
From this site:
https://www.tek-tips.com/viewthread.cfm?qid=1500861
C# does allow the use of the [Optional] attribute (from VB, though not functional in C#). So you can have a method like this:
```
```
using System.Runtime.InteropServices;
public void Foo(int a, int b, [Optional] int c)
{
  ...
}
```
```
In our API wrapper, we detect optional parameters (ParameterInfo p.IsOptional) and set a default value. The goal is to mark parameters as optional without resorting to kludges like having "optional" in the parameter name.


q: I have come to see an Installer class item in Visual studio. Why they have maintain an seperate item for Installer. Do they create any custom installers ?

[A]
The Installer class can be used to configure items such as performance counters and message queues as part of the installation of your code.  They can be included with any assembly and the most basic way to install components related to an assembly is to use InstallUtil yourassembly.dll which would contain your code and custom installers.  It is good practice to provide an uninstall option for anything added in this manner.
See here fore more information
http://msdn.microsoft.com/en-us/library/z3xc61bs(VS.80).aspx


q:
I'm trying to get a postgres jdbc connection working in eclipse. It would be nice to use the Data Source Explorer, but for now I'm just trying to get a basic connection. What I have done so far is download the postgres JDBC connector. I then tried two different things. First, Preferences-> Data Management, I tried to add the postgres connector. Second, I added the jar to my project and tried to load the driver using Class.forName("org.postgresql.Driver"); but neither worked. Does anyone have any ideas?

Thanks,
   Charlie

[A]
Here's one way to get PostgreSQL connectivity to your application:
Get an instance of
```
org.postgresql.ds.PGSimpleDataSource
```
Setup it with values matching to your database (see methods below)
Proceed using the DataSource as you would use any other, I'd assume at this point you'd be interested in the
```
DataSource.getConnection()
```
method.
The proprietary methods for configuring this particular DataSource are
```
setServerName()
```
,
```
setDatabaseName()
```
,
```
setUser()
```
and
```
setPassword()
```
.
I wouldn't recommend doing this for anything else than testing though and it's possible your problem lies in the way you're trying to get an instance of the object using
```
Class.forName()
```
There's almost a dozen different ways to get an instance of an object with subtle differences, I suggest Googling for it since it is a subject a lot of people have already written about all over the Internet.


q:
I have the following fields:

Inventory control (16 byte record)

Product ID code (int – 4 bytes)

Quantity in stock (int – 4 bytes)

Price (double – 8 bytes)

How do I create a fixed length random access file using the above lengths? I tried some examples online, but I either get an EOF exception or random address values when I try to access them.

I tried some more examples and couldn't understand the concept very well. I'm trying a project with it and will try to explore more on it.

Here is some example data. There might be holes in the data where No. in stock could be 23 == 023.

          Quantity
ID. No.   In Stock   Price

-------   --------   ------
 1001       476      $28.35
 1002       240      $32.56
 1003       517      $51.27
 1004       284      $23.75
 1005       165      $32.25

Thanks for the help.

[A]
java.io.RandomAccessFile is the class you're looking for. Here's an example implementation (you'll probably want to write some unit tests, as I haven't :)
```
```
package test;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Raf {
    private static class Record{
        private final double price;
        private final int id;
        private final int stock;

        public Record(int id, int stock, double price){
            this.id = id;
            this.stock = stock;
            this.price = price;
        }

        public void pack(int n, int offset, byte[] array){
            array[offset + 0] = (byte)(n & 0xff);
            array[offset + 1] = (byte)((n >> 8) & 0xff);
            array[offset + 2] = (byte)((n >> 16) & 0xff);
            array[offset + 3] = (byte)((n >> 24) & 0xff);
        }

        public void pack(double n, int offset, byte[] array){
            long bytes = Double.doubleToRawLongBits(n);
            pack((int) (bytes & 0xffffffff), offset, array);
            pack((int) ((bytes >> 32) & 0xffffffff), offset + 4, array);
        }

        public byte[] getBytes() {
            byte[] record = new byte[16];
            pack(id, 0, record);
            pack(stock, 4, record);
            pack(price, 8, record);
            return record;
        }
    }

    private static final int RECORD_SIZE = 16;
    private static final int N_RECORDS = 1024;

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        RandomAccessFile raf = new RandomAccessFile(args[0], "rw");
        try{
            raf.seek(RECORD_SIZE * N_RECORDS);

            raf.seek(0);

            raf.write(new Record(1001, 476, 28.35).getBytes());
            raf.write(new Record(1002, 240, 32.56).getBytes());
        } finally {
            raf.close();
        }
    }
}
```
```


q:
I have an application running in tomcat that has a bunch of configuration files that are different for each environment it runs in (dev, testing, and production). But not every line in a config file will be different between environments so there's invariably duplicated information that doesn't get updated if something changes.

Is there a good framework/library that collapses the separate files into one with environment specific blocks? Or some other way of dealing with this?

[A]
A Properties file is what I've always used.  It's editable by hand as well as in in your software and the Properties object can read itself in and write itself out to the filesystem.  Here's the javadoc page:
http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html


q:
I have a div that contains several child elements, one of which is a flash movie.

When rolling over this div, I want it to change style to indicate it is rolled over. My problem is that the mouseover and mouseout events don't always trigger, especially if the user moves the mouse over the flash element too quickly.

Any suggestions for how I can ensure that a mouseover event always get triggered.

I can't add an event to the flash movie itself because it is proprietary code that I don't have the source for.

Also I can't cover the flash movie in a div/image because I need rollover and click events to occur within the flash itself.

[A]
What you could do is cover the flash element with an invisible div. Place your onmouseover handler on that div, and add a line to the handler to hide the covering div. At the same time, add an
```
onmouseover
```
function to the window - this should get triggered when the mouse leaves the flash element. (I hope).
There's a
```
<div>
```
covering your flash.
When the user mouses over it:
It calls whatever function it needs to do.
It hides itself, allowing normal interaction with the SWF.
It places a mouseover function on the window which will:
Show the original
```
div
```
again.
Calls your "mouseout" function.
Removes the
```
window.onmouseover
```
function.


q:
I'm trying to do a domain lookup in vba with something like this:

DLookup("island", "villages", "village = '" & txtVillage & "'")

This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error.

I've written a trivial function that escapes single quotes - it replaces "'" with "''".  This seems to be something that comes up fairly often, but I can't find any reference to a built-in function that does the same.  Have I missed something?

[A]
It's worse than you think.  Think about what would happen if someone entered a value like this, and you haven't escaped anything:
```
```
'); DROP TABLE [YourTable]
```
```
Not pretty.
The reason there's no built in function to simply escape an apostrophe is because the correct way to handle this is to use query parameters.  For an Ole/Access style query you'd set this as your query string:
```
```
DLookup("island", "village", "village = ? ")
```
```
And then set the parameter separately.  I don't know how you go about setting the parameter value from vba, though.


q: As the title: How would I tell NHibernate, once and for all, that all table and column names are to be quoted in the SQL it generates?

[A]
I've not tried this, but as far as i can determine based on the
documentation
a custom implementation of the naming strategy allows you to rewrite the table/column names thus also enables you to quote them.


q:
Is it possible to add comments somehow, somewhere?

I don't pretend to be any sort of expert when using MySQL and certainly don't spend all day in it.  More often than I would like I forget how I intend to use a column (usally the bit ones) and would be very excited if I could add a comment to remind me if 1 is good or bad, for example.

I'd be happy if it only showed up in something like 'show create table', but any obscure place within the table structures would be better and easier to find than the current post-it notes on my desk.

[A]
Are you sure you're not looking to use an ENUM column instead? Good MySQL tables should be self-documenting.
An alternate approach would be to comment the schema files that have the SQL you use to define your tables (I assume you have those, and that you're not using PHPMyAdmin to grow table schemas on the fly...)
But if you insist, the
INFORMATION_SCHEMA COLUMNS
table, specifically the COLUMN_COMMENT column, is probably what you're looking for. It's proprietary MySQL syntax though, so I would tend to avoid it (although the idea of database interoperability is really a joke).


q:
I have 2 tables. One (domains) has domain ids, and domain names (dom_id, dom_url).

the other contains actual data, 2 of which columns require a TO and FROM domain names. So I have 2 columns rev_dom_from and rev_dom_for, both of which store the domain name id, from the domains table.

Simple.

Now I need to actually display both domain names on the webpage. I know how to display one or the other, via the LEFT JOIN domains ON reviews.rev_dom_for = domains.dom_url query, and then you echo out the dom_url, which would echo out the domain name in the rev_dom_for column.

But how would I make it echo out the 2nd domain name, in the dom_rev_from column?

[A]
you'd use another join, something along these lines:
```
```
SELECT toD.dom_url AS ToURL,
    fromD.dom_url AS FromUrl,
    rvw.*

FROM reviews AS rvw

LEFT JOIN domain AS toD
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD
    ON fromD.Dom_ID = rvw.rev_dom_from
```
```
EDIT
:
All you're doing is joining in the table multiple times.   Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read
here
.


q:
In C# there is a method SetApartmentState in the class Thread.
How do I do the same thing in C++?

[A]
c++ doesn't have built in thread support. What you are looking for depends on how you are implementing threads in your application. Win32? pthreads? boost::threads? Whichever API you are using will determine the answer to your question.
EDIT: looks like this may have an example for you:
http://msdn.microsoft.com/en-us/library/system.threading.apartmentstate.aspx
It looks like it applies to managed c++.


q:
How can I find out the folder where the windows service .exe file is installed dynamically?

Path.GetFullPath(relativePath);

returns a path based on C:\WINDOWS\system32 directory.

However, the XmlDocument.Load(string filename) method appears to be working against relative path inside the directory where the service .exe file is installed to.

[A]
Try
```
```
System.Reflection.Assembly.GetEntryAssembly().Location
```
```


q: The gcc -S option will generate assembly code in AT&T syntax, is there a way to generate files in Intel syntax?  Or is there a way to convert between the two?

[A]
Use
```
-masm=intel
```
```
```
gcc -S -masm=intel -Og -fverbose-asm test.c
```
```
That works with GCC, and clang3.5 and later.
GCC manual
:
```
-masm=dialect
```
Output asm instructions using selected dialect.  Supported choices
are intel or att (the default one).  Darwin does not support intel.
For Mac OSX, note that by default, the
```
gcc
```
command actually runs clang.  Modern clang supports
```
-masm=intel
```
as a synonym for this, but
this always works with clang
:
```
```
clang++ -S -mllvm --x86-asm-syntax=intel test.cpp
```
```
Note that
until clang 14
, this does
not
change how clang processes inline
```
asm()
```
statements,
unlike for GCC
.
These are the options used by Matt Godbolt's Compiler Explorer site by default:
https://godbolt.org/
See also
How to remove "noise" from GCC/clang assembly output?
for other options and tips for getting asm output that's interesting to look at.


q:
Let's say I wanted to have an application that could easily switch the DB at the back-end.

I'm mostly thinking of SQL Server as the primary back-end, but with the flexibility to go another DB engine.  Firebird and PostGreSQL seem to have (from my brief wikipedia excursion) the most in common w/ SQL Server (plus they are free).

How similar would the DB setup, access, queries, etc.. be for Firebird, PostGreSQL and MS SQL Server?

[A]
Unfortunately, SQL varies widely across providers. It's almost impossible to write all but the most trivial SQL to run on a number of RDBMS - and then you're into lowest common denominator territory. Far better to use an abstraction layer to handle at least the connection to the database (inc. access, sending queries), and either an ORM to handle the SQL itself or per-provider SQL.
If you want to look into how they vary - good examples are auto-incrementing ids and obtaining the ID of the last inserted record.


q: In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like Ans or % to retrieve the last computed value. Is there a similar facility in the Python shell?


q:
In my experience Meta-templates are really fun (when your compilers are compliant), and can give good performance boosts, and luckily I'm surrounded by seasoned C++ programmers that also grok meta-templates, however occasionally a new developer arrives and can't make heads or tails of some of the meta-template tricks we use (mostly Andrei Alenxandrescu stuff), for a few weeks until he gets initiated appropriately.

So I was wondering what's the situation for other C++ programmers out there?
Should meta-template programming be something C++ programmers should be "required" to know (excluding entry level students of course), or not?

Edit: Note my question is related to production code and not little samples or prototypes

[A]
If you can you find enough candidates who really know template meta-programing then by all means, require it.  You will be showing a lot of qualified and potentially productive people the door (there are plenty of legitimate reasons not to know how to do this, namely that if you do it on a lot of platforms, you will create code that can't compile, or that average developers will have trouble understanding).  Template meta-programming is great, but let's face it, it's pushing C++ to the limit.
   Now, a candidate should probably understand basics (compute n! at compile time, or at least explain how it works if they are shown the code).  If your new developers are reliably becoming productive within a few weeks, then your current recruiting is probably pretty good.


q: I have access to an Oracle server that has some databases that I would like to access. However, the machine that I have access from has none of the oracle client software. Is there any alternative to oracle's client software the provides the functionality of something like MySQL's mysql or Postgres' psql? I'd like to be able to poke around a bit in the database before writing software against it.

[A]
If you download the
free
Oracle Instant Client
you'd be able to use any JDBC or ODBC Database tool such as
DbVisualizer
or
SquirrelSQL
.  Those are GUI tools; I've not come across a JDBC command line tool but there may be one out there.
Alternatively, there is an
Instant Client version of SQL*Plus
which will give you an Oracle
```
sqlplus
```
command line without a full Oracle install.


q: In C#, how do I get the name of the drive that the Operating System is installed on?

[A]
This should do it for you:
```
```
Path.GetPathRoot(Environment.SystemDirectory)
```
```


q: I am doing 2nd year computer science and we have a software engineering group project. There are 5 people in the group and we would like to build a web application in php. Please suggest some ideas for me

[A]
How about a
content management system
?
This allows you to show off every part of your web development skill and it shouldn't be hard to do with a 5 person team. CMSs often include file uploads, file management and on-line text editors (something like TinyMCE).
They're actually quite fun to develop and when the system is completed it has a great "wow" factor. Especially when you show people how you can edit the contents of your website on-line.


q:
Possible Duplicate:

  How to parse a string to an int in C++?

How do you convert a C++ string to an int?

Assume you are expecting the string to have actual numbers in it ("1", "345", "38944", for example).

Also, let's assume you don't have boost, and you really want to do it the C++ way, not the crufty old C way.

[A]
Use the C++ streams.
```
```
std::string       plop("123");
std::stringstream str(plop);
int x;

str >> x;

/* Lets not forget to error checking */
if (!str)
{
     // The conversion failed.
     // Need to do something here.
     // Maybe throw an exception
}
```
```
PS. This basic principle is how the boost library
```
lexical_cast<>
```
works.
My favorite method is the boost
```
lexical_cast<>
```
```
```
#include <boost/lexical_cast.hpp>

int x = boost::lexical_cast<int>("123");
```
```
It provides a method to convert between a string and number formats and back again. Underneath it uses a string stream so anything that can be marshaled into a stream and then un-marshaled from a stream (Take a look at the >> and << operators).


q:
What is the difference between UTF and UCS.

What are the best ways to represent not European character sets (using UTF) in C++ strings. I would like to know your recommendations for:

Internal representation inside the code

For string manipulation at run-time

For using the string for display purposes.

Best storage representation (i.e. In file)

Best on wire transport format (Transfer between application that may be on different architectures and have a different standard locale)

[A]
UTC is Coordinated Universal Time, not a character set (I didn't find any charset called UTC).
For internal representation, you may want to use
```
wchar_t
```
for each character, and std::wstring for strings. They use exactly 2 bytes for each character, so seeking and random access will be fast.
For storage, if most of the data are not ASCII (i.e. code >= 128), you may want to use UTF-16 which is almost the same as serialized
```
wstring
```
and
```
wchar_t
```
.
Since UTF-16 can be little endian or big endian, for wire transport, try to convert it to UTF-8, which is architecture-independent.


q:
Is it possible to search for an object by one of its properties in a Generic List?

Public Class Customer

    Private _id As Integer

    Private _name As String

    Public Property ID() As Integer
        Get
            Return _id
        End Get
        Set
            _id = value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set
            _name = value
        End Set
    End Property

    Public Sub New(id As Integer, name As String)
        _id = id
        _name = name
    End Sub

End Class

Then loading and searching

Dim list as new list(Of Customer)

list.Add(New Customer(1,"A")

list.Add(New Customer(2,"B")

How can I return customer object with id =1? Does this have to do with the "Predicate" in Generics?

Note: I am doing this in VB.NET.

[A]
If you are using .NET 3.5 this can be done with
LINQ to Objects
:
How to: Query an ArrayList with LINQ
If not, in .NET 2.0 you can use the
```
Find
```
method of the list
.
The idea is that you will need to provide an method that return true if a property of your object satisfies a certain condition.


q: So what's the best way to create new tables in a Sqlite database in Rails 2. I have created the database using rake db:migrate command. So should I write individual sql scripts to create a database or use rake somehow. I don't need scaffolding.

[A]
If you are not using scaffolding then you should use
```
script/generate migration
```
to create a migration file for each table. There is no need to use sql scripts. After creating some migrations you can apply them to your database using rake db:migrate.


q:
I have a Stored procedure which schedules a job. This Job takes a lot of time to get completed (approx 30 to 40 min). I need to get to know the status of this Job.
Below details would help me

1) How to see the list of all jobs that have got scheduled for a future time and are yet to start

2) How to see the the list of jobs running and the time span from when they are running

3) How to see if the job has completed successfully or has stoped in between because of any error.

[A]
You haven't specified how would you like to see these details.
For the first sight I would suggest to check
Server Management Studio
.
You can see the jobs and current statuses in the SQL Server Agent part, under Jobs. If you pick a job, the Property page shows a link to the Job History, where you can see the start and end time, if there any errors, which step caused the error, and so on.
You can specify alerts and notifications to email you or to page you when the job finished successfully or failed.
There is a Job Activity Monitor, but actually I never used it. You can have a try.
If you want to check it via T-SQL, then I don't know how you can do that.


q:
I need to use an alias in the WHERE clause, but It keeps telling me that its an unknown column. Is there any way to get around this issue? I need to select records that have a rating higher than x. Rating is calculated as the following alias:

sum(reviews.rev_rating)/count(reviews.rev_id) as avg_rating

[A]
You could use a HAVING clause, which
can
see the aliases, e.g.
```
```
HAVING avg_rating>5
```
```
but in a where clause you'll need to repeat your expression, e.g.
```
```
WHERE (sum(reviews.rev_rating)/count(reviews.rev_id))>5
```
```
BUT! Not all expressions will be allowed - using an aggregating function like SUM will not work, in which case you'll need to use a HAVING clause.
From the
MySQL Manual
:
It is not allowable to refer to a
  column alias in a WHERE clause,
  because the column value might not yet
  be determined when the WHERE  clause
  is executed. See
Section B.1.5.4,
  “Problems with Column Aliases”
.


q:
I'm experimenting with an updated build system at work; currently, I'm trying to find a good way to set compiler & flags depending on the target platform.

What I would like to do is something like

switch $(PLATFORM)_$(BUILD_TYPE)
  case "Linux_x86_release"
     CFLAGS = -O3
  case "Linux_x86_debug"
     CFLAGS = -O0 -g
  case "ARM_release"
     CC = armcc
     AR = armlink
     CFLAGS = -O2 -fx
     ...

which is not supported by GNU Make. Now, my first thought was to just do

-include $(PLATFORM)_$(BUILD_TYPE)

which is a pretty decent solution, however, it makes it hard to get an overview of what differs between files, not to mention that I'm looking forward to writing & maintaining a good 60-80 files, each containing a set of variable definitions.

Does anyone happen to know a better way to accomplish this? I.e. setting a set of flags and other options based on another variable?

[A]
Configuring such parameters would be the task of a
```
configure
```
script.
That being said, you can look into the syntax for
conditionals
and
conditional functions
. For example, you could try the following:
```
```
ifeq ($(PLATFORM)_$(BUILD_TYPE),Linux_x86_release)
    CFLAGS = -O3
endif
ifeq ($(PLATFORM)_$(BUILD_TYPE),Linux_x86_debug)
    CFLAGS = -O0 -g
endif
```
```


q:
How do I generate excel reports with rich formatting including charts with a ASP.Net application?

As per http://support.microsoft.com/kb/257757 server-side automation of office is not advisable and also our admin does not allow installation of office on the server

Customer is not ready to spend a lot on 3rd party components

A must requirement is to retain the formatting used by the end user already and also use ONLY excel 2003.

Thanks

Update: We are using ExcelXmlWriter from http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx as it was the most fit.

[A]
Two options you might consider:
1) The ReportViewer control.  You can design your report, including charts, and have it output to excel.  You can allow the report to be shown within the control, or bypass that and export it directly to excel.  The version it will be open in depends on what the client has installed.
2) You could create a page that with the lay out you are seeking using a GridView, or plain old HTML tables with your chart images embedded.  Modify the response headers so this page downloads as an excel file.
If you need to preserve Excel charts that change when data is changed in the resulting Excel file, I'm not sure if that is possible without the use of third party controls or Office automation.  The options above work if you are embedding a chart image created by your asp.net app.


q:
I've a small project that I want to share with a few others on a machine that we all have access to. I created a bare copy of the local repo with

git clone --bare --no-hardlinks path/to/.git/ repoToShare.git

I then moved repoToShare.git to the server.

I can check it out with the following:

git clone ssh://user@address/opt/gitroot/repoToShare.git/ test

I can then see everything in the local repo and make commits against that. When I try to push changes back to the remote server I get the following error.

*** Project description file hasn't been set
error: hooks/update exited with error code 1
error: hook declined to update refs/heads/master

Any ideas?

[A]
Git installs a bunch of pre-configured hooks in the hooks directory, out of the box they do not execute. If you happen to allow execute on them (Eg. chmod +x) then git will try to run them. The particular error pops up cause the default update is failing to run. To fix, delete the default update hook.
Does
this link
help? From the text:
A colleague of mine experienced a
  similar issue here where push was not
  working. You could not push to a local
  or remote public repository. He was
  getting a project description file
  hasn't been set error thrown by
  .git/hooks/update. This error was not
  happening for the same project on a
  linux or Windows box, and seemed to be
  happening only on Windows Vista. From
  my research hooks/update is not by
  default executed, but in windows vista
  the file permissions meant that it
  was. Deletion of hooks/update resolved
  these issues.


q:
I'm using the MIDP 2.0 (JSR 118) and I just noticed that there is no reader for strings in J2ME.

Does anyone know how you are supposed to read Strings from an InputStream or InputStreamReader in a platform independent way (i.e. between two java enabled cell phones of different models)?

[A]
Which profile are you using? The MID profile in JSR 118 specifies
InputStreamReader
(not StringReader, but that wouldn't help you read from an InputStream anyway).
EDIT: To reflect the change to the question :)
You use InputStreamReader.read(char[], int, int) and when you've read all you want to, create a new string from a char array. If you want to read a line at a time as you would from BufferedReader, you basically need to implement the functionality of BufferedReader yourself (keeping a buffer of "read but not consumed" chars) and keep reading until you hit a line break.


q:
I don't understand it.

The ids of html elements in the master page are changed by the same id but with a prefix and it's breaking the css design.

In the master page I have:

<div id="container" runat="server">

    <asp:ContentPlaceHolder ...

...

The above code is rendered

<div id="ctl00_ctloo_container">

     ...

And the CSS styles are gone obviously.

How do I stop it?

Thanks!

[A]
AFAIK you cannot do this. This is the default behaviour because of the control tree.
If you would like to use CSS then set the CSS class directly, don't depend on IDs, like
```
```
<asp:Whatever runat="server" id="whatever" CssClass="whateverClass">
```
```
Update:
Here
is a similair thread, but it won't help on your CSS problem.


q:
I've read all the marketing speak about how mvc and webforms are complementary etc...

However it seems that all the blogs talk about is mvc and the only news coming out is about mvc.

Is Microsoft going to continue to IMPROVE webforms as a first class citizen or will it just be a supported technology as they move all their real efforts, developers and resources to mvc over time?

Is there any real evidence of any new exciting improvements coming to webforms in the near future?

[A]
I was at a conference (Remix 08) and Scott Gu said they will definatly be continuing to support both methods and that MVC was not appropriate for every application. Scott said there were a number of coming improvements for web forms model (although didnt say what they were).
The web forms model will not disapear because:
Web forms model is better for some types of applications, e.g. small apps, those requiring long processes that make use of view state useful
Many applications are using it
Many third party components developed for it
ASP.net implementation is not mature yet (although does seem pretty good so far)
Microsoft will probably announce a number of new features in PDC in a few weeks time.


q: i've never created a shopping cart, or forum in php. aside from viewing and analyzing another persons project or viewing tutorials that display how to make such a project or how to being such a project. how would a person know how to design the database structure to create such a thing? im guessing its probbably through trial and error...

[A]
you should read up and understand the basics of
normalization
. for most projects, normalizing to 3rd normal form will be just fine. there are always certain scenarios when you want more or less normalization, but understanding the concepts behind it will allow you to think about how your database is structured in a normalized format.
here's a very basic example of normalizing a table:
```
```
students
  student_id
  student_name
  student_class
  student_grade
```
```
a pretty standard table containing various data, but we can see some issues right away. we can see that a student's name is dependant on his ID, however, a student may be involved in more than one class, and each class would conceivably have a different grade. we can then think about the tables as such:
```
```
students
  student_id
  student_name

class
  class_id
  class_name
```
```
this is not bad, now we can see we have various students, and various classes, but we haven't captured the student's grades.
```
```
grades
  student_id
  class_id
  grade
```
```
now we have a 3rd table, which allows us to understand the relation between a particular student, a particular class, and a grade associated with that class. from our first initial table, we now have 3 tables in a normalized database (let's assume we don't need to normalize grades any further for sake of example :) )
a few things we can glean from this very basic example:
our data is all tied to a key of some sort (student_id, class_id, and student_id + class_id). these are unique identifiers within each table.
with our keyed relations, we're able to relate information to each other (how many classes is student #4096 enrolled in?)
we can see our tables will not contain duplicated data now (think about our first table, where student_class could be the same value for many students. if we had to change the class name, we'd have to update all the records. in our normalized format, we can just update class_name of class_id)


q:
How to create a table with a timestamp column that defaults to DATETIME('now')?

Like this:

CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    t TIMESTAMP DEFAULT DATETIME('now')
);

This gives an error.

[A]
As of
version 3.1.0
you can use
```
CURRENT_TIMESTAMP
```
with the
DEFAULT
clause:
If the default value of a column is CURRENT_TIME, CURRENT_DATE or CURRENT_TIMESTAMP, then the value used in the new row is a text representation of the current UTC date and/or time. For CURRENT_TIME, the format of the value is "HH:MM:SS". For CURRENT_DATE, "YYYY-MM-DD". The format for CURRENT_TIMESTAMP is "YYYY-MM-DD HH:MM:SS".
```
```
CREATE TABLE test (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    t TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```
```


q:
This is probably a very simple question, but what is the technical term for this class of language?

They use an "intermediate" assembly type language which is sent through the JVM or CLR.  They both are object oriented and they both depend on an intermediary such as the Java Virtual Machine or the Common Language Runtime to compile into native machine laguage.

Unlike Asm/C/C++ they don't compile directly into native machine language and require intensive memory allocation knowledge.  They both use garbage collection.

Is there a technical term which seperates Java and C# from C++?

[A]
A key difference between C++ and .NET/Java is the automatic reclaiming of memory that is no longer required.  This is known as
garbage collection
.  For this property, they are known as
managed
platforms.
Both Java/.NET delay the compilation of bytecode into native code until the last minute.  For this property they are known as
JIT-compiled
(Just In Time).
The C#/Java/C++ languages are known as
imperative, object-oriented
languages.
The type system in both .NET and Java only allows verifiable invocation of methods.  For this property they are known as
statically typed
.
C#/Java/C++ are
Turing complete
, meaning that, in practice, they can produce any calculation.


q:
Does anybody knows why this snippet returns false even if the passed string is "Active"?

if ($('status_'+id).getText()=="Active")

I've also tried changing the code to

if ($('status_'+id).getText()==String("Active"))

and

if (String($('status_'+id).getText())=="Active")

and still no luck.

I've also checked $('status_'+id).getText() through console.log to verify if it really returns "Active"

i wonder why it doesnt work?
any ideas?


q:
I have created a custom installer dll & everything is working fine.  I just want to call another installer's Uninstall method from my current installation.  When I do this, I get error code 1618 (signifies another installer is already running).  However when I call the uninstall of the same product from a test project, it is working fine.

Could anyone suggest a solution to this?

Can I uninstall another application from the current installer?

[A]
If this other product is your own (and hence you have access to what the installer should be doing), or you want to do something dirty, you could try removing the files/registry entries/etc yourself then unregistering the program in the registry (
```
HKEY_LOCAL(MACHINE|USER)\Software\Microsoft\Windows\CurrentVersion\Uninstall\{PROGRAM}
```
). Not really the greatest idea ever, but if you have access to what the installer should be doing, then it'll work for you.


q: I've never learnt JavaScript, but I imagine this is quite a simple problem. Just wanted to know which method is most advised these days.

[A]
```
```
// use this to avoid redirects when a user clicks "back" in their browser
window.location.replace('http://somewhereelse.com');

// use this to redirect, a back button call will trigger the redirection again
window.location.href = "http://somewhereelse.com";

// given for completeness, essentially an alias to window.location.href
window.location = "http://somewhereelse.com";
```
```
edit
: looks like the user who posted the better answer has left SO, i've consolidated his answers here.


q: We are currently thinking of building a cache-system to hold data pulled out of an SQL database and make it available to a couple of other applications (website, webservice, etc). We imagine the cache to be running as a windows service and basically consist of a smart dictionary which holds the cache entries. My question is, is there a limit to the working set of the application (it will be running under windows server 2003)? Or is the amount of physical memory the limit?

[A]
As with any other Windows program, you're limited by address space. That is: on 32-bit, you can have 2GB of address space. On x64, you can have 8TB.
If you don't have 8TB of physical memory, it will start to page.


q:
Is there a way to select designtime packages on a project bases?

Packages are very useful in large project to keep the build time acceptable, but they are a real pita in those large projects too. When one developer adds a new package, it breaks to build for all other until they install the new package on their machine. And then there is versioning of the packages ...

So has anyone a proper solution for this? (it has been bothering me for years now)

[A]
This is not easy too do.  You can do it though, with the use of a custom registry hack, and a specific bds shortcut per configuration you are interested in:
To use, just create a new shortcut and
  modify the command line to pass e.g.
  -rMyAlternateBDSReg. Then after launching that once, the reg entry is
  created and they can configure that
  alternate registry all they want,
  deleting packages, etc, without
  worrying about messing up the default
  install.
From
codegear
If you set up a configuration for each project, you can then start the appropriate shortcut for the given project.  It's not automatic, but it is better than having everything there all the time.
A nice side effect is that the load times will be improved.


q:
I want to filter two list with any fastest method in python script. I have used the built-in filter() method for this purpose. but it is quite slow and taking too much time because I have very big list, I think more than 5 million item in each list or may be more.
I do not know how I will make it. Please if anybody have idea or write small function for it.

[A]
I guess filter() is as fast as you can possibly get without having to code the filtering function in C (and in that case, you better code the whole filtering process in C).
Why don't you paste the function you are filtering on? That might lead to easier optimizations.
Read
this
about optimization in Python. And
this
about the Python/C API.


q:
The CSS syntax highlighting in vim is not entirely optimal. For example:

div.special_class

stops the highlighting at the _.

Is there an improved highlighter that doesn't bite on an underscore?

Update:
I'm using VIM - Vi IMproved 7.1 (2007 May 12, compiled Jun 17 2008 15:22:40)

and the header of my css.vim is:

" Vim syntax file
" Language:     Cascading Style Sheets
" Maintainer:   Claudio Fleiner <claudio@fleiner.com>
" URL:          http://www.fleiner.com/vim/syntax/css.vim
" Last Change:  2006 Jun 19
" CSS2 by Nikolai Weibull
" Full CSS2, HTML4 support by Yeti

[A]
What version of vim are you using?
My css.vim is
```
```
" Vim syntax file
" Language: Cascading Style Sheets
" Maintainer:   Claudio Fleiner <claudio@fleiner.com>
" URL:      http://www.fleiner.com/vim/syntax/css.vim
" Last Change:  2005 Nov 23
" CSS2 by Nikolai Weibull
" Full CSS2, HTML4 support by Yeti
```
```
as shipped with vim 7.0, and it does not expose the behaviour you described.


q:
I need to model a system where by there will be a team who will consist of users who perform roles in the team and have skills assigned to them.

i.e. a team A 5 members, one performs the team leader role, all perform the reply to
email role, but some have an extra skill to answer the phone

I'm trying to determine how I can best model this.

This problem must have been solved before, are there any good resources on how to model this?

EDIT: I need to determine what a user is allowed to do, which could be because they are in a certain team, perform a certain role or have been assigned a certain skill

[A]
Not really anything I've heard from, but it's simple enough to be solved in variety of ways.
So there's Teams, Members, Roles and Skills. Teams are just Member-containers and Member has roles and skills.
Here's yet a small pseudo to give you the whole idea:
```
```
class Team
    container[Member] members

class Member
    container[Role] roles
    container[Skill] skills
```
```
Then you instantiate or subclass roles and skills, depending about what kind of things they are and the capabilities of your programming language.
..In other hand, In practise it'd may make sense to make a Team -class similar to Role and Skill -class - a property of Member -class. If you need to find out things like what one member has access into.


q: What is meant by "Constant Amortized Time" when talking about time complexity of an algorithm?

[A]
It means that over time, the worst case scenario will default to O(1), or constant time. A common example is the dynamic array. If we have already allocated memory for a new entry, adding it will be O(1). If we haven't allocated it we will do so by allocating, say, twice the current amount. This particular insertion will
not
be O(1), but rather something else.
What is important is that the algorithm guarantees that after a sequence of operations the expensive operations will be amortised and thereby rendering the entire operation O(1).
Or in more strict terms,
There is a constant c, such that for
every
sequence of operations (also one ending with a costly operation) of
  length L, the time is not greater than
  c*L (Thanks
Rafał Dowgird
)


q:
I have two multidimensional arrays (well actually they're only 2D) which have inferred size. How do I deep clone them? Here's what I have gotten so far:

public foo(Character[][] original){
    clone = new Character[original.length][];
    for(int i = 0; i < original.length; i++)
          clone[i] = (Character[]) original[i].clone();
}

A test for equality original.equals(clone); spits out a false. Why? :|

[A]
You might want to check out the
java.util.Arrays.deepEquals
and
java.util.Arrays.equals
methods.
I'm afraid the
```
equals
```
method for array objects performs a shallow comparison, and does not properly (at least for this case) compare the inner
```
Character
```
arrays.


q:
I'm rebuilding a site with a lot of incoming links, and the URL structure is completely changing. I'm using the stock mod_rewrite solution to redirect all old links to new pages.
However, as I'm sure a few links will slip through the net, I've built a small script that runs on my custom 404 page, to log the incoming visitors' referrer URL. This will help me track down any broken links.

In addition to referrer, is there also a way of logging the url that the user entered, or clicked that caused a 404? I ask this as referrer is obviously a bit 'hit & miss'.

I suspect not, but thought it worth a question.


q:
I have been recommended "Resource Tuner console" but it's a little out of my price range.

I'm looking for something that could be launched from a nant build script and told to stamp an exe with an additional property as described in my previous question.

[A]
Hi my name is Archit and few monts age i felt for same question...
Now,
There are many tools which will give you command line editing ,
Resource hacker : Free and good one,
it provides scripting and saving resources go through help file where u get hell lot of examples about that ,
by the way u only asked for cheap OR free utilities ,
but there are several tolls which can perform efficiently (not free one)
if u want some more util call me ...
and yes most of the paying resource editor tools provide command line editing free.....means u can download trail and go for cmd line editor absolutely free....


q:
I need to call a VBScript file (.vbs file extension) in my C# Windows application.
How can I do this?

There is an add-in to access a VBScript file
in Visual Studio.
But I need to access the script in code behind. How to do this?

[A]
The following code will execute a VBScript script with no prompts or errors and no shell logo.
```
```
System.Diagnostics.Process.Start(@"cscript //B //Nologo c:\scripts\vbscript.vbs");
```
```
A more complex technique would be to use:
```
```
Process scriptProc = new Process();
scriptProc.StartInfo.FileName = @"cscript";
scriptProc.StartInfo.WorkingDirectory = @"c:\scripts\"; //<---very important
scriptProc.StartInfo.Arguments ="//B //Nologo vbscript.vbs";
scriptProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; //prevent console window from popping up
scriptProc.Start();
scriptProc.WaitForExit(); // <-- Optional if you want program running until your script exit
scriptProc.Close();
```
```
Using the
```
StartInfo
```
properties will give you quite granular access to the process settings.
You need to use
Windows Script Host
if you want windows, etc. to be displayed by the script program. You could also try just executing
```
cscript
```
directly but on some systems it will just launch the editor :)


q:
I've tried a couple of approaches to update a column in a mySQL database table from another table but am not having any luck.

I read somewhere that version 3.5.2 does not support multi-table updates and I need a code-based solution - is that correct?

If not can anybody point me in the right direction using sql?

UPDATE products SET products_ordered = (
    SELECT SUM(products_quantity)
    FROM orders_products
    WHERE products_id = products.products_id
);

or:

Create temporary table my_temp_table
as
SELECT products_id, SUM(products_quantity) as total
FROM orders_products
GROUP BY products_id

UPDATE products, my_temp_table
SET products.products_ordered = my_temp_table.total
WHERE products.products_id = my_temp_table.products_id

[A]
Multi-table updates are not support in MySQL <= 4.0.4
I would highly recommend to update your server to MySQL 5.0.xx


q:
I'm sorry for this very newbish question, I'm not much given into web development. I've got this cool JavaScript in a .js file that we want to use on a small web site. (It's a script to run Cooliris on it).

How do use the .js file or attach it to my HTML code?

[A]
```
```
<script type="text/javascript" src="myfile.js"></script>
```
```
Usually inserted in the <head> tag. After that, it depends wether or not your script need additional initialization or customisation to work.