Question:
I have a VB6 program that someone recently helped me convert to VB.NET

In the program, when saving files, I stamp them with the date which I was getting by calling the Today() function.

When I try to run the new VB.NET code in Vista it throws a permission exception for the Today() . If I run Visual Studio Express (this is the 2008 Express version) in Admin mode, then the problem doesn't occur, but clearly I want to end up with a stand-alone program which runs for all users without fancy permissions.

So how can a normal VB.NET program in Vista get today's date?

Answer:
Use
```
DateTime.Now
```
or
```
DateTime.Today
```
.  These are entirely managed and shouldn't throw security exceptions.
The old VB6 functions, such as
```
Len()
```
,
```
Left()
```
,
```
Right()
```
,
```
OpenFile()
```
,
```
FreeFile()
```
are all present in the .NET Framework in the Microsoft.VisualBasic DLL.  To maintain backwards compatibility, they all call the old functions in unmanaged code.  Unmanaged code requires special security permissions because it can be dangerous.
Whenever possible, try and use the newer .NET functions.  They are usually much faster (File IO using Streams for instance) and safer.


Question: I am rewriting code to handle some embedded communications and right now the protocol handling is implemented in a While loop with a large case/switch statement.  This method seems a little unwieldy. What are the most commonly used flow control methods for implementing communication protocols?

Answer:
For cases where you key off of a field in a protocol header to direct you to the next stage of processing for that protocol, arrays of function pointers can be used. You use the value from the protocol header to index into the array and call the function for that protocol.
You
must
handle all possible values in this array, even those which are not valid. Eventually you will get a packet containing the invalid value, either because someone is trying an attack or because a future rev of the protocol adds new values.


Question:
I'm using the following method to send mail from Python using SMTP. Is it the right method to use or are there gotchas I'm missing ?

from smtplib import SMTP
import datetime

debuglevel = 0

smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect('YOUR.MAIL.SERVER', 26)
smtp.login('USERNAME@DOMAIN', 'PASSWORD')

from_addr = "John Doe <john@doe.net>"
to_addr = "foo@bar.com"

subj = "hello"
date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" )

message_text = "Hello\nThis is a mail from your server\n\nBye\n"

msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s"
        % ( from_addr, to_addr, subj, date, message_text )

smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

Answer:
The main gotcha I see is that you're not handling any errors:
```
.login()
```
and
```
.sendmail()
```
both have
documented exceptions
that they can throw, and it seems like
```
.connect()
```
must have some way to indicate that it was unable to connect - probably an exception thrown by the underlying socket code.


Question:
How do I use Perl to create graphs?

I'm running scheduled job that creates text reports.  I'd like to move this to the next step (for the management) and also create some graphs that go along with this.  Is this possible / feasible?   It'd be great if I could do this using Office some how.

update: solutions i'm going to investigate in this order

Spreadsheet::WriteExcel (this seems to now have changed from the last time i investigated this .... wait, this was suggested by the author of the module.  cool.)

GD Graph - this is now available for ActivePerl(wasn't last time i looked)

SVG

Open Charts look interesting.

Chartdirector

Answer:
```
```
Spreadsheet::WriteExcel::Chart
```
```
You might need something like strawberry or vanilla Perl to get this to compile. Or PPM might have the module.
Tutorial link:
http://search.cpan.org/dist/Spreadsheet-WriteExcel/charts/charts.pod


Question:
I've started to work a bit with master pages for an ASP.net mvc site and I've come across a question.  When I link in a stylesheet on the master page it seems to update the path to the sheet correctly.  That is in the code I have

<link href="../../Content/Site.css" rel="stylesheet" type="text/css" />

but looking at the source once the page is fed to a browser I get

<link href="Content/Site.css" rel="stylesheet" type="text/css" />

which is perfect.  However the same path translation doesn't seem to work for script files.

<script src="../../Content/menu.js" type="text/javascript"></script>

just comes out as the same thing.  It still seems to work on a top level page but I suspect that is just the browser/web server correcting my error.  Is there a way to get the src path to be globbed too?

Answer:
Use this instead:
```
```
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
```
```


Question:
PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this:

var_dump(explode('/', '1/2//3/'));
array(5) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(0) ""
  [3]=>
  string(1) "3"
  [4]=>
  string(0) ""
}

Is there some different function or option or anything that would return everything except the empty strings?

var_dump(different_explode('/', '1/2//3/'));
array(3) {
  [0]=>
  string(1) "1"
  [1]=>
  string(1) "2"
  [2]=>
  string(1) "3"
}

Answer:
```
```
function not_empty_string($s) {
  return $s !== "";
}

array_filter(explode('/', '1/2//3/'), 'not_empty_string');
```
```


Question: I was discussing neural networks (NN) with a friend over lunch the other day and he claimed the the performance of a NN written in Java would be similar to one written in C++.  I know that with 'just in time' compiler techniques Java can do very well, but somehow I just don't buy it.  Does anyone have any experience that would shed light on this issue?  This page is the extent of my reading on the subject.

Answer:
The Hotspot JIT can now produce code
faster
than C++.  The reason is run-time empirical optimization.
For example, it can see that a certain loop takes the "false" branch 99% of the time and reorder the machine code instructions accordingly.
There's lots of articles about this.  If you want all the details, read
Sun's excellent whitepaper
.  For more informal info,
try this one
.


Question: Is it possible to use both JScript and VBScript in the same HTA? Can I call VBScript functions from JScript and vice-versa? Are there any "gotchas," like the JScript running first and the VBScript running second (classic ASP pages have this issue).

Answer:
Yeah, just separate them into different script tags:
```
```
<script language="javascript">
   // javascript code
</script>

<script language="vbscript">
   ' vbscript code
</script>
```
```
Edit: And, yeah, you can cross call between Javascript and VBScript with no extra work.
Edit: This is also true of ANY Windows Scripting technology.  It works in WSF files and can include scripts written in any supported ActiveScript language such as Perl as long as the engine is installed.
Edit: The specific "gotcha" of all JScript being executed first, then VBScript is related to how ASP processes scripts. The MSHTA host (which uses IE's engine) does not have this problem. I'm not much into HTAs though, so I can't address any other possible "gotchas".


Question:
Do I risk losing sales by disabling SSL 2.0 and PCT 1.0 in IIS5?

Clarification: Sales would be lost by client not being able to connect via SSL to complete ecommerce transaction because SSL 2.0 or PCT 1.0 is disabled on the web server.

Microsoft kbase article: http://support.microsoft.com/kb/187498

Answer:
Only you can really answer that question. Your customers' experience of your site will be mediated by their browser. The first place to look for browser information is at a listing of the user-agents that are being used to access your website. Hopefully you have a good log analyzer such as Analog, Weblog, Google Analytics, WebTrends, etc. This is the first place to look and should give you a good idea of the SSL level that your general community supports.
You may also want to alter your application to check for the SSL level supported by your users' browsers that get to the "complete ecommerce transaction" part of your website. This is the best method to determine if you are turning away customers.
Remember that the SSL level is auto negotiated between the server and the client (best encryption used first) so you don't necessarily need to disable older versions, but you could pop up a message to the user encouraging them to upgrade.


Question: I know next to nothing when it comes to the how and why of https connections.  Obviously, when I'm transmitting secure data like passwords or especially credit card information, https is a critical tool.  What do I need to know about it, though?  What are the most common mistakes you see developers making when they implement it in their projects?  Are there times when https is just a bad idea?  Thanks!

Answer:
Be sure that, when on an HTTPS page, all elements on the page come from an HTTPS address. This means that elements should have relative paths (e.g. "/images/banner.jpg") so that the protocol is inherited, or that you need to do a check on every page to find the protocol, and use that for all elements.
NB: This includes all outside resources (like Google Analytics javascript files)!
The only down-side I can think of is that it adds (nearly negligible) processing time for the browser and your server. I would suggest encrypting only the transfers that need to be.


Question: What's the proper way to convert from a scientific notation string such as "1.234567E-06" to a floating point variable using C#?

Answer:
```
```
Double.Parse("1.234567E-06", System.Globalization.NumberStyles.Float);
```
```


Question:
If I issue the find command as follows:

find . -name *.ear

It prints out:

./dir1/dir2/earFile1.ear
./dir1/dir2/earFile2.ear
./dir1/dir3/earFile1.ear

I want to 'print' the name and the size to the command line:

./dir1/dir2/earFile1.ear  5000 KB
./dir1/dir2/earFile2.ear  5400 KB
./dir1/dir3/earFile1.ear  5400 KB

Answer:
```
```
find . -name "*.ear" -exec ls -l {} \;
```
```


Question:
I'm using the JFrame plugin with jquery 1.2.6.

It works fine in FF3, however it won't display the requested pages in IE 7.

The jQuery library and the JFrame plugin are called in the included header.cfm.

Page code is here (note: ignore the ColdFusion calls, I don't think they're generating the problem): http://cfm.pastebin.com/m20c1b013

Answer:
When you have a problem like this, the best way of tracking down the problem is to reduce the page to the minimum necessary to reproduce the problem.
"Ignore the [x] because I don't think that's the problem"
is no good, if you don't think that's the problem, save it to a temporary static page, delete the things you think are unrelated, and then you
know
whether or not they are the problem.  Keep deleting things you think are unrelated, and eventually you will either find the bit that's screwing things up when you remove it, or you will end up with a very small file that is:
Much easier to debug
Much more likely to attract help from people
Much better testcase for the times when it's a genuine bug in a library
Not many people are willing to pick apart Coldfusion and table layout code to get to your bug - after all, you're the one with the problem, and even you couldn't be bothered to do it, so why would anybody else?


Question:
Theres is a little problem I want to solve with Haskell:
let substitute a function that change all of the wildcards in a string for one concrete parameter. The function has de signature of:

subs :: String -> String -> String -> String
-- example:
-- subs 'x' "x^3 + x + sin(x)" "6.2" will generate
--          "6.2^3 + 6.2 + sin(6.2)"

Answer:
You could use the
Text.Regex
package.
Your example might look something like this:
```
```
import Text.Regex(mkRegex, subRegex)

subs :: String -> String -> String -> String
subs wildcard input value = subRegex (mkRegex wildcard) input value
```
```


Question:
What is a non recursive algorithm for deciding whether a passed in amount can be built additively from a set of numbers.

In my case I'm determining whether a certain currency amount (such as $40) can be met by adding up some combination of a set of bills (such as $5, $10 and $20 bills).  That is a simple example, but the algorithm needs to work for any currency set (some currencies use funky bill amounts and some bills may not be available at a given time).

So $50 can be met with a set of ($20 and $30), but cannot be met with a set of ($20 and $40).  The non-recursive requirement is due to the target code base being for SQL Server 2000 where the support of recursion is limited.

In addition this is for supporting a multi currency environment where the set of bills available may change (think a foreign currency exchange teller for example).

Answer:
Edit:
The following will work
some
of the time.  Think about why it won't work all the time and how you might change it to cover other cases.
Build it starting with the largest bill towards the smallest.  This will yeild the lowest number of bills.
Take the initial amount and apply the largest bill as many times as you can without going over the price.
Step to the next largest bill and apply it the same way.
Keep doing this until you are on your smallest bill.
Then check if the sum equals the target amount.


Question: Coming from J2ME programming are there any similarities that would make it easy to adapt to Android API. Or is Android API completely different from the J2ME way of programming mobile apps.

Answer:
A good start would be to watch the Android architecture videos and look at some of the documentation.
http://www.youtube.com/view_play_list?p=586D322B5E2764CF
http://code.google.com/android/what-is-android.html
Google is very good about documenting. From what I've heard Android very very similar to J2ME in its goals. It may be slightly different in programming style and structure but if you have J2ME experience you should be more then ready to move on to Android.
Good Luck!!!


Question: How can I poll disk activity in Applescript? Check to see if disk X is being read, written, or idle every N seconds and do something.

Answer:
In general, polling is less efficient than being notified when something happens. Additionally, if you're checking whether something is reading from a disk, you will probably be accessing said disk yourself, possibly influencing what you're trying to observe.
Since 10.5, OSX includes something called the File System Events framework, which provides course-grained notifications of changes to the file system. The problem in your case is that this is Objective-C only. Apple has some nice
documentation
about this API.
Fortunately, there is also the
```
call method
```
AppleScript command. This allows you to work with Objective-C objects from within AppleScript. Here's the
documentation
on that.
I have no experience with either, hence the documentation references. Hopefully, this should get you going.


Question:
int i = 4;
string text = "Player ";
cout << (text + i);

I'd like it to print Player 4.

The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?

Answer:
```
```
cout << "Player" << i ;
```
```


Question:
Most text editors have a navigation pane that lets you see all the files you currently have open.  Or a pane that lets you browse a file directory.

How do I do this in Emacs?

Answer:
C-x b TAB
will give you an auto complete with all open buffers.   Alternatively, click on the
```
Buffers
```
menu item if you are in a windowed version (not sure if there is a terminal equivalent of that).
EDIT: Also
C-x C-f
will let you open a file, and you can use
TAB
for autocomplete, then
TAB
again to view files/directories in that current directory (assuming the first tab did not autocomplete something).


Question: Is there a way to substring in JSP files, using struts2 technologies? I mean, struts2 has its own taglib and also uses ognl. How can I get a substring from a stacked value or bean value?

Answer:
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html
Look for fn:substring and its variants.
I've used Struts 1, but not 2.


Question:
As of the fall of 2008 I'm about to embark on a new development cycle for a major product that has a winforms and an asp.net interface.  We use Telerik, DevExpress and Infragistics components in it and all are going to have a release within a month or so which will be the one I target for our spring release of our product.

They all support VS2005 and we will continue to target .net 2+ so I can't see any compelling reason so far to upgrade to VS2008.

Has anyone found a compelling reason for upgrading to VS2008?

Answer: It's worth it. It's faster, the designer is vastly improved (split view, faster context switching), it has better support for javascript and when you're ready to target 3.5, you'll be ready to go.


Question: I believe I need a DTD to define the schema and an XSLT if I want to display it in a browser and have it look "pretty". But I'm not sure what else I would need to have a well-defined XML document that can be queried using XQuery and displayed in a web browser.

Answer:
Strictly speaking, you need nothing. XML, even without a schema definition, works.
A schema definition (in XSD, RelaxNG or DTD) helps various tools that work with the XML, because they can verify that the structure of the XML conforms to what you want.
An XSLT translation to HTML is nice if the XML contains information you'll want to look at with a browser. It's far from necessary, though.
To query the XML with XPath or XQuery, you need an XPath or XQuery processor.


Question: Has anybody used C# to write a sample screen scraper for IBM as400?

Answer: I wrote one in C many years ago for a project at Frigidaire.  The internal card would cause all sorts of fun with memory leaks but I eventually found a solution by allocating arrays at the boundary of the communication card.  This was over 8 years ago, I'm sure today's cards are much better and/or using native comm to read the AS400 screens.


Question:
How would you write (in C/C++) a macro which tests if an integer type (given as a parameter) is signed or unsigned?

      #define is_this_type_signed (my_type) ...

Answer:
In C++, use
```
std::numeric_limits<type>::is_signed
```
.
```
```
#include <limits>
std::numeric_limits<int>::is_signed  - returns true
std::numeric_limits<unsigned int>::is_signed  - returns false
```
```
See
https://en.cppreference.com/w/cpp/types/numeric_limits/is_signed
.


Question: I need to deploy an application on the WAS ND 6.1 and do not know anything about it and cannot afford to go to training...

Answer:
There is the RedBook
WebSphere Application Server V6.1: System Management and Configuration
with Chapter 14 talking about application deployment, this could help.


Question: During the load of my cocoa application, my program crashes with the messsage EXC_BAD_ACCESS.  The stack trace is not helpful.  Any clues to how I can find the problem?

Answer:
This is one possible reason.  There is a IBOutlet object that isn't being initialized and a message is being invoked on nil.  The stack trace might look like this:
```
```
#0    0x90a594c7 in objc_msgSend
#1    0xbffff7b8 in ??
#2    0x932899d8 in loadNib
#3    0x932893d9 in +[NSBundle(NSNibLoading) _loadNibFile:nameTable:withZone:ownerBundle:]
#4    0x9328903a in +[NSBundle(NSNibLoading) loadNibFile:externalNameTable:withZone:]
#5    0x93288f7c in +[NSBundle(NSNibLoading) loadNibNamed:owner:]
#6    0x93288cc3 in NSApplicationMain
#7    0x00009f80 in main at main.mm:17
```
```
Since the stack trace is not helpful you will have to step through your code to find the error.  If for some reason you aren't able to set breakpoints early in your execution, try inserting some Debugger(); calls which will break to the debugger.


Question:
Is it possible to select from show tables in MySQL?

SELECT * FROM (SHOW TABLES) AS `my_tables`

Something along these lines, though the above does not work (on 5.0.51a, at least).

Answer:
Have you looked into querying INFORMATION_SCHEMA.Tables?  As in
```
```
SELECT ic.Table_Name,
    ic.Column_Name,
    ic.data_Type,
    IFNULL(Character_Maximum_Length,'') AS `Max`,
    ic.Numeric_precision as `Precision`,
    ic.numeric_scale as Scale,
    ic.Character_Maximum_Length as VarCharSize,
    ic.is_nullable as Nulls,
    ic.ordinal_position as OrdinalPos,
    ic.column_default as ColDefault,
    ku.ordinal_position as PK,
    kcu.constraint_name,
    kcu.ordinal_position,
    tc.constraint_type
FROM INFORMATION_SCHEMA.COLUMNS ic
    left outer join INFORMATION_SCHEMA.key_column_usage ku
        on ku.table_name = ic.table_name
        and ku.column_name = ic.column_name
    left outer join information_schema.key_column_usage kcu
        on kcu.column_name = ic.column_name
        and kcu.table_name = ic.table_name
    left outer join information_schema.table_constraints tc
        on kcu.constraint_name = tc.constraint_name
order by ic.table_name, ic.ordinal_position;
```
```


Question:
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms.
Thus splitting the respective string by the space-character is not sufficient anymore.

Example:

input : 'foo bar "lorem ipsum" baz'
output: ['foo', 'bar', 'lorem ipsum', 'baz']

I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations.

Any help would be greatly appreciated!

Answer:
```
```
'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g);
```
```
the bounding quotes get included though


Question: I want to create templates for base new reports on to have common designs.  How do you do it?

Answer:
The need to produce reports with a common starting design and format is key to any project involving clients and their reports.  I have been working on reports for over 10 years now.  This has not been the largest portion of my jobs through the years but it has been a very import one.  The key to any report project is not to recreate the mundane aspects of the reports for each but to use templates.  The use of templates is not a common task or knowledge for Microsoft's SQL Server Reporting Services.  Knowing how to save reports templates so that you and your team can create these shortcuts at the creation of a new report in Visual Studio 2005 will help save time and have all reports use the same layout and design.
Create of a set of reports with the following suggestions:
Page size -- 8.5 by 11 (letter) and 8.5 by 14 (legal)
Orientation -- portrait and landscape for all paper sizes
Header -- Text Box for report name, Text Box for report subtitle, client or brand logo
Footer -- page number/total pages, date and time report printed
Take all the rdl files for the reports created from the suggestions and copy the files to the following directory:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\PrivateAssemblies\ProjectItems\ReportProject
When creating a new report in your Visual Studio 2005 report project through Add|New Item
alt text http://www.cloudsocket.com/images/image-thumb14.png
The new report dialog will present the list of items from the directory where the new templates were placed.
alt text http://www.cloudsocket.com/images/image-thumb15.png
Select the report that fits the requirement needed and proceed to develop your reports without needing to create the basics.


Question:
As stated in the title, i'm looking for an XML schema (XSD-file) for the Glade markup language?

Wikipedia states that Glade is a schema based markup language (list of schemas at wikipedia). I tried to search the web, wikipedia and the glade website,but i couldn't find an XSD for Glade.

Thx,
Juve

Answer:
http://svn.async.com.br/cgi-bin/viewvc.cgi/libglade/glade-2.0.dtd?view=markup
(The main version @
http://glade.gnome.org/glade-2.0.dtd
doesn't seem to be working)


Question: How do you create SQL Server 2005 stored procedure templates in SQL Server 2005 Management Studio?

Answer:
You bring up
Template Explorer
using Ctrl+Alt+T or trough
View > Template Explorer
. Then you can right click tree nodes to add new Templates or new folders to organize your new templates.


Question:
How do I create a unique constraint on an existing table in SQL Server 2005?

I am looking for both the TSQL and how to do it in the Database Diagram.

Answer:
```
```
ALTER TABLE dbo.<tablename> ADD CONSTRAINT
            <namingconventionconstraint> UNIQUE NONCLUSTERED
    (
                <columnname>
    ) ON [PRIMARY]
```
```


Question:
I'm working with a support person who is supposed to be able to install SSL certs on a web server he maintains.  He has local admin rights to the server via a domain security group.  He also has permissions on our internal CA running Windows 2003 Server Certificate Authority: "Request cert" and "Issue and Manage certs".

The server he's working with is running Windows 2000 SP4 / IIS 5.  When he attempts to create an online server cert the IIS wizard ends with "Failed to install.  Access is Denied.".  The event viewer is not working properly, so I can't find any details there.  I suspect the permission issue is locally and not with the CA.

My account is a domain admin account and I know I am able to do this operation, however I need to make this work for others that are not domain admins.

Any ideas why he can't perform this operation?

Answer:
I had this exact same issue a few months ago when I was setting up a cert for a client.
There's a MachineKeys folder that the Administrator need rights -
```
```
\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
```
```
give
Administrator
(or the Administrator group)
Full Control
over this directory.  I don't think you have to restart IIS, but it never hurts .
I have no idea why Admin doesn't control this as default.
Once this is changed, the Certificate Creation Wizard will successfully generate the certificate request.
I think there's even a Microsoft KB article about it somewhere.
EDIT: Here's the KB article :
http://support.microsoft.com/kb/908572
-Jon


Question:
How would I remove the border from an iframe embedded in my web app? An example of the iframe is:

<iframe src="myURL" width="300" height="300">Browser not compatible.</iframe>

I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help.

Answer:
Add the
```
frameBorder
```
attribute (note the
capital ‘B’
).
So it would look like:
```
```
<iframe src="myURL" width="300" height="300" frameBorder="0">Browser not compatible.</iframe>
```
```


Question:
As far as I know, in gcc you can write something like:

#define DBGPRINT(fmt...) printf(fmt);

Is there a way to do that in VC++?

Answer:
Almost. It's uglier than that though (and you probably don't want a trailing semi-colon in the macro itself:
```
```
#define DBGPRINT(DBGPRINT_ARGS) printf DBGPRINT_ARGS // note: do not use '(' & ')'
```
```
To use it:
```
```
DBGPRINT(("%s\n", "Hello World"));
```
```
(was missing a pair of parens).
Not sure why all the negatives, the original question didn't state a version of VC++, and variadic macros aren't supported by all compilers.


Question:
I am refactoring some CSS on a website. I have been working on, and noticed the absence of traditional HTML IDs in the code.

There is heavy use of CssClass='&hellip;', or sometimes just class='&hellip;', but I can't seem to find a way to say id='…' and not have it swapped out by the server.

Here is an example:

<span id='position_title' runat='server'>Manager</span>

When the response comes back from the server, I get:

<span id='$aspnet$crap$here$position_title'>Manager</span>

Any help here?

Answer:
.Net will always replace your id values with some mangled (every so slightly predictable, but still don't count on it) value.  Do you really NEED to have that id runat=server?  If you don't put in runat=server, then it won't mangle it...
ADDED:
Like leddt said, you can reference the span (or any runat=server with an id) by using ClientID, but I don't think that works in CSS.
But I think that you have a larger problem if your CSS is using ID based selectors. You can't re-use an ID. You can't have multiple items on the same page with the same ID. .Net will complain about that.
So, with that in mind, is your job of refactoring the CSS getting to be a bit larger in scope?


Question:
If i have a simple named query defined, the preforms a count function, on one column:

  <query name="Activity.GetAllMiles">
    <![CDATA[
      select sum(Distance) from Activity
    ]]>

  </query>

How do I get the result of a sum or any query that dont return of one the mapped entities, with NHibernate using Either IQuery or ICriteria?

Here is my attempt (im unable to test it right now), would this work?

    public decimal Find(String namedQuery)
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            IQuery query = session.GetNamedQuery(namedQuery);

            return query.UniqueResult<decimal>();
        }
    }

Answer:
As an indirect answer to your question, here is how I do it without a named query.
```
```
var session = GetSession();
var criteria = session.CreateCriteria(typeof(Order))
            .Add(Restrictions.Eq("Product", product))
            .SetProjection(Projections.CountDistinct("Price"));
return (int) criteria.UniqueResult();
```
```


Question:
Is there a performant equivalent to the isnull function for DB2?

Imagine some of our products are internal, so they don't have names:

Select product.id, isnull(product.name, "Internal)
From product

Might return:

1 Socks
2 Shoes
3 Internal
4 Pants

Answer:
I'm not familiar with DB2, but have you tried COALESCE?
ie:
```
```
SELECT Product.ID, COALESCE(product.Name, "Internal") AS ProductName
FROM Product
```
```


Question:
I'd like to be able to write a PHP class that behaves like an array and uses normal array syntax for getting & setting.

For example (where Foo is a PHP class of my making):

$foo = new Foo();

$foo['fooKey'] = 'foo value';

echo $foo['fooKey'];

I know that PHP has the _get and _set magic methods but those don't let you use array notation to access items.  Python handles it by overloading __getitem__ and __setitem__.

Is there a way to do this in PHP?  If it makes a difference, I'm running PHP 5.2.

Answer:
If you extend
```
ArrayObject
```
or implement
```
ArrayAccess
```
then you can do what you want.
ArrayObject
ArrayAccess


Question:
We have a live MySQL database that is 99% INSERTs, around 100 per second. We want to archive the data each day so that we can run queries on it without affecting the main, live database. In addition, once the archive is completed, we want to clear the live database.

What is the best way to do this without (if possible) locking INSERTs? We use INSERT DELAYED for the queries.

Answer:
Could you keep two mirrored databases around? Write to one, keep the second as an archive. Switch every, say, 24 hours (or however long you deem appropriate). Into the database that was the archive, insert all of todays activity. Then the two databases should match. Use this as the new live db. Take the archived database and do whatever you want to it. You can backup/extract/read all you want now that its not being actively written to.
Its kind of like having mirrored raid where you can take one drive offline for backup, resync it, then take the other drive out for backup.


Question: What are the common algorithms being used to measure the processor frequency?

Answer:
I'm not sure why you need assembly for this.  If you're on a machine that has the /proc filesystem, then running:
```
```
> cat /proc/cpuinfo
```
```
might give you what you need.


Question: If I want to use the validation framework that you can use with ASP.NET MVC, will the JavaScript conflict with other JavaScript frameworks like jQuery or YUI?

Answer:
There are many MVC frameworks. There are many JavaScript frameworks that have different functionalities. If you want a meaningful answer, you should choose an MVC and a JavaScript framework and ask concerning those two. Please be as detailed as possible in your questions.
As an example, the validation handling on ActiveRecord (used in Ruby on Rails) only performs validations on the server end. You can always add JavaScript validations on top of that, but the server-side validations are what really matters for data integrity.


Question:
We are planning to use the jQuery library to augment our client side JavaScript needs.

Are there any major issues in trying to use both ASP.Net AJAX and jQuery? Both libraries seem to use $ for special purposes. Are there any conflicts that we need to be aware of?

We also use Telerik controls that use ASP.Net AJAX.

TIA

Answer:
jQuery has a noConflict() method as a part of the core, but it then requires that you either use jQuery as your named function or something else of your choosing (instead of the dollar selector). However, I will say that the method is often dependent on the implementation of the "competing" library. I have tried to use it for a Ning social network (which used Dojo), and for Magento (which uses Prototype), and I could not get either to play right with jQuery. This is just my personal experience, and others have been very successful.
http://docs.jquery.com/Core/jQuery.noConflict


Question: What's the easiest way to get the filename associated with an open HANDLE in Win32?

Answer:
On unixes there is no real way of reliably doing this.  In unix with the traditional unix filesystem, you can open a file and then unlink it (remove its entry from the directory) and use it, at which point the name isn't stored anywhere.  In addition, because a file may have multiple hardlinks into the filesystem, each of the names are equivalent, so once you've got just the open handle it wouldn't be clear which filename you should map back towards.
So, you may be able to do this on Win32 using the other answers, but should you ever need to port the application to a unix enviornment, you'll be out of luck.  My advice to you is to refactor your program, if possible, so that you don't need the OS to be able to maintain an open resource to filename connection.


Question:
Using jQuery, how can I dynamically set the size attribute of a select box?

I would like to include it in this code:

$("#mySelect").bind("click",
    function() {
        $("#myOtherSelect").children().remove();
        var options = '' ;
        for (var i = 0; i < myArray[this.value].length; i++) {
            options += '<option value="' + myArray[this.value][i] + '">' + myArray[this.value][i] + '</option>';
        }
        $("#myOtherSelect").html(options).attr [... use myArray[this.value].length here ...];
    });
});

Answer:
Oops, it's
```
```
$('#mySelect').attr('size', value)
```
```


Question:
I was recently asked to come up with a script that will allow the end user to upload a PSD (Photoshop) file, and split it up and create images from each of the layers.

I would love to stay with PHP for this, but I am open to Python or Perl as well.

Any ideas would be greatly appreciated.

Answer:
Oops, it's
```
```
$('#mySelect').attr('size', value)
```
```


Question:
We have a number of web-apps running on IIS 6 in a cluster of machines. One of those machines is also a state server for the cluster. We do not use sticky IP's.

When we need to take down the state server machine this requires the entire cluster to be offline for a few minutes while it's switched from one machine to another.

Is there a way to switch a state server from one machine to another with zero downtime?

Answer:
You could use the SQL server option to store state. I've used this in the past and it works well as long as the ASPState table it creates is in memory. I don't know how well it would scale as an on-disk table.
If SQL server is not an option for whatever reason, you could use your load balancer to create a virtual IP for your state server and point it at the new state server when you need to change. There'd be no downtime, but people who are on your site at the time would lose their session state. I don't know what you're using for load balancing, so I don't know how difficult this would be in your environment.


Question:
I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception:

org.apache.axis.ConfigurationException: No service named <web service name> is available

any idea?

Answer:
This is what my code looks like. It seems to work fine.
Are you using a service locator or just creating your service?
```
```
SomeServiceLocator locator = new SomeServiceLocator();
SomeService service = null;
try
{
    service = locator.getSomeServiceImplPort();
}
catch (ServiceException e)
{
    e.printStackTrace();
}
```
```


Question:
How do I add an instance method to a class using a metaclass (yes I do need to use a metaclass)? The following kind of works, but the func_name will still be "foo":

def bar(self):
    print "bar"

class MetaFoo(type):
    def __new__(cls, name, bases, dict):
        dict["foobar"] = bar
        return type(name, bases, dict)

class Foo(object):
    __metaclass__ = MetaFoo

>>> f = Foo()
>>> f.foobar()
bar
>>> f.foobar.func_name
'bar'

My problem is that some library code actually uses the func_name and later fails to find the 'bar' method of the Foo instance. I could do:

dict["foobar"] = types.FunctionType(bar.func_code, {}, "foobar")

There is also types.MethodType, but I need an instance that does'nt exist yet to use that. Am I missing someting here?

Answer:
I think what you want to do is this:
```
```
>>> class Foo():
...   def __init__(self, x):
...     self.x = x
...
>>> def bar(self):
...   print 'bar:', self.x
...
>>> bar.func_name = 'foobar'
>>> Foo.foobar = bar
>>> f = Foo(12)
>>> f.foobar()
bar: 12
>>> f.foobar.func_name
'foobar'
```
```
Now you are free to pass
```
Foo
```
s to a library that expects
```
Foo
```
instances to have a method named
```
foobar
```
.
Unfortunately, (1) I don't know how to use metaclasses and (2) I'm not sure I read your question correctly, but I hope this helps.
Note that
```
func_name
```
is only assignable in Python 2.4 and higher.


Question: How does one automatically find categories for text based on content?

Answer:
There is a good paper written on this:
http://www.cs.utexas.edu/users/hyukcho/classificationAlgorithm.html


Question: When working with large and/or many Javascript and CSS files, what's the best way to reduce the file sizes?

Answer:
Minify
seems to be one of the easiest ways to shrink Javascript.
Turning on zip at the web server level can also help.


Question:
What techniques or tools are recommended for finding broken links on a website?

I have access to the logfiles, so could conceivably parse these looking for 404 errors, but would like something automated which will follow (or attempt to follow) all links on a site.

Answer:
For Chrome Extension there is
hexometer
See
LinkChecker
for Firefox.
For Mac OS there is a tool
Integrity
which can check URLs for broken links.
For Windows there is
Xenu's Link Sleuth
.


Question:
In Tomcat 5.5 the server.xml can have many connectors, typically port only 8080, but for my application a user might configure their servlet.xml to also have other ports open (say 8081-8088).  I would like for my servlet to figure out what socket connections ports will be vaild (During the Servlet.init() tomcat has not yet started the connectors.)

I could find and parse the server.xml myself (grotty), I could look at the thread names (after tomcat starts up - but how would I know when a good time to do that is? )  But I would prefer a solution that can execute in my servlet.init() and determine what will be the valid port range.   Any ideas?   A solution can be tightly bound to Tomcat for my application that's ok.

Answer:
In Tomcat 6.0 it should be something like:
```
```
org.apache.catalina.ServerFactory.getServer().getServices
```
```
to get the services. After that you might use
```
```
Service.findConnectors
```
```
which returns a Connector which finally has the method
```
```
Connector.getPort
```
```
See the
JavaDocs
for the details.


Question:
How would I get the here and and here to be on the right, on the same lines as the lorem ipsums? See the following:

Lorem Ipsum etc........here
blah.......................
blah blah..................
blah.......................
lorem ipsums.......and here

Answer:
The first line would consist of 3
```
<div>
```
s. One outer that contains two inner
```
<div>
```
s. The first inner
```
<div>
```
would have
```
float:left
```
which would make sure it stays to the left, the second would have
```
float:right
```
, which would stick it to the right.
```
```

stuff

stuff

```
```
... obviously the inline-styling isn't the best idea - but you get the point.
2,3, and 4 would be single
```
<div>
```
s.
5 would work like 1.


Question: I want to delete foo() if foo() isn't called from anywhere.

Answer:
Resharper
does this, and not just with methods. It also does it with using statements, variables etcetera.


Question:
I've been attempting to write a Lisp macro that would perfom the equivalent of ++ in other programming languages for semantic reasons.  I've attempted to do this in several different ways, but none of them seem to work, and all are accepted by the interpreter, so I don't know if I have the correct syntax or not.  My idea of how this would be defined would be

(defmacro ++ (variable)
  (incf variable))

but this gives me a SIMPLE-TYPE-ERROR when trying to use it.  What would make it work?

Answer:
Remember that a macro returns an expression to be evaluated. In order to do this, you have to backquote:
```
```
(defmacro ++ (variable)
   `(incf ,variable))
```
```


Question:
I'm a longtime Java programmer working on a PHP project, and I'm trying to get PHPUnit up and working.  When unit testing in Java, it's common to put test case classes and regular classes into separate directories, like this -

/src
  MyClass.java

/test
  MyClassTest.java

and so on.

When unit testing with PHPUnit, is it common to follow the same directory structure, or is there a better way to lay out test classes?  So far, the only way I can get the "include("MyClass.php")" statement to work correctly is to include the test class in the same directory, but I don't want to include the test classes when I push to production.

Answer:
You need to modify PHP's include_path so that it knows where to find MyClass.php when you
```
include()
```
it in your unit test.
You could have something like this at the top of your test file (preceding your include):
```
```
set_include_path(get_include_path() . PATH_SEPARATOR . "../src");
```
```
This appends your
```
src
```
directory onto the include path and should allow you to keep your real code separate from your test code.


Question: Someone told me it's more efficient to use StringBuffer to concatenate strings in Java than to use the + operator for Strings. What happens under the hood when you do that? What does StringBuffer do differently?

Answer:
One shouldn't be faster than the other. This wasn't true before Java 1.4.2, because when concatenating more than two strings using the "+" operator, intermediate
```
String
```
objects would be created during the process of building the final string.
However, as the
JavaDoc for StringBuffer
states, at least since Java 1.4.2 using the "+" operator compiles down to creating a
```
StringBuffer
```
and
```
append()
```
ing the many strings to it. So no difference, apparently.
However, be careful when using adding a string to another inside a loop! For example:
```
```
String myString = "";

for (String s : listOfStrings) {
  // Be careful! You're creating one intermediate String object
  // for every iteration on the list (this is costly!)
  myString += s;
}
```
```
Keep in mind, however, that usually concatenating a few strings with "+" is cleaner than
```
append()
```
ing them all.


Question: Maybe this is a silly question, but I've always assumed each number delineated by a period represented a single component of the software. If that's true, do they ever represent something different?  I'd like to start assigning versions to the different builds of my software, but I'm not really sure how it should be structured.  My software has five distinct components.

Answer:
It can be very arbitrary, and differs from product to product. For example, with the Ubuntu distribution, 8.04 refers to 2008.April
Typically the left most (major) numbers indicate a major release, and the further you go to the right, the smaller the change involved.


Question:
This link describes an exploit into my app using fckEditor:
http://knitinr.blogspot.com/2008/07/script-exploit-via-fckeditor.html

How do I make my app secure while still using fckEditor?   Is it an fckEditor configuration?   Is it some processing I'm supposed to do server-side after I grab the text from fckEditor?

It's a puzzle because fckEditor USES html tags for its formatting, so I can't just HTML encode when I display back the text.

Answer:
The bug is not actually FCKeditors fault. As long as you let users edit HTML that will be displayed on your web site they will always have to possibility to do harm unless you check the data before you output it.
Some people use HTMLencoding to do this, but that will destroy all the formatting done by FCKeditor, not what you want.
Maybe you can use the
Microsoft Anti-Cross Site Scripting Library
. Samples on
MSDN


Question:
I've been looking for this information for my commercial desktop product, with no avail.

Specifically, what I'm look for, is deployment statistics of the .NET framework for end-users (both granny "I'm just browsing the internet" XP, and high-end users, if possible), and in the commercial/business sector.

Edit: Other than the data points below, here's an interesting blog post about .NET deployment rates.

Answer: I don't have any hard numbers, but these days, it is pretty safe to assume most Windows XP and Vista users have at least .NET 2.0. I believe this was actually dropped via Windows Update for XP, and Vista came with at least 2.0 (apparently with 3.0 as pointed out in the comments to this answer).


Question:
I'm querying a bunch of information from cisco switches using SNMP.  For instance, I'm pulling information on neighbors detected using CDP by doing an snmpwalk on .1.3.6.1.4.1.9.9.23

Can I use this OID across different cisco models?  What pitfalls should I be aware of?  To me, I'm a little uneasy about using numeric OIDs - it seems like I should be using a MIB database or something and using the named OIDs, in order to gain cross-device compatibility, but perhaps I'm just imagining the need for that.

Answer:
It is very consistent.
Monitoring tools depend on the consistency and the MIBs produced by Cicso rarely change old values and usually only implement new ones.
Check out the Cisco
OID look up tool
.
Notice how it doesn't ask you what product the look up is for.
-mw


Question:
I worked on an embedded system this summer written in straight C.  It was an existing project that the company I work for had taken over.  I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.

Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit?  Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.

Answer:
One unit testing framework in C is
Check
; a list of unit testing frameworks in C can be found
here
and is reproduced below.  Depending on how many standard library functions your runtime has, you may or not be able to use one of those.
AceUnit
AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the
AceUnit homepage
.
GNU Autounit
Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the
GNU Autounit homepage
.
cUnit
Also uses GLib, but does not fork to protect the address space of unit tests.
CUnit
Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the
CUnit homepage
.
CuTest
A simple framework with just one .c and one .h file that you drop into your source tree. See the
CuTest homepage
.
CppUnit
The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the
CppUnit homepage
.
embUnit
embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit.
Embedded Unit homepage
.
MinUnit
A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the
MinUnit homepage
.
CUnit for Mr. Ando
A CUnit implementation that is fairly new, and apparently still in early development. See the
CUnit for Mr. Ando homepage
.
This list was last updated in March 2008.
More frameworks:
CMocka
CMocka is a test framework for C with support for mock objects. It's easy to use and setup.
See
the CMocka homepage
.
Criterion
Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed.
See the
Criterion homepage
for more information.
HWUT
HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output.
See
the HWUT homepage
.
CGreen
A modern, portable, cross-language unit testing and mocking framework for C and C++. It offers an optional BDD notation, a mocking library, the ability to run it in a single process (to make debugging easier). A test runner which discover automatically the test functions is available. But you can create your own programmatically.
All those features (and more) are explained in
the CGreen manual
.
Wikipedia gives a detailed list of C unit testing frameworks under
List of unit testing frameworks: C


Question:
VMware ESX, ESXi, and VirtualCenter are supposed to be able to support HTTP PUT uploads since version 3.5. I know how to do downloads, that's easy. I've never done PUT before.

Background information on the topic is here: http://communities.vmware.com/thread/117504

Answer:
You should have a look at the
```
Send-PoshCode
```
function in the
PoshCode
cmdlets script module ... it uses a POST, not a PUT, but the technique is practically identical.  I don't have PUT server I can think of to test against, but basically, set your $url and your $data, and do something like:
```
```
param($url,$data,$filename,[switch]$quiet)

$request = [System.Net.WebRequest]::Create($url)
$data = [Text.Encoding]::UTF8.GetBytes( $data )

## Be careful to set your content type appropriately...
## This is what you're going to SEND THEM
$request.ContentType = 'text/xml;charset="utf-8"' # "application/json"; # "application/x-www-form-urlencoded";
## This is what you expect back
$request.Accept = "text/xml" # "application/json";

$request.ContentLength = $data.Length
$request.Method = "PUT"
## If you need Credentials ...
# $request.Credentials = (Get-Credential).GetNetworkCredential()

$put = new-object IO.StreamWriter $request.GetRequestStream()
$put.Write($data,0,$data.Length)
$put.Flush()
$put.Close()

## This is the "simple" way ...
# $reader = new-object IO.StreamReader $request.GetResponse().GetResponseStream() ##,[Text.Encoding]::UTF8
# write-output $reader.ReadToEnd()
# $reader.Close()

## But there's code in PoshCode.psm1 for doing a progress bar, something like ....

$res = $request.GetResponse();
if($res.StatusCode -eq 200) {
   [int]$goal = $res.ContentLength
   $reader = $res.GetResponseStream()
   if($fileName) {
      $writer = new-object System.IO.FileStream $fileName, "Create"
   }

   [byte[]]$buffer = new-object byte[] 4096
   [int]$total = [int]$count = 0
   do
   {
      $count = $reader.Read($buffer, 0, $buffer.Length);
      if($fileName) {
         $writer.Write($buffer, 0, $count);
      } else {
         $output += $encoding.GetString($buffer,0,$count)
      }
      if(!$quiet) {
         $total += $count
         if($goal -gt 0) {
            Write-Progress "Downloading $url" "Saving $total of $goal" -id 0 -percentComplete (($total/$goal)*100)
         } else {
            Write-Progress "Downloading $url" "Saving $total bytes..." -id 0
         }
      }
   } while ($count -gt 0)

   $reader.Close()
   if($fileName) {
       $writer.Flush()
       $writer.Close()
   } else {
       $output
   }
}
$res.Close();
```
```


Question:
I get this error:

Can't locate Foo.pm in @INC

Is there an easier way to install it than downloading, untarring, making, etc?

Answer:
```
sudo perl -MCPAN -e 'install Foo'
```


Question:
Is it recommended that I use an initialization vector to encrypt/decrypt my data? Will it make things more secure? Is it one of those things that need to be evaluated on a case by case basis?

To put this into actual context, the Win32 Cryptography function, CryptSetKeyParam allows for the setting of an initialization vector on a key prior to encrypting/decrypting. Other API's also allow for this.

What is generally recommended and why?

Answer:
An IV is essential when the same key might ever be used to encrypt more than one message.
The reason is because, under most encryption modes, two messages encrypted with the same key can be analyzed together.  In a simple stream cipher, for instance, XORing two ciphertexts encrypted with the same key results in the XOR of the two messages, from which the plaintext can be easily extracted using traditional cryptanalysis techniques.
A weak IV is part of what made WEP breakable.
An IV basically mixes some unique, non-secret data into the key to prevent the same key ever being used twice.


Question:
I would like to read the text and binary attachments in a saved Outlook message (.msg file) from a Java application, without resorting to native code (JNI, Java Native Interface).

Apache POI-HSMF seems to be in the right direction, but it's in very early stages of development...

Answer:
You could use Apache POIFS, which
seems to be a little more mature,
but that would appear to duplicate the efforts of POI-HSMF.
You could use POI-HSMF and contribute changes to get the
features you need working.  That's
often how FOSS projects like that expand.
You
could use com4j, j-Interop, or some
other COM-level interop feature and
interact directly with the COM
interfaces that provide access to
the structured document.  That would
be much easier than trying to hit it
directly through JNI.


Question:
This should be simple. I'm trying to import data from Access into SQL Server. I don't have direct access to the SQL Server database - it's on GoDaddy and they only allow web access. So I can't use the Management Studio tools, or other third-party Access upsizing programs that require remote access to the database.

I wrote a query on the Access database and I'm trying to loop through and insert each record into the corresponding SQL Server table. But it keeps erroring out. I'm fairly certain it's because of the HTML and God knows what other weird characters are in one of the Access text fields. I tried using CFQUERYPARAM but that doesn't seem to help either.

Any ideas would be helpful. Thanks.

Answer:
It's never advisable to loop through records when a SQL Update can be used.
It's not clear from your question what database interface layer you are using, but it is possible with the right interfaces to insert data from a source outside a database
if
the interface being used supports both types of databases. This can be done in the FROM clause of your SQL statement by specifying not just the table name, but the connect string for the database. Assuming that your web host has ODBC drivers for Jet data (you're not actually using Access, which is the app development part -- you're only using the Jet database engine), the connect string should be sufficient.
EDIT: If you use the Jet database engine to do this, you should be able to specify the source table something like this (where tblSQLServer is a table in your Jet MDB that is linked via ODBC to your SQL Server):
```
```
INSERT INTO tblSQLServer (ID, OtherField )
SELECT ID, OtherField
FROM [c:\MyDBs\Access.mdb].tblSQLServer
```
```
The key point is that you are leveraging the Jet db engine here to do all the heavy lifting for you.


Question:
I was asked this question in a job interview. The interviewer and I disagreed on what the correct answer was. I'm wondering if anyone has any data on this.

Update: I should have mentioned that the use of shuffle() was strictly forbidden... sorry.

Answer:
```
```
shuffle($arr);
```
```
:)
edit: I should clarify... my definition of best involves not just algorithm efficiency but code readability and maintainability as well. Using standard library functions means maintaining less code and reading much less too. Beyond that, you can get into year-long debates with PhD professors about the best "true random" function, so somebody will always disagree with you on randomization questions.


Question:
I want to use a file to store the current version number for a piece of customer software which can be used by a start-up script to run the binary in the correct directory.

For Example, if the run directory looks like this:

.
..
1.2.1
1.2.2
1.3.0
run.sh
current_version

And current_version contains:

1.2.2

I want run.sh to descend into 1.2.2 and run the program foo.

The current solution is this:

#!/bin/sh
version = `cat current_version`
cd $version
./foo

It works but is not very robust.  It does not check for file existence, cannot cope with multiple lines, leading spaces, commented lines, blank files, etc.

What is the most survivable way to do this with either a shell or perl script?

Answer:
That's a common approach.  You can check for dir/file existence using test operators such as "if [ -d "somedirectory" ]; then" or [ -t "somefile" ]
I use symbolic links more often, though.  Then, you can just change your symbolic link to use the version you want.
For example,
```
$ ln -s 1.2.2 current_version
$ ls -al
total 20
drwxr-xr-x 5 dbreese dbreese 4096 2008-09-15 13:34 .
drwxr-xr-x 3 dbreese dbreese 4096 2008-09-15 13:34 ..
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.1
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.2.2
drwxr-xr-x 2 dbreese dbreese 4096 2008-09-15 13:34 1.3.0
lrwxrwxrwx 1 dbreese dbreese    6 2008-09-15 13:34 current_version -> 1.2.2/
```
Then your script can just use "cd current_version".


Question:
Is it possible to have XML-embedded JavaScript executed to assist in client-side (browser-based) XSL transformations?  How is it done and how official is it?

Microsoft's XML DOM objects allow this on the server-side (i.e. in ASP/ASP.NET).

Clarification: I do not mean HTML DOM scripting performed after the document is transformed, nor do I mean XSL transformations initiated by JavaScript in the browser (e.g. what the W3Schools page shows).  I am referring to actual script blocks located within the XSL during the transformation.

Answer:
Yes. It's browser dependant but you can use Javascript. There is a small but practical tutorial on w3schools.com. It's part of the XSLT tutorial.
The page:
http://www.w3schools.com/xsl/xsl_client.asp
The XSLT tutorial:
http://www.w3schools.com/xsl/default.asp
That site will be more helpful than myself. Good luck!


Question: I know you could make a helper pretty easily given the data. So, if possible, please only submit answers that also include getting the data.

Answer:
We are using an action filter for this.
...
```
```
public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = (Controller) filterContext.Controller;
        Breadcrumb[] breadcrumbs = _breadcrumbManager.PushBreadcrumb(_breadcrumbLinkText);
        controller.ViewData.Add(breadcrumbs);
    }
```
```
before you mention it, I too have a distaste for service location in the filter attributes - but we are left with few options.  IBreadcrumbManager looks like this:
```
```
public interface IBreadcrumbManager
{
    Breadcrumb[] PushBreadcrumb(string linkText);
}
```
```
The implementation puts Breadcrumb objects into the Session. The Url is
```
HttpContext.Current.Request.RawUrl
```


Question:
I'm using Visual Studio (2005 and up). I am looking into trying out making an application where the user can change language for all menues, input formats and such. How would I go on doing this, as I suppose that there is some complete feature within .Net that can help me with this?

I need to take the following into account (and fill me in if I miss some obvious stuff)

Strings (menues, texts)

Input data (parsing floats, dates, etc..)

Should be easy to add support for another language

Answer:
For strings you should just separate your strings from your code (having an XML/DLL that will transform string IDs to real strings is one way to go). However you do need to make sure that you are supporting double byte characters for some languages (this is relevant if you use C/C++).
For input data what you want is to have different locale's. In Java this is relatively easy, and if you use C# it probably is quite easy also. In C/C++ I don't really know. The basic idea is that the input parsers should be different based on the locale selected at that time. So each field (textfield, textbox, etc.) must have an abstract parser that is then implemented by a different class depending on the locale (right to left, double byte, etc.).
Check the Java implementation for details on how they did it. It is quite functional.


Question:
I've seen examples like this:

public class MaxSeconds {
   public static final int MAX_SECONDS = 25;
}

and supposed that I could have a Constants class to wrap constants in, declaring them static final. I know practically no Java at all and am wondering if this is the best way to create constants.

Answer:
That is perfectly acceptable, probably even the standard.
```
```
(public/private) static final TYPE NAME = VALUE;
```
```
where
```
TYPE
```
is the type,
```
NAME
```
is the name in all caps with underscores for spaces, and
```
VALUE
```
is the constant value;
I highly recommend NOT putting your constants in their own classes or interfaces.
As a side note:  Variables that are declared final and are mutable can still be changed; however, the variable can never point at a different object.
For example:
```
```
public static final Point ORIGIN = new Point(0,0);

public static void main(String[] args){

    ORIGIN.x = 3;

}
```
```
That is legal and
```
ORIGIN
```
would then be a point at (3, 0).


Question:
I'm responsible for some test database servers.  Historically, too many other poeple have access to them.  They run on SQL Server 2005.

I've been writing queries and wrapping them in scripts so I can run a regular audit of rights.  Finding out which users had Administrator rights on the server itself was fine, as was finding out who had the sysadmin role on their login - it was a single line query for the latter.

But how to find out which logins have a User Mapping to a particular (or any) database?

I can find the sys.database_principals and sys.server_principals tables.  I have located the sys.databases table.  I haven't worked out how to find out which users have rights on a database, and if so, what.

Every Google search brings up people manually using the User Mapping pane of the Login dialog, rather than using a query to do so. Any ideas?

Answer:
```
```
select * from Master.dbo.syslogins l inner join sys.sysusers u on l.sid = u.sid
```
```
This will get you what users are mapped to which logins within a single database.


Question: Is there any visible progress?  Is it now just an academic exercise?  Do you believe Perl will continue to evolve with or without Perl 6 or will soon be forgotten?

Answer:
I feel like some good things may come from Perl 6 (e.g. parrot), but I'm not counting on ever doing anything with the language.
In the bioinformatics development group where I work, we're encouraging use of Python for new development where Perl would have been the language of choice in the past.  Python appears to provide a better path forward for us.


Question:
I have a Visual Studio application with a splash screen image cut into "slices". The positions are specified in the Form Designer so they line up properly on the screen. However, the images are out of place when the application is run on the Chinese version of Windows XP. It looks as if the image slices were "exploded" apart.

What's going on here? Do international versions of Windows have a different meaning of the "top left" coordinate of the picture? How can I force the images to be precisely displayed where I want them?

Answer:
In the OnLoad event of the form, you could always explicitly set the location of each section. If starting at the top left with the first and assuming an array with the images in order:
```
```
images[0].Location = new Point(0,0);
for (int i = 1; i < images.Length; i++)
{
  images[i].Location = new Point(images[i - 1].Location.X + images[i - 1].Width, 0);
}
```
```
That will set the first image to the top left corner and all subsequent images to just after the last image.


Question:
Do you refactor your SQL first? Your architecture? or your code base?
Do you change languages? Do you throw everything away and start from scratch? [Not refactoring]

Answer:
This really depends on the state of the codebase... are there massive classes? one class with mega-methods? Are the classes tightly coupled? is configuration a burden?
Considering this, I suggest reading
Working Effectively with Legacy Code
, picking out your problems, and applying the recommendations.


Question: When using Google Chrome, I want to debug some JavaScript code. How can I do that?

Answer:
Try adding this to your source:
```
```
debugger;
```
```
It works in most, if not all browsers. Just place it somewhere in your code, and it will act like a breakpoint.


Question:
I have a servlet that is used for many different actions, used in the Front Controller pattern.  Does anyone know if it is possible to tell if the data posted back to it is enctype="multipart/form-data"?  I can't read the request parameters until I decide this, so I can't dispatch the request to the proper controller.

Any ideas?

Answer:
Yes, the
```
Content-type
```
header in the user agent's request should include
```
multipart/form-data
```
as described in (at least) the HTML4 spec:
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2


Question:
I'm writing a mobile phone game using j2me. In this game, I am using multiple Canvas objects.
For example, the game menu is a Canvas object, and the actual game is a Canvas object too.
I've noticed that, on some devices, when I switch from one Canvas to another, e.g from the main menu to the game, the screen momentarily "flickers". I'm using my own double buffered Canvas.

Is there anyway to avoid this?

Answer:
Do you use double buffering? If the device itself does not support double buffering you should define a off screen buffer (Image) and paint to it first and then paint the end result to the real screen. Do this for each of your canvases. Here is an example:
```
```
public class MyScreen extends Canvas {
   private Image osb;
   private Graphics osg;
   //...

   public MyScreen()
   {
         // if device is not double buffered
         // use image as a offscreen buffer
         if (!isDoubleBuffered())
         {
            osb = Image.createImage(screenWidth, screenHeight);
            osg = osb.getGraphics();
            osg.setFont(defaultFont);
         }
   }

   protected void paint(Graphics graphics)
   {
      if (!isDoubleBuffered())
      {
         // do your painting on off screen buffer first
         renderWorld(osg);

         // once done paint it at image on the real screen
         graphics.drawImage(osb, 0, 0, Tools.GRAPHICS_TOP_LEFT);
      }
      else
      {
         osg = graphics;
         renderWorld(graphics);
      }
   }
}
```
```


Question:
Is there a way to check to see if an iPhone is online from a web app. That is, in mobile Safari, can I check the online status of the device to see if I should try an AJAX call or not.

In Firefox/regular WebKit, this would be:

if(navigator.onLine)
{
    onlineCode()
}

Answer:
That same code should work in the WebKit nightly build as of May 16th 2008. I guess that means you need to hope the 2.1 update included a new build of safari.
https://bugs.webkit.org/show_bug.cgi?id=19105


Question: Can ANTLR output C# using StringTemplate or any text I want it to like Yacc/Bison or does it only output to java?  From the examples I've looked at it appears to be a very java centric tool.

Answer:
You can download the latest source code as a tar file from
here
.  The C# runtime (binary) is also available directly,
here
.
Which solution are you looking for?


Question:
I have the following Java 6 code:

    Query q = em.createNativeQuery(
        "select T.* " +
        "from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
        "where I.launchDate between :start and :end " +
        "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
        "TripResults" );

    q.setParameter( "start", range.getStart(), TemporalType.DATE );
    q.setParameter( "end", range.getEnd(), TemporalType.DATE );

    @SqlResultSetMapping( name="TripResults",
        entities={
            @EntityResult( entityClass=TripEntity.class ),
            @EntityResult( entityClass=CommercialTripEntity.class )
        }
    )

I receive a syntax error on the last closing right parenthesis. Eclipse gives: "Insert EnumBody to complete block statement" and "Insert enum Identifier to complete EnumHeaderName".  Similar syntax error from javac.

What am I doing wrong?

Answer:
The Hibernate annotations docs (
http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/
) suggest that this should be a class-level annotation rather than occurring inline within your code.  And indeed when I paste that code into my IDE and move it around, the compile errors are present when the annotation is inline, but vanish when I put it in above the class declaration:
```
```
@SqlResultSetMapping( name="TripResults",
        entities={
            @EntityResult( entityClass=TripEntity.class ),
            @EntityResult( entityClass=CommercialTripEntity.class )
        }
    )
public class Foo {
   public void bogus() {
      Query q = em.createNativeQuery(
        "select T.* " +
        "from Trip T join Itinerary I on (T.itinerary_id=I.id) " +
        "where I.launchDate between :start and :end " +
        "or ADDDATE(I.launchDate, I.equipmentPullDayOfTrip) between :start and :end",
        "TripResults" );

      q.setParameter( "start", range.getStart(), TemporalType.DATE );
      q.setParameter( "end", range.getEnd(), TemporalType.DATE );
   }
}
```
```
...obviously I have no evidence that the above code will actually work.  I have only verified that it doesn't cause compile errors.


Question:
I know that garbage collection is automated in Java. But I understood that if you call System.gc() in your code that the JVM may or may not decide to perform garbage collection at that point. How does this work precisely? On what basis/parameters exactly does the JVM decide to do (or not do) a GC when it sees System.gc()?

Are there any examples in which case it's a good idea to put this in your code?

Answer:
In practice, it
usually
decides to do a garbage collection.  The answer varies depending on lots of factors, like which JVM you're running on, which mode it's in, and which garbage collection algorithm it's using.
I wouldn't depend on it in your code.  If the JVM is about to throw an OutOfMemoryError, calling System.gc() won't stop it, because the garbage collector will attempt to free as much as it can before it goes to that extreme.  The only time I've seen it used in practice is in IDEs where it's attached to a button that a user can click, but even there it's not terribly useful.


Question: How do I get started?

Answer:
You'll need an interface to the Oracle SQL database. As Bob pointed out, Allegro CL has such an interface.
GNU CLISP apparently comes with an interface to the database as well.


Question:
Is there a way to detect, from within the finally clause, that an exception is in the process of being thrown?

See the example below:

try {
    // code that may or may not throw an exception
} finally {
    SomeCleanupFunctionThatThrows();
    // if currently executing an exception, exit the program,
    // otherwise just let the exception thrown by the function
    // above propagate
}

or is ignoring one of the exceptions the only thing you can do?

In C++ it doesn't even let you ignore one of the exceptions and just calls terminate(). Most other languages use the same rules as java.

Answer:
No I do not believe so.  The catch block will run to completion before the finally block.
```
```
try {
    // code that may or may not throw an exception
} catch {
// catch block must exist.
finally {
    SomeCleanupFunctionThatThrows();
// this portion is ran after catch block finishes
}
```
```
Otherwise you can add a synchronize() object that the exception code will use, that you can check in the finally block, which would help you identify if in a seperate thread you are running an exception.


Question: I'm trying to convert old QuickTime framework code to the 64-bit Cocoa-based QTKit on OS X, which means that I can't drop down to the straight C function calls at any time.  Specifically, I'm trying to find a way to write QuickTime VR movies with QTKit, as they require some special metadata to set the display controller.  How can I do this with QTKit?

Answer:
As far as I can tell from the QTKit Documentation there is not way to do this in straight QTKit cocoa calls.  You'll need to
do this using the Quicktime-C APIs
, which of course aren't available to 64-bit applications.
I've run into issues like this numerous times when trying to convert a 32-bit app that uses Quicktime into a 64-bit app.  Here's hoping that Quicktime X will have a more fully featured QTKit set of APIs.


Question: I've created a python object, but I want to send signals on it.  I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.

Answer:
Here is how:
```
```
import gobject

class MyGObjectClass(gobject.GObject):
    ...

gobject.signal_new("signal-name", MyGObjectClass, gobject.SIGNAL_RUN_FIRST,
    None, (str, int))
```
```
Where the second to last argument is the return type and the last argument is a tuple of argument types.


Question:
Are there any advantages compiling for .NET Framework 3.5 instead of 2.0?

For example less memory consumption, faster startup, better performance...

Personally I don't think so however, I may have missed something.

Edits

Of course there are more features in the 3.5 framework, but these are not the focus of this question.

There seem to be no advantages.

Yes I meant targeting the Framework. I have installed the latest 3.5 SP1 and VS 2008 so what's the difference between compiling with and targeting a framework? I can target the framework in the project options but how do I 'compile with' a specific framework version? I did not know that there is a difference.

So for now we agree that there are no advantages.

Answer: 3.5 has classes that 2.0 doesn't. Func<...> for instance. If you aim for 2.0, you can't use them.


Question:
How can i add a line break to the text area in a html page?
i use VB.net for server side coding.

Answer:
Add a linefeed ("\n") to the output:
```
```
<textarea>Hello

Bybye</textarea>
```
```
Will have a newline in it.


Question:
Where can I find a guide for integrating JavaScript and JMS (Java Messaging Service)?

I would like a best practice or established technology that allows me to directly or indirectly receive messages from a topic and update a site based on the message. I was thinking of creating two components, a servlet for the Web module, and an MDB (Message-Driven Bean) for the EJB module. The web client will comsume messages from the JMS topic, and the MDB will handle the onMessage.

Does this sound correct? Have you seen any examples?

Edit: I am using ActiveMQ for the JMS.

Answer:
I would try using
DWR
to integrate JavaScript with your Java app. It makes Java to JavaScript communication transparent and only requires one servlet + configuration of what to expose. I haven´t done this with JMS, but it should work the same. There are three technologies that together solve all my integration problems,
Spring
,
Mule
, and DWR.


Question:
I want a user-privileged (not root) process to launch new processes as user nobody. I've tried a straight call to setuid that fails with -1 EPERM on Ubuntu 8.04:

#include <sys/types.h>
#include <unistd.h>

int main() {
       setuid(65534);
       while (1);
       return 0;
}

How should I do this instead?

Answer: As far as I know, you can't unless you're root or have sudo set up to allow you to switch users.  Or, you can have your executable have the suid bit set up on it, and have it owned by nobody.  But that requires root access too.


Question:
I'm looking to find alternatives to Solr from the Apache Software Foundation.

For those that don't know, Solr is an enterprise search server. A client application uses a web-services like interface to submit documents for indexing and also to perform search queries. Solr has other features built in like caching and replication. I believe it was originally started by CNet and then open-sourced.

I'm looking for other search servers out there that might be seen as the competition.

Answer:
IBM Omnifind Yahoo Edition
is an Enterprise search server which uses
Apache Lucene
for indexing. It is simple, easy to install and administer. It also has a built in Open Search API. It has multi-platform support and its Free!!
This product was launched by IBM to compete with
Google Mini
in the Enterprise Search market.


Question:
So you have a String that is retrieved from an admin web UI (so it is definitely a String). How can you find out whether this string is an IP address or a hostname in Java?

Update: I think I didn't make myself clear, I was more asking if there is anything in the Java SDK that I can use to distinguish between IPs and hostnames? Sorry for the confusion and thanks for everybody who took/will take the time to answer this.

Answer:
You can use a regular expression with this pattern:
```
```
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
```
```
That will tell you if it's an IPv4 address.


Question:
We are automating Excel using VB.Net, and trying to place multiple lines of text on an Excel worksheet that we can set to not print. Between these we would have printable reports.
We can do this if we add textbox objects, and set the print object setting to false. (If you have another way, please direct me)

The code to add a textbox is:

ActiveSheet.Shapes.AddTextbox(msoTextOrientationHorizontal, 145.5, 227.25, 304.5, 21#)

but the positioning is in points. We need a way to place it over a specific cell, and size it with the cell. How can we find out where to put it when we just know which cell to put it over?

Answer:
If you have the cell name or position, you can do:
```
```
With ActiveSheet
  .Shapes.AddTextbox msoTextOrientationHorizontal, .Cells(3,2).Left, .Cells(3,2).Top, .Cells(3,2).Width, .Cells(3,2).Height
End With
```
```
This will add a textbox over cell B3. When B3 is resized, the textbox is also.


Question:
Is there an Eclipse command to surround the current selection with parentheses?

Creating a template is a decent workaround; it doesn't work with the "Surround With" functionality, because I want to parenthesize an expression, not an entire line, and that requires ${word_selection} rather than ${line_selection}.

Is there a way that I can bind a keyboard shortcut to this particular template? Ctrl-space Ctrl-space arrow arrow arrow isn't as slick as I'd hoped for.

Answer:
Easy, Window->Prefs, then select Java->Editor->Templates
Create a new template with : (${line_selection}${cursor})
The "line_selection" means you have to select more than one line.
You can try creating another one with "word_selection", too.
Then, select text, right click, Surround With... and choose your new template.


Question: Google maps in some region can serve traffic information showing the blocked roads and so on. I was wondering if there is any code example demonstrating how can I serve traffice information for my own region.

Answer:
Google is mum on what source they use for their traffic data.  You might contact them directly to see if they want to implement something for you, but my guess is that they'd simply refer you to their provider if they really wanted your data.
Keep in mind that traffic data is available for more than just the metropolitan areas, but Google isn't using it for a variety of reasons - one of the big reasons is that the entire tile set for the traffic overlay in areas with traffic tiles has to be regenerated every 15 minutes or so.  It just doesn't scale.
So even if you managed to get your data in their flow, it likely won't be rendered.
-Adam


Question:
I'm coding a framework along with a project which uses this framework. The project is a Bazaar repository, with the framework in a subfolder below the project.

I want to give the framework a Bazaar repository of its own. How do I do it?

Answer:
As far as I know, there is not a way to do this easily with bazaar.   One possibility is to take the original project, branch it, and then remove everything unrelated to the framework.  You can then move the files in the subdir to the main dir.  It's quite a chore, but it is possible to preserve the history.
you will end up with something like:
```
```
branch project:
.. other files..
framework/a.file
framework/b.file
framework/c.file

branch framework:
a.file
b.file
c.file
```
```


Question:
I am implementing a quite simple state-machine order processing application. It is a e-commerce application with a few twists. The users of the application will not be editing workflows by themselves.

Microsoft claims that asp.net and Windows Workflow is possible to combine. How hard is it to install and maintain a combination of asp.net and Windows Workflow? I would be keeping the workflow state in sql-server.

Is it easier for me to roll my own state machine code or is Windows Workflow the right tool for the job?

Answer:
If your state machine is very simple, then I would say that you should just roll your own.  You have more control over everything.  You can deal with persistence on your own terms and not worry about how they do it.
WF does look pretty cool though, but I think that it's power probably lies in the fact that it is easy to tie it into frameworks like CRM and Sharepoint.  If you are going to use these in your application, then I would definitely consider using WF.
Full disclosure:  I am definitely not a WF expert.


Question: I want to extend a WPF application with database functionality. Which database engine would you suggest and why? SQLite, SQL CE, other?

Answer:
Depending on the applications use,
I would recommend using SQL Lite
because it doesn't require you to install any other software (SQL CE or Express, etc. usually would require a separate install).
A list of the most important benefits for SQL Lite from the provider link at the bottom of this post:
SQLite is a small C library that
  implements a self-contained,
  embeddable, zero-configuration SQL
  database engine. Features include:
Zero-configuration - no setup or
  administration needed.
Implements most of SQL92. (Features
  not supported)
A complete database is stored in a
  single disk file.
Database files can be freely shared
  between machines with different byte
  orders.
Supports databases up to 2 terabytes
  (2^41 bytes) in size.
Small code footprint: less than 30K
  lines of C code, less than 250KB
  code space (gcc on i486)
Faster than popular client/server
  database engines for most common
  operations.
Simple, easy to use API.
Self-contained: no external
  dependencies.
Sources are in the public domain.
  Use for any purpose.
Since you're using WPF I can assume you're using at least .NET 3.0.  I would then recommend going to .NET 3.5 SP1 (sames size as .NET 3.5 but includes a bunch of performance improvements) which includes LINQ.
When using SQLite, however, you would want to use the following SQLite Provider which should provide LINQ support:
An open source ADO.NET provider for the SQLite database engine


Question:
We have a WinForms application written in C# that uses the AxAcroPDFLib.AxAcroPDF component to load and print a PDF file. Has been working without any problems in Windows XP. I have moved my development environment to Vista 64 bit and now the application will not run (on Vista 64) unless I remove the AxAcroPDF component. I get the following error when the application runs:

"System.Runtime.InteropServices.COMException:
Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))."

I have been advised on the Adobe Forums that the reason for the error is that they do not have a 64 bit version of the AxAcroPDF ActiveX control.

Is there some way around this problem?  For example can I convert the 32bit ActiveX control to a 64bit control myself?

Answer:
You can't convert Adobe's ActiveX control to 64bit yourself, but you can force your application to run in 32bit mode by setting the platform target to x86.
For instructions for your version of Visual Studio, see section 1.44 of
Issues When Using Microsoft Visual Studio 2005


Question:
There are various documents describing threading on Solaris/Linux, but nowwhere describing the Windows implementation. I have a passing interest in this, it seems strange that something so critical is (seemingly) not documented.

Threading is not the same on different OS' - "Write Once, Run Anywhere" isn't true for threading.

See http://java.sun.com/docs/hotspot/threads/threads.html

Answer:
The document in question discusses the Solaris threading model and how the VM maps to it. This has nothing to do with Linux. Also, the document discusses performance only. The program's overall behaviour should not change no matter what you choose.
Java's exposed threading model is the same on every platform and defined in the Java specifications. To a Java application, the underlying OS should be completely transparent even for threading.
If you have to know, though ... The Sun JVM maps its threads 1:1 to Windows threads. It doesn't use multiple processes or fibers.


Question: How do I determine using TSQL what roles are granted execute permissions on a specific stored procedure? Is there a system stored procedure or a system view I can use?

Answer:
You can try something like this.  Note, I believe 3 is EXECUTE.
```
```
SELECT
grantee_principal.name AS [Grantee],
CASE grantee_principal.type WHEN 'R' THEN 3 WHEN 'A' THEN 4 ELSE 2 END - CASE 'database' WHEN  'database' THEN 0 ELSE 2 END AS [GranteeType]
FROM
sys.all_objects AS sp
INNER JOIN sys.database_permissions AS prmssn ON prmssn.major_id=sp.object_id AND prmssn.minor_id=0 AND prmssn.class=1
INNER JOIN sys.database_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id
WHERE
(sp.type = N'P' OR sp.type = N'RF' OR sp.type='PC')and(sp.name=N'myProcedure' and SCHEMA_N
```
```
I got that example by simply using SQL Profiler while looking at the permissions on a procedure.  I hope that helps.


Question: How do you iterate through every file/directory recursively in standard C++?

Answer:
You need to call OS-specific functions for filesystem traversal, like
```
open()
```
and
```
readdir()
```
. The C standard does not specify any filesystem-related functions.


Question: I have quite a few developers asking me if certain SQL jobs ran, and I would like to give them access to check it on their own without giving them sysadmin rights.  I know that in SQL 2005, you can grant them the SQLAgentReaderRole, but I am looking for a solution in SQL 2000.

Answer:
Pretty sure there isn't one out of the box.  This thread seems to be pretty decent...halfway down they discuss creating a role and then locking that down further.  Also you could just create a mini-program (sp even?) to email the results of the job as a summary, or add to each job an on completion event to email an email group.
http://sqlforums.windowsitpro.com/web/forum/messageview.aspx?catid=60&threadid=43021&enterthread=y


Question: I have an iframe.  The content is wider than the width I am setting so the iframe gets a horizontal scroll bar.  I can't increase the width of the iframe so I want to just remove the scroll bar.  I tried setting the scroll property to "no" but that kills both scroll bars and I want the vertical one.  I tried setting overflow-x to "hidden" and that killed the horizontal scroll bar in ff but not in IE. sad for me.

Answer:
You could try putting the iframe inside a div and then use the div for the scrolling. You can control the scrolling on the div in IE without issues, IE only really has problems with iframe scrolling. Here's a quick example that should do the trick.
```
```

        <title>iframe test</title>

```
```


Question: Why isn't there a Team Foundation Server Express Edition?

Answer:
And individuals shouldn't be using TFS?? That's like saying source control is only for groups and not individuals.
If they had an express edition of TFS, then they'd probably get more people using it and paying for their company to use it.


Question:
GNU sed version 4.1.5 seems to fail with International chars. Here is my input file:

Gras Och Stenar Trad - From Moja to Minneapolis DVD [G2007DVD] 7812 | X
<br>
Gras Och Stenar Trad - From Möja to Minneapolis DVD [G2007DVD] 7812 | Y

(Note the umlaut in the second line.)

And when I do

sed 's/.*| //' < in

I would expect to see only the X and Y, as I've asked to remove ALL chars up to the '|' and space beyond it. Instead, I get:

X<br>
Gras Och Stenar Trad - From M? Y

I know I can use tr to remove the International chars. first, but is there a way to just use sed?

Answer:
```
sed
```
is not very well setup for non-ASCII text. However you can use (almost) the same code in
```
perl
```
and get the result you want:
```
```
perl -pe 's/.*\| //' x
```
```


Question:
I have a "watcher" module that is currently using global hierarchies inside it.  I need to instantiate a second instance of this with a second global hierarchy.

Currently:

module watcher;
wire sig = `HIER.sig;
wire bar = `HIER.foo.bar;
...
endmodule

watcher w; // instantiation

Desired:

module watcher(input base_hier);
wire sig = base_hier.sig;
wire bar = base_hier.foo.bar;
...
endmodule

watcher w1(`HIER1); // instantiation
watcher w2(`HIER2); // second instantiation, except with a different hierarchy

My best idea is to use vpp (the Verilog preprocessor) to brute-force generate two virtually-identical modules (one with each hierarchy), but is there a more elegant way?

Answer:
My preference is to have a single module (or a small number of modules) in your testbench that contains all your probes but no other functionality. All other modules in your testbench that require probes then connect to that "probe module". Use SystemVerilog interfaces in preference to raw wires if that's an option for you. This circumvents your problem since no watcher will require global hierarchies and your testbench on the whole will be considerably easier to maintain. See the
Law of Demeter
.
Alternatively... (but this puts hierarchy in your instantiations...)
```
```
module watcher(sig, bar);
  input sig;
  input bar;
...
endmodule

watcher w1(`HIER1.sig, `HIER1.foo.bar); // instantiation
watcher w2(`HIER2.sig, `HIER2.foo.bar); // second instantiation, except with a different hierarchy
```
```
Subsequently you can also:
```
```
`define WATCHER_INST(NAME, HIER) watcher NAME(HIER.sig, HIER.foo.sig)

`WATCHER_INST(w1, `HIER1);
`WATCHER_INST(w2, `HIER2);
```
```


Question:
I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers?  At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting entries into a sorted vector.

To clarify "dynamically", I am looking for a container that I can modify the sorting order at runtime - e.g. sort it in an ascending order, then later re-sort in a descending order.

Answer:
```
std::set
```
is basically a sorted container.


Question: How can I show a web page in a transparent window and have the white part of the web page also transparent.

Answer: Can't you just write a link to a "zip server" or whatnot?  Why does the zip archive itself need to be served from Django?  A 90's era CGI script to generate a zip and spit it to stdout is really all that's required here, at least as far as I can see.


Question:
Let's say the first N integers divisible by 3 starting with 9.

I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.

Answer:
I can't say this is any good, I'm not a C# expert and I just whacked it out, but I think it's probably a canonical example of the use of
```
yield
```
.
```
```
internal IEnumerable Answer(N)
{
  int n=0;
  int i=9;
  while (true)
  {
    if (i % 3 == 0)
    {
      n++;
      yield return i;
    }

    if (n>=N) return;
    i++;
  }
}
```
```


Question:
I'd like to have a TabNavigator component that has a close button for some of the tabs. How do I do that?

It seems that the TabNavigator component does not allow (or I could not find)  extensibility of this form.
Help. Thanks

Answer:
You should take a look at the SuperTabNavigator component from the
FlexLib
project:
SuperTabNavigator example
SuperTabNavigator documentation
FlexLib Component list
If you don't want all of the tabs to have close buttons (I understand from the question that you don't) it looks like you could use the
setClosePolicyForTab()
method for specifying which tabs you want to have them.


Question: I'm looking for a profiler in order to find the bottleneck in my C++ code. I'd like to find a free, non-intrusive, and good profiling tool. I'm a game developer, and I use PIX for Xbox 360 and found it very good, but it's not free. I know the Intel VTune, but it's not free either.

Answer:
CodeXL
has now superseded the End Of Line'd
AMD Code Analyst
and both are free, but not as advanced as VTune.
There's also
Sleepy
, which is very simple, but does the job in many cases.
Note:
All three of the tools above are unmaintained since several years.


Question:
I have a need to do auditing all database activity regardless of whether it came from application or someone issuing some sql via other means. So the auditing must be done at the database level. The database in question is Oracle. I looked at doing it via Triggers and also via something called Fine Grained Auditing that Oracle provides. In both cases, we turned on auditing on specific tables and specific columns. However, we found that Performance really sucks when we use either of these methods.

Since auditing is an absolute must due to regulations placed around data privacy, I am wondering what is best way to do this without significant performance degradations. If someone has Oracle specific experience with this, it will be helpful but if not just general practices around database activity auditing will be okay as well.

Answer:
I'm not sure if it's a mature enough approach for a production
system, but I had quite a lot of success with monitoring database
traffic using a network traffic sniffer.
Send the raw data between the application and database off to another
machine and decode and analyse it there.
I used PostgreSQL, and decoding the traffic and turning it into
a stream of database operations that could be logged was relatively
straightforward. I imagine it'd work on any database where the packet
format is documented though.
The main point was that it put no extra load on the database itself.
Also, it was passive monitoring, it recorded all activity, but
couldn't block any operations, so might not be quite what you're looking for.