q:
I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error:

ORA-12154: TNS:could not resolve the connect identifier specified

If i run the application in my pc with visual studio it works fine.

Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A".

In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere

any idea?
Thanks for the help.

[A]
Have you tried this yet? (from
http://ora-12154.ora-code.com/
)
ORA-12154:  TNS:could not resolve the connect identifier specified
Cause:  A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.
Action:
- If you are using local naming (TNSNAMES.ORA file):
Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)
Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.
Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.
Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.
If you are using directory naming:
Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
Verify that the LDAP directory server is up and that it is accessible.
Verify that the net service name or database name used as the connect identifier is configured in the directory.
Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier
If you are using easy connect naming:
Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
Make sure the host, port and service name specified are correct.
Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.


q: I have a database with user 'dbo' that has a login name "domain\xzy".  How do I change it from "domain\xzy" to "domain\abc".

[A]
This is a Windows login, not a SQL Server login, so you cannot 'change' the login name since it is linked to the user account in Active Directory.
Create a new Server Login (Windows) mapped to the new windows user (and remove the old one if necessary). Then in login's Security > User Mapping, permission that login to the appropriate database as user 'dbo' (or assign to the db_owner role)

s: huggingface

c: devops

d: intermediate


q:
One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:

self.__value = 1

def value():
    return self.__value

Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.

I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?

[A]
Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '__value' attribute, the attribute is actually being stored as '
```
_ContainerThing__value
```
'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.
This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a
single
leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.
For the record, '
```
__value
```
' and '
```
value
```
' (and '
```
_value
```
') are not the same name. The underscores are part of the name.


q:
I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time.

How would I do that? Platform: win32.

[A]
From the MSDN documentation:
The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.
Note that
```
strncpy
```
doesn't check for valid destination space; that is left to the programmer.  Prototype:
```
char *strncpy(
   char *strDest,
   const char *strSource,
   size_t count
);
```
Extended example:
```
```
void send250(char *inMsg, int msgLen)
{
    char block[250];
    while (msgLen > 0)
    {
         int len = (msgLen>250) ? 250 : msgLen;
         strncpy(block, inMsg, 250);

         // send block to other entity

         msgLen -= len;
         inMsg  += len;
    }
}
```
```


q:
I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup?

All the google searches I did were inconclusive, I saw bits about some initial test runs on beta 2 but nothing more recent seemed to show up.

Edit: http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04

They've confirmed here 1.0 w/2.6 works fine as far as they know.

[A]
The impression I get is that 2.6 should work fine with Django 1.0. As found here:
http://simonwillison.net/2008/Oct/2/whatus/


q:
I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.

I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.

But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.

Is there a way to log the machine name via log4net in this manner?

[A]
you can create a parameter similar to the following:
```
```
<parameter>
  <parameterName value="@machine" />
  <dbType value="String" />
  <size value="255" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%X{machine}" />
  </layout>
</parameter>
```
```
Then add this line before writing to the log:
```
MDC.Set("machine", Environment.MachineName);
```


q:
Can you package up the .Net framework in an installer created in Visual Studio? If so how?

I've seen this done with Install4J packaging a JVM but I think that was the JVM to run Install4J.

[A]
Sucky, yeah - I created an installer just recently before realizing that the .Net Framework (which was one of the things I needed to install) was required.  I ended up making a c++ program that installed .Net before my installer was launched.
Seems kind of odd to me to offer the ability to create an installer and not have it offer to install what it needs to run.  Kinda pointless at that point, eh?  Unless you know that every machine you give the installer to will have the necessary components...
Oh well, live and learn


q:
I'm quite new to NHibernate and starting to find my way around.

I have a domain model that is somewhat like a tree.

Funds have Periods have Selections have Audits

Now I would like to get all Audits for a specific Fund

Would look like this if I made it in SQL

SELECT A.*

FROM Audit A

JOIN Selection S ON A.fkSelectionID = S.pkID

JOIN Period P ON S.fkPeriodID = P.pkID

JOIN Fund F ON P.fkFundID = F.pkID

WHERE F.pkID = 1

All input appreciated!

[A]
Try this
```
```
select elements(s.Audits)
from Fund as f inner join Period as p inner join Selection as s
where f = myFundInstance
```
```


q:
How do you include a file that is more than 2 directories back. I know you can use ../index.php to include a file that is 2 directories back, but how do you do it for 3 directories back?
Does this make sense?
I tried .../index.php but it isn't working.

I have a file in /game/forum/files/index.php and it uses PHP include to include a file. Which is located in /includes/boot.inc.php; / being the root directory.


q:
I'm a Mac user and I've decided to learn Emacs. I've read that to reduce hand strain and improve accuracy the CTRL and CAPS LOCK keys should be swapped. How do I do this in Leopard?

Also, in Terminal I have to use the ESC key to invoke meta. Is there any way to get the alt/option key to invoke meta instead?

update: While the control key is much easier to hit now, the meta key is also used often enough that its position on my MacBook and Apple Keyboard also deserves attention. In fact, I find that the control key is actually easier to hit, so I've remapped my control key to act as a meta key. Does anyone have a better/more standard solution?

[A]
Swapping CTRL and CAPS LOCK
Go into
System Preferences
Enter the
Keyboard & Mouse
preference pane
In the
Keyboard
tab, click
Modifier Keys...
Swap the actions for
Caps Lock
and
Control
.
Using ALT/OPTION as META
In the menu bar, click
Terminal
Click
Preferences...
Under the
Settings
tab, go to the
Keyboard
tab
Check the box labeled
Use option as meta key
That's it! You should be well on your way to becoming an Emacs master!


q:
Given the following C function in a DLL:

char * GetDir(char* path );

How would you P/Invoke this function into C# and marshal the char * properly.
.NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.

[A]
Try
```
```
[DllImport("your.dll", CharSet = CharSet.Ansi)]
string GetDir(StringBuilder path);
```
```
string is automatically marshalled to a zero-terminated string, and with the CharSet property, you tell the Marshaller that it should use ANSI rather than Unicode.
Note: Use string (or System.String) for a const char*, but StringBuilder for a char*.
You can also try MarshalAs, as in
this example
.


q: If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket.

[A]
Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.
This is known as
Ajax
, and there are a
number
of
libraries
that help you do it..


q: I have an HTTP server that returns large bodies in response to POST requests (it is a SOAP server). These bodies are "streamed" via chunking. If I encounter an error midway through streaming the response how can I report that error to the client and still keep the connection open? The implementation uses a proprietary HTTP/SOAP stack so I am interested in answers at the HTTP protocol level.

[A]
Once the server has sent the status line (the very first line of the response) to the client, you can't change the status code of the response anymore. Many servers delay sending the response by buffering it internally until the buffer is full. While the buffer is filling up, you can still change your mind about the response.
If your client has access to the response headers, you could use the fact that chunked encoding allows the server to add a trailer with headers after the chunked-encoded body. So, your server, having encountered the error, could gracefully stop sending the body, and then send a trailer that sets some header to some value. Your client would then interpret the presence of this header as a sign that an error happened.


q:
I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not.

The closest I have been able to manage is this:

If IsNull({ValuationReport.YestPrice}) Then
    'N/A'
Else
    ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2)

However this represents negative numbers using a negative sign, not parentheses.

I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?

[A]
I think you are looking for
```
ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
```
You can use
```
CCur
```
to convert numbers or string to Curency formats.
```
CCur(number)
```
or
```
CCur(string)
```
I think this may be what you are looking for,
```
Replace (ToText(CCur({field})),"$" , "")
```
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting


q:
I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.

Basically I have three questions:

Why use pointers over normal variables?

When and where should I use pointers?

How do you use pointers with arrays?

[A]
Pointers are one way of getting an indirect reference to another variable.  Instead of holding the
value
of a variable, they tell you its
address
.  This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).
The best explanation of pointers and pointer arithmetic that I've read is in K & R's
The C Programming Language
.  A good book for beginning learning C++ is
C++ Primer
.


q:
So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.

From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files?

[A]
Subversion can do this, but you have to do it with
```
```
svn move <oldfile> <newfile>
```
```
Edit: And in this decade, we do
```
git mv <oldfile> <newfile>
```
, or just use
```
mv
```
and git usually figures it out on its own.


q:
How does one dynamically load a new report from an embedded resource? I have created a reporting project that contains a report as an embedded resource. I added a second report file and use the following code to switch reports:

this.reportViewer1.LocalReport.ReportEmbeddedResource = "ReportsApplication2.Report2.rdlc";
this.reportViewer1.LocalReport.Refresh();
this.reportViewer1.RefreshReport();

When this code executes, the original report remains visible in the report viewer.

I have also tried using

LocalReport.LoadReportDefinition

but had the same result.

[A]
The answer: you have to call
```
```
<ReportViewer>.Reset();
```
```
prior to changing the value of ReportEmbeddedResource or calling LoadReportDefinition.
After you do so, you'll also have to call
```
```
<ReportViewer>.LocalReport.DataSources.Add( ... );
```
```
to re-establish the data sources.


q:
If I open a file using urllib2, like so:

remotefile = urllib2.urlopen('http://example.com/somefile.zip')

Is there an easy way to get the file name other then parsing the original URL?

EDIT: changed openfile to urlopen... not sure how that happened.

EDIT2: I ended up using:

filename = url.split('/')[-1].split('#')[0].split('?')[0]

Unless I'm mistaken, this should strip out all potential queries as well.

[A]
Do you mean
```
urllib2.urlopen
```
?  There is no function called
```
openfile
```
in the
```
urllib2
```
module.
Anyway, use the
```
urllib2.urlparse
```
functions:
```
```
>>> from urllib2 import urlparse
>>> print urlparse.urlsplit('http://example.com/somefile.zip')
('http', 'example.com', '/somefile.zip', '', '')
```
```
Voila.


q:
In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.

I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?

[A]
This works for MSVC++ and
```
g++
```
:
```
```
#if defined(_M_X64) || defined(__amd64__)
  // code...
#endif
```
```


q: Thinking in regards to Sliverlight, I would like to know where would be good places to go to get a refresher on 3d space, transforms, matrix manipulation, and all that good stuff.

[A]
Think I may have found it myself.  Was looking at:
http://msdn.microsoft.com/en-us/library/cc189037(VS.95).aspx
and
http://www.c-sharpcorner.com/UploadFile/mgold/TransformswithGDIplus09142005064919AM/TransformswithGDIplus.aspx


q:
I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3's and jpg's.  I have tried both of the following with no luck:

Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories);
Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories);

Is there a way to do this in one call?

[A]
Nope. Try the following:
```
```
List<string> _searchPatternList = new List<string>();
    ...
    List<string> fileList = new List<string>();
    foreach ( string ext in _searchPatternList )
    {
        foreach ( string subFile in Directory.GetFiles( folderName, ext  )
        {
            fileList.Add( subFile );
        }
    }

    // Sort alpabetically
    fileList.Sort();

    // Add files to the file browser control
    foreach ( string fileName in fileList )
    {
        ...;
    }
```
```
Taken from:
http://blogs.msdn.com/markda/archive/2006/04/20/580075.aspx


q:
I have a polygon soup of triangles that I would like to construct a BSP tree for.  My current program simply constructs a BSP tree by inserting a random triangle from the model one at a time until all the triangles are consumed, then it checks the depth and breadth of the tree and remembers the best score it achieved (lowest depth, lowest breadth).

By definition, the best depth would be log2(n) (or less if co-planar triangles are grouped?) where n is the number of triangles in my model, and the best breadth would be n (meaning no splitting has occurred).  But, there are certain configurations of triangles for which this pinnacle would never be reached.

Is there an efficient test for checking the quality of my BSP tree?  Specifically, I'm trying to find a way for my program to know it should stop looking for a more optimal construction.

[A]
Randomly building BSP trees until you chance upon a good one will be really, really inefficient.
Instead of choosing a tri at random to use as a split-plane, you want to try out several (maybe all of them, or maybe a random sampling) and pick one according to some heuristic. The heuristic is typically based on (a) how balanced the resulting child nodes would be, and (b) how many tris it would split.
You can trade off performance and quality by considering a smaller or larger sampling of tris as candidate split-planes.
But in the end, you can't hope to get a totally optimal tree for any real-world data so you might have to settle for 'good enough'.


q:
In Oracle, I can re-create a view with a single statement, as shown here:

CREATE OR REPLACE VIEW MY_VIEW AS
SELECT SOME_FIELD
FROM SOME_TABLE
WHERE SOME_CONDITIONS

As the syntax implies, this will drop the old view and re-create it with whatever definition I've given.

Is there an equivalent in MSSQL (SQL Server 2005 or later) that will do the same thing?

[A]
You can use 'IF EXISTS' to check if the view exists and drop if it does.
```
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
        WHERE TABLE_NAME = 'MyView')
    DROP VIEW MyView
GO

CREATE VIEW MyView
AS
     ....
GO
```


q:
On a 32-bit CPU, an integer is 4 bytes and a short integer is 2 bytes.  If I am writing a C/C++ application that uses many numeric values that will always fit within the provided range of a short integer, is it more efficient to use 4 byte integers or 2 byte integers?

I have heard it suggested that 4 byte integers are more efficient as this fits the bandwidth of the bus from memory to the CPU.  However, if I am adding together two short integers, would the CPU package both values in a single pass in parallel (thus spanning the 4 byte bandwidth of the bus)?

[A]
Yes, you should definitely use a 32 bit integer on a 32 bit CPU, otherwise it may end up masking off the unused bits (i.e., it will always do the maths in 32 bits, then convert the answer to 16 bits)
It won't do two 16 bit operations at once for you, but if you write the code yourself and you're sure it won't overflow, you can do it yourself.
Edit
: I should add that it also depends somewhat on your definition of "efficient".  While it will be able to do 32-bit operations more quickly, you will of course use twice as much memory.
If these are being used for intermediate calculations in an inner loop somewhere, then use 32-bit.  If, however, you're reading this from disk, or even if you just have to pay for a cache miss, it may still work out better to use 16-bit integers.  As with all optimizations, there's only one way to know:
profile it
.


q:
I am just beginning to do research into the feasibility of using Amazon's SimpleDB service as the datastore for RoR application I am planning to build. We will be using EC2 for the web server, and had planned to also use EC2 for the MySQL servers. But now the question is, why not use SimpleDB?

The application will (if successful) need to be very scalable in terms of # of users supported, will need to maintain a simple and efficient code base, and will need to be reliable.

I'm curious as to what the SO communities thoughts are on this.

[A]
Well, considering simple DB doesn't use SQL, or even have tables, means that it's a completely different beast than MySQL and other SQL-based things (
http://aws.amazon.com/simpledb/
). There are no constraints, triggers, or joins. Good luck.
Here's one way of getting it up and running:
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1242
(via
http://rubyforge.org/projects/aws-sdb/
)
I suppose if you're never going to need to query the data outside of rails, then SimpleDB may prove to be OK. But as it's not a first-class supported DB, you're likely to run into bugs that are difficult to fix. I wouldn't want to run a production rails app in a semi-beta backend.


q:
I'm trying to have the modrewrite rules skip the directory vip. I've tried a number of things as you can see below, but to no avail.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#RewriteRule ^vip$ - [PT]
RewriteRule ^vip/.$ - [PT]
#RewriteCond %{REQUEST_URI} !/vip
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

How do I get modrewrite to entirely ignore the /vip/ directory so that all requests pass directly to the folder?

Update:

As points of clarity:

It's hosted on Dreamhost

The folders are within a wordpress directory

the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important

[A]
I'm not sure if I understand your objective, but the following might do what you're after?
```
```
RewriteRule ^/vip/(.*)$   /$1?%{QUERY_STRING} [L]
```
```
This will cause a URL such as
http://www.example.com/vip/fred.html
to be rewritten without the /vip.


q: I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS

[A]
```
```
DateTime startDate;
DateTime endDate;

DateTime currentDate = startDate;
List<DateTime> dates = new List<DateTime> ();

while (true)
{
    dates.Add (currentDate);
    if (currentDate.Equals (endDate)) break;
    currentDate = currentDate.AddDays (1);
}
```
```
It assumes that startDate < than endDate, you get the results on the "dates" list


q:
I want to read all items of a feed in C#. The solutions I've found are only for the latest items like just the last 10 days.

Anybody has a good solution for this?

[A]
Libraries for reading feeds typically read all the data in the feed, but feeds typically only contain recent data - you need a source of data that includes older items, not a better library for reading the data you have.
Most entities publish feeds to allow people to track when new content is published, not to make all their data available in a more convenient machine readable format. For this purpose, publishing recent data only makes sense as it saves on bandwidth.


q:
I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java String flavor and pasted it into Java code, it does not work. The following class prints false:

public class RegexFoo {

    public static void main(String[] args) {
        String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
        String text = "http://google.com";
        System.out.println(IsMatch(text,regex));
}

    private static boolean IsMatch(String s, String pattern) {
        try {
            Pattern patt = Pattern.compile(pattern);
            Matcher matcher = patt.matcher(s);
            return matcher.matches();
        } catch (RuntimeException e) {
        return false;
    }
}
}

Does anyone know what I am doing wrong?

[A]
Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.
```
```
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
```
This works too:
```
```
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
```
Note:
```
```
String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>

String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
```
```


q:
I have monthly sales figures stored in separate sheets.  I would like to create a plot of sales for multiple products per month.  Each product would be represented in a different colored line on the same chart with each month running along the x axis.

What is the best way to create a single line chart that pulls from the same relative cells on multiple sheets?

[A]
Use the Chart Wizard.
On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.
Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.
Select your new series.
There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.
Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.
Hope that helps.
EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.


q:
Normally I program in C# but have been forced to do some work in C++. It seems that the integration with Visual Studio (2008) is really poor compared to C# but I was wondering if there are any good tools, plugins or configurations that can improve the situation.

Another post pointed out the program Visual Assist X, which at least helps with some things such as refactoring (though it is a bit expensive for me). My major problem is, though, that the compile errors give little clue about what is wrong and I spend most of my time figuring out what I did wrong. It just feels like it is possibly to statically check for a lot more errors than VS does out of the box. And why doesn't it provide the blue underlines as with C#, that shouldn't be too hard?!

I realize that half the problem is just the fact that I am new to C++ but I really feel that it can be unreasonably hard to get a program to compile. Are there any tools of this sort out there or are my demands too high?

[A]
I think there are two possibilities: 1) either you're trying out C++ stuff that is waaay over your knowledge (and consequently, you don't know what you did wrong and how to interpret error messages), 2) you have too high expectations.
A hint: many subsequent errors are caused by the first error.  When I get a huge list of errors, I usually correct just the first error and recompile.  You'd be amazed how much garbage (in terms of error messages) a missing delimiter or type declaration could produce :)
It is difficult to syntactically analyze a C++ program before compilation mainly for two reasons: 1) the C++ grammar is context-dependent, 2) templates are Turing-complete (think of them as of a functional programming language with a weird syntax).


q:
I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?

public class Test {
    public static void main(String args[]) {
        Test t = new Test();
        t.testT(null);
    }

    public <T extends Test> void testT(Class<T> type) {
        Class<T> testType = type == null ? Test.class : type; //Error here
        System.out.println(testType);
    }
}

Type mismatch: cannot convert from Class<capture#1-of ? extends Test> to Class<T>

By casting Test.class to Class<T> this compiles with an Unchecked cast warning and runs perfectly.

[A]
Remove the conditional and the error is a little nicer...
```
```
public class Test {
    public static void main(String args[]) {
        Test t = new Test();
        t.testT(null);
    }

    public <T extends Test> void testT(Class<T> type) {
    Class<T> testClass = Test.class;
        System.out.println(testClass);
    }
}

Test.java:10: incompatible types
found   : java.lang.Class<Test>
required: java.lang.Class<T>
        Class<T> testClass = Test.class;
```
```


q:
I have a web application where users enter arbitrary sql queries for later batch processing. We want to validate the syntax of the query without actually executing it. Some of the queries will take a long time, which is why we don't want to execute them. I'm using Oracle's dbms_sql.parse to do this.

However, I now have a situation where I need to know the number and type of the result set columns. Is there a way to do this without actually executing the query? That is, to have Oracle parse the query and tell me what the result datatypes/names will be returned when the query is actually executed? I'm using Oracle 10g and and it's a Java 1.5/Servlet 2.4 application.

Edit: The users who enter the queries are already users on the database. They authenticate to my app with their database credentials and the queries are executed using those credentials. Therefore they can't put in any query that they couldn't run by just connecting with sqlplus.

[A]
You should be able to prepare a SQL query to validate the syntax and get result set metadata.  Preparing a query should not execute it.
```
```
import java.sql.*;
. . .
Connection conn;
. . .
PreparedStatement ps = conn.prepareStatement("SELECT * FROM foo");
ResultSetMetadata rsmd = ps.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
```
```
Then you can get metadata about each column of the result set.


q: Does MS Access 2007 support internal foreign keys within the same table?

[A]
Yes.  Create the table with the hierarchy.
id - autonumber - primary key
parent_id - number
value
Go to the relationships screen.  Add the hierarchy table twice.  Connect the id and the parent_id fields.  Enforce referential integrity.


q:
Is there a way to use Enum values inside a JSP without using scriptlets.

e.g.

package com.example;

public enum Direction {
    ASC,
    DESC
}

so in the JSP I want to do something like this

<c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">...

[A]
You could implement the web-friendly text for a direction within the enum as a field:
```
```
<%@ page import="com.example.Direction" %>
...

Direction is <%=foo.direction.getFriendlyName()%>

<% if (foo.direction == Direction.ASC) { %>

That means you're going to heaven!

<% } %>
```
```
but that mixes the view and the model, although for simple uses it can be view-independent ("Ascending", "Descending", etc).
Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons.


q:
Any failed ASSERT statements on Windows cause the below debug message to appear and freeze the applications execution. I realise this is expected behaviour but it is running periodically on a headless machine so prevent the unit tests from failing, instead waiting on user input indefinitely.

Is there s a registry key or compiler flag I can use to prevent this message box from requesting user input whilst still allowing the test to fail under ASSERT?

Basically, I want to do this without modifying any code, just changing compiler or Windows options.

Thanks!

Microsoft Visual C++ Debug Library ASSERT http://img519.imageshack.us/img519/853/snapshotbu1.png

[A]
From MSDN about the ASSERT macro:
In an MFC ISAPI application, an assertion in debug mode will bring up a modal dialog box (ASSERT dialog boxes are now modal by default); this will interrupt or hang the execution. To suppress modal assertion dialogs, add the following lines to your project source file (projectname.cpp):
```
```
// For custom assert and trace handling with WebDbg
#ifdef _DEBUG
CDebugReportHook g_ReportHook;
#endif
```
```
Once you have done this, you can use the WebDbg tool (WebDbg.exe) to see the assertions.


q: I am creating an installer for an ASP.Net website using WiX.  How do you set the ASP.Net version in IIS using WiX?

[A]
First find the correct .NET version folder. Use DirectorySearch/FileSearch to perform search.
Use the above path to call aspnet_regiis.exe and set the version for the webapp from a custom action.
```
aspnet_regiis.exe -s W3SVC/1/ROOT/SampleApp1
```


q: I'm trying to debug an MSBuild task, and I know there is some way to write to the MSBuild log from within a custom task but I forget how.

[A]
The base
Task
class has a
```
Log
```
property you can use:
```
```
Log.LogMessage("My message");
```
```


q: I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?

[A]
In a debug compilation,
```
Assert
```
takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true.
If you compile in Release, all
```
Debug.Assert
```
's are automatically left out.


q:
If I do the following:

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]

I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen.  How do I work around this?

[A]
I figured out this workaround:
```
```
>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()
```
```
Is there a better one?


q:
I have a Flex application that calls a function which searches a large document collection. Depending on the search term, the user may want to stop the request from flex.

I’d like to not only stop the flex application from expecting the request, but also stop the CFC request. Is this possible? What’s the best approach for doing this?

[A]
You can programmatically end requests with either
```
<cfabort/>
```
or
```
<cfsetting requesttimeout="0"/>
```
- but that's on the CF server side of things, which I don't think is what you're asking?
Ending it remotely... well, if you have FusionReactor it
might
be possible to contact that using Flex and have it interrupt the request for you.
(You can certainly try to end requests within FusionReactor, but whether or not Flex can actually ask FR to stop it... you'd have to ask that on the FR mailing list if there's a way to do that.)
Possibly an alternative solution is to try and architect the search so that it works over multiple requests, but how feasible that is will depend on exactly what you're searching.


q:
In the GNOME Terminal, Bash does smart auto-completion. For example

apt-get in<TAB>

becomes

apt-get install

In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source /etc/bash_completion. The above example sticks as in or auto-completes with a filename in the current directory rather than a valid apt-get command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in shell-mode?

[A]
I don't know the answer to this. But the reason that it doesn't work as you expect is probably because the completion in emacs shells is handled by emacs internally (by the comint-dynamic-complete function), and doesn't have those smart completion functions built-in.
I'm afraid it is not an easy thing to fix.
Edit: njsf's suggestion of using term-mode is probably as good as it gets. Start it with
```
M-x term
```
It is included in the standard emacs distribution (and in emacs21-common or emacs22-common on Ubuntu and Debian at least).


q:
I frequently need to debug .NET binaries on test machines (by test-machine, I mean that the machine doesn't have Visual Studio installed on it, it's frequently re-imaged, It's not the same machine that I do my development on, etc).

I love the Visual Studio debugger, but it's not practical for me to install visual studios on a freshly imaged test-machine just to debug an assertion or crash (the install takes way too long, the footprint is too large, etc).

I'd really like a quickly installed program that could break into a running process, let me specify the location of symbols/source code, and let me jump right into debugging.  For native binaries, windbg works great, but I haven't found anything similiar for managed binaries. Any recommendations?

(as a side note, I am aware of visual studios remote debugging capabilities, but for some reason it never seems to work consistently for me...  I often have connection issues)

[A]
There is always
mdbg
and
cordbg
, but I would suggest digging more into why remote debugging doesn't work consistently.
VS2005/8 seem a lot more reliable than earlier versions here (though I primarily do unmanaged) and it saves you from having to have the symbols accessible on the target machine.


q: In light of how ajax is actually used by most sites today; why is ajax embraced while frames are still regarded as a bad idea?

[A]
Ajax and frames are completely different from an accessibility standpoint (they're also completely different full stop).
Frames offer very little positive effect but bring with them a host of negative issues.
Ajax on the other hand makes the user interface more dynamic without compromising usability in most cases.


q:
Which profiler is better for general purpose profiling and heap analysis? 90% of our apps are standalone command line programs with substantial database and numeric processing. The other 10% are webapps/servlet container apps (with very little JSP and NO SCRIPLETS!). Target user would be Sr Software Engineer with 5-10 years of industry experience. We need support only for Sun JDK 5 and.

As of writing this question (2008-10-02), JProfiler was at 5.1.4 and YourKit was 7.5. Looks like YourKit 8.0 will be released soon.

[A] If you're on jdk >=1.6_07 you might also want to look at jvisualvm which comes bundled.


q:
What would you recommend for class that needs to keep a list of unique integers?

I'm going to want to Add() integers to the collection and also check for existence e.g. Contains().

Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21".

[A]
HashSet
:
The
```
HashSet<T>
```
class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
The capacity of a
```
HashSet<T>
```
object is the number of elements that the object can hold. A
```
HashSet<T>
```
object's capacity automatically increases as elements are added to the object.
The
```
HashSet<T>
```
class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the
```
Dictionary<TKey, TValue>
```
or
```
Hashtable
```
collections. In simple terms, the
```
HashSet<T>
```
class can be thought of as a
```
Dictionary<TKey, TValue>
```
collection without values.
A
```
HashSet<T>
```
collection is not sorted and cannot contain duplicate elements...


q:
I have a lot of XML files and I'd like to generate a report from them. The report should provide information such as:

root 100%
 a*1 90%
 b*1 80%
  c*5 40%

meaning that all documents have a root element, 90% have one a element in the root, 80% have one b element in the root, 40% have 5 c elements in b.

If for example some documents have 4 c elements, some 5 and some 6, it should say something like:

c*4.3 4 6 40%

meaning that 40% have between 4 and 6 c elements there, and the average is 4.3.

I am looking for free software, if it doesn't exist I'll write it. I was about to do it, but I thought about checking it. I may not be the first one to have to analyze and get an structural overview of thousand of XML files.

[A]
Here's an XSLT 2.0 method.
Assuming that
```
$docs
```
contains a sequence of document nodes that you want to scan, you want to create one line for each element that appears in the documents. You can use
```
<xsl:for-each-group>
```
to do that:
```
```
<xsl:for-each-group select="$docs//*" group-by="name()">
  <xsl:sort select="current-group-key()" />
  <xsl:variable name="name" as="xs:string" select="current-grouping-key()" />
  <xsl:value-of select="$name" />
  ...
</xsl:for-each-group>
```
```
Then you want to find out the stats for that element amongst the documents. First, find the documents have an element of that name in them:
```
```
<xsl:variable name="docs-with" as="document-node()+"
  select="$docs[//*[name() = $name]" />
```
```
Second, you need a sequence of the number of elements of that name in each of the documents:
```
```
<xsl:variable name="elem-counts" as="xs:integer+"
  select="$docs-with/count(//*[name() = $name])" />
```
```
And now you can do the calculations. Average, minimum and maximum can be calculated with the
```
avg()
```
,
```
min()
```
and
```
max()
```
functions. The percentage is simply the number of documents that contain the element divided by the total number of documents, formatted.
Putting that together:
```
```
<xsl:for-each-group select="$docs//*" group-by="name()">
  <xsl:sort select="current-group-key()" />
  <xsl:variable name="name" as="xs:string" select="current-grouping-key()" />
  <xsl:variable name="docs-with" as="document-node()+"
    select="$docs[//*[name() = $name]" />
  <xsl:variable name="elem-counts" as="xs:integer+"
    select="$docs-with/count(//*[name() = $name])" />
  <xsl:value-of select="$name" />
  <xsl:text>* </xsl:text>
  <xsl:value-of select="format-number(avg($elem-counts), '#,##0.0')" />
  <xsl:text> </xsl:text>
  <xsl:value-of select="format-number(min($elem-counts), '#,##0')" />
  <xsl:text> </xsl:text>
  <xsl:value-of select="format-number(max($elem-counts), '#,##0')" />
  <xsl:text> </xsl:text>
  <xsl:value-of select="format-number((count($docs-with) div count($docs)) * 100, '#0')" />
  <xsl:text>%</xsl:text>
  <xsl:text>
</xsl:text>
</xsl:for-each-group>
```
```
What I haven't done here is indented the lines according to the depth of the element. I've just ordered the elements alphabetically to give you statistics. Two reasons for that: first, it's significantly harder (like too involved to write here) to display the element statistics in some kind of structure that reflects how they appear in the documents, not least because different documents may have different structures. Second, in many markup languages, the precise structure of the documents can't be known (because, for example, sections can nest within sections to any depth).
I hope it's useful none the less.
UPDATE:
Need the XSLT wrapper and some instructions for running XSLT? OK. First, get your hands on
Saxon 9B
.
You'll need to put all the files you want to analyse in a directory. Saxon allows you to access all the files in that directory (or its subdirectories) using a collection using a
special URI syntax
. It's worth having a look at that syntax if you want to search recursively or filter the files that you're looking at by their filename.
Now the full XSLT:
```
```
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="xs">

<xsl:param name="dir" as="xs:string"
  select="'file:///path/to/default/directory?select=*.xml'" />

<xsl:output method="text" />

<xsl:variable name="docs" as="document-node()*"
  select="collection($dir)" />

<xsl:template name="main">
  <xsl:for-each-group select="$docs//*" group-by="name()">
    <xsl:sort select="current-group-key()" />
    <xsl:variable name="name" as="xs:string" select="current-grouping-key()" />
    <xsl:variable name="docs-with" as="document-node()+"
      select="$docs[//*[name() = $name]" />
    <xsl:variable name="elem-counts" as="xs:integer+"
      select="$docs-with/count(//*[name() = $name])" />
    <xsl:value-of select="$name" />
    <xsl:text>* </xsl:text>
    <xsl:value-of select="format-number(avg($elem-counts), '#,##0.0')" />
    <xsl:text> </xsl:text>
    <xsl:value-of select="format-number(min($elem-counts), '#,##0')" />
    <xsl:text> </xsl:text>
    <xsl:value-of select="format-number(max($elem-counts), '#,##0')" />
    <xsl:text> </xsl:text>
    <xsl:value-of select="format-number((count($docs-with) div count($docs)) * 100, '#0')" />
    <xsl:text>%</xsl:text>
    <xsl:text>
</xsl:text>
  </xsl:for-each-group>
</xsl:template>

</xsl:stylesheet>
```
```
And to run it you would do something like:
```
> java -jar path/to/saxon.jar -it:main -o:report.txt dir=file:///path/to/your/directory?select=*.xml
```
This tells Saxon to start the process with the template named
```
main
```
, to set the
```
dir
```
parameter to
```
file:///path/to/your/directory?select=*.xml
```
and send the output to
```
report.txt
```
.


q:
Where can I find a good Rails newbie-friendly reference about generating rails models with foreign key relationships?

I've found some pages indicating that you should add has_many and belongs_to to the relevant models to specify these relationships, but haven't seen any instructions for getting the scaffolds to generate the correct controller and view code that would reflect these relationships.

[A]
There are a bunch of StackOverflow questions asking for newbie reference materials. I recommend that you start with the two Peepcode screencasts:
Rails From Scratch Part I
Rails From Scratch Part II
They do a great job of visually introducing you to Rails 2 development. Then, I'd recommend you pick up the Rails 2.1 PDF by Ryan Daigle, to get the hang of the 2.1 features not covered in the screencasts.
I'm not sure what you're driving at with your question. What are you expecting the scaffolding to do? Create multi-object relationship links automatically? That's something you have to start layering in yourself....and as you do so, the scaffolding starts to be replaced with a real application. The scaffolding is just a starting point: it's not meant to guess what your inter-object relationships are going to look like in the application.


q:
I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it.

Here's a quick example to make it clearer... this is what I have now:

Pages: 1 2 3 4 [5] 6 7 8 9 10 11

This is what I want to end up with:

Pages: ... 3 4 [5] 6 7 ...

(In this example, I'm only showing 2 adjacent pages to the current page)

I'm implementing it in PHP/Mysql, and the "basic" pagination  (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it...

[A]
Here is some code based on original code from
this very old link
. It uses markup compatible with Bootstrap's pagination component, and outputs page links like this:
```
```
[1] 2 3 4 5 6 ... 100
1 [2] 3 4 5 6 ... 100
...
1 2 ... 14 15 [16] 17 18 ... 100
...
1 2 ... 97 [98] 99 100
```
```
```
```
<?php

// How many adjacent pages should be shown on each side?
$adjacents = 3;

//how many items to show per page
$limit = 5;

// if no page var is given, default to 1.
$page = (int)$_GET["page"] ?? 1;

//first item to display on this page
$start = ($page - 1) * $limit;

/* Get data. */
$data = $db
    ->query("SELECT * FROM mytable LIMIT $start, $limit")
    ->fetchAll();

$total_pages = count($data);

/* Setup page vars for display. */
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages / $limit);
//last page minus 1
$lpm1 = $lastpage - 1;

$first_pages = "
1
" .
    "
2";

$ellipsis = "
...
";

$last_pages = "
$lpm1
" .
    "
$lastpage";

$pagination = "";
$pagincation .= "
";

//previous button

$disabled = ($page === 1) ? "disabled" : "";
$pagination.= "
« previous
";

//pages
//not enough pages to bother breaking it up
if ($lastpage < 7 + ($adjacents * 2)) {
    for ($i = 1; $i <= $lastpage; $i++) {
        $active = $i === $page ? "active" : "";
        $pagination .= "
$i
";
    }
} elseif($lastpage > 5 + ($adjacents * 2)) {
    //enough pages to hide some
    //close to beginning; only hide later pages
    if($page < 1 + ($adjacents * 2)) {
        for ($i = 1; $i < 4 + ($adjacents * 2); $i++) {
            $active = $i === $page ? "active" : "";
            $pagination .= "
$i
";
        }
        $pagination .= $ellipsis;
        $pagination .= $last_pages;
    } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
        //in middle; hide some front and some back
        $pagination .= $first_pages;
        $pagination .= $ellipsis
        for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) {
            $active = $i === $page ? "active" : "";
            $pagination .= "
$i
";
        }
        $pagination .= $ellipsis;
        $pagination .= $last_pages;
    } else {
        //close to end; only hide early pages
        $pagination .= $first_pages;
        $pagination .= $ellipsis;
        $pagination .= "
...
";
        for ($i = $lastpage - (2 + ($adjacents * 2)); $i <= $lastpage; $i++) {
            $active = $i === $page ? "active" : "";
            $pagination .= "
$i
";
        }
    }
}

//next button
$disabled = ($page === $last) ? "disabled" : "";
$pagination.= "
next »
";

$pagination .= "
";

if($lastpage <= 1) {
    $pagination = "";
}

echo $pagination;

foreach ($data as $row) {
    // display your data
}

echo $pagination;
```
```


q:
I have a Person model that has a foreign key relationship to Book, which has a number of fields, but I'm most concerned about author (a standard CharField).

With that being said, in my PersonAdmin model, I'd like to display book.author using list_display:

class PersonAdmin(admin.ModelAdmin):
    list_display = ['book.author',]

I've tried all of the obvious methods for doing so, but nothing seems to work.

Any suggestions?

[A]
According to the documentation, you can only display the
```
__unicode__
```
representation of a ForeignKey:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display
Seems odd that it doesn't support the
```
'book__author'
```
style format which is used everywhere else in the DB API.
Turns out there's
a ticket for this feature
, which is marked as Won't Fix.


q:
A co worker of mine asked me to review some of my code and he sent me a diff file.  I'm not new to diffs or version control in general but the diff file was very difficult to read because of the changes he made.  Specifically, he used the "extract method" feature and reordered some methods.  Conceptually, very easy to understand but looking at the diff, it was very hard to tell what he had done.  It was much easier for me to checkout the previous revision and use Eclipse's "compare" feature, but it was still quite clunky.

Is there any version control system that stores metadata related to refactoring.  Of course, it would be IDE and Programming Language specific, but we all use Eclipse and Java!  Perhaps there might be some standard on which IDEs and version control implementations can play nicely?

[A]
Eclipse can
export refactoring history
(see
3.2 release notes
as well).  You could then view the refactoring changes via preview in Eclipse.


q:
Is there any alternative for WPF (windows presentation foundation) in python?

http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF

[A]
You might want to look at
pygtk
and
glade
.
Here
is a tutorial.
There is a long
list of alternatives
on the
Python Wiki
.


q:
Suppose I have a "tags" table with two columns: tagid and contentid.  Each row represents a tag assigned to a piece of content.  I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342.

The "easy" way to do this would be (pseudocode):

select contentid from tags where tagid = 334 and contentid in (
    select contentid from tags where tagid = 338 and contentid in (
        select contentid from tags where tagid = 342
    )
)

However, my gut tells me that there's a better, faster, more extensible way to do this.  For example, what if I needed to find the intersection of 12 tags?  This could quickly get horrendous.  Any ideas?

EDIT: Turns out that this is also covered in this excellent blog post.

[A]
The only alternative way i can think of is:
```
```
select a.contentid from tags a
inner join tags b on a.contentid = b.contentid and b.tagid=334
inner join tags c on a.contentid = c.contentid and c.tagid=342
where a.tagid=338
```
```


q:
I'm putting together a little tool that some business people can run on their local filesystems, since we don't want to setup a host for it.

Basically, its just HTML + Javascript (using jQuery) to pull some reports using REST from a 3rd party.

The problem is, FF3 and IE don't allow the ajax call, I get:

Access to restricted URI denied" code: "1012

Obviously its an XSS issue...how do I work around it? The data returned is in XML format.

I was trying to do it this way:

$.get(productUrl, function (data){
    alert (data);
});

EDIT: To be clear...I'm not setting up an internal host for this(Way to much red tape), and we CANNOT host this externally due to the data being retrieved.

EDIT #2: A little testing shows that I can use an IFRAME to make the request. Does anyone know if there any downsides to using a hidden IFRAME?

[A]
If you have Python installed, a webserver to serve files can be as simple as
```
```
python -c “import SimpleHTTPServer;SimpleHTTPServer.test()”
```
```
Edit:
Original poster can't use this approach, but in general I think this is the way to solve this particular problem for future users with this issue.


q:
I have never clearly understood the usage of MAXDOP. I do know that it makes the query faster and that it is the last item that I can use for Query Optimization.

However, my question is, when and where it is best suited to use in a query?

[A]
This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.
From Books Online, on MAXDOP:
Sets the maximum number of processors
  the query processor can use to execute
  a single index statement. Fewer
  processors may be used depending on
  the current system workload.
See
Rickie Lee's blog
on parallelism and CXPACKET wait type. It's quite interesting.
Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.
Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.


q:
What are some good algorithms for automatically labeling text with the city / region  or origin?  That is, if a blog is about New York, how can I tell programatically.  Are there packages / papers that claim to do this with any degree of certainty?

I have looked at some tfidf based approaches, proper noun intersections, but so far, no spectacular successes, and I'd appreciate ideas!

The more general question is about assigning texts to topics, given some list of topics.

Simple / naive approaches preferred to full on Bayesian approaches, but I'm open.

[A]
You're looking for a
named entity recognition
system, or short NER. There are
several
good
toolkits
available to help you out. LingPipe in particular has a very
decent tutorial
.
CAGEclass
seems to be oriented around NER on geographical place names, but I haven't used it yet.
Here's
a nice blog entry about the difficulties of NER  with geographical places names.
If you're going with Java, I'd recommend using the LingPipe NER classes. OpenNLP also has some, but the former has a better documentation.
If you're looking for some theoretical background,
Chavez et al. (2005)
have constructed an interesting syntem and documented it.


q: I know that you can do this in SQL Server 2005, but I'm at a loss for 2000.

[A]
From all the research I've done on this in the past, I unfortunately have to say no. SQL Server 2000 simply does not store this information, and I've never seen any solution for retrieving it.
There are a few alternative methods, but they all involve user intervention. Besides keeping stored procedure scripts in a source control system, I think the next best approach is to use comments inside the stored procedure. Not ideal, but it's better than nothing if you want to track what gets updated.


q:
Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.).

For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line interface (CLI).

What complications / headaches / surprises should I expect? What, for example, if I use a third-party library which still uses std::string?

Since support for international strings isn't that strong of a requirement for the type of embedded systems that I work on, I would only do it if it isn't going to cause major headaches.


q: Is there a connection limit on Sql Server 2005 Developers Edition.  We have many threads grabbing connections, and I know ADO.NET does connection pooling, but I get OutOfMemory exceptions.  We take out the db connections and it works fine.

[A]
You may not be closing or disposing of your connection objects correctly.  Make sure your code looks something like this:
```
```
using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    conn.Open();

    // database access code goes here
}
```
```
The using block will automatically close and dispose of your connection object.


q:
Should log classes open/close a log file stream on each write to the log file or should it keep the log file stream open throughout the application's lifetime until all logging is complete?

I'm asking in context of a desktop application.  I have seen people do it both ways and was wondering which approach yields the best all-around results for a logger.

[A]
If you have frequent read/writes it is more efficient to keep the file open for the lifetime with a
single open/close
.
You might want to
flush periodically or after each write
though. If your application crashes you might not have all the data written to your file. Use fflush on Unix-based systems and FlushFileBuffers on Windows.
If you are running on Windows as well you can use the CreateFile API with FILE_FLAG_NO_BUFFERING to go direct to the file on each write.
It is also
better to keep the file open
for the lifetime,
because
each time you open/close you might have a failure if the file is in use.  For example, you might have
a backup application that runs and opens/closes your file
as it's backing it up.  And this
might cause your program to not be able to access your own file
.   Ideally, you would want to keep your file open always and specify sharing flags on Windows (FILE_SHARE_READ).  On Unix-based systems, sharing will be default.


q:
in a C program I have an long* that I want to serialize (thus converting to chars). A long doesn't fit in a single char, and the size varies depending of the processor (can be 4 bytes or 8 bytes).

Theres a good way to make the serialization and de-serialization?

[A]
If you create a char pointer that points to the beginning of the long array, when you increment through the char "array", you'll get 8 bits at a time. Be aware, though, that the long won't be null-terminated (necessarily, it might be), so you need to keep track where the end of it is.
For example:
```
```
long list[MAX];
char *serial = list;
int chunk = sizeof(long);
int k;
for(k=0; k<(MAX*chunk); k++){
  // do something with the "char"
}
```
```


q:
For example, suppose I have a class:

class Foo
{
public:
    std::string& Name()
    {
        m_maybe_modified = true;
        return m_name;
    }

    const std::string& Name() const
    {
        return m_name;
    }
protected:
    std::string m_name;
    bool m_maybe_modified;
};

And somewhere else in the code, I have something like this:

Foo *a;
// Do stuff...
std::string name = a->Name(); // <-- chooses the non-const version

Does anyone know why the compiler would choose the non-const version in this case?

This is a somewhat contrived example, but the actual problem we are trying to solve is periodically auto-saving an object if it has changed, and the pointer must be non-const because it might be changed at some point.

[A]
Two answers spring to mind:
The non-const version is a closer match.
If it called the const overload for the non-const case, then under what circumstances would it
ever
call the non-const overload?
You can get it to use the other overload by casting
```
a
```
to a
```
const Foo *
```
.
Edit:
From
C++ Annotations
Earlier, in section 2.5.11 the concept
of function overloading was
introduced. There it noted that member
functions may be overloaded merely by
their const attribute. In those cases,
the compiler will use the member
function
matching most closely the
const-qualification of the object:


q:
I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it.

I have no knowledge of deploying "real-life" Python applications, though I have used py2exe in the past with varied success. How would I obfuscate the code? Can I somehow deploy only the bytecode?

An ideal solution would not jeopardize my intellectual property (source code), would not require a direct installation of Python (though I'm sure it will need to have some embedded interpreter), and would be cross-platform (Windows, Mac, and Linux). Does anyone know of any tools or resources in this area?

Thanks.

[A]
Wow, there are a lot of questions in there:
It is possible to run the bytecode (.pyc) file directly from the Python interpreter, but I haven't seen any bytecode obfuscation tools available.
I'm not aware of any "all in one" deployment solution, but:
For Windows you could use NSIS(
http://nsis.sourceforge.net/Main_Page
).  The problem here is that while OSX/*nix comes with python, Windows doesn't.  If you're not willing to build a binary with py2exe, I'm not sure what the licensing issues would be surrounding distribution of the Python runtime environment (not to mention the technical ones).
You could package up the OS X distribution using the "bundle" format, and *NIX has it's own conventions for installing software-- typically a "make install" script.
Hope that was helpful.


q:
I have two DataTables, A and B, produced from CSV files.  I need to be able to check which rows exist in B that do not exist in A.

Is there a way to do some sort of query to show the different rows or would I have to iterate through each row on each DataTable to check if they are the same?  The latter option seems to be very intensive if the tables become large.

[A]
You can use the Merge and GetChanges methods on the DataTable to do this:
```
```
A.Merge(B); // this will add to A any records that are in B but not A
return A.GetChanges(); // returns records originally only in B
```
```


q:
As far as I can tell there's no simple way of retrieving a character offset from a TextRange object in Internet Explorer. The W3C Range object has a node, and the offset into the text within that node. IE seems to just have pixel offsets. There are methods to create, extend and compare ranges, so it would be possible to write an algorithm to calculate the character offset, but I feel I must be missing something.

So, what's the easiest way to calculate the character offset of the start of an Internet Explorer TextRange?

[A]
You can iterate through the body element's
```
TextRange.text
```
property using
```
String.substring()
```
to compare against the TextRange for which you want the character offset.
```
```
function charOffset(textRange, parentTextRange)
 { var parentTxt = parentTextRange.text;
   var txt       = textRange.text;
   var parentLen = parentTxt.length;

   for(int i=0; i < parentLen ; ++i)
    { if (parentTxt.substring(i, txt.length+i) == txt)
       { var originalPosition = textRange.getBookmark();

         //moves back one and searches backwards for same text
         textRange.moveStart("character",-1);
         var foundOther = textRange.findText(textRange.text,-parentLen,1);

         //if no others were found return offset
         if (!foundOther) return i;

         //returns to original position to try next offset
         else textRange.moveToBookmark(originalPosition);
       }
    }

   return -1;
 }
```
```
[
Reference for
```
findText()
```
]


q:
Which is a better format to store graphic assets for a Flex application, SWF or SWC?

Are there any real differences, and if so what are they?

[A]
SWC is what you use when you're looking for a library to compile into your app. You have access to the classes and can import individual parts. SWF is more likely what you're looking for when embedding graphics.
Here's the docs you might be interested in:
http://livedocs.adobe.com/flex/3/html/help.html?content=layoutperformance_06.html#223998
I've been having good success with SVG for images, but there's some caveats since Flex only implements a subset of the features.


q:
If I want to construct a std::string with a line like:

std::string my_string("a\0b");

Where i want to have three characters in the resulting string (a, null, b), I only get one.  What is the proper syntax?

[A]
I have no idea
why
you'd want to do such a thing, but try this:
```
```
std::string my_string("a\0b", 3);
```
```


q:
The following code receives seg fault on line 2:

char *str = "string";
str[0] = 'z';  // could be also written as *str = 'z'
printf("%s\n", str);

While this works perfectly well:

char str[] = "string";
str[0] = 'z';
printf("%s\n", str);

Tested with MSVC and GCC.

[A]
Because the type of
```
"whatever"
```
in the context of the 1st example is
```
const char *
```
(even if you assign it to a non-const char*), which means you shouldn't try and write to it.
The compiler has enforced this by putting the string in a read-only part of memory, hence writing to it generates a segfault.


q:
Specifically, we've got some external JavaScript tracking code on our sites that throws itself into an infinite loop each time an anchor is clicked on.

We don't maintain the tracking code, so we don't know exactly how it works.  Since the code causes the browser to lock up almost immediately, I was wondering if there's anyway to log the results of Firebug's 'profile' functionality to an external file for review?

[A]
Forget HTML and make a PDF. HTML printing is extremely variable - not just across browsers but across different versions of the same browser. PDF is a lot easier.
Even if you get it exactly right with one browser / font setup / printer / phase of the moon, it will be the most fragile thing you've ever had to maintain. No matter how long you think it will take to make a PDF (and it's not really that hard as there are some free libraries out there), HTML will ultimately take a lot more of your time. PDF readers are widely deployed and print more consistently than even Word files.


q:
I have code from PowerBuilder 5 that can't be built. The compiler just stops before it is done without any error codes.

I would like to upgrade the code to the recent version of PowerBuilder but there are some intermediate versions of PowerBuilder that have binary dependencies to an old Microsoft java dll that Microsoft no longer can distribute due to some court case.

So, is there a way to get my code running in a newer environment?

/johan/

[A]
Very unusual sounding problem.  You could give a try to migrating the code to a more recent version of PowerBuilder and see if it will compile or at least fail but give you some useful error messages.
I would also recommend posting this in the PowerBuilder section of the Sybase newsgroups. They are very active and full of some brilliant PB minds with lots of experience.  You can find them here:
http://forums.sybase.com


q: We are trying to automate a build of one of our products which includes a step where it packages some things with WISE.  At one point WISE pops up a window with a progress bar on it to show how it is doing.  If one is connected to the machine with remote desktop the build works fine but if one is not connected the build stalls until you reconnect at which point the window opens and the build progresses.  Does anybody know of a work around for this?  Some way of tricking windows into believing that there is a desktop session connected?

[A]
What version are you using?  Looking at the feature set, it looks like their "std" version might be limited.  Perhaps unattended installs require the Pro version?
That's just a guess....
Regardless, I wonder whether you could simply code up an auto-run task for the box that calls
CreateDesktop
to pretend there's an interactive login?
I found a
CreateDesktop example
that's about desktop switching, and
an example about unattended installs
-- you might be able to use one of them as a starting point to "fake out" WISE :)
It might be worth a try...


q:
I need to get the Folder size and display the info on a report (SSRS). I need to do this for a number of Databases (loop!). These DB's are websites' backends.

Are any samples available for this? Does xp_filesize and the like the right solution?

[A]
Could you clarify who should do what in your scenario? Do you want SQL Server do get the info or do you want Reporting Server do that?
What exactly do you mean by "folder size"? Is "one folder, sum up each file" enough or does it need to be recursive? Either way, I'd go for a little custom .NET function that uses
```
System.IO.Directory
```
and it's relatives.


q:
Any XPath like /NodeName/position() would give you the position of the Node w.r.t it's parent node.

There is no method on the XElement (Linq to XML) object that can get the position of the Element. Is there?

[A]
```
```
static int Position(this XNode node) {
  var position = 0;
  foreach(var n in node.Parent.Nodes()) {
    if(n == node) {
      return position;
    }
    position++;
  }
  return -1;
}
```
```


q: How can I make my std::fstream object start reading a text file from the second line?

[A]
Use getline() to read the first line, then begin reading the rest of the stream.
```
```
ifstream stream("filename.txt");
string dummyLine;
getline(stream, dummyLine);
// Begin reading your stream here
while (stream)
   ...
```
```
(Changed to std::getline (thanks  dalle.myopenid.com))


q:
I know there is done some research on TDD at the North Carolina State University. They have published a paper called 'An Initial Investigation of Test Driven Development in Industry'. Other publications by NCSU can be found here.

Can anybody point me to other good publications on this topic?

[A]
The
ACM Digital Library
has quite a few papers on TDD.  Simply Search for Test Driven Development.
The top results from Google's
Test driven development academic research
:
Test-Driven Development: Concepts, Taxonomy, and Future Direction
in the IEEE Computer Society.
software Architecture Improvement through TDD
at the ACM


q: For example, I'm writing a multi-threaded time-critical application that processes and streams audio in real-time. Interruptions in the audio are totally unacceptable. Does this mean I cannot use the STL because of the potential slow down when an exception is thrown?

[A]
Generally, the only exceptions that STL containers will throw by themselves is an std::bad_alloc if new fails. The only other times are when user code (for example constructors, assignments, copy constructors) throws. If your user code never throws then you only have to guard against new throwing, which you would have had to do anyways most likely.
Other things that can throw exceptions:
- at() functions can throw std::out_of_range if you access them out of bounds. This is a serious program error anyways.
Secondly, exceptions aren't always slow. If an exception occurs in your audio processing, its probably because of a serious error that you will need to handle anyways. The error handling code is probably going to be significantly more expensive than the exception handling code to transport the exception to the catch site.


q: I'm wondering if its possible to add new class data members at run-time in PHP?

[A]
It is. You can add public members are run time with no additional code, and can affect protected/private members using the magical overloading methods __get() / __set(). See
here
for more details.


q:
How can I print a message to the error console, preferably including a variable?

For example, something like:

print('x=%d', x);

[A]
Install
Firebug
and then you can use
```
console.log(...)
```
and
```
console.debug(...)
```
, etc. (see
the documentation
for more).


q:
I'm processing a file, line-by-line, and I'd like to do an inverse match.  For instance, I want to match lines where there is a string of six letters, but only if these six letters are not 'Andrea'. How should I do that?

I'm using RegexBuddy, but still having trouble.

[A]
```
```
(?!Andrea).{6}
```
```
Assuming your regexp engine supports negative lookaheads...
...or maybe you'd prefer to use
```
[A-Za-z]{6}
```
in place of
```
.{6}
```
Note that lookaheads and lookbehinds are generally not the right way to "inverse" a regular expression match. Regexps aren't really set up for doing negative matching; they leave that to whatever language you are using them with.


q:
The standalone flashplayer takes no arguments other than a .swf file when you launch it from the command line. I need the player to go full screen, no window borders and such. This can be accomplished by hitting ctrl+f once the program has started. I want to do this programmatically as I need it to launch into full screen without any human interaction.

My guess is that I need to some how get a handle to the window and then send it an event that looks like the "ctrl+f" keystroke.

If it makes any difference, it looks like flashplayer is a gtk application and I have python with pygtk installed.

UPDATE (the solution I used... thanks to ypnos' answer):

./flashplayer http://example.com/example.swf & sleep 3 && ~/xsendkey -window "Adobe Flash Player 10" Control+F

[A]
I've actually done this a long time ago, but it wasn't petty.  What we did is use the
Sawfish window manager
and wrote a hook to recognize the flashplayer window, then strip all the decorations and snap it full screen.
This may be possible without using the window manager, by registering for X window creation events from an external application, but I'm not familiar enough with X11 to tell you how that would be done.
Another option would be to write a pygtk application that embedded the standalone flash player inside a gtk.Socket and then resized itself.  After a bit of thought, this might be your best bet.


q: In .NET, if a class contains a member that is a class object, should that member be exposed as a property or with a method?

[A]
Property. A Property is basically just a 'cheap' method. Getting or setting a reference to an object is pretty cheap.
Just to clarify, properties are usually supposed to represent the internal state of an object. However, the implementation of a member as a property or method tells the user how expensive the call is likely to be.


q: Is there a library/software which can accept a number of keypoints and matches of them between images and produce a morph? Or any ideas/algorithms on how to do it?

[A]
An older piece of software by
Gryphon Software
could do image morphing. I saw an article about it from 1994. I couldn't find a company site, so they may be abandon ware now.
Her is a quote from a Wikipedia article about a film editing
technique called Dissolve
.
In non-linear video editing, a dissolve is done in software, by interpolating gradually between the RGB values of each pixel of the image.
Hope that helps.


q:
I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 database, Visual Studio 2005 and am quite OK with creating stored procedures and datasets.

Can someone please point me in the right direction for creating reports? I just can't seem work it out. Some examples would be a good start, or a simple How-to tutorial... anything really that is a bit better explained than the MSDN docs.

I'm using the CrystalDecisions.Windows.Forms.CrystalReportViewer control to display the reports, I presume this is correct.

If I'm about to embark on a long and complex journey, what's the simplest way to create and display reports that can also be printed?

[A]
Crystal is one possible option for creating reports. It has been around a long time and a lot of people seem to like it.
You might want to take a look at SQL reporting services. I have used both but my preferance is SQL reporting services. Its pretty well integrated into studio and works similar to the other microsoft projects. Its also free with the sql express etc.
This is a good article on beginning reporting services:
http://www.simple-talk.com/sql/learn-sql-server/beginning-sql-server-2005-reporting-services-part-1/


q:
How do I create a grails war file so that it doesn't have the version number

(e.g. foo-0.1.war)

attached to the end when I execute the 'grails war' command?

[A]
I think you can specify the war name in the war command.
```
```
grails war foo.war
```
```
Also check the latest Grails documentation for where to set this as a configuration option. See the other answers for details.


q:
In my C# source code I may have declared integers as:

int i = 5;

or

Int32 i = 5;

In the currently prevalent 32-bit world they are equivalent. However, as we move into a 64-bit world, am I correct in saying that the following will become the same?

int i = 5;
Int64 i = 5;

[A]
No. The C# specification rigidly defines that
```
int
```
is an alias for
```
System.Int32
```
with exactly 32 bits. Changing this would be a
major
breaking change.


q: I am building an ontology-processing tool and need lots of examples of various owl ontologies, as people are building and using them in the real world.  I'm not talking  about foundational ontologies such as Cyc, I'm talking about smaller, domain-specific ones.

[A]
There's no definitive collection afaik, but these links all have useful collections of OWL and RDFS ontologies:
schemaweb.info
vocab.org
owlseek
linking open data constellation
RDF schema registry
(rather old now)
In addition, there are some general-purpose RDF/RDFS/OWL search engines you may find helpful:
sindice
swoogle
Ian


q: What happens when the Office 2003 PIA prerequisite and launch condition in a Windows installer are run against an Office 2007 system?

[A]
I believe the 2003 PIA require Office 2003 be installed (so I'm guessing it would fail). AFAIK, the 2003 interops won't work with the 2007 applications. More information about these types of scenarios can be found
here
. So even if it did install (pretty easy to test) you might not have a working application.
Are you trying to get some 2003 Add-ins to work with Office 2007?


q: I just want to know the best way to emulate a C# style enumeration in Ruby.

[A]
I don't think Ruby supports true enums -- though, there are still solutions available.
Enumerations and Ruby


q:
There are lots of tools for creating installers on Windows (InstallShield, InnoSetup, NSIS, just to name a few). All tools I've seen fall in one or both of these categories

Point-and-click. Nice GUI for creating the installer, but the installer definition/project file can not be manually edited.

Textfile: No (official) GUI. The installer is compiled from a definition in a text-file which is manually edited.

The installers I'm building are all defined using a DSL (represented as YAML files), so using a GUI is out of the question, and creating is textfile is cumbersome although doable.

What I really would want is a tool which exposes a (complete) API, through which I can control the creation of the installer. Are there any such tools out there?

Edit: I'd love to hear about non-MSI based tools as well. MSI is not a requirement (rather the other way around...)

[A]
Wix 3.0 beta
has .NET support included for this purpose. I don't know how well it works but it includes documentation. It's a framework of types for manipulating the installation creation process and all that goodness, so I don't think you even need to write a line of WiX XML if you don't want to.


q:
How do you return values or structures from a Popup window in Powerbuilder 9.0? The CloseWithReturn is only valid for Response windows and thus is not available. When I set a value to the Message.PowerObjectParm, the value becomes null when the Popup window closes. I need to use a Popup window so the user can click back to the caller window and scroll through rows.

Program flow:
1) Window A OpenWithParm
2) Window B is now open
3) User interacts with both windows
3) User closes Window B
4) Window B needs to pass a structure back to window A

[A]
You won't be able to accomplish this the way you are thinking.  Since the window you are opening from the parent is not a Response window, the two aren't explicitly linked together.
But you could accomplish this by having a public instance variable in the parent window that is of the type of your custom structure.  Then from the child window before you close it, explicitly set the variable in the parent window via something like this:
```
```
w_my_parent_window_name.istr_my_structure = lstr_my_structure
```
```
This should only be done if there will only be one instance of w_my_parent_window_name instantiated.


q:
Consider the case of a simple news article web application that has a DB table column of "Status" that is accessible by a radio button set of:

Status - [x] Publish [ ] Draft [ ] Archive

...where "Publish" shows an article publicly and "Draft" and "Archive" do not.  Functionally "Draft" and "Archive" do the same thing but carry additional meta data meanings.  The two functional states of "show" and "hide" along with the meta data of "publish", "draft" and "archive" are intermixed in the same column of "status".

Is this a good practice?  While this is a very simple case, larger cases might reveal flaws with such a practice (or not...).

[A]
In this instance, I would say that this is the appropriate functionality.
We've all seen WTF's in the media where someone accidentally hit show[x]
and draft[x] at the same time.
The way it is now, it is impossible to accidentally show a draft.  This is important in newspapers as reporters are notorious for stuff like:
John Doe, of StackOverflow  said, "---I can't remember what that ugly f*cker said - Check the tape and fill in later"
Which probably shouldn't be printed.


q:
$array = explode(".", $row[copy]);
$a = $array.length -1;

I want to return the last element of this array but all i get from this is -1.

[A]
I think your second line should be more like:
```
```
$index = count($array) - 1;
$a = $array[$index];
```
```
If you want an element from an array you need to use square brackets.


q:
I've got an issue when accessing a web site, I can access it by using the NetBIOS name, but when accessing with the FQDN i get an error.

Any ideas on how to troubleshoot this?

(There is no DNS configured yet, we have modified the Hosts file to enter the related names and IP.)

[A]
Just to make sure, you have something like this
```
```
192.168.100.5 othermachine othermachine.mydomain.local
```
```
with both the netbios and the FQDN in it and not just the IP and netbios name?


q: Every time I try to create a new project or solution in visual studio (2005 and 2008), I get an error saying, "Project Creation failed."  I even tried running vs in administrative mode, but I still get the same answer. Anyone have any suggestions, in short of uninstalling all of VS and reinstalling it?

[A]
It sounds like an Add-in behaving badly.  Can you launch it in safe mode?
```
```
devenv.exe /SafeMode
```
```


q:
Vi and Vim allow for really awesome customization, typically stored inside a .vimrc file. Typical features for a programmer would be syntax highlighting, smart indenting and so on.

What other tricks for productive programming have you got, hidden in your .vimrc?

I am mostly interested in refactorings, auto classes and similar productivity macros, especially for C#.

[A]
This isn't in my .vimrc file, but yesterday I learned about the
```
]p
```
command. This pastes the contents of a buffer just like
```
p
```
does, but it automatically adjusts the indent to match the line the cursor is on! This is excellent for moving code around.


q:
The following snippet of C# code:

  int i = 1;
  string result = String.Format("{0},{1},{2}", i++, i++, i++);
  Console.WriteLine(result);

writes out: 1,2,3

Before I tried this in the compiler I was expecting the assignments to take place and then the evaluations, so my expected output was: 1,1,1

So my question is: Does this "pattern" (is it called a pattern?) of assign and then evaluate each parameter have a name?

EDIT: I'm referring to the pattern of evaluating and assigning the parameters to the String.Format() function. Not the incrementing of i.

(I may be incorrectly using the word evaluate in the question above because if the parameter was say (i + j) then we know that it would be evaluated before it was assigned. When using the word evaluate in that context I'm referring to the incrementing of i.)

[A]
The
order of evaluation
of arguments is strictly left-to-right in C#.  When you evaluate the expression
```
i++
```
, what happens is the value of
```
i
```
is calculated and pushed, then the value of
```
i
```
is incremented.
The ++ operator on System.Int32 is effectively a function with the special name
```
++
```
and the special syntax of calling it by writing a reference to a variable and then the characters ++.
So in effect, what you wrote is
```
```
// assume this function is defined:
int Inc(ref int i)
{
  var old = i;
  i = i + 1;
  return old;
}

...
int i = 1;
string result = String.Format("{0},{1},{2}", Inc(ref i), Inc(ref i), Inc(ref i));
Console.WriteLine(result);
...
```
```
Since arguments are evaluated left-to-right,
```
Inc(ref i)
```
is called 3 times, each time incrementing
```
i
```
after passing the current value of
```
i
```
to
```
String.Format(...)
```
.  This is exactly what happens in your code, as well.


q: How can I write from Java to the Windows Event Log?

[A]
Log4J is a Java-based logging utility.  The class
```
NTEventLogAppender
```
can be used to "append to the NT event log system". See the documentation here:
http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/nt/NTEventLogAppender.html
Edit:
There is a newer version,
Log4j 2
"that provides significant improvements over its predecessor."


q:
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves.

My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound like a good idea as the people I sell it to too could just make copies of them and pass them on.

I think for the purpose of this problem it would be safe to assume that everyone who buys this would be running the same (LAMP) setup.

[A]
The way I'd go about it is this:
Encrypt all of the code
Write an installer that contacts the server with the machine's hostname and license file and gets the decryption key, then decrypts the code and compiles it to python bytecode
Add (in the installer) a module that checks the machine's hostname and license file on import and dies if it doesn't match
This way the user only has to contact the server when the hostname changes and on first install, but you get a small layer of security.  You could change the hostname to something more complex, but there's really no need -- anyone that wants to pirate this will do so, but a simple mechanism like that will keep honest people honest.


q: Is there a way to enable STRICT_ALL_TABLES for a single MySQL database?

[A] Don't think you can do this directly but you might get close with setting Strict for the current session when working on a particular database. Could do this in the config files of specific users.


q: I've searched for the solution to change the background color on the Compact Framework's MainMenu control, and the only answer I've found is that you need to create a custom control.  Does anyone have example code for this?

[A]
There is no way of doing this.
Your right in that you'll probably need to create your own control.
This was something I was considering doing anyway to make the application go on Windows CE and Windows Mobile.
The problem with adding menus when the application needs to work with both is that the menu goes to the top of the screen on Windows CE and covers any controls that might be there.
It would be less hassle in the long run just make a new control.


q:
When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.

Do I use a variation of .ToString() for this?

[A]
```
```
decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m
```
```
or
```
```
decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m
```
```
or
```
```
decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m
```
```


q:
What is the best way to find out if a primary key with a certain value already exists in a table?

I can think of:

SELECT key FROM table WHERE key = 'value';

and count the results, or:

SELECT SQL_CALC_FOUND_ROWS key FROM table WHERE key = 'value' LIMIT 1;
SELECT FOUND_ROWS();

[A]
I think either of your suggestions in the question are suitable.
Depending on how you are using this though, you can potentially save time by doing an INSERT IGNORE, which allows you to insert a new row if the primary key doesn't exist. If it does exist, the error is ignored so you can continue as normal.
Other similar options depending on your usage include using the REPLACE or the INSERT ON DUPLICATE KEY UPDATE types of inserts. This allows you to update the existing entry if the primary key already exists, otherwise it just inserts your new entry.


q:
I'm looking at introducing multi-lingual support to a mature CGI application written in Perl.  I had originally considered rolling my own solution using a Perl hash (stored on disk) for translation files but then I came across a CPAN module which appears to do just what I want (i18n).

Does anyone have any experience with internationalization (specifically the i18n CPAN module) in Perl?  Is the i18n module the preferred method for multi-lingual support or should I reconsider a custom solution?

Thanks

[A]
There is a
Perl Journal article
on software localisation.  It will provide you with a good idea of what you can expect when adding multi-lingual support.  It's beautifully written and humourous.
Specifically, the article is written by the folks who wrote and maintain
```
Locale::Maketext
```
, so I would recommend that module simply based upon the amount of pain it is clear the authors have had to endure to make it work correctly.


q:
I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically.

I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers.

[A]
The usual approach, to raise a to the b, for an integer exponent, goes something like this:
```
```
result = 1
while b > 0
  if b is odd
    result *= a
    b -= 1
  b /= 2
  a = a * a
```
```
It is generally logarithmic in the size of the exponent.  The algorithm is based on the invariant "a^b*result = a0^b0", where a0 and b0 are the initial values of a and b.
For negative or non-integer exponents, logarithms and approximations and numerical analysis are needed.  The running time will depend on the algorithm used and what precision the library is tuned for.
Edit: Since there seems to be some interest, here's a version without the extra multiplication.
```
```
result = 1
while b > 0
  while b is even
    a = a * a
    b = b / 2
  result = result * a
  b = b - 1
```
```