q:
I just wrote a new web part and now I am getting this error when I try to deploy them on my non-dev servers:

the default namespace
  'http://schemas.microsoft.com/WebPart/v2'
  is a reserved namespace for base Web
  Part propertiees. Custom Web Part
  properties require a unique namespace
  (specified through an
  XmlElementAttribute on the property ,
  or an XmlRootAttribute on the class).

I am writing the web parts into CAB files and deploying them with this:

stsadm -o addwppack -filename web_part_name.CAB -url http://your_url_here -globalinstall -force

Everything works fine until I try to add the web part, then I get this error in a popup.  It works just fine on my dev VM...?

Any ideas would be appreciate, thank you.

[A]
A bit of a educated guess here but anyway :-
First check that you have XmlRoot attribute like this in your web part
```
```
[XmlRoot(Namespace = "Your.Namespace")]
public class YourWebPart: WebPart
{
...
```
```
and XmlElement attribute on your custom properties
```
```
[DefaultValue(0)]
    [WebPartStorage(Storage.Shared)]
    [Browsable(false)]
    [XmlElement(ElementName = "YourProperty")]
    public Int64 YourProperty
    {
       ...
    }
```
```
This error is happening when .NET is attempting to desterilize the data from the .DWP file and set the custom properties in your web part.
I suspect that the error may have nothing to do with namespace conflicts as SharePoint sometimes tends to fall back to an error messages that can be a red herring.
I would firstly examine your .dwp file. Do you have any custom properties set there, if so remove them and retest.
Comment out the custom properties in your web part code one by one and retest at each step.
I think you will find one of these is causing the problem - exactly why is the next question!


q:
There is this style of exception system where a component throws component-specific exception. For example, all data access classes throw DataAccessException.

In this style, I often find myself having to catch and rethrow the component specific exception, because called methods are delcared as throws Exception:

try {
    int foo = foo();
    if (foo != expectedValue) {
        throw new ComponentException("bad result from foo(): " + foo);
    }
    bar();
}
catch (ComponentException e) {
    throw e;
}
catch (Exception e) {
    throw new ComponentException(e);
}

Do you find yourself doing the same? Do you find it ugly?

This question is not about validity of this style, but something within the constraints of this style.

[A]
That is ugly as hell. There isn't much more to comment on that ugly style, I think. If you already have all the code to handle different issues using the cause, that'd work. It's just that using
```
```
try {
  componentCall();
} catch (ComponentException e) {
  Throwable t = e.getCause();
  //Handle each possible cause
}
```
```
is less maintainable and more confusing than the other way, and the main point is that I see no advantage to using it.
Given that you are restricted to using it, I'd at least try to avoid throwing the ComponentException both with and without a cause, that makes it more confusing than it needs to be, in your example I'd add a InvalidFooException and add it as a cause for the generic ComponentException.
```
```
try {
    int foo = foo();
    if (foo != expectedValue) {
        throw new InvalidFooException("bad result from foo(): " + foo);
    }
    bar();
}
catch (Exception e) {
    throw new ComponentException(e);
}
```
```
getCause()
is intended for
chains of exceptions
that are only causally instead of semantically related.
If you need them to differentiate between different exceptions (for instance, a SQLExecutionException should be corrected by a different action than an AccessDeniedException) then your method is not applicable (because forcing the use of getCause() in each catch to see what needs to be done is awful and offers no benefit than just catching the right exception out front).
If all the calling classes have to do is report an error and cancel, then the wrapping might be okay, but I wouldn't do it, as it adds little benefit and if you later need to differentiate will make you rewrite lots of stuff.
What is useful is to create a
hierarchy of exceptions
for exception of the same type, in the lines of:
If DataAccessException would be the root, then you could for example have DataSourceUnavailableException, InvalidDataSourceException, InvalidDataException and then you can decide to catch either parent only (if the action is the same) or to catch each exception separately.
Why do you need this to behave this way, by the way?

s: huggingface

c: devops

d: intermediate


q:
I am having an VB Script. I need to log the error information in a file. I need to log every information like error number error description and in which sub routine does the error occured.

Please provide some code

[A]
For error handling in VBScript is used "On Error" clausule.
There are 3 ways, how to handle errors:
On Error Resume Next '' ignore errors
On Error GoTo 0 '' removes error handlning
On Error GoTo HandleError '' on error will code jump to specified signal
Samples:
```
```
On Error Resume Next '' ignore errors
SomeIgnorableFunction()

On Error GoTo 0 '' removes error ignoring
SomeImportantFunction()

On Error GoTo HandleError '' on error will code jump to specified signal
Dim a
a = 15 / 0

GoTo Finish '' skips error handling

HandleError:
Dim msg
Set msg = Err.Description & vbCrLf & Err.Number
MsgBox msg

Finish:
'' there is end of sciprt
```
```


q: Any good logging libraries that support .NET compact framework?

[A]
log4net actually supports compact framework 1.0, will try it out!
Read more
here


q: I'm familiar with a handful of the free static analysis tools available for Java, such as FindBugs and PMD.  What I'd like to know is how the commercial products such as Klocwork and Coverity stack up against these.  What are their strengths and weaknesses?

[A]
here's a list of commercial analysis tools :
http://en.wikipedia.org/wiki/List_of_tools_for_static_code_analysis#Java_2
coverity has several tools :
http://www.coverity.com/html/coverity-readiness-manager-java.html
: this should be on par with findbugs and PMD but with better presentation
prevent :
http://www.coverity.com/html/prevent-for-java.html
: low FALSE POSITIVES.
thread analyzer :
http://www.coverity.com/html/coverity-thread-analyzer-java.html
: this is what is absent in most open source tools.


q:
I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried:

ofstream outFile("test.txt", std::ios::out | std::ios::binary);
wstring hello = L"hello";
outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t));
outFile.close();

Opening test.txt in for example Firefox with encoding set to UTF16 it will show as:

h�e�l�l�o�

Could anyone tell me why this happens?

EDIT:

Opening the file in a hex editor I get:

FF FE 68 00 00 00 65 00 00 00 6C 00 00 00 6C 00 00 00 6F 00 00 00

Looks like I get two extra bytes in between every character for some reason?

[A]
You should look at the output file in a hex editor such as
WinHex
so you can see the actual bits and bytes, to verify that the output is actually UTF-16.  Post it here and let us know the result.  That will tell us whether to blame Firefox or your C++ program.
But it looks to me like your C++ program works and Firefox is not interpreting your UTF-16 correctly.  UTF-16 calls for two bytes for every character.  But Firefox is printing twice as many characters as it should, so it is probably trying to interpret your string as UTF-8 or ASCII, which generally just have 1 byte per character.
When you say "Firefox with encoding set to UTF16" what do you mean?  I'm skeptical that that work work.


q:
I would like to develop a mobile application that is able to access all the features of the mobile device it runs on (camera, files, phone and network connectivity). I intend to build a series of applications that each have a specific function to perform, rather than a single application with a large feature set. My programming background is C, C# and web applications.

What would be the best tool set to use to do this? I have looked at using the NetBeansIDE to create a Java ME applications using LWUIT - this looks promising, but what are the caveat's?

I want to target the largest universe of mobile devices possible.

[A]
If your primary goal is to reach the
consumer market
, Java 2 Micro Edition (J2ME) is probably your best bet. All popular mobile phones (from Nokia, Sony Ericsson, Samsung) come with a Java Virtual Machine installed. If you look at Google, for example, they are developing all of their mobile applications (like Gmail and Google Maps) in Java.
If you instead are targeting
business customers
, the Microsoft .NET Compact Framework is the way to go in my opinion. The Windows Mobile operating system holds a strong position in the business market, mainly because of Outlook Mobile and its integration with Exchange.


q:
I have a touch screen kiosk that displays a webpage and a pdf document. Can I remove the menu bar? Users must not have "save", "print" and other such features.

Update

random screenshot on flickr - I am refering to the print, back/forward, zoom bar that controls the PDF -- not the browser menu. Sorry for not beeing specific.

[A]
Good discussion on using IE7 in Kiosk mode:
http://samanathon.com/internet-explorer-7s-kiosk-mode/
If Firefox is on option for you, see this plugin:
R-kiosk
Real Kiosk is a Firefox 2.0 - 3.0 extension that defaults to full screen, disables all menus, toolbars, key commands and right button menus. Alt+Home still takes you home


q:
we can use time in a unix environment to see how long something took...

shell> time some_random_command
real    0m0.709s
user    0m0.008s
sys     0m0.012s

is there an equivalent for recording memory usage of the process(es)?

in particular i'm interested in peak allocation.

[A]
Can you not use ps? e.g.
```
ps v <pid>
```
will return memory information.


q:
I'm looking for a good algorithm that can give me the unique edges from a set of polygon data. In this case, the polygons are defined by two arrays. One array is the number of points per polygon, and the other array is a list of vertex indices.

I have a version that is working, but performance gets slow when reaching over 500,000 polys. My version walks over each face and adds each edge's sorted vertices to an stl::set. My data set will be primarily triangle and quad polys, and most edges will be shared.

Is there a smarter algorithm for this?

[A]
Just to clarify, you want, for a polygon list like this:
```
```
A +-----+ B
   \    |\
    \ 1 | \
     \  |  \
      \ | 2 \
       \|    \
      C +-----+ D
```
```
Then instead of edges like this:
```
```
A - B -+
B - C  +- first polygon
C - A -+

B - D -+
D - C  +- second polygon
C - B -+
```
```
then you want to remove the duplicate B - C vs. C - B edge and share it?
What kind of performance problem are you seeing with your algorithm? I'd say a set that has a reasonable hash implementation should perform pretty ok. On the other hand, if your hash is not optimal for the data, you'll have lots of collisions which might affect performance badly.


q:
I know how to fill an std::vector with non-trivial initial values, e.g. sequence numbers:

void IndexArray( unsigned int length, std::vector<unsigned int>& v )
{
    v.resize(length);
    for ( unsigned int i = 0; i < length; ++i )
    {
        v[i] = i;
    }
}

But this is a for-loop. Is there an elegant way to do this with less lines of code using stl functionality (and not using Boost)?

[A]
You can use the generate algorithm, for a more general way of filling up containers:
```
```
#include <iostream>
#include <algorithm>
#include <vector>

struct c_unique {
   int current;
   c_unique() {current=0;}
   int operator()() {return ++current;}
} UniqueNumber;

int main () {
  vector<int> myvector (8);
  generate (myvector.begin(), myvector.end(), UniqueNumber);

  cout << "\nmyvector contains:";
  for (vector<int>::iterator it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;

  cout << endl;

  return 0;
}
```
```
This was shamelessly lifted and edited from
cplusplusreference
.


q:
I am using sql express 2008 and vs2008, writing in c#.

I have a db table with a Geography column in it, into which I need to put gps data I collected. When I tried creating an Entity-Framework mapping for this table, it just ignored the column with some warning about not being able to map such column types.
I then looked at nHibernate.Spatial project, but it seems like it only translates the Geometry types, not the Geography. No luck there.
I've been told I can use a view with casting the Geography to VarBinary, and then in the created entity class add another Property that deserializes the binary back into Geography. I guess that will work for reading the data from the db, but I also need to insert those rows into my db, and I can't add rows to the view.
Is there some other trick I can use in order to easily read and write Geography data from my db, in my c# code?

[A]
I don't know much about EF, but NHibernate allows you to extend it's type framework using
```
IUserType
```
. There's a bit about it on
Ray Houston's Blog
.
I've successfully used this to create a type for that uses XmlSerialization to an Xml field, based on
Ayende's example


q:
It doesn't look like basic javascript but nor can I use JQuery commands like $('myId'). Is this or similar functions documented anywhere?

For reason I don't want to go into, I am not able to use 3rd party libraries like JQuery but if some powerful javascript extensions come with asp then I would like to know about them.

[A]
$get is a function from the (now depreciated) ms ajax core javascript library. In the future they will be using jquery therefore $get will just be $('#myid') so I dont understand your feelings about not using jQuery, MS have decided to embrace OpenSource and bundle it with visual studio, check out Scott Gu and Hanslemans announcements on their blogs.
The ms ajax $get('foo') and jQuery $('#someID') are both just shortened wrappers around native javascript document.getElementById('bla')
ms ajax docs
http://www.asp.net/ajax/documentation/


q:
I am new to C and i have this question. why does the following code crash:

int *a = 10;
*a = 100;

[A]
You need to assign the pointer to a
memory location
, not arbitrary value (10).
```
```
int cell = 10;
int *a = &cell; // a points to address of cell
*a = 100;       // content of cell changed
```
```
See
my answer
to another question, about being careful with
C
.


q:
my question is similar to other friend posted here...we are trying to develop an application that supports possibly terabytes of information based on a land registry in Paraguay with images and normal data.

The problem is that we want to reduce the cost of operation to  minimum as possible because it´s like a competition between companies, and for that reason we want to use a free database....I have read a lot of information about it but I am still confused. We have to realize that the people who is gonna use it are government people so the DB has to be easy to manage at the same time.

What would u people recommend me?

Thanu very much

[A]
Postgresql
,
SQL Server 2008
and
Any recent version of Oracle
all have spatial indexing, table partitioning and BLOBs and are capable of acting as the back-end of a large geographic database.  You might also want to check out two open-source GIS applications:
GRASS
and
QGIS
, which might support doing what you want with less modification work than writing a bespoke application.  Both can use Postgresql and other database back-ends.
As for support, any commercial or open-source database is going to need the attentions of a competent DBA if you want to get it to work well on terabyte-size databases.  I don't think you will get away with a model of pure end-user support - attempts to do this are unlikely to work.


q:
There has been a lot of press about IPv6 and the impending switch over to IPv6 from IPv4.  I have some understanding of IPv6, but I've often wondered how much impact IPv6 has on application development & design (specifically)?

Are there some tangible/well known benefits IPv6 provides which we don't already have today?

I know Windows Vista and Server 2008 support IPv6 out-of-the-box, is anyone using (or designing with IPv6 in mind) today, and if so, what are the benefits?  Should we be considering IPv6 in current and future projects?

Are there any good examples of IPv6-aware applications?

[A]
Initially not much. The switch from IPv4 to v6 should be transparent for most desktop and web applications.
But eventually applications that use network models that are made easier by IPv6 will become more common. For example most users are behind a NAT so mesh-networks are only feasible for a technical audience. Anyone who has had to open ports on his router for P2P software knows this is not something his mom could use.
Streaming and broadcasting are also things that are made easier by IPv6.


q:
I am using Eclipse 3.3 ("Europa"). Periodically, Eclipse takes an inordinately long time (perhaps forever) to start up. The only thing I can see in the Eclipse log is:

    !ENTRY org.eclipse.core.resources 2 10035 2008-10-16 09:47:34.801
    !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

Googling reveals someone's suggestion that I remove the folder:

workspace\.metadata\.plugins\org.eclipse.core.resources\.root\.indexes

This does not appear to have helped.

Short of starting with a new workspace (something which I am not keen to do, as it takes me hours to set up all my projects again properly), is there a way to make Eclipse start up properly?

[A]
You can try to start
```
Eclipse
```
first with the
```
-clean
```
option.
On Windows you can add the
```
-clean
```
option to your shortcut for eclipse. On
```
Linux
```
you can simply add it when starting
```
Eclipse
```
from the command line.


q:
Is it less efficient to use TEXT than varchar in an SQL database?

If so why?

If not why would you not just always use TEXT?

I'm not targetting a specific database here but oracle is probably the most relevant, although I'm testing on MySQL for the time being as part of a proof of concept.

[A]
From Microsoft
here
ntext, text, and image data types will
  be removed in a future version of
  Microsoft SQL Server. Avoid using
  these data types in new development
  work, and plan to modify applications
  that currently use them. Use
  nvarchar(max), varchar(max), and
  varbinary(max) instead.
When you use
```
varchar(max)
```
over text you can use it in the
```
WHERE
```
clause, because they work the same as their smaller counterparts,
```
varchar,nvarchar and varbinary
```
. Below is a small list of what should be used as opposed what was to be used:
Use varchar(max) instead of text
Use nvarchar(max) instead of ntext
Use varbinary(max) instead of image


q:
I've a dialog which contains a Qt TabWidget with a number of tabs added.

I'd like to hide one of the tabs.

_mytab->hide()

doesn't work.  I don't want to just delete the tab and all its widgets from the .ui file because other code relies on the widgets within the tab.  However, it would be fine to generate the tab code but somehow not ::insertTab in the generated uic_mydialog.cpp.  Setting the hidden property in the ui file does not work either.

I'm using Qt 3.3

[A]
I would use QTabDialog::removePage(QWidget* pTabPage) which does not delete pTabPage, which is what you want.
```
```
_myTabDlg->removePage(_mytab);
```
```
I'm using it and it works fine !


q:
I want this method to work for any given number of arguments, i can do that with code generation(with a lot of ugly code), can it be done with recursion? if so how? I understand recursion, but i dont know how to write this.

private static void allCombinations(List<String>... lists) {
    if (lists.length == 3) {
        for (String s3 : lists[0]) {
            for (String s1 : lists[1]) {
                for (String s2 : lists[2]) {
                    System.out.println(s1 + "-" + s2 + "-" + s3);
                }
            }
        }
    }
    if (lists.length == 2) {
        for (String s3 : lists[0]) {
            for (String s1 : lists[1]) {
                    System.out.println(s1 + "-" + s3);
            }
        }
    }
}

[A]
Do you particularly need it to be recursive? I'd make it non-recursive but still not special case things:
```
```
public static void allCombinations(List<String>... lists) {
    int[] indexes = new int[lists.length];

    while (incrementIndexes(lists, indexes)) {
        StringBuilder builder = new StringBuilder();
        for (int i=0; i < indexes.length; i++) {
            if (i != 0) {
                builder.append("-");
            }
            builder.append(lists[i].get(indexes[i]));
        }
        System.out.println(builder);
    }
}

private static boolean incrementIndexes(List<String>[] lists, int[] indexes) {
    for (int depth = indexes.length-1; depth >= 0; depth--) {
        indexes[depth]++;
        if (indexes[depth] != lists[depth].size()) {
            return true;
        }
        // Overflowed this index. Reset to 0 and backtrack
        indexes[depth] = 0;
    }
    // Everything is back to 0. Finished!
    return false;
}
```
```


q:
I have a database that contains a table that looks a bit like this:

PropertyId, EntityId, Value

PropertyId and EntityId are a combined primary key. Every Entity is spread over a couple of rows where every row contains a single property of the entity. I have no control over this database so I'll have to work with it.

Is it possible to use NHibernate to map entities from this table to single objects? I only have to read from this table, this might make things a bit easier. Or would I be better off just using DataReaders and do the mapping myself?

[A]
Not quite done that, but you could use a custom SQL query to define your entities (distinct entityid, plus any entity level attributes), see
here
.
Although I can see you might want the property/values mapped to attributes of the entity object.  Which might mean further queries to populate them by hand - which may mean your data reader route is best.
If your happy for them to be a collection of the entity then that should be no problem.


q: I have a databound DataGridView. When a new row is added and the user presses Esc I want to delete the entire row. How can I do this?

[A]
quite easy actually
```
```
private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)27)
    {
        if (dataGridView1.Rows.Count > 0)
        {
            dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
            MessageBox.Show("Last row deleted!");
        }
        e.Handled = true;
    }
}
```
```
but take in mind that:
Rows cannot be programmatically removed unless the DataGridView is data-bound to an IBindingList that supports change notification and allows deletion


q:
In the course of my career I've noticed that developers working on new functionality are, as a rule, more cheerful than these assigned to troubleshooting and fixing bugs.

Good tips on keeping business support a happy? Organising business support in the way that team's morale isn’t hurt?

[A]
I have seen this too.
There are few approaches that I can think of:
1. Give some thought to selection process.
Not everyone have same career aspirations. While some people are always dying to work for the latest technology and challenging projects, there are others who are content at a stable work environment. Picking the person with right KSA (Knowledge, Skills, Attitude) is always central to good person-job match. In this case, you just need to put more stress on the Attitude part.
2. Choose the right lead
Team leads play crucial role in controlling the motivation and morale of the team. There must be an open and frank channel of communication with team lead and upper management. Ideally a person from the senior management should be made the owner of the team in formal organization chart. Team lead should actively try to foster a team-culture that suites the nature of the team.
3. Rewards
Rewards off course are key tool for managing motivational issues. Just make sure the person receiving the rewards understand that the nature of job was also taken into consideration in decision to reward. If this point is not addressed, it is likely that the person will not take this factor into account when perceiving internal equity.


q: I'm not sure what the best api for simple 2d graphics with Java is. I know java.awt.Graphics2D was the standard but has it been replaced? Swing is the new API for Java GUI apps but it seems a bit heavy for what I want. What I really want is something like the C SDL library.

[A]
Java 2D
(
```
Graphics2D
```
and friends) is indeed the best choice that I know of. Swing is actually implemented on top of Java 2D, so yes, if you want non-GUI-type graphics, Java 2D is the way to go.


q:
I was wondering if anybody could point me towards a free ftps module for python.

I am a complete newbie to python, but this is something I need for a work project. I need an ftps client to connect to a 3rd party ftps server.

thanks,

David.

[A]
I haven't tried it myself (yes, I just used Google and followed some links), but
http://www.lag.net/paramiko/
seems to be the recommended solution. From a cursory glance, it's an SSH implementation in pure Python, which allows tunneling for things like FTP.
Update: a commenter pointed out that I mixed up sftp and ftps, sorry. I still suggest at least investigating Paramiko briefly to see if it matches the requirements.


q: How do I get a platform-dependent newline in Java? I can’t use "\n" everywhere.

[A]
You can use
```
```
System.getProperty("line.separator");
```
```
to get the line separator


q:
I have a large query in a PostgreSQL database.
The Query is something like this:

SELECT * FROM table1, table2, ... WHERE table1.id = table2.id...

When I run this query as a sql query, the it returns the wanted row.

But when I tries to use the same query to create a view, it returns an error:

"error: column "id" specified more than once."

(I use pgAdminIII when executing the queries.)

I'll guess this happens because the resultset will have more than one column named "id". Is there someway to solve this, without writing all the column names in the query?

[A]
That happens because a view would have two id named columns, one from table1 and one from table2, because of the select *.
You need to specify which id you want in the view.
```
```
SELECT table1.id, column2, column3, ... FROM table1, table2
WHERE table1.id = table2.id
```
```
The query works because it can have equally named columns...
```
```
postgres=# select 1 as a, 2 as a;
 a | a
---+---
 1 | 2
(1 row)

postgres=# create view foobar as select 1 as a, 2 as a;
ERROR:  column "a" duplicated
postgres=# create view foobar as select 1 as a, 2 as b;
CREATE VIEW
```
```


q:
In our administration team everyone has root passwords for all client servers.
But what should we do if one of the team members is not longer working with us?
He still has our passwords and we have to change them all, every time someone leave us.

Now we are using ssh keys instead of passwords, but this is not helpful if we have to use something other than ssh.

[A]
The systems I run have a
sudo
-only policy. i.e., the root password is
```
*
```
(disabled), and people have to use sudo to get root access. You can then edit your
```
sudoers
```
file to grant/revoke people's access. It's very granular, and has lots of configurability---but has sensible defaults, so it won't take you long to set up.


q:
Say I create an object thus:

var myObject =
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};

What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:

keys == ["ircEvent", "method", "regex"]

[A]
In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in
Object.keys
method:
```
```
var keys = Object.keys(myObject);
```
```
The above has a full polyfill but a simplified version is:
```
```
var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}
```
```
Alternatively replace
```
var getKeys
```
with
```
Object.prototype.keys
```
to allow you to call
```
.keys()
```
on any object.  Extending the prototype has some side effects and I wouldn't recommend doing it.


q:
I'm looking for a way to selectively apply a CSS class to individual rows in a GridView based upon a property of the data bound item.

e.g.:

GridView's data source is a generic list of SummaryItems and SummaryItem has a property ShouldHighlight. When ShouldHighlight == true the CSS for the associated row should be set to highlighted

any ideas?

[A]
very easy
```
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView drv = e.Row.DataItem as DataRowView;
        if (drv["ShouldHighlight"].ToString().ToLower() == "true")
            e.Row.CssClass = "highlighted";
    }
}
```
```
the code above works if you use a
DataTable as DataSource
change to:
```
```
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        myClass drv = (myClass)e.Row.DataItem;
        if (drv.ShouldHighlight)
            e.Row.CssClass = "highlighted";
    }
}
```
```
just for the example above when using generics:
```
```
public class myClass
{
    public Boolean ShouldHighlight
    { get; set; }
}
```
```
if you are working with
Generics
(List, Dictionary, etc)
keep in mind:
```
```
e.Row.dataItem
```
```
always return the entire object that you are populating the row with, so it is easy from here to manipulate the appearance of the data in the webpage.
you should use RowDataBound event that will trigger after the data is attached to the row object but not yet written the HTML code in the page, in this way you can check the ShouldHighlight value (I converted to a String cause I do not know the type, you can change it if you know it's a boolean value).
this code runs much faster than megakemp code cause you're not creating a List object and populated with the entire data source for each row...
P.S. take a
look at this website
, you can find several tutorials for your project using the GridView object


q:
I want to develop a website in ASP classic that uses HTTP Authentication against a database or password list that is under the control of the script. Ideally, the solution should involve no components or IIS settings as the script should be runnable in a hosted environment.

Any clues/code deeply appreciated.

[A]
Hi are you trying to get a list of users from a database or use network based permissions on the HTTP server?
If you are using a database use ODBC and DSN
```
```
Dim DatabaseObject1
Set DatabaseObject1 = Server.CreateObject("ADODB.Connection")
DatabaseObject1.Open("DSN=DSNname;")
```
```
If you are wanting a password dialogue box (from the server), you will need to alter IIS settings for a good guide to this..
http://www.authenticationtutorial.com/tutorial/


q:
If i can use

<td><textarea><bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/>
</textarea></td>

to displace a value how can i use the struts tags to save a vaiable to the sesssion

in sudo code

session.setAttribute("test" , "<bean:write name="smlMoverDetailForm"
property="empFDJoiningDate"/>");

is this possible?

[A]
I don't think so.
Struts tags are only available in jsp pages.
But you can do something like this:
if the bean smlMoverDetailForm is in scope request
```
```
session.setAttribute("test",((THECLASSOFTHEBEAN)request.getAttribute("smlMoverDetailForm")).getEmpFDJoiningDate());
```
```
else if the bean smlMoverDetailForm is in scope session
```
```
session.setAttribute("test",((THECLASSOFTHEBEAN)request.getSession().getAttribute("smlMoverDetailForm")).getEmpFDJoiningDate());
```
```


q:
In Visual Studio 2008 (and others) when creating a .NET or silverlight application if you look at your project properties, it seems like you can only have one assembly name - across all configurations. I would like to compile my application as:

MyAppDebug - in debug mode
and just
MyApp - in release mode

Does anyone know if this is possible?

Edit:

It seems some people are questioning the reasoning behind the question, so I'll explain a little further:

I'm working on a Silverlight application which gets automatically uploaded to our test site when I to a "build solution". The trouble is, the test team are now testing the online version, whilst I work on a new one. So, I want to have a url like .\MyApp.html for the regular version that the QA team will test and then .\MyApp.html?version=debug for the current version that I'm working on.

[A]
Sure you can add a post-build event to rename the assembly. This will work if your solution has only one assembly.
But if your solution consists of several projects, you normally have one project referencing the assembly generated by another problem. Imagine your solution has has two projets: the first one creates a Windows Forms exe (MyApp.EXE), which references the assembly created by the second project (MyData.DLL).
In this example the debug EXE would be named MyAppDebug.EXE, and it needs to reference MyDataDebug.EXE. And this will not work with renaming in a post-build event.
Therefore I strongly recommend not to do any renaming.


q:
Apache/2.2.6 (Unix) DAV/2 mod_python/3.2.8 Python/2.4.4 configured ...

One of apache processes spawns some long-running python script asynchronously, and apparently doesn't seem to collect its child process table entry. After that long-run-in-subprocess python script finishes - defunct python process has been left.

# ps -ef | grep httpd
root     23911     1  0 Oct15 ?        00:00:01 /usr/sbin/httpd
...
qa       23920 23911  0 Oct15 ?        00:00:00 /usr/sbin/httpd

# ps -ef | grep python
...
qa       28449 23920  0 12:38 ?        00:00:00 [python] <defunct>

What is the way to make the Apache process to collect its children? Is it possible to do the job via a mod_python request handler ( like PythonCleanupHandler for example)?

Thanks.


q:
I am using Spring Forms for my web application. For nested properties, the form tag generates the input elements having id / name in form of .

For example, Person is the command class and Address is contained into its address field then the city element would be,

<input type="text" id="address**.**city" name="address**.**city" />

now, the problem is whenever I try to get its value using jQuery,

$("#address.city").val();

jQuery fails to select any appropriate element !

Please let me know any solution.

Thanks in advance.

[A]
Try this:
```
```
$("#address\\.city").val();
```
```
From
the documentation
:
Note: if you wish to use any of the meta-characters described above as a literal part of a name, you must escape the character with two backslashes (
```
\
```
). For example:
```
```
#foo\\:bar
#foo\\[bar\\]
#foo\\.bar
```
```


q:
Given an object:

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

How do I remove the property regex to end up with the following myObject?

let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI"
};

[A]
To remove a property from an object (mutating the object), you can do it like this:
```
```
delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];
```
```
Demo
```
```
var myObject = {
    "ircEvent": "PRIVMSG",
    "method": "newURI",
    "regex": "^http://.*"
};
delete myObject.regex;

console.log(myObject);
```
```
For anyone interested in reading more about it, Stack Overflow user
kangax
has written an incredibly in-depth blog post about the
```
delete
```
statement on their blog,
Understanding delete
. It is highly recommended.
If you'd like a
new
object with all the keys of the original except some, you could use
destructuring
.
Demo
```
```
let myObject = {
  "ircEvent": "PRIVMSG",
  "method": "newURI",
  "regex": "^http://.*"
};

// assign the key regex to the variable _ indicating it will be unused
const {regex: _, ...newObj} = myObject;

console.log(newObj);   // has no 'regex' key
console.log(myObject); // remains unchanged
```
```


q: I want to write a program for this: In a folder I have n number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for n number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.

[A]
```
```
import sys

# argv is your commandline arguments, argv[0] is your program name, so skip it
for n in sys.argv[1:]:
    print(n) #print out the filename we are currently processing
    input = open(n, "r")
    output = open(n + ".out", "w")
    # do some processing
    input.close()
    output.close()
```
```
Then call it like:
```
./foo.py bar.txt baz.txt
```


q:
We've currently got four web servers in a farm generating IIS web logs about 100Mb per day. These can be compressed pretty effieciently down to somewhere around 5% of their size.

We are planning to use waRmZip to move them off the servers and onto a SAN. After a week or so we can be confident we don't have any technical issues to investigate so the only other thing would be using them for trend analysis as a compliment to Google Analytics.

What retention periods do people recommend? Are there any legal requirements to keep this data?

[A]
Legal requirements will depend on your country, how much you're logging, and quite possibly the nature of your business. Talk to your company's lawyers - legal advice on SO is likely to be worth what you pay for it.
If you're only storing 5MB per day, you should be able to store them for basically as long as you want without worrying on the
technical
front.


q:
By default the SQL Server comes with the Langauge set to "English (United States)", setting the date format to mm/dd/yy instead of the date format I want it in, which is Australian and has a date format such as dd/mm/yy.

Is there an option in the Server Management Studio / Configuration tools where I can set the locale of the SQL Server, which will prevent the DateTime fields from being formatted in US date format?

If not, how can I convert it when I am using a SQL query such as (forgive me if there is incorrect syntax, I made it up on the spot):

Dim dc As New SqlCommand("INSERT INTO hello VALUES (@Date)", cn)
dc.Parameters.Add(New SqlParameter("Date", System.DateTime.Now))

Many thanks in advance. :)

[A]
have no idea what is the format in "down under"
dd/mm/yyyy hh:mm:ss ?
if yes, that date is the British/French annotation, so all you need to do is:
```
```
INSERT INTO hello VALUES convert(datetime, @Date + ' 00:00:00', 103)
```
```
or
```
```
INSERT INTO hello VALUES convert(datetime, @Date, 103)
```
```
if you actually place the time
for more info,
check Books online on MSDN
to get the correct Code number.
even in Selects I always use this, no matter what's in SQL (cause I tend to use Hosting SQL and there I can't change the formats), like:
```
```
SELECT myColumn FROM myTable WHERE myDateField >= convert(datetime, @Date + '00:00:00', 103)
```
```
hope it helps


q:
I have my J2EE application deployed into a JBossAS. My Application has to respond to two different hostnames (https://foo.com/myApp and https://bar.com/myApp). It is the same instance of the app serving those two hostnames.

But I don't know how to configure the keystores. I need different keystores for each hostname. Is there a way to tie a virtual host in JBoss' server.xml to a specific connector?

Or do I have to use two different IP-addresses and create a connector for each?

A solution that does not require a second IP-address would be greatly appreciated.

[A]
With SSL you have to use two different I.P. addresses if you wish to use different SSL certificates. This isn't a shortcoming in Tomcat/JBoss, it is just the reality of the protocol.
I can't remember the technical reason off the top of my head (Google knows), but it comes down to the server not being able to read the domain name until it has decoded the incoming SSL request.
To use two different keystores you will need to define two different connectors (using different I.P. addresses or ports) in the jbossweb-tomcat55.sar/server.xml file. This will get your SSL certificates working, but if you only have one I.P. your second certificate will need to be setup on a non-standard port.


q:
I'm writing an app in C# (.net 3.5) and I have a question about class design:

I'd like to create a class which accesses a file (read, write) and provides its content to the users (instanciators) of the class. The most common operation on an instance will be to retrieve a certain value from the file. The actual read and write (io) operations are faily expensive so I'd like to keep the file data in memory and let all instances access this data. The class is located in an assembly that is used from various applications simultaniously, so I guess I should be worrying about thread safety.

How do I design this with respect to thread-safety and unit-testability (for unit-tests, different inputfiles must be used than in operational code)? Any help is greatly appreciated.

[A]
Firstly, make your class implement an appropriate interface. That way, clients can test their behaviour without needing real files at all.
Testing the thread safety is hard - I've never seen anything which is really useful on that front, though that's not to say the tools aren't out there.
For unit testing your class, I'd suggest that if possible it should work with a general stream rather than just a file. Then you can embed different test files in your test assembly, and refer to them with
GetManifestResourceStream
. I've done this several times in the past, with great success.


q:
I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A.

So

DataTable dt = new DataTable()
dt = dataset.Table["A"]

Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7.

Let's say I only want to get columns a3 and a4 then bind it to my datagrid.

How do I do this?

[A]
Ignore the fact that you have more data than you need. Set
```
AutoGenerateColumns
```
to
```
false
```
. Create
```
BoundColumns
```
for
```
a3
```
and
```
a4
```
.


q: In db2 a query with a 'with ur' clause allows the query to be an uncommitted read and so does the 'with nolock' clause in mysql. Is there such an option in oracle too... If not why??

[A]
Tom provides a great answer to this:
On Transaction Isolation Levels
He says:
The READ UNCOMMITTED
  isolation level allows dirty reads.
  Oracle Database doesn't use dirty
  reads, nor does it even allow them.
  The basic goal of a READ UNCOMMITTED
  isolation level is to provide a
  standards-based definition that allows
  for nonblocking reads.
...
Now, a database that allowed a dirty
  read ... not only does it return the
  wrong answer, but also it returns ... [an answer] ... that never existed in the table.
  In a multiuser database, a dirty read
  can be a dangerous feature.
  Personally, I've never seen the
  usefulness of it...
The point here is that dirty read is
  not a feature; rather, it's a
  liability. In Oracle Database, it's
  just not needed. You get all of the
  advantages of a dirty read—no
  blocking—without any of the incorrect
  results.


q: I've created a jQuery wee plugin for myself which takes care of showing, hiding and submitting a form to give in-place editing. Currently I have several of these on a page which function independently and I am happy. However, I'm thinking that an 'Edit All' might be useful. I'd therefore want to be able to access all instances of the plugin within the page and access their show/hide/validate/submit functions in unison. Is there a way to do this?

[A]
Hmmm I guess I could create an array of instances...
```
```
var plugins = new Array();

plugins.push($('first_editable_section').pluginThing());
plugins.push($('second_editable_section').pluginThing());
```
```
and access them through that.


q: i know that i can get stacktrace by using Thread.getAllStackTraces()(it returns Map, but clear does not work). When I run recursion method i can get exception because of stacktrace being too big, is there any way to clear it?

[A] It's not the stack trace that is causing your problem, it's the stack itself.  Every time you call a method, information gets put on the stack that allows you to return to the calling method.  If you recurse enough, eventually you fill all the space on the stack (which is bound by a maximum size) and your program stops.  The stack trace simply shows you your history of calls.  You probably have an infinite recursion going on and need to find a way to stop it before your program fails.  Either there is an error in your algorithm or you need to find a way to solve it differently within the bounds of the memory available to you.


q:
How can I tell if an App is ASP.NET 2.0 or ASP.NET 1.1. This is in C#

I don't have the source code and I  don't have access to IIS Manager. But I can ftp and check the ASPX files. Any Ideas?

[A]
if you can get an error message to show it will tell you at the bottom of the page what version of the framework is in use.
or, if you could upload a file, you could upload an aspx page containing code to output the framework version:
```
```
<%@ Page Language="C#" EnableSessionState="False" EnableViewState="False" Trace="False" Debug="False" %>

<script language="C#" runat="server">

protected void Page_Load(object s, EventArgs e)
{
    Response.Write(System.Environment.Version);
}
</script>
```
```
this was just typed in, there could be syntax or other code errors.


q:
I took a wsp file, and did my stsadm -o addsolution like usual.  Then I went into central administration->solution management and it showed up just fine.  Then I deployed the web part, no problems so far.

The problem is when I go to add it to the webpart gallery (Web Part Gallery: New Web Parts) usually the web part is in the list, I check the box next to it and click populate gallery but it is not showing up in the list?  Could I be missing something in my manifest.xml to cause this?  I just wrote and deployed another web part this exact same way and it went fine.  Also, I wrote a dummy webpart that does nothing but print "working" and tried it with that getting the same results.

Any ideas?

[A]
I had sometime same behaviour. Finally we wrote a cmd-tool, which run "stsadm - o addsolution" and then add to web part gallery all xml files for web parts.
There is source ( little-bit edited ):
```
```
string cmd_StsAdm = @"C:\Program files\Common files\Microsoft Shared\web server extensions\12\BIN\stsadm.exe";
string url_Site = "http://localhost";
string url_Web = "http://localhost";
if ( string.IsNullOrEmpty( url_Web ) ) { url_Web = url_Web; }

Console.WriteLine( "Deleting sharepoint solution" );
string args_DeleteSolution = string.Format( "-o deletesolution -name \"{0}\" -override", startInfo.fileNameWsp );
ShellWait( cmd_StsAdm, args_DeleteSolution );

string filePathWsp = "**** path to wsp file ****";
Console.WriteLine( "Adding sharepoint solution" );
string args_AddSolution = string.Format( "-o addsolution -filename \"{0}\"", filePathWsp );
ShellWait( cmd_StsAdm, args_AddSolution );

Console.WriteLine( "Deploy sharepoint solution" );
string args_DeploySolution = "-o deploysolution -name \"{0}\" -local -allowGacDeployment -url \"{1}\" -force";
args_DeploySolution = string.Format( args_DeploySolution, startInfo.fileNameWsp, url_Web );
ShellWait( cmd_StsAdm, args_DeploySolution );

int counter = 0;
foreach ( CWebPartVytvoreniInfo wpRslt in solutionInfo.WebParts ) {
    counter++;
    string msg = string.Format( "Aktivace web part {0} - {1} z {2}", wpRslt.Info.Nazev, counter, solutionInfo.WebParts.Count );
    Console.WriteLine( msg );
    string args_ActivateFeature = "-o activatefeature -id {0} -url {1}";
    args_ActivateFeature = string.Format( args_ActivateFeature, wpRslt.Info.ID, url_Site );
    ShellWait( cmd_StsAdm, args_ActivateFeature );
}

Console.WriteLine( "Connecting to sharepoint site" );
using ( Microsoft.SharePoint.SPSite site = new Microsoft.SharePoint.SPSite( url_Site ) ) {
    Microsoft.SharePoint.SPList ctg_WebParts = site.GetCatalog( Microsoft.SharePoint.SPListTemplateType.WebPartCatalog );

    counter = 0;
    foreach ( WebPartInfo wpInfo in solutionInfo.WebParts ) {
        counter++;
        string dirPath = System.IO.Path.Combine( wpInfo.DirectoryPath );
        string fileName = wpRslt.Info.Nazev + ".webpart";
        string filePath = System.IO.Path.Combine( dirPath, fileName );

        string msg = string.Format( "Uploading file '{0}' - {1} z {2}", fileName, counter, solutionInfo.WebParts.Count );
        Console.WriteLine( msg );
        using ( System.IO.FileStream fstrm = OtevritSoubor( filePath ) ) {
            ctg_WebParts.RootFolder.Files.Add( fileName, fstrm, true );
        }
    }
}
```
```


q: How can I set the font used by the FLVPlaybackCaptioning component for subtitles?  Using the style property of the textarea does nothing, and using a TextFormat makes the text go blank, even though the font had been embedded.

[A]
It seems the font, as well as the other properties of the text, are specified in the XML file where the subtitles are read (this is from the
documentation
):
```
```
<?xml version="1.0" encoding="UTF-8"?>
  <tt xml:lang="en" xmlns="http://www.w3.org/2006/04/ttaf1"  xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling">

          <styling>


q: What is the difference between anonymous methods of C# 2.0 and lambda expressions of C# 3.0.?

[A]
The MSDN page on anonymous methods explains it
In versions of C# before 2.0, the only
  way to declare a delegate was to use
  named methods. C# 2.0 introduced
  anonymous methods and in C# 3.0 and
  later, lambda expressions supersede
  anonymous methods as the preferred way
  to write inline code. However, the
  information about anonymous methods in
  this topic also applies to lambda
  expressions. There is one case in
  which an anonymous method provides
  functionality not found in lambda
  expressions. Anonymous methods enable
  you to omit the parameter list, and
  this means that an anonymous method
  can be converted to delegates with a
  variety of signatures. This is not
  possible with lambda expressions. For
  more information specifically about
  lambda expressions, see Lambda
  Expressions (C# Programming Guide).
And regarding lambda expressions
:
A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
  All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:


q:
Is it possible to expose an API in a .NET application by embedding a scripting language like IronPython?

How is it done?

[A]
I haven't used it personally, but you should look at
Visual Studio Tools for Applications
I'm not sure if Iron Python is supported as a language for it or not, but that would be the easiest path to enable your application to be programmable.


q:
Are C# enums typesafe?

If not what are the implications?

[A]
Yes they are.
The following is from
http://www.csharp-station.com/Tutorials/Lesson17.aspx
Enums are strongly typed constants. They are essentially unique types that allow you to assign symbolic names to integral values. In the C# tradition, they are strongly typed, meaning that an enum of one type may not be implicitly assigned to an enum of another type even though the underlying value of their members are the same. Along the same lines, integral types and enums are not implicitly interchangable. All assignments between different enum types and integral types require an explicit cast.


q:
How can I have a view render a partial (user control) from a different folder?
With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to preview 5 this is not possible anymore.
Instead we got the RenderPartial method, but it's not offering me the functionality I'm looking for.

[A]
Just include the path to the view, with the file extension.
Razor:
```
```
@Html.Partial("~/Views/AnotherFolder/Messages.cshtml", ViewData.Model.Successes)
```
```
ASP.NET engine:
```
```
<% Html.RenderPartial("~/Views/AnotherFolder/Messages.ascx", ViewData.Model.Successes); %>
```
```
If that isn't your issue, could you please include your code that used to work with the RenderUserControl?


q:
When I plug my HP Laserjet 3015, Windows detects the correct model and then tries to install the appropriate drivers.

How can I detect the model of connected printer(s)? I don't want to use the list of installed printers because a Zebra printer can be installed with a Generic/Text only driver.

I'm a Delphi and C# programmer, so any tips in any language will be appreciated.

[A]
Recently I made a little demo with this. Just put a
```
TComboBox
```
and a
```
TMemo
```
on a Form and replace the code with this:
```
```
unit Unit1;

interface

uses
  Windows, StdCtrls, Classes, Controls, Forms;

type
  TForm1 = class(TForm)
    ComboBox1: TComboBox;
    Memo1: TMemo;
    procedure ComboBox1Change(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses
  Printers, WinSpool, SysUtils;

type
  _DRIVER_INFO_6A = record
    cVersion: DWORD;
    pName: PAnsiChar;
    pEnvironment: PAnsiChar;
    pDriverPath: PAnsiChar;
    pDataFile: PAnsiChar;
    pConfigFile: PAnsiChar;
    pHelpFile: PAnsiChar;
    pDependentFiles: PAnsiChar;
    pMonitorName: PAnsiChar;
    pDefaultDataType: PAnsiChar;
    pszzPreviousNames: PAnsiChar;
    ftDriverDate: TFileTime;
    dwlDriverVersion: Int64;
    pszMfgName: PAnsiChar;
    pszOEMUrl: PAnsiChar;
    pszHardwareID: PAnsiChar;
    pszProvider: PAnsiChar;
  end;
  TDriverInfo6A = _DRIVER_INFO_6A;
  PDriverInfo6A = ^TDriverInfo6A;
  PDriverInfo6 = PDriverInfo6A;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ComboBox1.Items.Assign(Printer.Printers);
  ComboBox1.ItemIndex := 0;
  ComboBox1Change(nil);
end;

function FileTimeToDateTime(ft: TFileTime): TDateTime;
var
  st: TSystemTime;
  lt: TFileTime;
begin
  FillChar(st, SizeOf(st), 0);
  FillChar(lt, SizeOf(lt), 0);
  FileTimeToLocalFileTime(ft, lt);
  FileTimeToSystemTime(lt, st);
  result := SystemTimeToDateTime(st);
end;

procedure TForm1.ComboBox1Change(Sender: TObject);
var
  hPrinter: THandle;
  PrtName: String;
  DriverInfo: PDriverInfo6;
  dwNeeded: DWORD;
begin
  Memo1.Clear;
  PrtName := Combobox1.Text;
  OpenPrinter(PChar(PrtName), hPrinter, nil);
  DriverInfo := nil;
  try
    GetPrinterDriver(hPrinter, nil, 6, DriverInfo, 0, dwNeeded);
    GetMem(DriverInfo, dwNeeded);
    try
      if GetPrinterDriver(hPrinter, nil, 6, DriverInfo, dwNeeded, dwNeeded) then begin
        Memo1.Lines.Add('cVersion: ' + IntToStr(DriverInfo.cVersion));
        Memo1.Lines.Add('pName: '+StrPas(DriverInfo.pName));
        Memo1.Lines.Add('pEnvironment: '+StrPas(DriverInfo.pEnvironment));
        Memo1.Lines.Add('pDriverPath: '+StrPas(DriverInfo.pDriverPath));
        Memo1.Lines.Add('pDataFile: '+StrPas(DriverInfo.pDataFile));
        Memo1.Lines.Add('pConfigFile: '+StrPas(DriverInfo.pConfigFile));
        Memo1.Lines.Add('pHelpFile: '+StrPas(DriverInfo.pHelpFile));
        Memo1.Lines.Add('pDependentFiles: '+StrPas(DriverInfo.pDependentFiles));
        Memo1.Lines.Add('pMonitorName: '+StrPas(DriverInfo.pMonitorName));
        Memo1.Lines.Add('pDefaultDataType: '+StrPas(DriverInfo.pDefaultDataType));
        Memo1.Lines.Add('pszzPreviousNames: '+StrPas(DriverInfo.pszzPreviousNames));
        Memo1.Lines.Add('ftDriverDate: '+DateTimeToStr(FileTimeToDateTime(DriverInfo.ftDriverDate)));
        Memo1.Lines.Add('dwlDriverVersion: '+IntToStr(DriverInfo.dwlDriverVersion));
        Memo1.Lines.Add('pszMfgName: '+StrPas(DriverInfo.pszMfgName));
        Memo1.Lines.Add('pszOEMUrl: '+StrPas(DriverInfo.pszOEMUrl));
        Memo1.Lines.Add('pszHardwareID: '+StrPas(DriverInfo.pszHardwareID));
        Memo1.Lines.Add('pszProvider: '+StrPas(DriverInfo.pszProvider));
      end else
        Memo1.Lines.Add('No Info needed = ' + IntToStr(dwNeeded));
    finally
      FreeMem(DriverInfo);
    end;
  finally
    ClosePrinter(hPrinter);
  end;
end;

end.
```
```
edit: removed the unnecessary function
```
GetDriverNameByOSPrinterName
```
BTW: In
```
pName
```
you have the Name of the Driver not the Name of the Printer. The Printername is changeable in Windows, so if you want go sure, use the Printerdrivername.


q: What issues or refactoring did you have to do when you upgraded from ASP.NET MVC Preview 5 to the newly released Beta version?

[A]
I'm about to do this myself.  Here's the list of changes from the readme:
Changes Made Between CodePlex Preview 5 and Beta
Changed the default validation messages to be more end-user friendly.
Renamed CompositeViewEngine to AutoViewEngine.
Added a Url property to Controller of type UrlHelper. This makes it convenient to generate routing-based URLs from within a controller.
Added the ActionNameSelectorAttribute abstract base class, which serves as the base type for ActionNameAttribute. By inheriting from this base attribute class, you can create custom attributes that participate in action selection by name.
Added a new ReleaseView method to IViewEngine that allows custom view engines to be notified when a view is done rendering. This is useful for cleanup or for view-pooling scenarios.
Renamed the ControllerBuilder method DisposeController to ReleaseController to fit with the pattern that is established for view engines.
Removed most of the methods on the HtmlHelper class, converting them to extension methods of the HtmlHelper class instead. These methods exist in a new namespace (System.Web.Mvc.Html). If you are migrating from Preview 5, you must add the following element to the namespaces section of the Web.config file:
```
<add namespace="System.Web.Mvc.Html"/>
```
This makes it possible for you to completely replace our helper methods with your own.
Changed the default model binder (DefaultModelBinder) to handle complex types. The IModelBinder interface has also been changed to accept a single parameter of type ModelBindingContext.
Added a new HttpVerbs enumeration that contains the most commonly used HTTP verbs (GET, POST, PUT, DELETE, HEAD). Also added a constructor overload to AcceptVerbsAttribute that accepts the enumeration. The enumerated values can be combined. Because it is possible to respond to HTTP verbs that are not included in the enumeration, the AcceptVerbsAttribute retains the constructor that accepts an array of strings as a parameter.  For example, the following snippet shows an action method that can respond to both POST and PUT requests.
```
```
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)]
public ActionResult Update() {...
}
```
```
Modified the RadioButton helper method to ensure that every overload accepts a value. Because radio buttons are used to specify a choice from a set of possible values, specifying a value for a radio button is necessary.
Made modifications and fixes to the default project template. This includes moving script files to a new Scripts folder. The default template uses the ModelState class to report validation errors.
Changed action-method selection. If two action methods match a request, but only one of those has an attribute that derives from ActionMethodSelectorAttribute that matches the request, that action is invoked. In earlier releases, this scenario resulted in an exception.
For example, the following two action methods are in the same controller:
```
```
public ActionResult Edit() {
  //...
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(FormCollection form) {
  //...
}
```
```
In Preview 5, a POST request for the Edit action would cause an exception, because two methods match the request. In the Beta, precedence is given to the method that matches the current request via the AcceptVerb attribute. In this example, the first method will handle any non-POST requests for the Edit action.
Added an overload for the ViewDataDictionary.Eval method that accepts a format string.
Removed the ViewName property from the ViewContext class.
Added an IValueProvider interface for value providers, along with a default implementation, DefaultValueProvider. Value providers supply values that are used by the model binders when binding to a model object. The UpdateModel method of the Controller class has been updated to allow you to specify a custom value provider.


q:
I came across the function InterlockedExchange and was wondering when I should use this function. In my opinion, setting a 32 Bit value on an x86 processor should always be atomic?

In the case where I want to use the function, the new value does not depend on the old value (it is not an increment operation).
Could you provide an example where this method is mandatory (I'm not looking for InterlockedCompareExchange)

[A]
```
InterlockedExchange
```
is both a write
and
a read -- it returns the previous value.
This is necessary to ensure another thread didn't write a different value just after you did.  For example, say you're trying to increment a variable.  You can read the value, add 1, then set the new value with
```
InterlockedExchange
```
.  The value returned by
```
InterlockedExchange
```
must match the value you originally read, otherwise another thread probably incremented it at the same time, and you need to loop around and try again.


q:
Does anyone know how I can retrieve the previous JSP URL that a page has come from within a JSP?

Can I retrieve this from the session/ request/ response object?

Hope this makes sense, Thank you

[A]
(assuming Struts 1)
Well in the struts-config.xml there is a input parameter in the action element (in the action-mappings section)
So in your action (java class) you can access this value like this :
```
public ActionForward action(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
     //do some stuff
     return mapping.getInputForward(); //return to the caller
  }
```
so if you want an action to return to its originating page, you can define
multiple action entry pointing to the same action but with a different name and input value.
Hope that helps.


q:
As most of you probably noticed, when uninstalling an MSI package Windows will ask for the original .msi file. Why is that?

I can only see disadvantages to that:

not resilient to network changes.

not resilient to local disk changes.

unexpected by users.

typically requires users to leave their desk and start a crusade to get the correct CD.

kind of proves installations are not self-contained.

promotes the use of unsafe tools such as msizap.

which in turn promotes the "next time I'll just use a zip file" mentality.

Could someone shed some light on this?

[A]
There are a few reasons for keeping the original msi:
The uninstaller uses it to know what files and registry keys were installed and make sure they are all cleaned up.
The msi may contain special uninstall actions that need to be performed.
It allows you do to a 'repair' operation from the Add/Remove Programs menu, regardless of whether or not you saved the install file yourself.
The normal way of things is for Windows to keep the file cached for you, so you don't have to think about it.  See your
```
%WINDIR%\Installer\
```
folder.  The only reason it would ask your for the original msi is if something is wrong with the saved file.  This addresses most of your concerns, though it does raise a new one (disk-space).


q:
Currently, I'm using:

DataTable dt = CreateDataTableInSomeWay();

List<DataRow> list = new List<DataRow>();
foreach (DataRow dr in dt.Rows)
{
    list.Add(dr);
}

Is there a better/magic way?

[A]
You could use
```
```
List<DataRow> list = new List<DataRow>(dt.Select());
```
```
```
dt.Select()
```
will return all rows in your table, as an array of datarows, and the
```
List
```
constructor accepts that array of objects as an argument to initially fill your list with.


q: The back button just causes my page to refresh. Is there a way around this without disabling the cache?

[A]
Try adding this to your HTML header:
```
```
<META HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">
```
```


q:
I have a class which is marked with a custom attribute, like this:

public class OrderLine : Entity
{
    ...
    [Parent]
    public Order Order { get; set; }
    public Address ShippingAddress{ get; set; }
    ...
}

I want to write a generic method, where I need to get the Property on a Entity which is marked with the  Parent attribute.

Here is my Attribute:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class ParentAttribute : Attribute
{
}

How do I write this?

[A]
This works for me:
```
```
public static object GetParentValue<T>(T obj) {
    Type t = obj.GetType();
    foreach (var prop in t.GetProperties()) {
        var attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);
        if (attrs.Length != 0)
            return prop.GetValue(obj, null);
    }

    return null;
}
```
```


q:
I was wondering peoples opinions on the naming of ID columns in database tables.

If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.

Where I am workind current they have called all ID columns ID.

So they would do the following:

Select
    i.ID
,   il.ID
From
    Invoices i
    Left Join InvoiceLines il
        on i.ID = il.InvoiceID

Now, I see a few problems here:

1. You would need to alias the columns on the select

2. ID = InvoiceID does not fit in my brain

3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on?

What are other peoples thoughts on the topic?

[A]
We use
```
InvoiceID
```
, not
```
ID
```
.  It makes queries more readable -- when you see
```
ID
```
alone it could mean anything, especially when you alias the table to
```
i
```
.


q:
I have successfully been able to rename a table and drop all constraints on that table with foreign key relationships and build they all back up. However, now I am at a point where the PK_tblFoo exists in more than one place (when I transfer the table to another DB). Renaming the table does not rename the primary key.

How would I cascade rename the primary key? I have renamed the table, I just need to get this portion figured out.

[A]
I believe I will need to this manually, drop all FK constraints, run this guy:
```
```
IF EXISTS ( SELECT  *
        FROM    sys.indexes
        WHERE   object_id = OBJECT_ID(N'[dbo].[tblFoo]')
                AND name = N'PK_tblBusinessListings' )
ALTER TABLE [dbo].[tblFoo] DROP CONSTRAINT [PK_tblBusinessListings]
GO
ALTER TABLE [dbo].[tblFoo]
ADD CONSTRAINT [PK_tblFoo_1] PRIMARY KEY CLUSTERED ( [ListingID] ASC )
    WITH ( PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF,
           ONLINE = OFF ) ON [PRIMARY]
```
```
Then go through and set up all the FK constraint with the new PK name....errrgh....this is going to take a while.


q:
I have a draggable with a custom helper. Sometimes the helper is a clone and sometimes it is the original element.

The problem is that when the helper is the original element and is not dropped on a valid droppable it gets removed. My solution looks like this so far:

in my on_dropped callback I set ui.helper.dropped_on_droppable to true;

In the stop callback of the draggable, I check for that variable and then ... what do I do?

$('.my_draggable').draggable({
    stop   : function(e, ui) {
        if (!ui.helper.dropped_on_droppable) {
            /* what do I do here? */
        }
    },

Is this even the right approach?

[A]
I might be missing something here, but is it not simply a case of adding
```
```
revert: "invalid"
```
```
to the options of the draggable if the draggable is of an original element, not a clone?


q:
I have a DTS package that is raising an error with a "Copy SQL Server Objects" task. The task is copying a table plus data from one SQL Server 2000 SP4 server to another (same version) and is giving the error: -

Could not find CHECK constraint for 'dbo.MyTableName', although the table is flagged as having one.

The source table has one check constraint defined that appears to cause the problem. After running the DTS package, the thing appears to work properly - the table, all constraints and data ARE created on the destination server? But the error above is raised causing subsequent steps not to run.

Any idea why this error is raised ?

[A]
This indicates that the metadata in the sys tables has gotten out of sync with your actual schema. If you aren't seeing any other signs of more generalized corruption, doing a rebuild of the table by copying it to another table (select * into newtable from oldtable), dropping the old table and then renaming the new one and replacing the constraints will help. This is similar to how the Enterprise manager for 2000 does things when you insert a column that isn't at the end of the table, so inserting a new column in the middle of the table and then removing will achieve the same thing if you don't want to manually write the queries.
I would be somewhat concerned by the state of the database as a whole if you see other occurrences of this kind of error. (I'm assuming here that you have already done CHECKDB commands and that the error is persisting...)


q: I've begun to the the built-in TraceSource and TraceListener classes and I would like to modify the output format of the events independently of the TraceSources and TraceListeners.  It seems that the TraceListeners apply their own formatting.  Is it possible to completely change the formatting without creating a new class for each and every TraceListener I use?

[A]
You can use the direct
```
Write()
```
or
```
WriteLine()
```
methods on
```
Trace
```
to put straight text into your TraceListener.


q: How can I strip out extra whitespace from jsp pages' output?  Is there a switch I can flip on my web.xml?  Is there a Tomcat specific setting?

[A]
There is a trimWhiteSpaces directive that should accomplish this,
In your JSP:
```
```
<%@ page trimDirectiveWhitespaces="true" %>
```
```
Or in the jsp-config section your web.xml (Note that this works starting from servlet specification 2.5.):
```
```
<jsp-config>
  <jsp-property-group>
    <url-pattern>*.jsp</url-pattern>
    <trim-directive-whitespaces>true</trim-directive-whitespaces>
  </jsp-property-group>
</jsp-config>
```
```
Unfortunately if you have a required space it might also need strip that, so you may need a non-breaking space in some locations.


q:
What is the return value of the WaitForObject() function?

I do not mean the type of return value (int).

What does it return if the event is signalled and what does it return if the event is not signalled?

[A]
There is no
```
WaitForObject
```
function. I assume that you mean either
```
WaitForSingleObject
```
or
```
WaitForMultipleObjects
```
.
```
WaitForSingleObject
```
will return
```
WAIT_TIMEOUT
```
,
```
WAIT_OBJECT_0
```
or
```
WAIT_ERROR
```
.
```
WaitForMultipleObjects
```
will return
```
WAIT_TIMEOUT
```
,
```
WAIT_OBJECT_0 + n
```
(where n is the index to the object in the array) or
```
WAIT_ERROR
```
.


q:
has anybody managed to get Djangos site map framework to run on Google App Engine?

I receive the following exception:

ImproperlyConfigured at /sitemap.xml

You haven't set the DATABASE_ENGINE setting yet.

Request Method: GET
Request URL: http://127.0.0.1:8080/sitemap.xml
Exception Type: ImproperlyConfigured
Exception Value: You haven't set the DATABASE_ENGINE setting yet.
Exception Location: D:\Program Files\Google\google_appengine\lib\django\django\db\backends\dummy\base.py in complain, line 13

[A]
I'm not familiar with GAE, but I may have a solution to your problem. Check out the Sitemap Framework docs @
http://docs.djangoproject.com/en/dev/ref/contrib/sitemaps/
Look at both the
Simple Example
and the
Example
. The sitemap code takes a dict of name:SiteMap. Any valid Sitemap object will work. The minimum for a Sitemap class is to  define items(), which returns a list of objects that came from
somewhere
.
We have a StaticSitemap class which just reads a list of URLs from a file and returns that, plus it has a location(item) method that just returns the item (since it's a simple path).


q: We are working with some legacy code that accesses a shared drive by the letter (f:\ for example). Using the UNC notation is not an option.  Our Java wrapper app will run as a service, and as the first step, I would like to map the drive explicitly in the code. Has anyone done this?

[A]
I think the easiest way is to use the Runtime.getRuntime().exec() method and call the "net use" command.
For example:
```
```
try {
        // Execute a command without arguments
        String command = "C:\\Windows\\system32\\net.exe use F: \\\\server\\share /user:user password";
        Process child = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
    }
```
```


q:
So, I want to export all my contacts from Outlook as vcards. If I google that, I get a bunch of shareware programs, but I want something free that just works.

If I'm to code it myself, I guess I should use the Microsoft.Office.Interop.Outlook assembly. Has anyone already code to convert ContactItems to vcards?

Edit: I solved it in a completely different way, see answer below, but I have marked dok1.myopenid.com's answer as accepted because it answers my original question.

[A]
They sure make it hard to find, don't they? See if this helps.
http://msdn.microsoft.com/en-us/library/aa579624(EXCHG.80).aspx
That includes: The following example uses the CDO Person object to obtain vCard information for a contact.
```
```
Dim oPerson As New CDO.Person
Dim strm As New ADODB.Stream

' Assume strURL is a valid URL to a person contact item
oPerson.DataSource.Open strURL

' You can set the ADO Stream object to the returned vCard stream
Set strm = oPerson.GetvCardStream

' Save the stream to a file.
' Note: using adSaveCreateOverwrite may cause an existing
' contact to be overwritten.
strm.SaveToFile "d:\vcard.txt", adSaveCreateOverwrite

' You don't have to set a Stream object,
' just use the Stream methods off GetvCardStream directly
oPerson.GetvCardStream.SaveToFile "d:\vcard.txt", adSaveCreateOverwrite
```
```
Yep, the only code sample there is in VB.


q:
Normally when using VMWare Server 1.0.7 you are asked if you would like to connect to the local machine or a remote host.  Installing the same software on 64-bit Windows 2008 only gives the remote host option.

I have tried entering the local machine name as the host and entering creds that have admin rights to the server but I just get a "Cannot connect as the target machine actively rejected it" error.  I have tried to find a solution on Google, but with no joy.

Anyone run into this before and can point me in the right direction?

[A]
It would seem the drivers for VMWare Server 1.0.7 are unsigned and 64-bit windows refuses to load them.  Prior to security update KB932596 you could disable this check, but they have now stopped this.
I have previously tried VMWare Server 2, but have not found it that stable.
Running out of ideas......


q:
I am searching for "o" then prints all lines with "o". Any suggestion/code I must apply?

data.txt:

j,o,b:
a,b,d:
o,l,e:
f,a,r:
e,x,o:

desired output:

j,o,b:
o,l,e:
e,x,o:

[A]
```
```
grep "o" data.txt
```
```
Does that help? I don't know Perl, but you can get the same output using the above grep.


q: Is it possible to encode an assignment into an expression tree?

[A]
No, I don't believe so.
Certainly the C# compiler disallows it when converting a lambda expression:
```
```
int x;
Expression<Func<int,int>> foo = (x=y); // Assign to x and return value
```
```
This yields the error:
```
```
CS0832: An expression tree may not contain an assignment operator
```
```


q:
When I launch CruiseControl.NET with a particular configuration file I receive the following error:

ThoughtWorks.CruiseControl.Core.Config.ConfigurationException: Duplicate node detected

What does this mean, and what causes it?


q:
I'm trying to write an audio analysis application, and I need to identify local maxima in a 2D array which represents a spectrogram. I've already got an open source library that can generate the spectrogram using Fast Fourier Transforms, but I was wondering if anybody knew of any good libraries to help me with actually finding the maxima? I'm not quite sure what to search Google for - the best I could think of was "numerical library" but that hasn't got me very far.

Preferably in C, but I'm open to other suggestions.


q:
something.each do |x|

  #lots of stuff

end if some_condition

[A]
I'd personally advocate against that for the pure and simple reason that it is too easy to miss. Even with that shortened version it took me a double-take to realise you had the
```
```
if some_condition
```
```
at the end


q:
I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched.

classdef testprop
    properties
        numRequests=0;
    end
    methods
        function Request(this, val)
            disp(val);
            this.numRequests=this.numRequests+1;
        end
    end
end

.

>> a=testprop;
>> a.Request(9);
>> a.Request(5);
>> a.numRequests

ans = 0

[A]
Using a Value (Vanilla) Class
When using a value class you need to tell Matlab to store a modified copy of the object to save the changes in the property value.  So,
```
```
>> a=testprop
>> a.Request(5); % will NOT change the value of a.numRequests.
5

>> a.Request(5)
5

>> a.numRequests
ans =
       0

>> a=a.Request; % However, this will work but as you it makes a copy of variable, a.
5

>> a=a.Request;
5

>> a.numRequests
ans =
       2
```
```
As
Kamran
notes, this requires changing the definition of function
```
Request
```
to be
```
```
function this = Request(this, val)`
```
```
Using a Handle Class
If you inherit from the handle class, that is
```
```
classdef testprop < handle
```
```
then you can write,
```
```
>> a.Request(5);
>> a.Request(5);
>> a.numRequests
ans =
       2
```
```
Note that this changes the behavior of the objects, see
the documentation
to learn the difference between a value class and a handle class.


q:
A few years ago I have worked on a green field project where we did Extreme Programming. I also see a lot of people mention the Scrum methodology.

Could someone tell me the main differences between Scrum and XP?

[A]
Scrum is a software development methodology, XP is a programming practice. Both are "agile" techniques and are often used together.
Scrum outlines a process for identifying and cataloging work that needs to be done, prioritizing that work by communicating with the customer or customer representative, and implementing that work using iterative releases.
When my team first started experimenting with Scrum I found the
Implementing Scrum
website to be helpful.


q:
I have an input type="image". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image is paired with, I setup an event handler for the input-image. Then when the user clicks the image, they get a little popup to add some notes to the data.

My problem is that when a user enters a zero into the text box, I need to disable the input-image's event handler. I have tried the following, but to no avail.

$('#myimage').click(function { return false; });

[A]
maybe the unbind method will work for you
```
```
$("#myimage").unbind("click");
```
```


q:
I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.

In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.

[A]
You're right - prototype doesn't provide a utility for ascertaining the browser name or version.
If you
specifically
need to get the browser info as a plugin, I would suggest adding the following (taken from directly jQuery):
```
```
var Browser = Class.create({
  initialize: function() {
    var userAgent = navigator.userAgent.toLowerCase();
    this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1];
    this.webkit = /webkit/.test( userAgent );
    this.opera = /opera/.test( userAgent );
    this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );
    this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );
  }
});
```
```


q: Since Access 2003 doesn't have the control anchoring functionality as exists in 2007, I was wondering if anyone has or is aware of some VBA script, or a freeware control, that can give this functionality?

[A]
I know of no exact duplication of the 2007 functionality in 2003. There are multiple components for resolution independence (resizing the controls on a form based on the users monitor resolution) and for resizing with the form resize event (such as
http://www.fmsinc.com/products/components/ControlTour/resize.htm
). None that I'm aware of quite replicate the 2007 experience, but a similar question (and code to handle it) can be found here:
http://www.experts-exchange.com/Microsoft/Development/MS_Access/Q_23662850.html
Personally, I just handled the resize event myself. The easiest way is to do so is to create the form in the minimum size you wish to support, and then record the base positions and widths (either in a table or as form scoped constants). From there you can resize using:
```
```
resizeRatio = currentFormWidth / baseFormWidth

control.left = baseLeft * resizeRatio
control.width = baseWidth * resizeRatio
```
```
The advantage to doing this yourself is that over time you evolve it, with things such as keeping the labels on the left side the same width but expanding the fields to the right (this is done by not resizing the labels at all, and subtracting the end of the labels area off from the width of the form before applying the position and width changes, such as):
```
```
resizeRatio = (currentFormWidth - labelsAreaWidth) / (baseFormWidth - labelsAreaWidth)

control.left = (baseLeft - labelsAreaWidth) * resizeRatio + labelsAreaWidth
control.width = baseWidth * resizeRatio
```
```


q:
I'm looking for a plugin for jQuery that can validate as a key is pressed and after it loses focus (text boxes).

I'm currently using jVal - jQuery Form Field Validation Plugin. It works pretty good.  The only issue I have is that I can only use a generic error message.

For example:
  I need a string to between 2 and 5 characters.  If its too short I would like to display an error message that indicates it to short, equally if its too long. I know I could display an error message that requires the string to between 2 and 5 characters.  The validation that is being done is more complicated.

Any ideas of other validators or how I could use this plug-in to display unique error messages.

Edit:

The validation tool needs to prevent particular letters or numbers and not require a form.

Thanks

[A]
This one looks like it would fit your description:
jQuery plugin:validation (Homepage)
demo
API docs
Here's a snippet of code copied from the source of the demo:
```
```
// validate signup form on keyup and submit
$("#signupForm").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2
        },
        password: {
            required: true,
            minlength: 5
        },
        confirm_password: {
            required: true,
            minlength: 5,
            equalTo: "#password"
        },
        email: {
            required: true,
            email: true
        },
        topic: {
            required: "#newsletter:checked",
            minlength: 2
        },
        agree: "required"
    },
    messages: {
        firstname: "Please enter your firstname",
        lastname: "Please enter your lastname",
        username: {
            required: "Please enter a username",
            minlength: "Your username must consist of at least 2 characters"
        },
        password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long"
        },
        confirm_password: {
            required: "Please provide a password",
            minlength: "Your password must be at least 5 characters long",
            equalTo: "Please enter the same password as above"
        },
        email: "Please enter a valid email address",
        agree: "Please accept our policy"
    }
});
```
```


q:
How would I assign a variable within scriplet code in JSP <%>  and then use struts logic tags to do stuff based on the value of the variable assigned in the scriplet code block?

I have tried using struts:logic equal and greaterthan to no avail....

Many Thanks,

[A]
What you are trying to do (if I understand you correct) is basically this:
```
```
<% String foo = "Test"; %>
<bean:write name="foo" />
```
```
Which, as you already know, doesn't work. That would give an error like this:
Cannot find bean foo in any scope
What I usually do, is to put my data in the page scope like this:
```
```
<% pageContext.setAttribute("foo", "Test"); %>
<bean:write name="foo" />
```
```
(This is for Struts 1.1. Newer versions may provide a better way to do it.)


q:
We are logging any exceptions that happen in our system by writing the Exception.Message to a file. However, they are written in the culture of the client. And Turkish errors don't mean a lot to me.

So how can we log any error messages in English without changing the users culture?

[A]
I would imagine one of these approaches:
The exceptions are only ever read by you, i.e. they are not a client feature, so you can use hardwired non localised strings that won't change when you run in Turkish mode.
Include an error code e.g.
```
0x00000001
```
with each error so that you can easily look it in up in an English table.


q: I need to make a mouseover menu that opens diagonally (from top-left to bottom-right).

[A]
Use a Tween to tween the height from 0 to whatever height you want, and width from 0 to whatever width you want.
You can take examples of making a popup menu show from the code here, as well as examples of performing actions on hover.


q:
I would like to match the time (10.00) from a string with the date and time ("21.01.08 10.00"). I'm using the following regular expression:

new RegExp("\\b[0-9]{1,2}\\.[0-9]{1,2}\\b" "g");

But this matches 21.01 from 21.01.08 and 10.00.

I'm using PCRE as my regualar expression engine.

Update:

I'm sorry, i should have more been more clear. The data and time are part of a larger string. I want to extract the time from that string.

For example:

"On 21.01.08 from 10.00 a party will take place in the library"
"21.08.08 - At 10:00 there will be a party"
"On 21.08.08 you are scheduled for a ... . The ... will begin at 10.00"

Is this possible?


q:
I've been looking at Dojo, and it has some nice tricks, however its quite huge IMHO. Basically when viewing my test my slow machine (600mhz), just loading Dojo was kind of painful, and can imagine lots of mobile devices will also not be happy with it.

Is there a slim version or something like that available?

[A]
What do you mean by 'loading Dojo'?
If you mean opening a page with a clean cache, and the site takes a long time to load, then it may be because you're using a non-minified version of the library.
If you mean loading some Dijits, or
a full-featured page
, then that's probably a combination of your browser's speed with JS, your computer's speed, and Dojo's speed.
Try loading something similar from another framework like
Ext JS
or
jQuery
to see if they are any different.


q: Are htaccess redirects any slower/put any more strain on Apache than redirects in configuration files? Also, how big can a number of redirects in htaccess get before they start decreasing performance?

[A]
Using a .htaccess file is slower than using a configuration file - a .htaccess file is parsed whenever a request is made to a directory it affects - this allows for changing the file without restarting the server. Since a configuration file is parsed only once at server start, it's faster.
The amount of directives you can have in a .htaccess file without significant performance impact will be based on the complexity of the rules and your server's specifics, although the main performance hit will be from using the .htaccess file at all.


q:
Other than Visual Studio, what tool have you found best to create, edit, maintain, and possibly debug your XSLT files?

I work on a fairly big project and we have tons of XSLT files and they have grown quite complex in their implementation.

The language seems so brittle. It would be nice to navigate and identify errors more quickly.

[A]
Liquid XML Studio
is pretty good at real-time interpretation of your XPATH queries.
Cooktop
also lets me run my XPATH queries and shows me the XML and HTML generated by running the XSLT against a given XML.
Also, a colleague tells me that newer versions of
Adobe Dreamweaver
allows you to associate an XML file with an XSLT file and run the transformation.
Whenever possible i use
Subversion
for change-tracking.
And for navigation, i most often use
VIM
(or
VIEmu
) and sometimes a custom Visual Studio extension that builds an index of the current document's xsl:template and xsl:variable nodes to provide one-click navigation to the root entries.


q:
I know I should be using htmlentities for all my form text input fields but this doesn't work:

<?php
echo "<tr>
        <td align=\"right\">".Telephone." :</td>
        <td><input type=\"text\" name=\"telephone\" size=\"27\"
            value=\"htmlentities($row[telephone])\"> Inc. dialing codes
        </td>
</tr>";
?>

It simply shows the input value as "htmlentities(0123456789)" in the form? What have I done wrong please?

[A]
try using
```
```
value=\"" . htmlentities($row[telephone]) . "\"
```
```
there. Currently, your string simply contains the htmlentities string and splices the variable in. You need to get out the string, call the function and put it's result in place, as above.


q:
I've got a unidirectional tree of objects, in which each objects points to its parent. Given an object, I need to obtain its entire subtree of descendants, as a collection of objects. The objects are not actually in any data structure, but I can easily get a collection of all the objects.

The naive approach is to examine each object in the batch, see if the given object is an ancestor, and keep it aside. This would not be too efficient... It carries an overhead of O(N*N), where N is the number of objects.

Another approach is the recursive one, meaning search for the object's direct children and repeat the process for the next level. Unfortunately the tree is unidirectional... there's no direct approach to the children, and this would be only slightly less costly than the previous approach.

My question: Is there an efficient algorithm I'm overlooking here?

Thanks,

Yuval =8-)

[A]
Your question is a little abstract, but
nested sets
(scroll down, might be a little too mysql-specific) might be an option for you. It's extremely fast for read operations, though any modifications are quite complex (and have to modify half the tree on average).
That requires the ability to modify your data structure, though. And I guess if you can modify the structure, you could just as well add references to child objects. If you can't modify the structure, I doubt there's anything faster than your ideas.


q:
I am trying to use a third party DLL that wants an int** as one of the parameters to the method.  It describes the parameter as the address of the pointer that will point to the memory allocation.

Sorry for any confusion.  The parameter is two-way I think.  The DLL is for talking to an FPGA board and the method is setting up DMA transfer between the host PC and the PCI board.

[A]
Use a by-ref
```
System.IntPtr
```
.
```
```
[DllImport("thirdparty.dll")]
 static extern long ThirdPartyFunction(ref IntPtr arg);

 long f(int[] array)
  { long retval = 0;
    int  size   = Marshal.SizeOf(typeof(int));
    var  ptr    = IntPtr.Zero;

    try
     { ptr = Marshal.AllocHGlobal(size * array.Length);

       for (int i= 0; i < array.Length; ++i)
        { IntPtr tmpPtr = new IntPtr(ptr.ToInt64() + (i * size));
          Marshal.StructureToPtr(array, tmpPtr, false);
        }

       retval = ThirdPartyFunction(ref ptr);
     }
    finally
     { if (ptr != IntPtr.Zero) Marshal.FreeHGlobal(ptr);
     }

    return retval;
  }
```
```


q:
I have a chart in a Worksheet in Excel and I have a macro set up so that when I change the value in a certain cell the range of data in the chart is set to A2 down as far as the row number corresponding in this certain cell.

What I can't seem to be able to do is to modify the axis as the specified axis no longer covers the range of the graph i.e. the current X axis is set to:

=Sheet1!$C$2:$C$600

I can't figure out how I can update this in a macro. Any help would be much appreciated.

[A]
You should be able to set the XValues property in the same way you did in Lance's answer for your
other question
.
```
```
Charts("chartname").SeriesCollection(1).XValues = "=MYXAXIS"
```
```
or whatever you call the named range for the x-axis values. If you have multiple series in your chart, you'll want to change the value in SeriesCollection to refer to the right series.


q:
I am currently developing an approval routing WCF service that will allow an user to create "rules" which determine how an request is routed.  The route is determined by comparing the "ObjectToEvaluate" property of the Request class against the "ObjectToEvaluate" property of the "Rule" class.  The "UnitOfMeasurement" enum determines how to cast the "ObjectToEvaluate" property for each class.

public enum UnitOfMeasurement
{
    Currency = 1,
    Numeric = 2,
    Special = 3,
    Text = 4,
}

public class Request
{
    public object ObjectToEvaluate { get; set; }
}

public class Rule
{
    public object ObjectToEvaluate { get; set; }

    public virtual void ExecuteRule()
    {
        //logic to see if it passes the rule condition
    }
}

What would be the best way to implement the method to cast the "ObjectToEvaluate" property using the "UnitOfMeasurement" enum?

[A]
Where are you getting the unit of measurement from? I can see the enum, but I don't see any reference to it elsewhere in the API.
Assuming you do get it from somewhere, the easiest solution may well be a switch statement. It's a bit ugly, but:
It'll work
It's easy to understand
It'll be fast
I'm still not entirely convinced I understand everything about the question though - particularly as you haven't explained what the other objects will be used for after casting.


q:
I have  stfw but I cannot find a simple / standalone  way to create a webservice client in java.

Does anyone have a link/sample into this?

[A]
How about using
Axis2
?
Just follow the
quickstart guide
and you should be on your way.
Here is another more descriptive
guide


q: If I have a string (010) and i want to add 1 to it (011) what value type should i use to convert this string into a number for adding and at the same time preserve the whole number and not 10 + 1 = 11.

[A]
```
```
if (int.TryParse(str, out i))
    str = (i + 1).ToString("000");
```
```
HTH.
(
edit
: fixed the problems pointed out by BoltBait and steffenj)


q:
I have a WPF ListView which currently scrolls everytime I click on an item which is only partially visible.  How can I keep the control from scrolling that item into view (instead simply selecting the partially visible one)?  This behavior is very annoying when doing a drag from this control.

Thanks.

Added:  I am looking for a solution to keep the control itself from scrolling when contents are clicked that the control believes are not fully visible.  Often this is by a few pixels and the scroll is not necessary.

[A]
have you tried
this approach
?
just as an addon, I don't know how much you know about the subject, but
here is a good place
to read more about it.
added:
I just found that you can
prevent the mouse wheel of scrolling
as well.


q:
I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9:

$ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/
$ python tut09_files.py
Traceback (most recent call last):
  File "tut09_files.py", line 48, in <module>
    from cherrypy.lib import static
ImportError: cannot import name static

The previous line in the file:

import cherrypy

passes without error, so it appears that it can find cherrypy on the path. What am I missing?

[A]
I am a big fan of the proposed HTML 5 solution (
```
data-
```
prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).