Question:
Jeffrey Richter is looking for some input on how people are using his PowerThreading library. If anyone out there is using this, what parts of it are you using? He is looking to clean up the library and wants to know what classes people are using.

http://www.wintellect.com/PowerThreading.aspx

EDIT: See http://tech.groups.yahoo.com/group/PowerThreading/message/88

Answer:
An indirect answer (I don't use that library myself) - if I was looking at complex threading, I'd be very tempted to look at what the
TPL
has to offer in the current CTP, especially looking forward to .NET 4.0.


Question: I understand that they force you to implement methods and such but what I cant understand is why you would want to use them. Can anybody give me a good example or explanation on why I would want to implement this.

Answer:
There are a number of reasons to do so. When you use an interface, you're ready in the future when you need to refactor/rewrite the code.  You can also provide an sort of standardized API for simple operations.
For example, if you want to write a sort algorithm like the quicksort, all you need to sort any list of objects is that you can successfuuly compare two of the objects.  If you create an interface, say ISortable, than anyone who creates objects can implement the ISortable interface and they can use your sort code.
If you're writing code that uses a database storage, and you write to an storage interface, you can replace that code down the line.
Interfaces encourage looser coupling of your code so that you can have greater flexibility.


Question:
How can I launch an application using C#?

Requirements:
Must work on Windows XP and Windows Vista.

I have seen a sample from DinnerNow.net sampler that only works in Windows Vista.

Answer:
```
```
System.Diagnostics.Process.Start("PathToExe.exe");
```
```


Question:
I created a list of lists:

xs = [[1] * 4] * 3

# xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

Then, I changed one of the innermost values:

xs[0][0] = 5

# xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]

Why did every first element of each sublist change to 5?

Answer:
```
```
[[1] * 4] * 3
```
```
or even:
```
```
[[1, 1, 1, 1]] * 3
```
```
Creates a list that references the internal
```
[1,1,1,1]
```
3 times - not three copies of the inner list, so any time you modify the list (in any position), you'll see the change three times.
It's the same as this example:
```
```
>>> inner = [1,1,1,1]
>>> outer = [inner]*3
>>> outer
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
>>> inner[0] = 5
>>> outer
[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
```
```
where it's probably a little less surprising.


Question:
What is the difference between new/delete and malloc/free?

Related (duplicate?): In what cases do I use malloc vs new?

Answer:
The  most relevant difference is that the
```
new
```
operator allocates memory then calls the constructor, and
```
delete
```
calls the destructor then deallocates the memory.


Question:
I want to read line n1->n2 from file foo.c into the current buffer.

I tried: 147,227r /path/to/foo/foo.c

But I get: "E16: Invalid range", though I am certain that foo.c contains more than 1000 lines.

Answer:
The {range} refers to the destination in the current file, not the range of lines in the source file.
After some experimentation, it seems
```
```
:147,227r /path/to/foo/foo.c
```
```
means
insert the contents of
```
/path/to/foo/foo.c
```
after line 227 in this file.
i.e.: it ignores the 147.


Question:
Ok, I am reading in dat files into a byte array.  For some reason, the people who generate these files put about a half meg's worth of useless null bytes at the end of the file.  Anybody know a quick way to trim these off the end?

First thought was to start at the end of the array and iterate backwards until I found something other than a null, then copy everything up to that point, but I wonder if there isn't a better way.

To answer some questions:
Are you sure the 0 bytes are definitely in the file, rather than there being a bug in the file reading code? Yes, I am certain of that.

Can you definitely trim all trailing 0s? Yes.

Can there be any 0s in the rest of the file? Yes, there can be 0's other places, so, no, I can't start at the beginning and stop at the first 0.

Answer:
Assuming 0=null, that is probably your best bet... as a minor tweak, you might want to use
```
Buffer.BlockCopy
```
when you finally copy the useful data..


Question:
I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner.

I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows:

selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/");

How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task?

For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves.

I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do.

Many thanks if anyone can help.

Answer:
Anytime I need to integrate with an external entity using NAnt I either end up using the
exec task
or writing a
custom task
. Given the information you posted it would seem that writing your own would indeed be a good solution, However you state you're not happy with it. Can you elaborate a bit on why you don't think you current solution is an
elegant
one?
Update
Not knowing
internal
details it seems like you've solved it pretty well with a custom task. From what I've heard, that's how I would have done it.
Maybe a new solution will show itself in time, but for now be light on yourself!


Question:
I'd like something like a generic, re-usable getPosition() method that will tell me the number of bytes read from the starting point of the stream.  Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources.

Does such a beast exist?  If not, can anyone recommend an existing implementation of a counting InputStream?

Answer:
No.
```
InputStream
```
is intended to handle potentially infinite amounts of data, so a counter would get in the way. In addition to wrapping them all, you might be able to do something with aspects.


Question:
I use Struts v1.3 and have following input form:

In struts-config.xml:

    <form-bean name="testForm"
               type="org.apache.struts.validator.DynaValidatorForm">
        <form-property name="displayName" type="java.lang.String" />
    </form-bean>

In validation.xml:

    <form name="testForm">
        <field property="displayName" depends="required">
            <arg key="input.displayName" />
        </field>
    </form>

How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?

Answer:
You may have a chance to trim the string right at the moment, the request processor updates the data from the input fields to the form. This was not tested, but what happens when you modify the setter setDisplayName(String displayName) to something like
```
```
public void setDisplayName(String displayName) {
    this.displayName = displayName.trim();
}
```
```
This is not a very good solution, because it migrates logic into a setter.
regards


Question:
I need a date formula in Oracle SQL or T-SQL that will return a date of the previous week (eg Last Monday's date).

I have reports with parameters that are run each week usually with parameter dates mon-friday or sunday-saturday of the previous week.  I'd like to not have to type in the dates when i run the reports each week.

The data is in Oracle and I am using SQL Server 2005 Reporting Services (SSRS) for the reports.

Answer:
T-SQL:
```
```
SELECT
  DateColumn,
  DateColumn - CASE DATEPART(dw, DateColumn)
                WHEN 1 THEN 6
                ELSE DATEPART(dw, DateColumn) - 2
              END MondayOfDateColumn
FROM
  TheTable
```
```
Do you need the time part to be "00:00:00", too?
If so, add this expression to the calculation:
```
```
DATEADD(dd, 0, DATEDIFF(dd, 0, DateColumn)) - CASE DATEPART(dw, /* etc. etc. */
```
```


Question:
I have a ClickOnce deployed application I want to launch from VBScript, similar to launching Microsoft Word in the following example:

Dim word
Set word = CreateObject("Word.Application")
word.Visible = True

The problem is I don't know what parameter to pass into the CreateObject function to launch my application. Where would I find the master list of applications installed on my PC/the shortcut to call to launch them?

Answer:
ClickOnce simply isn't installed that way. They don't typically have COM hooks (for CreateObject), and are installed in an isolated part of the user's profile (not that machine's profile). And don't forget you can also get multiple copies/versions of the same app at once via ClickOnce (from different locations).
One option (in 3.5/VS2008) might be to use the new file associations stuff... associate your app with ".foo" files, create an empty ".foo" file and start it. That might work. Look on the Publish=>Options dialog in VS2008.
Otherwise - basically, if you want this type of usage, I suspect you will need to use msi (i.e. a regular installer; not ClickOnce) to register your app as a COM library (dll). Note that .NET doesn't make a good COM server (exe) - so doesn't compare directly to Word. If you want a .NET COM server, then "serviced components" are your best bet - but these don't tend to be big on UI.
For info, the isolated area is somewhere around "%userprofile%\Local Settings\Apps\2.0", but this is just for interest so you can see it.. don't try running it from there.


Question:
I'm looking for a way to convert a preprocessor token to a string.

Specifically, I've somewhere got:

#define MAX_LEN 16

and I want to use it to prevent buffer overrun:

char val[MAX_LEN+1]; // room for \0
sscanf(buf, "%"MAX_LEN"s", val);

I'm open to other ways to accomplish the same thing, but standard library only.

Answer:
I found an answer online.
```
```
#define VERSION_MAJOR 4
#define VERSION_MINOR 47

#define VERSION_STRING "v" #VERSION_MAJOR "." #VERSION_MINOR
```
```
The above does not work but hopefully
    illustrates what I would like to do,
    i.e. make VERSION_STRING end up as
    "v4.47".
To generate the proper numeric form
  use something like
```
```
#define VERSION_MAJOR 4
#define VERSION_MINOR 47

#define STRINGIZE2(s) #s
#define STRINGIZE(s) STRINGIZE2(s)
#define VERSION_STRING "v" STRINGIZE(VERSION_MAJOR) \
"." STRINGIZE(VERSION_MINOR)

#include <stdio.h>
int main() {
    printf ("%s\n", VERSION_STRING);
    return 0;
}
```
```


Question:
We have a POST to a PL/SQL database procedure that (a) does some database operations based on the POST parameters and (b) redirects the user to a page showing the results.

The problem is, when the user does a browser "refresh" of the results page, that still has the original request, so it calls the database procedure and resends the parameters.

There are things we can do with saving state so bad things don't happen if the request gets sent in again. But that got me wondering.

Is there a way to tell the browser to set the url to the redirect call, not the original user request? This would probably be in either the redirect itself, or in Javascript on the target page.

Answer:
I found an answer online.
```
```
#define VERSION_MAJOR 4
#define VERSION_MINOR 47

#define VERSION_STRING "v" #VERSION_MAJOR "." #VERSION_MINOR
```
```
The above does not work but hopefully
    illustrates what I would like to do,
    i.e. make VERSION_STRING end up as
    "v4.47".
To generate the proper numeric form
  use something like
```
```
#define VERSION_MAJOR 4
#define VERSION_MINOR 47

#define STRINGIZE2(s) #s
#define STRINGIZE(s) STRINGIZE2(s)
#define VERSION_STRING "v" STRINGIZE(VERSION_MAJOR) \
"." STRINGIZE(VERSION_MINOR)

#include <stdio.h>
int main() {
    printf ("%s\n", VERSION_STRING);
    return 0;
}
```
```


Question:
In a class diagram, is there a way of specifying that a class is an internal class of another class ?

Or is it considered as a pure implementation choice ?

Answer:
For this kind of thing you have separate Diagrams showing the internal structure or processing of a class.
usually, those extra diagrams are activity diagrams to show processing.  Sometimes one per method.  You might also have an internal sequence diagram showing the API interactions.
No reason you can't have an additional class diagram to show internal structure of a class.


Question:
as google does not deliver what i want to know, i try to ask stackoverflow :)
what is the number of max concurrent connections to a sql ce 3.5 database?
thanks
j.

Answer:
I believe the information you are looking for is the SQL Server Edition Comparison.
For standard Editions -
Compare Features
For Compact Edition -
Compare Features
Edit
Sorry, this
Word Document
is most likely what you need.
Edit again
The answer is 256 concurrent connections for Compact, unlimited for express.  See table 1 in the linked word doc.


Question:
Of course, there are a whole range of possible errors relating to document validity, but my immediate stumbling block occurs when changing a paragraph (p) into an address element. My current method is (more-or-less):

var p = $('p#test');
p.replaceWith('<address>' + p.html() + '</address>');

but that fails for this specific case; it works perfectly for p -> blockquote or h2 -> h3. Firebug suggests that a self-closing element (<address/>) has been added to the document, for some reason.

Can anyone spot the bug or suggest an alternative method?

Answer:
You'll could use a placeholder around the title:
```
<span id="demo"><h1>Title</h1></span>
```
Then use JavaScript DOM to create new values for the innerHTML property.
```
<script type="javascript">

setTitle = function(id, tag, title) {
  var container = document.getElementById(id);
  container.innerHTML = '<' + tag + '>' + title + '</' + tag + '>';
}

setTitle('demo', 'h1', 'My Title');

</script>
```


Question: It would be a shame if it doesn't, because it will make for more attractive looking Android applications.

Answer:
Not right now, and it would be a nontrivial task to make it work. Android doesn't have all the libraries that the typical desktop JRE does. Although since Android is open source and it will run anything that can be compiled to Dalvik byte code, it's not impossible.
Really, I don't really think JavaFX will make for more attractive looking Android applications - the most important thing is how integrated the application is into the hardware and the Android display framework has a lot of stuff to make that easier.


Question: I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.

Answer:
I Agree with carson, sessions should work for this.  Make sure you are calling
session_start()
before anything else on any page you want to use the session variables.
Also, I would not store password info directly, rather use some kind of authentication token mechanism.  IMHO, it is not
intrinsically
unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.


Question:
I have a string from an email header, like Date: Mon, 27 Oct 2008 08:33:29 -0700. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?

And for the fastest ones -- this is not going to work properly:

SimpleDateFormat format = ... // whatever you want
Date date = format.parse(myString)
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTime(date)

because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return -7 * milisInAnHour.

Answer:
I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually.
http://joda-time.sourceforge.net/
So anyway, if Joda Time is an option, something like this
should
work:
```
```
DateTimeFormatter formatter =
    DateTimeFormat.forPattern("your pattern").withOffsetParsed();
DateTime dateTime = formatter.parseDateTime("your input");
GregorianCalendar cal = dateTime.toGregorianCalendar();
```
```
I hope this helps.


Question:
I have a weird date rounding problem that hopefully someone can solve.  My client uses a work week that runs from Monday through Sunday.  Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2008', which is Sunday's date).

One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week.

So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above.  Thanks for your help.  I have a solution that works, but I'm too embarassed to post it.

Oh, and I can't use LINQ.

Answer:
```
```
public DateTime WeekNum(DateTime now)
{
    DateTime NewNow = now.AddHours(-11).AddDays(6);

    return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);
}

public void Code(params string[] args)
{

    Console.WriteLine(WeekNum(DateTime.Now));
    Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));
    Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));
    Console.WriteLine(WeekNum(new DateTime(2008,10,28)));
    Console.WriteLine(WeekNum(new DateTime(2008,10,25)));

}
```
```
You may hard-code DateTime.Now instead of passing a DateTime object.  It just made testing easier this way.


Question:
Does anyone know of a simple web app that supports running ant tasks?  Alternatively it could run command line programs.  I need to allow the user to choose parameters for running the ant task.  I effectively want a web interface to run the ant task and provide any parameters.

I can write one but this is generic enough that it seems like there should already be a few standard packages that do this.

Answer:
You could put this in a PHP-file:
```
```
echo shell_exec('ant');
```
```
It would run ant and return the output to the browser.


Question:
I have the following rails migration:

create_table :articles do |t|
  t.integer :user_id, :allow_null => false
  t.integer :genre_id, :allow_null => false
  t.string :url, :limit => 255, :allow_null => false
  t.string :title, :limit => 60, :allow_null => false
  t.text :summary, :limit => 350, :allow_null => false
  t.integer :votes_count, :default => 0
  t.datetime :published_at, :default => nil
  t.timestamps
end

All the fields that are "NOT NULL" are validated in the model first, so I'm wondering if I need to bother having allow_null in the migration? I'm not sure what benefits "NOT NULL" gives to the database, if any.

Answer:
Not much if you mean in terms of performance or storage efficiency.  However, it's just good practice to push as many of your low-level constraints into the database layer.  For one thing, it guarantees that a subtle bug in Rails isn't going to lead to some randomly
```
NULL
```
data in a not-null field.  Likewise, if you ever run another app against the same database, it will be extremely helpful to have the constraints in a central place for maintenance and to avoid duplication.


Question:
Is there a good way to remove HTML from a Java string? A simple regex like

replaceAll("\\<.*?>", "")

will work, but some things like &amp; won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the .*? in the regex will disappear).

Answer:
If the user enters
```
<b>hey!</b>
```
, do you want to display
```
<b>hey!</b>
```
or
```
hey!
```
?  If the first, escape less-thans, and html-encode ampersands (and optionally quotes) and you're fine.  A modification to your code to implement the second option would be:
```
```
replaceAll("\\<[^>]*>","")
```
```
but you will run into issues if the user enters something malformed, like
```
<bhey!</b>
```
.
You can also check out
JTidy
which will parse "dirty" html input, and should give you a way to remove the tags, keeping the text.
The problem with trying to strip html is that browsers have very lenient parsers, more lenient than any library you can find will, so even if you do your best to strip all tags (using the replace method above, a DOM library, or JTidy), you will
still
need to make sure to encode any remaining HTML special characters to keep your output safe.


Question:
I have tried the following two statements:

SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num results in a syntax error

SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: str2" for what looks like every result. However, no results are actually returned.

I figured one of the two statements would work, but they aren't.

Answer:
```
```
SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num
```
```


Question:
I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.

I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing static and not containing final, and not ending in a {?

The last part about not ending with a { will eliminate static methods.

An example:

public class FlagOffendingStatics {
  private static String shouldBeFlagged = "not ok";
  private static final String ok = "this is fine";
  public static void methodsAreOK() {

  }
}

Answer:
Eclipse should have some sort of Java search built-in where you could specify that... Else, instead of writing one large monster regexp, try chaining together a bunch of greps:
```
grep -r static . | grep -v final
```
in the 1st statement, the -r causes the grep to recurse over a directory tree starting at the local directory, the results get piped to the 2nd grep which removes all the
```
final
```
's. Keep adding -v until everything superfluous is removed from the results. This is usually easier --albeit less elegant-- than figuring out a complicated regexp to take care of everything.


Question: I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?

Answer:
You can do this by creating an
intermediate model
for the M2M relationship and use it as your hook for the
```
post_save
```
and
```
post_delete
```
signals to update the denormalised column in the
```
Article
```
table.
For example, I do this for favourited
```
Question
```
counts in
soclone
, where
```
User
```
s have a M2M relationship with
```
Question
```
s:
```
```
from django.contrib.auth.models import User
from django.db import connection, models, transaction
from django.db.models.signals import post_delete, post_save

class Question(models.Model):
    # ...
    favourite_count = models.PositiveIntegerField(default=0)

class FavouriteQuestion(models.Model):
    question = models.ForeignKey(Question)
    user     = models.ForeignKey(User)

def update_question_favourite_count(instance, **kwargs):
    """
    Updates the favourite count for the Question related to the given
    FavouriteQuestion.
    """
    if kwargs.get('raw', False):
        return
    cursor = connection.cursor()
    cursor.execute(
        'UPDATE soclone_question SET favourite_count = ('
            'SELECT COUNT(*) from soclone_favouritequestion '
            'WHERE soclone_favouritequestion.question_id = soclone_question.id'
        ') '
        'WHERE id = %s', [instance.question_id])
    transaction.commit_unless_managed()

post_save.connect(update_question_favourite_count, sender=FavouriteQuestion)
post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)

# Very, very naughty
User.add_to_class('favourite_questions',
                  models.ManyToManyField(Question, through=FavouriteQuestion,
                                         related_name='favourited_by'))
```
```
There's been a bit of discussion on the django-developers mailing list about implementing a means of declaratively declaring denormalisations to avoid having to write code like the above:
Denormalisation, magic, and is it really that useful?
Denormalisation Magic, Round Two


Question:
I have an associative array in the form key => value where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.

I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?

Answer:
You could use a second associative array that maps human readable names to the id's.  That would also provide a Many to 1 relationship.  Then do something like this:
```
```
echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];
```
```


Question:
I am trying to download an xml.gz file from a remote server with HttpsURLConnection in java, but I am getting an empty response.  Here is a sample of my code:

URL server = new URL("https://www.myurl.com/path/sample_file.xml.gz");
HttpsURLConnection connection = (HttpsURLConnection)server.openConnection();
connection.connect();

When I try to get an InputStream from the connection, it is empty. (If I try connection.getInputStream().read() I get -1)  The file I am expecting is approximately 50MB.

To test my sanity, I aslo tried entering the exact same url in my browser, and it did return the file I needed. Am I missing something?  Do I have to set some sort of parameter in the connection?  Any help/direction is much appreciated.

Answer:
Is any exception being logged? Is the website presenting a self-signed SSL certificate, or one that is not signed by a CA? There are several reasons why it might work fine in your browser (the browser might have been told to accept self-signed certs from that domain) and not in your code.
What are the results of using
curl
or
wget
to fetch the URL?
The fact that the InputStream is empty / result from the InputStream.read() == -1 implies that there is nothing in the stream to read, meaning that the stream was not able to even be set up properly.
Update
:
See this page
for some info on how you can deal with invalid/self-signed certificates in your connection code. Or, if the site is presenting a certificate but it is invalid, you can import it into the keystore of the server to tell Java to trust the certificate.
See this page for more info
.


Question:
Does anyone have any suggestions for a good approach to finding all the CPAN dependencies that might have arisen in a bespoke development project. As tends to be the case your local development environment rarely matches your live one and as you build more and more projects you tend to build up a local library of installed modules. These then lead to you not necessarily noticing that your latest project has a requirement on a non-core module. As there is generally a requirement to package the entire project up for deployment to another group (in our case our operations team), it is important to know what modules should be included in the package.

Does anyone have any insights into the problem.

Thanks

Peter

Answer:
In the past I have used
Devel::Modlist
which is reasonably good allowing you to go
```
```
perl -d:Modlist script.pl
```
```
To get a list of the required modules.


Question:
I need to encrypt and decrypt a querystring in ASP.NET.

The querystring might look something like this:

http://www.mysite.com/report.aspx?id=12345&year=2008

How do I go about encrypting the entire querystring so that it looks something like the following?

http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a

And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?

Answer:
I can't give you a turn key solution off the top of my head, but you should avoid TripleDES since it is
not as secure as other encryption methods
.
If I were doing it, I'd just take the entire URL (domain and querystring) as a
URI object
, encrypt it with one of the
built-in .NET libraries
and supply it as the
```
crypt
```
object. When I need to decrypt it, do so, then create a new URI object, which will let you get everything back out of the original querystring.


Question:
I'm running SQL Server 2000 and I need to export the SQL Statement from all the DTS objects so that they can be parsed and put into a wiki documentation if needed.

Is there a way to do that?

maybe dumping each DTS object out into a text file with the object name as the file name with the name of the process and the date it was extracted as a file header.

thanks.

Answer:
There is an API with an object model for the DTS packages.  You can get the SQL text through this.  The Books on Line docs describe this to some extent
Here.
You can get examples of the object model usage by
Saving the DTS package to a Visual BASIC file
and looking at what the VB file does to the object model.


Question: Has anyone used jQuery to populate an autocomplete list on a textbox using ASP.NET webforms? If so, can anyone recommend a good method? From my reading so far, it seems like most people are using delimited lists rather than JSON to bring the items back. I'm open to any ideas that will get me up and running rather quickly.

Answer:
There are many, many examples on the web. I've used this one before, and if I recall you only need to create an aspx that will return matching terms as a
```
<BR/>
```
separated list:
http://www.dyve.net/jquery/?autocomplete
The documentation shows php in the example, but there's no difference in the way the plugin itself works and I didn't have to do anything special as a result.
From the documentation:
```
```
> $("#input_box").autocomplete("my_autocomplete_backend.php");
```
```
In the above example, Autocomplete
  expects an input element with the id
  "input_box" to exist. When a user
  starts typing in the input box, the
  autocompleter will request
  my_autocomplete_backend.php with a GET
  parameter named q that contains the
  current value of the input box. Let's
  assume that the user has typed
  "foo"(without quotes). Autocomplete
  will then request
  my_autocomplete_backend.php?q=foo.
The backend should output possible
  values for the autocompleter, each on
  a single line. Output cannot contain
  the pipe symbol "|", since that is
  considered a separator (more on that
  later).
An appropiate simple output would be:
  foo
  fool
  foot
  footloose
  foo fighters
  food fight


Question:
I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:

double i=1;
double sinSoFar = 0;
int term = 1;
while(i >= .000001)
{
    i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1);
    sinSoFar=sinSoFar + i;
    term++;
}

Answer:
Some advices:
Start with term = 0. The canonical MacLaurin expansion also does
compute the powers and the factorial
while you are cycling
(that is, updating them at each step). Maybe the problem is within pow() or factorial().
EDIT. Suggestion: once you have computed the k-th term, you can compute the (k+1)-th one by:
Multiplying by (-1)
Multiplying by sinOf^2
Dividing by (2k+2)(2k+3)
In this way you can completely
avoid
the computation of powers and factorials.


Question:
I have seen some websites use the following tag:

<meta type="title" content="Title of the page" />

Is it needed when you have a <title>?

Also, what's the best formatting for a page title? Some ideas:

Page Description :: Company Name

Page Description - Company Name

Page Description <> Company Name

Company Name: Page Description

...

Does it matter to Google/Yahoo/etc? Do you include the company name or a general description of the site in the title on every page?

Answer:
Search engines often ignore meta tags as in the past they where used for spamming purposes. The best tag for title is precisely
```
<title>
```
.
As the best formatting for the title there is no best recipe, but instead try to make the title as descriptive as possible of the real contents of the page.


Question:
I've got a series of GIFs that I need to crop on the fly, I'm using a HTTP Handler in C# so I can better encapsulate the code - provide caching for the result etc.

Currently, when I draw the existing image to a new Image via the Graphics object all the transparency is lost.

I've tried various techniques to try and maintain the transparency, but to no avail.

Things I've tried:

Using the MakeTransparent (Color) method call

Using the ImageAttriutes with a combination of ColorMap and SetColorKey

I don't really want to start using unsafe operators or Win32 calls.

Any ideas?

Answer:
When I have used transparency I've always used
```
Bitmap
```
. I.e.
```
```
System.Drawing.Image SourceImage = System.Drawing.Image.FromFile("the.gif");
System.Drawing.Bitmap NewImage = new System.Drawing.Bitmap(SourceImage);
// Do Processing
NewImage.MakeTransparent();
// Store changes
NewImage.Save(..., System.Drawing.Imaging.ImageFormat.Png);
```
```
Of course if you cannot move away from the
```
Graphics
```
object then that may not be of much use.


Question:
I have a 4 side convex Polygon defined by 4 points in 2D, and I want to be able to generate random points inside it.

If it really simplifies the problem, I can limit the polygon to a parallelogram, but a more general answer is preferred.

Generating random points until one is inside the polygon wouldn't work because it's really unpredictable the time it takes.

Answer:
A. If you can restrict your input to parallelogram, this is really simple:
Take two random numbers between 0 and 1. We'll call then
```
u
```
and
```
v
```
.
If your parallelogram is defined by the points ABCD such that AB, BC, CD and DA are the sides, then take your point as being:
```
```
p = A + (u * AB) + (v * AD)
```
```
Where
```
AB
```
is the vector from A to B and
```
AD
```
the vector from A to D.
B. Now, if you cannot, you can still use the barycentric coordinates. The barycentric coordinates correspond, for a quad, to 4 coordinates
```
(a,b,c,d)
```
such that
```
a+b+c+d=1
```
. Then, any point
```
P
```
within the quad can be described by a 4-uple such that:
```
```
P = a A + b B + c C + d D
```
```
In your case, you can draw 4 random numbers and normalize them so that they add up to 1. That will give you a point. Note that the distribution of points will NOT be uniform in that case.
C. You can also, as proposed elsewhere, decompose the quad into two triangles and use the half-parallelogram method (i.e., as the parallelogram but you add the condition
```
u+v=1
```
) or the barycentric coordinates for triangles. However, if you want uniform distribution, the probability of having a point in one of the triangle must be equal to the area of the triangle divided by the area of the quad.


Question:
Can I call a stored procedure in Oracle via a database link?

The database link is functional so that syntax such as...

SELECT * FROM myTable@myRemoteDB

is functioning.  But is there a syntax for...

EXECUTE mySchema.myPackage.myProcedure('someParameter')@myRemoteDB

Answer:
The syntax is
```
```
EXEC mySchema.myPackage.myProcedure@myRemoteDB( 'someParameter' );
```
```


Question:
I'm currently working on a project where a section of the code looks like this:

Select Case oReader.Name
    Case "NameExample1"
        Me.Elements.NameExample1.Value = oReader.ReadString
        ' ...
    Case "NameExampleN"
        Me.Elements.NameExampleN.Value = oReader.ReadString
        ' ...
End Select

It continues on for a while. The code is obviously verbose and it feels like it could be improved. Is there any way to dynamically invoke a property in VB.NET such that something like this can be done:

Dim sReadString As String = oReader.ReadString
Me.Elements.InvokeProperty(sReadString).Value = sReadString

Answer:
Others have answered perfectly reasonably, but just in case this is a performance-sensitive piece of code, you might want to compile the reflective calls into delegates.
I've got a
blog entry
about turning
MethodBase.Invoke
into delegates. The code is in C#, but the same technique can be applied to VB.NET as well. To use this with properties, get the appropriate "setter" method with
PropertyInfo.GetSetMethod
and then build a delegate which invokes that. You could have a map from field name to "delegate to call to set the field".
Just to reiterate, this is only really necessary if it's in a performance-critical piece of code. Otherwise, you might still want to create a
```
Dictionary<string, PropertyInfo>
```
to avoid calling
```
GetProperty
```
many times, but the step to convert it into a delegate probably isn't worth worrying about.


Question:
So in a .NET app , i got about 2 million items that i need to hold them in memory for processing , 1 by 1, would holding these items in a Stack collection , is better than holding them in a List collection, assuming that the memory used by the stack object will be keep minimizing every time an item is poped out of the stack object , or the memory allocated by the stack will keep the same till the stack is set to null, or cleared.

sorry if i couldn't express the question in the right way.. but here is another way, when a Stack collection is used, does the memory used by the stack get minimized every time an item is pulled out of the stack.

Thanks in advance

Answer:
They'll basically be the same for
```
Stack<T>
```
if you definitely want FILO behaviour - because when you remove an element from the end of a
```
List<T>
```
it doesn't need to copy anything.
Now if you were talking about a
```
Queue<T>
```
that would be different - removing from the
head
of a
```
List<T>
```
involves copying the rest of the items, which is inefficient.
The actual memory usage will be the same for either of them - I don't believe either
```
List<T>
```
or
```
Stack<T>
```
automatically "trim to size" when elements are removed.


Question:
When you have a derived class, is there an simpler way to refer to a variable from a method other than:

BaseClass::variable

EDIT

As it so happens, I found a page that explained this issue using functions instead:
Template-Derived-Classes Errors. Apparently it makes a difference when using templates classes.

Answer:
If the base class member variable is protected or public than you can just refer to it by name in any member function of the derived class.  If it is private to the base class the compiler will not let the derived class access it at all.  Example:
```
```
class Base
{
protected:
  int a;

private:
  int b;
};

class Derived : public Base
{
  void foo()
  {
    a = 5;  // works
    b = 10; // error!
  }
};
```
```
There is also something to be said for keeping all member variables private, and providing getters and setters as needed.
Also, beware of "hiding" data members:
```
```
class Base
{
public:
  int a;
};

class Derived : public Base
{
public:
  int a;
};
```
```
This will create two variables named
```
a
```
: one in
```
Base
```
, one in
```
Derived
```
, and it will likely lead to confusion and bugs.


Question:
From the MSDN documentation:

"Synchronized supports multiple writing threads, provided that no threads are reading the Hashtable. The synchronized wrapper does not provide thread-safe access in the case of one or more readers and one or more writers."

Source:
http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized.aspx

It sounds like I still have to use locks anyways, so my question is why would we use Hashtable.Synchronized at all?

Answer:
For the same reason there are different levels of DB transaction.  You may care that writes are guaranteed, but not mind reading stale/possibly bad data.
EDIT
I note that their specific example is an Enumerator.  They can't handle this case in their wrapper, because if you break from the enumeration early, the wrapper class would have no way to know that it can release its lock.
Think instead of the case of a counter.  Multiple threads can increase a value in the table, and you want to display the value of the count.  It doesn't matter if you display 1,200,453 and the count is actually 1,200,454 - you just need it close.  However, you don't want the data to be corrupt.  This is a case where thread-safety is important for writes, but not reads.


Question:
Is there some way to get a value from the last inserted row?

I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.

I am using Java with a JDBC and PostgreSQL.

Answer:
The sequences in postgresql are transaction safe. So you can use the
```
```
currval(sequence)
```
```
Quote:
currval
Return the value most recently obtained by nextval for this sequence
    in the current session. (An error is
    reported if nextval has never been
    called for this sequence in this
    session.) Notice that because this is
    returning a session-local value, it
    gives a predictable answer even if
    other sessions are executing nextval
    meanwhile.


Question:
I have a rich-text editor on my site that I'm trying to protect against XSS attacks. I think I have pretty much everything handled, but I'm still unsure about what to do with images. Right now I'm using the following regex to validate image URLs, which I'm assuming will block inline javascript XSS attacks:

"https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+"

What I'm not sure of is how open this leaves me to XSS attacks from the remote image. Is linking to an external image a serious security threat?

The only thing I can think of is that the URL entered references a resource that returns "text/javascript" as its MIME type instead of some sort of image, and that javascript is then executed.

Is that possible? Is there any other security threat I should consider?

Answer: Another thing to worry about is that you can easily embed PHP code inside an image and upload that most of the time. The only thing an attack would then have to be able to do is find a way to include the image. (Only the PHP code will get executed, the rest is just echoed). Check the MIME-type won't help you with this because the attacker can easily just upload an image with the correct first few bytes, followed by arbitrary PHP code. (The same is somewhat true for HTML and Javascript code).


Question: Im just starting a project and since this project is personal I was wondering what are the advantages of using Enterprise Library? We use the version 2 for several projects in the office but im not quite sure (aside of the good practices) of the advantages of it, especially in the database component. Any advice? Thanks

Answer:
For the database application block, the main advantage is that it makes it easier to produce database-agnostic code. The developer interacts mainly with generic Database and DbCommand objects, rather than eg SqlConnection, SqlCommand, etc.  Thus, switching to a different database (ie Oracle) becomes more feasible. Depending on your business needs, this could be a definite advantage.  EntLib also gently prods the developer in the direction of using DbParameter for query parameters, which reduces the risk of SQL injection attacks.
As another poster mentionned, the data app block is somewhat higher-level than the straight ADO.NET classes, so it tends to require fewer lines of code to do the same thing.
From my point of view, the data, exception and logging blocks are the most useful.  Exception and Logging together make it very easy to log exceptions (duh) to a number of places and in a number of formats.  For example, they can put the entire exception log entry, including the stack trace, in the Windows event log making it relatively easy to diagnose a problem.
One disadvantage of EntLib is that some app blocks place quite a bit of logic into configuration files.  So your logic is more spread out; some of it is in code, some in config files.  The upside is that the configuration can be modified post-build and even post-deployment.


Question:
I have a DataGridView with one DataGridViewComboBoxColumn in my WinForms application. I need to drop down (open) this DataGridViewComboBoxColumn manually, let's say after a button is clicked.

The reason I need this is I have set SelectionMode to FullRowSelect and I need to click 2-3 times to open the combo box. I want to click on the combobox cell and it should drop down immediately. I want to do this with CellClick event, or is there any other way?

I am searching in Google and VS help, but I haven't found any information yet.

Can anybody help please?

Answer:
I know this can't be the ideal solution but it does create a single click combo box that works within the cell.
```
```
Private Sub cell_Click(ByVal sender As System.Object, ByVal e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        DataGridView1.BeginEdit(True)
        If DataGridView1.Rows(e.RowIndex).Cells(ddl.Name).Selected = True Then
            DirectCast(DataGridView1.EditingControl, DataGridViewComboBoxEditingControl).DroppedDown = True
        End If
    End Sub
```
```
where "ddl" is the combobox cell I added in the gridview.


Question:
I recently introduced HTML into some RSS feeds that I publish (which up to now only had plain text, no markup), and I was wondering which method is better: use character encoding (such as htmlspecialchars) or just encapsulate everything in CDATA?

It seems to me that CDATA might be easier, but I'm unclear as to whether there might be any reasons (subtle or otherwise) for choosing one approach versus the other. (For starters, the CDATA approach would be easier to read when viewing source...)

Answer:
At the risk of giving you the answer you may not want to hear: use
Atom
instead of
RSS.
Atom is nicely namespaced XML, so you can mix and match XHTML right in, without having to worry about the encoding issue you ask about.
It's pretty much supported everywhere RSS is, and because it's just vanilla Atom, it's easier to roll your own if you really don't want to use a library to manipulate it.
Atom is also a IETF standard, which RSS isn't.


Question:
I've got a workspace with multiple RCP plugin projects.

We've set the target platform, so we can build against a standard set of plugins, but are not able to see source code and Javadoc for all the platform plugins.

The Windows -> Preferences -> Plug-in Development -> Target Platform -> Source Code Locations page doesn't seem to have any effect when I add the eclipse directory (it only allows you to add directories).

Copying the source jars from the eclipse directory into the target platform has a similar effect.

What am I doing wrong? How do I attach a set of Source jars to my target platform?

Answer:
I can modify the target platform at runtime, using the
```
-install
```
runtime option. Keep the targetPlatform as the eclipse platform.
However, this loses a lot of the benefits of using a target platform in the first place - i.e. compile time safety.


Question:
I was recently working with a DateTime object, and wrote something like this:

DateTime dt = DateTime.Now;
dt.AddDays(1);
return dt; // still today's date! WTF?

The intellisense documentation for AddDays() says it adds a day to the date, which it doesn't - it actually returns a date with a day added to it, so you have to write it like:

DateTime dt = DateTime.Now;
dt = dt.AddDays(1);
return dt; // tomorrow's date

This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.

Answer:
I saw this one posted the other day, and I think it is pretty obscure, and painful for those that don't know
```
```
int x = 0;
x = x++;
return x;
```
```
As that will return 0 and not 1 as most would expect


Question:
How do you create a simple, custom rule using the jQuery Validate plugin (using addMethod) that doesn't use a regex?

For example, what function would create a rule that validates only if at least one of a group of checkboxes is checked?

Answer:
You can create a simple rule by doing something like this:
```
```
jQuery.validator.addMethod("greaterThanZero", function(value, element) {
    return this.optional(element) || (parseFloat(value) > 0);
}, "* Amount must be greater than zero");
```
```
And then applying this like so:
```
```
$('validatorElement').validate({
    rules : {
        amount : { greaterThanZero : true }
    }
});
```
```
Just change the contents of the 'addMethod' to validate your checkboxes.


Question:
I want to filter the selectable dates on a datepicker. I basically need to filter by work days - i.e. make holidays and weekends not selectable.

I know you can specify dates using a function in the beforeShowDate: and you can also use $.datepicker.noWeekends.

Question is: can you do both?

Answer:
$.datepicker.noWeekends is a pretty simple bit of code:
```
```
function (date) {
    var day = date.getDay();
    return [day > 0 && day < 6, ""];
}
```
```
Since you're going to have to write up the function for holidays, you can just include this logic in that function too.


Question:
Is there anything built into Windows and the .Net framework for programmatically installing and executing applications remotely? Ie: an API for remote software deployment. I'd like to build a tool that can install services on a pool of new computers from one central admin workstation.

Update: The computers are part of an internal IT network, and the applications and services are mostly internally developed. The deployment program would be completely internal, and not sold commercially.

Answer:
All of the pieces are there (copying files to a remote machine, spawning a process on a remote machine, etc.) You will be looking at a fair amount of programming to put it all together into a robust application. You will also need to make sure the clients are configured properly and safely. Naively configuring the client to allow you to do this would most likely wind up with massive security holes on your client machines. I would suggest looking at SMS or one of the many similar third party apps. At the very least even if you can't afford to use an already written app (highly recommend that you do) then you could look at their feature lists to get an idea of what sort of issues you need to be thinking about.
With the further provided information, I would ask if you are using Group Policies in your environment. If you are, then you may be able to package your application as an MSI then deploy via policy.


Question:
Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?

Thanks!

Answer:
There's no such thing as "the" xpath of a node. For any given node there may well be many xpath expressions which will match it.
You can probably work up the tree to build up
an
expression which will match it, taking into account the index of particular elements etc, but it's not going to be terribly nice code.
Why do you need this? There may be a better solution.


Question:
My boss is bidding on a project to convert a desktop application into one that runs online as a client-server application. The original app has a little more than a quarter of a million lines of C++ (MFC) code that's not cleanly divided between engine and front-end.

I need to come up with estimates of how long it will take and how many people would be needed for such a project. We don't have anyone on staff capable of doing this project, and we don't have any Windows machines, so we'd have to subcontract/outsource.

Alternatively, what arguments can I use to convince my boss that this project is a bad idea?

Answer:
Without a clear division between the engine and the front-end, it's a bad idea. Giving over the code to a contractor or such would require a large amount of training just to understand the code, including parts that are meant to be rewritten as web apps.
You would first need to estimate how long it would take to clearly define that boundary, and then you can work out how long the rest of the project would take. That way you can train the contractor etc. on the parts that relate to the presentation tier and the API for the engine without explaining how the engine works (which should be irrelevant to the presentation components).


Question:
Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate.

Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager_id (parent_id) would be a good approximation of the problem I am solving.

In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect).

Answer:
There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).
I wrote a
tutorial
on what's going on under the hood.
You can also reference the official docs on
model inheritance
.


Question: In Team Foundation Server is there a way to have work items in one project linked to other projects so they show up in the reports in both. We are thinking about keeping release engineering items in their own project and want them linked to the project they are actaully for as well. Is this possible? So for instance I would create the item under release engineering assign it to an engineer and then link it to Product X so it showed up as a work item for Project X as well.

Answer:
Not out of the box as projects are discrete.  However there is nothing to stop you from writing against the API to fulfill this need, although this would take some considerable work.
Now for the good news.  If you keep your eyes
here
, you may find the answer in time.  As I see cross project reports are planned in
Rosario


Question:
I'm looking for Python code that removes C and C++ comments from a string. (Assume the string contains an entire C source file.)

I realize that I could .match() substrings with a Regex, but that doesn't solve nesting /*, or having a // inside a /* */.

Ideally, I would prefer a non-naive implementation that properly handles awkward cases.

Answer:
C (and C++) comments cannot be nested. Regular expressions work well:
```
```
//.*?\n|/\*.*?\*/
```
```
This requires the “Single line” flag (
```
Re.S
```
) because a C comment can span multiple lines.
```
```
def stripcomments(text):
    return re.sub('//.*?\n|/\*.*?\*/', '', text, flags=re.S)
```
```
This code should work.
/EDIT: Notice that my above code actually makes an assumption about line endings! This code won't work on a Mac text file. However, this can be amended relatively easily:
```
```
//.*?(\r\n?|\n)|/\*.*?\*/
```
```
This regular expression should work on all text files, regardless of their line endings (covers Windows, Unix and Mac line endings).
/EDIT: MizardX and Brian (in the comments) made a valid remark about the handling of strings. I completely forgot about that because the above regex is plucked from a parsing module that has additional handling for strings. MizardX's solution should work very well but it only handles double-quoted strings.


Question:
I'm looking at the following code snippet:

my @ret = <someMethod>
return (undef) if( $DB_ERROR );
return (undef) unless ($#ret >= 0);

Does $# just give you a count of elements in a array?

Answer:
```
$#arrayname
```
gives you the index of the last element, so if array
```
@ret
```
has 2 elements then
```
$#ret
```
is 1.
And, as noted by Barry Brown, an empty array gives -1.
To get the length you can use the array in scalar context:
```
```
print scalar @ret;
```
```


Question:
I'm wanting to add a class to the body tag without waiting for the DOM to load, but I'm wanting to know if the following approach would be valid. I'm more concerned with validity than whether the browsers support it for now.

<body>
  $("body").addClass("active");
  ...
</body>

Thanks,
Steve

Answer:
If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied.   If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced.  I believe this will work.
```
```

```
```
If you need to add the class to the body, I would definitely use $(document).ready().


Question:
How do I get a list of domain user accounts with win32 api?

In particular, I can't get this list when the computer is not the domain controller.  Instead it is a member of the domain.

Answer:
If the element doesn't exist in the DOM, the search will fail to find it and the action won't be applied.   If you can't do it in the $(document).ready() function, you might want to try putting the code after the element being referenced.  I believe this will work.
```
```

```
```
If you need to add the class to the body, I would definitely use $(document).ready().


Question:
I have a string that I need to convert to the equivalent array of bytes in .NET.

This ought to be easy, but I am having a brain cramp.

Answer:
You need to use an encoding
(
```
System.Text.Encoding
```
) to tell .NET what you expect as the output. For example, in
UTF-16 (=
```
System.Text.Encoding.Unicode
```
)
:
```
```
var result = System.Text.Encoding.Unicode.GetBytes(text);
```
```


Question:
For this xml (in a SQL 2005 XML column):

<doc>
 <a>1</a>
 <b ba="1" bb="2" bc="3" />
 <c bd="3"/>
<doc>

I'd like to be able to retrieve the names of the attributes (ba, bb, bc, bd) rather than the values inside SQL Server 2005. Well, XPath certainly allows this with name() but SQL doesn't support that. This is my chief complaint with using XML in SQL; you have to figure out which parts of the XML/Xpath/XQuery spec are in there.

The only way I can think of to do this is to build a CLR proc that loads the XML into an XML Document (iirc) and runs the XPath to extract the names of the nodes. I'm open to suggestions here.

Answer:
```
```
DECLARE @xml as xml
DECLARE @path as varchar(max)
DECLARE @index int, @count int

SET @xml =
'<doc>
 1

 <c bd="3"/>
</doc>'

SELECT @index = 1

SET @count = @xml.query('count(/doc/b/@*)').value('.','int')

WHILE @index <= @count
BEGIN
    SELECT  @xml.value('local-name((/doc/b/@*[sql:variable("@index")])[1])', 'varchar(max)')
    SET @index = @index + 1
END
```
```
for element 'b'
it returns
ba
bb
bc
You can build a loop to get attributes for each element in the xml.
BTW
The XML in your sample should be closed at closing doc tag.


Question: I'm also interested in other Symbian SDKs that allow to set their emulator's IMEI.

Answer:
I have never actually tried that but here's my best guess:
The emulator doesn't have a proper telephony implementation unless:
you link it to an actual phone over infrared/usb/serial. In which case the emulator telephony component will need configuration to use AT commands to pilot the phone (even if the phone isn't a Symbian phone). This allows you to make phone calls, send and receive SMS/MMS but certainly not change the IMEI.
you use the SIMTSY module. This is a component that uses configuration files to simulate telephony events. It can pretend to send SMS/MMS, pretend you are receiving a phone call...none of that actually creates any kind of network traffic, you understand. I assume the IMEI is in the configuration file but I don't expect you can properly change it  without restarting the emulator. I have never seen SIMTSY used outside of Symbian itself so I don't know whether it is available to third-party developer. It should be open-sourced with the rest of the operating system within the next 2 years, though.
There is also the possibility that the way the SDK itself was built disabled most of the telephony framework for the emulator, using build-time macro. You should check
http://forum.nokia.com


Question:
What is the best way to manage a database connection in a Java servlet?

Currently, I simply open a connection in the init() function, and then close it in destroy().

However, I am concerned that "permanently" holding onto a database connection could be a bad thing.

Is this the correct way to handle this?  If not, what are some better options?

edit: to give a bit more clarification: I have tried simply opening/closing a new connection for each request, but with testing I've seen performance issues due to creating too many connections.

Is there any value in sharing a connection over multiple requests?   The requests for this application are almost all "read-only" and come fairly rapidly (although the data requested is fairly small).

Answer:
You should only hold a database connection open for as long as you need it, which dependent on what you're doing is probably within the scope of your
```
doGet/doPost
```
methods.


Question:
As title.  I didn't find one via google, at any rate.

Update: thanks for the links from the two answers; this is very useful, but not what I was after - I am curious to see whether it is possible to query an IRepository backed by memcached (or some other distributed cache), backed by a RDBMS.  I've really no idea how that might work in practise; I don't know very much about the internals of either distributed caches or LINQ providers.

I'm maybe envisaging something like the cache LINQ provider generating cache-keys based on the query automatically (where query could be Expression> or some kind of Specification pattern implementation), and basically can be plumped down inbetween my app and my DB.  Does that sound useful?

Answer:
If you don't mind throwing
NHibernate
between them, you can use
LINQ to NHibernate
to query entities which
can be set
to use
memcached
as their cache.


Question:
I think the title pretty much says it all... I'm looking to implement an interface similar to the standard OS X sidebar used in all the above mentioned programs, and I'm wondering if anybody has any thoughts as to the easiest way to do it, namely about what view to use for the left hand selection pane. Really I don't think I even need the hierarchical component as seen in the apple apps, I just need a good looking flat list of choices which determine what's shown in the right hand pane.

The obvious start is a vertical split layout view, but beyond that I'm not entirely sure where to go. A collection view with only one column or something like that?

Answer:
I've done a few applications that use a similar setup.
I generally use an NSSplitView, with a single column NSTableView in the left pane.  Don't forget to disable the headers, and make it display as a "Source View" style.
If you want the disclosure triangles, then you'll want to use NSOutlineView instead of NSTableView, but at least for the first go, I'd stick to a simple NSTableView.
A pattern I also use is to make the NSTableView slightly shorter than the NSSplitView, and have buttons at the bottom (add, delete, etc).  I've usually built the program around Core Data, so it's easy to hook up these to methods to create/delete objects, and then bind the NSTableView to the array of objects.


Question:
My HTML is as follows:

<ul id="nav">
    <li><a href="./">Home</a></li>
    <li><a href="/About">About</a></li>
    <li><a href="/Contact">Contact</a></li>
</ul>

And my css:

#nav {
    display: inline;
}

However the whitespace between the li's shows up. I can remove the whitespace by collapsing them like so:

<ul id="nav">
    <li><a href="./">Home</a></li><li><a href="/About">About</a></li><li><a href="/Contact">Contact</a></li>
</ul>

But this is being maintained largely by hand and I was wondering if there was a cleaner way of doing it.

Answer:
Several options here, first I'll give you my normal practice when creating inline lists:
```
```

Home

Home

Home

```
```
Then the CSS to make it function as you intend:
```
```
#navigation li
  {
    display: inline;
    list-style: none;
  }
#navigation li a, #navigation li a:link, #navigation li a:visited
  {
    display: block;
    padding: 2px 5px 2px 5px;
    float: left;
    margin: 0 5px 0 0;
  }
```
```
Obviously I left out the hover and active sets, but this creates a nice block level navigation, and is a very common method for doing this while still keeping with standards. /* remember to tweak to your liking, add color to the background, et cetera */
If you would like to keep it just with text and just inline, no block elements I believe you'd want to add:
```
```
margin: 0 5px 0 0; /* that's, top 0, right 5px, bottom 0, left 0 */
```
```
Realizing you would like to REMOVE the whitespace, just adjust the margins/padding accordingly.


Question:
I want to write a program that would print every combination of a set of variables to a text file, creating a word list. Each answer should be written on a separate line and write all of the results for 1 digit, 2 digits, and 3 digits to a single text file.

Is there a simple way I can write a python program that can accomplish this? Here is an example of the output I am expecting when printing all the binary number combinations possible for 1, 2, and 3 digits:

Output:
0
1

00
01
10
11

000
001
010
011
100
101
110
111

Answer:
It shouldn't be too hard in most languages.  Does the following pseudo-code help?
```
```
for(int i=0; i < 2^digits; i++)
{
     WriteLine(ToBinaryString(i));
}
```
```


Question:
I just started creating my data-access layer using LinqToSql. Everybody is talking about the cool syntax and I really like Linq in general.

But when I saw how your classes get generated if you drag some tables on the LinqContext I was amazed: So much code which nobody would need?!

So I looked how other people used LinqToSql, for example Rob Connery at his StoreFront Demo.

As I don't like the way that all this code is generated I created my domain layer by hand and used the generated classes as reference. With that solution I'm fine, as I can use the features provided by Linq (dereferred execution, lazy loading, ...) and my domain layer is quite easy to understand.

How are you using LinqToSql?

Answer:
The created classes are not as heavy as it seems. Of course it takes quite a few lines of code, but all in all it is as lightweight as it can be for the features it's providing.
I used to create my own tables, too, but now instead I just use the LINQtoSQL DataContext. Why? Creating is simpler, the features are better, interoperability works, it is probably even faster than my own stuff (not in every aspect. Usually my own stuff was extremely fast in one thing, but the generic stuff was faster in everything else).
But the most important part: it is easier to bring new developers into the LINQ stuff than into my own. There are tutorials, example codes, documentation, everything, which I'd have to create for my code by myself. Same with using my stuff with other technology, like WCF or data binding. There are a lot of pitfalls to be taken care of.
I learned not to develop myself into a corner the hard way, it looks fast and easy at the start, is a lot more fun than learning how to use the libs, but is a real pain in the a after a few months down the road, usually even for myself.
After some time the novelty of creating my own data containers wears off, and I noticed the pain connected to adding a feature. A feature I would have had for free, if I had used the provided classes.
Next thing I had to explain my code to some other programmer. Had I used the provided classes, I could have pointed him to some web site to learn about the stuff. But for my classes, I had to train him himself, which took a long time and made it hard to get new people on a project.


Question: I'm a little unsure how the open source licensing stuff works.  If I were to choose a particular open source license, what do you actually have to do to make it applicable to your software?  I would imagine it would be a little more involved than just 'stating' that you're releasing your software under LGPL.  And how does this 'contract' bind legally to your software?

Answer:
It's as simple as deciding to license your software under a particular license.  This is not technically contract law, but copyright law.  As the owner/licenser of your intellectual property (the source and binaries) you may license its distribution anyway you see fit.  Providing a clear disclaimer as to the recipients rights under the license is all that is necessary.  Without a license, whether closed or open, no one has a right to distribute your copyrighted work.  The purpose of all licenses is to grant some of your rights to other parties.
See here
for more information.  Or for perhaps too much information, check out O'Reilly's
Understanding Open Source and Free Software Licensing
.
~ William Riley-Land


Question: What are some good jQuery Resources along with some gotchas when using it with ASP.Net?

Answer:
ASP.Net's autogenerated id's make using jQuery's selector syntax somewhat difficult.
Two easy ways around this problem:
Search for objects using css class instead of id
You can weed out the uniqueid garbage with:
```
$('[id$=myid]')
```


Question: Is there anyway to automatically run javascript:window.print() when the page finishes loading?

Answer:
```
<body onload="window.print()">
```
or
```
window.onload = function() { window.print(); }
```


Question:
Our testers are in the process of evaluating Visual Studio Team System 2008 Test Edition. As they are unfamiliar with the use of Visual Studio, I would like to give them as much help as I can.

I have had a look on Amazon for books on the Test edition of VS.Net, but there is only one VS.Net 2005 test edition book.

Does anyone know of any good books, or online training resources with a particular focus on the features of the Test Edition of Visual Studio Team System 2008?

Answer:
For someone evaluating features who isn't that familiar with Visual Studio, I'd recommend the videos from a few places:
"How Do I?" Videos for Team System
ASP.net's Learn section
Video tutorials at TeamSystemRocks.com
Plenty of videos between those sites on the various VSTS Test Edition features.  Note that many are about VS2005, but the fundamental concepts don't change when moving to 2008.
Once they get the basic features, here's a summary of
What's New in VS2008 Test Edition
.
See also:
VSTS 2008 Test Edition Home
(BTW, there's a link to a trial VPC w/TFS & VSTS Suite on the right-hand side)
Visual Studio 2008 Training Kit
- Not a lot on VSTS in here, but there are a few demos and resources that touch on the Test features, and it's a good general resource to have, anyway.


Question: If I import a library to use a method, would it be worth it? Does importing take up a lot of memory?

Answer:
Importing such a module is not likely to cost that much memory that you should refrain from it, though in this case probably a simple hash would be just as good. Something like
```
```
my %number_for = (
    jan => 1,
    feb => 2,
#etc...
);
#...
do_something_with($number_for{$month})
```
```


Question:
I have the Profile, CCK, and Views2 modules installed on a Drupal 6 site.  I added a string field to the user profile.  I can filter easily on preset values, thru the Views GUI builder, really nicely.  However, I'd like the filter criteria to be dynamically set based on other environment variables (namely the $_SERVER['SERVER_NAME']).

Is there a basic 'How-to-write-a-custom-drupal-views-filter' somewhere out there?  I've been looking thru the documentation, but it's not obvious to my simple mind on how to do it.

Answer:
There is the possibility, having looked at the sort of filters installed for my own site, that filters have to be based on some database field, in which case what you're trying to achieve is not possible.  It appears that the filters provide the WHERE clause to the generated SQL query.
Having said all that, if you want to pursue it further, your best bet is to start with a module that already provides filters for Views.  There are filters provided with Views for the Node module; alternatively, you could look at the
audio module
which also provides some filters.  Additionally, posting to the Drupal forums or support list may turn up another module that will allow you to achieve what you're attempting.


Question:
I have a few questions about whether or not it would be best to not use indexing.

BACKGROUND:
My records have a timestamp attribute, and the records will be inserted in order of their timestamps (i.e., inserted chronologically).

QUESTIONS:

If I DON'T use indexing is it typical for the database to insert the records in the order that they were inserted?

If answer to #1 is yes, when I do a "SELECT .. WHERE timestamp > X" type query will the database be efficient at it, or will it have to go through every single record since it isn't indexed?  I would assume if there were no index, the database would not "know" that the records were inserted in sorted order and could not, therefore, make use of sorted property of the database.

I assume a clustered index would be best for these types of records & their inserts.

Please let me know what you guys think.

Thanks,
jbu

Answer:
In my experience, yes, the database will insert stuff in the chronological order, especially if you never delete anything.  However, it is not guaranteed, and it's a really bad idea to try to rely on behaviour that is not guaranteed.
Also, the query planner isn't going to know this fact, so any query you do without an index will cause a full table scan.  Whether that's slower than an indexed query will depend a lot on what sort of data you have, and what percentage of it comes after the "X" in your query.


Question:
$fp_src=fopen('file','r');

$filter = stream_filter_prepend($fp_src, 'convert.iconv.ISO-8859-1/UTF-8');

while(fread($fp_src,4096)){
    ++$count;
    if($count%1000==0) print ftell($fp_src)."\n";
}

When I run this the script ends up consuming ~ 200 MB of RAM after going through just 35MB of the file.

Running it without the stream_filter zips right through with a constant memory footprint of ~10 MB.

What gives?

Answer:
From what I'm reading
here
, you are not implementing
```
stream_filter_prepend()
```
correctly, although there could be something I misunderstand about the process.
Als, I'm not totally sure, but I'm willing to bet that this has more to do with the fact that iconv is an expensive process, and less to do with the fact that you're using it as stream filter.
Good luck.


Question:
if(!eregi("^([0-9a-z_\[\]\*\- ])+$", $subuser))
    $form->setError($field, "* Username not alphanumeric");

Can anybody tell me why it is not allowing characters such as - and *?

if(!eregi("^([0-9a-z])+$", $subuser))
    $form->setError($field, "* Username not alphanumeric");

That is the original piece of code. A friend changed it to the top piece and it will allow a-z and 0-9 but it wont allow the other characters I need it to. Can anyone help me?

Thanks in advance.

Answer:
Your regex uses PCRE syntax, so you have to use preg_match() instead of eregi().
Try this code instead:
```
```
else if (!preg_match("/^([0-9a-z_\[\]* -])+$/i", $subuser)) {
$form->setError($field, "* Username not alphanumeric");
}
```
```


Question:
I am writing PHP code where I want to pass the session id myself using POST. I don't want a cookie to store the session, as it should get lost when the user gets out of the POST cycle.

PHP automatically sets the cookie where available. I learned it is possible to change this behaviour by setting session.use_cookies to 0 in php.ini. Unfortunately, I don't have access to that file and I also wouldn't want to break the behaviour of other scripts running on the same server.

Is there a way to disable or void the session cookie inside the PHP script?

EDIT: As the proposed solutions don't work for me, I used $_SESSION = array() at positions in the code where I found the session should be invalidated.

Answer:
Use
ini_set()
:
```
```
ini_set('session.use_cookies', '0');
```
```
Or in your php.ini file:
```
```
session.use_cookies = 0
```
```


Question:
If I had the following select, and did not know the value to use to select an item in advance like in this question or the index of the item I wanted selected, how could I select one of the options with jQuery if I did know the text value like Option C?

<select id='list'>
<option value='45'>Option A</option>
<option value='23'>Option B</option>
<option value='17'>Option C</option>
</select>

Answer:
```
```
var option;
$('#list option').each(function() {
    if($(this).text() == 'Option C') {
        option = this;
        return false;
    }
});
```
```


Question:
In a database prototype, I have a set of fields (like name, description, status) that are required in multiple, functionally different tables.

These fields always have the same end user functionality for labeling, display, search, filtering etc. They are not part of a foreign key constraint. How should this be modeled?

I can think of the following variants:

Each table gets all these attributes. In this case, how would you name them? The same, in each table, or with a table name prefix (like usrName, prodName)

Move them into a table Attributes, add a foreign key to the "core" tables, referencing Attributes.PK

As above, but instead of a foreign key, use the Attributes.PK as PK in the respective core table as well.

Answer:
Normalisation is often best practice in any relational database (within reason).
If you have fields like state (meaning the state within a country), then a reference table like "State" with (id, short_name, long_name etc...) might be the way to go, then each record that references a state only need a state_id column which, as you did mention, is a reference to a record in the State table.
However, in some instances normalisation of all data is not necessarily required as it just complicates things, but it should be obvious where to do it and where not to do it.
Hope this helps.


Question:
In VB6 you can do this:

Dim a As Variant
a = Array(1, 2, 3)

Can you do a similar thing in VB.NET with specific types, like so?:

Dim a() As Integer
a = Array(1, 2, 3)

Answer:
```
```
Dim a() As Integer = New Integer() {1, 2, 3}
```
```


Question:
I'm trying to parse an international datetime string similar to:

24-okt-08 21:09:06 CEST

So far I've got something like:

CultureInfo culture = CultureInfo.CreateSpecificCulture("nl-BE");
DateTime dt = DateTime.ParseExact("24-okt-08 21:09:06 CEST",
    "dd-MMM-yy HH:mm:ss ...", culture);

The problem is what should I use for the '...' in the format string? Looking at the Custom Date and Time Format String MSDN page doesn't seem to list a format string for parsing timezones in PST/CEST/GMT/UTC form.

Answer:
AFAIK the time zone abbreviations are not recognized. However if you replace the abbreviation with the time zone offset, it will be OK. E.g.:
```
```
DateTime dt1 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+2"), "dd-MMM-yy HH:mm:ss z", culture);
DateTime dt2 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02"), "dd-MMM-yy HH:mm:ss zz", culture);
DateTime dt3 = DateTime.ParseExact("24-okt-08 21:09:06 CEST".Replace("CEST", "+02:00"), "dd-MMM-yy HH:mm:ss zzz", culture);
```
```


Question:
There have been a couple of questions that sort of dealt with this but not covering my exact question so here we go.

For site settings, if these are stored in a database do you:

retrieve them from the db every time someone makes a request

store them in a session variable on login

???????

For user specific settings do I do the same as site settings??

Any guidance/best practice would be greatly appreciated.

Cheers

Answer:
Generally I would put site settings in the web.config file, unless you are building an application that has multiple sites and gets changed by the application itself frequently, it usually wouldn't make sense to put it in the database at first.
For user specific settings I would look into starting with the default asp.net Profile Provider which will store the settings in the database and manage the retrival of the user settings once per Request and save the updates to the end to minimize the number of DB calls. Once you start to hit performance problems you can consider extending the profile provider for caching and/or your specific needs.


Question:
I am writing a desktop application written in Swing developed using Java 1.5. Some of the users seem to be using Mac, but I am interested in Java 6's scripting feature (Java 6 ships with Rhino). Java 6, although it came out almost 2 years ago, doesn't seem to be widely in use. I also hear Apple ships Java 6 only for Intel 64 Macs only. Is Java 1.5 the last Java that runs everywhere?

Is Java 6 ready for end-user desktop application now? If not now, when?

Edit:
Don't get too hung up on the fact that I am using Swing. I would like to know when Java 6 can be considered ready for prime time, not the choice of UI library.

Answer: Java 6 is not officially out for all Macs yet.  If you want to be more widely accepted, go with 1.5 (5).


Question:
What's the difference between the two and when should I use each:

<person>
     <firstname>Joe</firstname>
     <lastname>Plumber</lastname>
</person>

versus

<person firstname="Joe" lastname="Plumber" />

Thanks

Answer:
In my company, we would favour the 2nd approach.
The way we think about it is that "firstname" and "lastname" are
attributes
of the "person" node, rather than
sub-fields
of the "person" node.  It's a subtle difference.
In my opinion the 2nd approach is more concise, and readability/maintainability is significantly improved, which is very important.
Of course it would depend on your application.  I don't think there is a blanket rule that covers all scenarios.


Question:
Has anyone had experience with MySource Matrix as a content management system? If so, thoughts/opinions/comments?

Thanks in advance.

Answer:
Absolutely excellent. It takes little while to get used to how it does things with its asset structure, but it is really flexible and powerful. Simple edit interfaces are great too.
Make sure you give it enough hardware. If you want dynamic content without caching you need heaps of grunt to make it hum.


Question:
I'm trying to use XPath to parse an XML document. One of my NSXMLElement's looks like the following, hypothetically speaking:

<foo bar="yummy">

I'm trying to get the value for the attribute bar, however any interpretation of code I use, gives me back bar="woo", which means I need to do further string processing in order to obtain access to woo and woo alone.

Essentially I'm doing something like

NSArray *nodes = [xmlDoc nodesForXPath:@"foo/@bar" error:&error];
xmlElement = [nodes objectAtIndex:0];

Is there anyway to write the code above to just give me yummy, versus bar="yummy" so I can relieve myself of parsing the string?

Thanks.

Assuming TouchXML is being used, is there still anyway to obtain similar results? As in grabbing just the value for the attribute, without the attribute="value"? That results in then further having to parse the string to get the value out.

Answer:
If you're trying to use the NSXMLDocument class on an iPhone, you're going to be sorely disappointed, because this class (and related NSXMLNode, NSXMLElement, etc classes) are not available on the phone (they ARE available in the Simulator, which can be confusing).
Take a look at libxml2 to do XML parsing on the phone. There are several free frameworks (I believe TouchXML is a good one) for doing this.
That being said, if you want to run this code on a Mac, you can use the NSXMLElement method
```
-attributeForName:
```
to pull out just the attribute you want.


Question:
Say I want to get the HTML of

http://www.google.com

as a String using some built-in classes of the Cocoa Touch framework.

What is the least amount of code I need to write?

I've gotten this far, but can't figure out how to progress. There must be an easier way.

CFHTTPMessageRef req;
NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
req = CFHTTPMessageCreateRequest(kCFAllocatorDefault,
                                 CFSTR("GET"),
                                 (CFURLRef)url,
                                 kCFHTTPVersion1_1);

Answer:
The
quickest
way is to use NSString's
```
+stringWithContentsOfURL:
```
method. However, this is a modal call, and your application will be non-responsive while it runs. You can either move it to a background thread, or use the NSURLConnection class to make a proper, asynchronous request.


Question:
I'm investigating SUDS as a SOAP client for python.  I want to inspect the methods available from a specified service, and the types required by a specified method.

The aim is to generate a user interface, allowing users to select a method, then fill in values in a dynamically generated form.

I can get some information on a particular method, but am unsure how to parse it:

client = Client(url)
method = client.sd.service.methods['MyMethod']

I am unable to programmaticaly  figure out what object type I need to create to be able to call the service

obj = client.factory.create('?')

res = client.service.MyMethod(obj, soapheaders=authen)

Does anyone have some sample code?

Answer:
According to
```
suds
```
documentation
, you can inspect
```
service
```
object with
```
__str()__
```
. So the following gets a list of methods and complex types:
```
```
from suds.client import Client;

url = 'http://www.webservicex.net/WeatherForecast.asmx?WSDL'
client = Client(url)

temp = str(client);
```
```
The code above produces following result (contents of
```
temp
```
):
```
```
Suds ( https://fedorahosted.org/suds/ )  version: 0.3.4 (beta)  build: R418-20081208

Service ( WeatherForecast ) tns="http://www.webservicex.net"
   Prefixes (1)
      ns0 = "http://www.webservicex.net"
   Ports (2):
      (WeatherForecastSoap)
         Methods (2):
            GetWeatherByPlaceName(xs:string PlaceName, )
            GetWeatherByZipCode(xs:string ZipCode, )
         Types (3):
            ArrayOfWeatherData
            WeatherData
            WeatherForecasts
      (WeatherForecastSoap12)
         Methods (2):
            GetWeatherByPlaceName(xs:string PlaceName, )
            GetWeatherByZipCode(xs:string ZipCode, )
         Types (3):
            ArrayOfWeatherData
            WeatherData
            WeatherForecasts
```
```
This would be much easier to parse. Also every method is listed with their parameters along with their types. You could, probably, even use just regular expression to extract information you need.


Question:
How do I alternate HTML table row colors using JSP?

My CSS looks something like:

tr.odd {background-color: #EEDDEE}
tr.even {background-color: #EEEEDD}

I want to use <c:forEach> to iterate over a collection.

<c:forEach items="${element}" var="myCollection">
  <tr>
    <td><c:out value="${element.field}"/></td>
    ...
  </tr>
</c:forEach>

I need an int count variable or boolean odd/even variable to track the row. Then my <tr> tag would look something like:

<tr class="odd or even depending on the row">

Answer:
I don't use JSP, so I can't give you an answer in your language, but here's what I do (using pseudo code)
```
```
counter = 0
foreach (elements)
    counter = counter + 1
    output:
...

```
```
Personally, I name the classes "row0" and "row1", which lets you alternate between them with a simple modulus calculation, also, if you decide to have rows alternating in triples or quads (instead of pairs), you can easily extend it to
```
row2
```
,
```
row3
```
and change your output code to be
```
counter % 4
```
, etc.


Question:
I would like create a web service in ASP.Net 2.0 that will supports JSON.  Is there a way to do this without WCF and .Net 3.5?  Can anyone point me to a good article or sample code?

Clarification

I need direction on what is the best method, using the .Net 2.0 framework, to communicate JSON objects to a client.  Is it possible to do this without serializing the object to a string and then deserializing on the client?

Answer:
You can utilize WCF for your website, The WCF JSON endpoint can even generate javascript client proxy for the service.
Check out this post
REST / SOAP endpoints for a WCF service
A download sample can be found
http://www.codemeit.com/wcf/wcf-restful-pox-json-and-soap-coexist.html


Question:
I have a number of generated .sql files that I want to run in succession.  I'd like to run them from a SQL statement in a query (i.e. Query Analyzer/Server Management Studio).

Is it possible to do something like this and if so what is the syntax for doing this?

I'm hoping for something like:

exec 'c:\temp\file01.sql'
exec 'c:\temp\file02.sql'

I am using SQL Server 2005 and running queries in management studio.

Answer:
use
xp_cmdshell
and
sqlcmd
```
```
EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName
```
```


Question:
The deceptively simple foundation of dynamic code generation within a C/C++ framework has already been covered in another question. Are there any gentle introductions into topic with code examples?

My eyes are starting to bleed staring at highly intricate open source JIT compilers when my needs are much more modest.

Are there good texts on the subject that don't assume a doctorate in computer science? I'm looking for well worn patterns, things to watch out for, performance considerations, etc. Electronic or tree-based resources can be equally valuable. You can assume a working knowledge of (not just x86) assembly language.

Answer:
I'm not aware of any sources specifically related to JITs, but I imagine that it's pretty much like a normal compiler, only simpler if you aren't worried about performance.
The easiest way is to start with a VM interpreter.  Then, for each VM instruction, generate the assembly code that the interpreter would have executed.
To go beyond that, I imagine that you would parse the VM byte codes and convert them into some sort of suitable intermediate form (three address code?  SSA?) and then optimize and generate code as in any other compiler.
For a stack based VM, it may help to to keep track of the "current" stack depth as you translate the byte codes into intermediate form, and treat each stack location as a variable.  For example, if you think that the current stack depth is 4, and you see a "push" instruction, you might generate an assignment to "stack_variable_5" and increment a compile time stack counter, or something like that.  An "add" when the stack depth is 5 might generate the code "stack_variable_4 = stack_variable_4+stack_variable_5" and decrement the compile time stack counter.
It is also possible to translate stack based code into syntax trees.  Maintain a compile-time stack.  Every "push" instruction causes a representation of the thing being pushed to be stored on the stack.  Operators create syntax tree nodes that include their operands.  For example, "X Y +" might cause the stack to contain "var(X)", then "var(X) var(Y)" and then the plus pops both var references off and pushes "plus(var(X), var(Y))".


Question:
How do I drop a Groovlet into a Grails app?  Say, for example, in web-app/groovlet.groovy

import java.util.Date

if (session == null) {
  session = request.getSession(true);
}

if (session.counter == null) {
  session.counter = 1
}

println """
<html>
    <head>
        <title>Groovy Servlet</title>
    </head>
    <body>
Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}
<br>
"""

Answer:
The way I understand it, groovlets are used when you have a Servlet container with Groovy scripting support,
I think in Grails you would need to move your business logic code to a
controller
and leave the view part to an HTML or a
GSP file
.
Something along those lines (meta-code from the top of my head, not tested):
grails-app/controllers/SampleController.groovy
```
```
class DateController {
    def index = {
        if (session == null) {
          session = request.getSession(true);
        }

        if (session.counter == null) {
          session.counter = 1
        }
    }
}
```
```
web-app/sample/index.gsp
```
```
<html>
    <head>
    <title>Groovy Servlet</title>
    </head>
    <body>
Hello, ${request.remoteHost}: Counter: ${session.counter}! Date: ${new Date()}
<br>
```
```
Hope that helps!


Question: How to set internationalization to a DateTimepicker or Calendar WinForm control in .Net when the desire culture is different to the one installed in the PC?

Answer:
For DateTimePicker
```
```
dtp.Format = DateTimePickerFormat.Custom;
dtp.CustomFormat = "yyyy-MM-dd"; // or the format you prefer
```
```


Question:
I am playing with the new stuff of C#3.0 and I have this code (mostly taken from MSDN) but I can only get true,false,true... and not the real value :

        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

        var oddNumbers = numbers.Select(n => n % 2 == 1);

        Console.WriteLine("Numbers < 5:");
        foreach (var x in oddNumbers)
        {
            Console.WriteLine(x);
        }

How can I fix that to show the list of integer?

Answer:
Change your "Select" to a "Where"
```
```
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

    var oddNumbers = numbers.Where(n => n % 2 == 1);

    Console.WriteLine("Odd Number:");
    foreach (var x in oddNumbers)
    {
        Console.WriteLine(x);
    }
```
```
The "Select" method is creating a new list of the lambda result for each element (true/false).  The "Where" method is filtering based on the lambda.
In C#, you could also use this syntax, which you may find clearer:
```
```
var oddNumbers = from n in numbers
                         where n % 2 == 1
                         select n;
```
```
which the compiler translates to:
```
```
var oddNumbers = numbers.Where(n => n % 2 == 1).Select(n => n);
```
```


Question:
When I restart my apache2 and reload a page, the log file shows

boogie.tontut.fi - - [28/Oct/2008:03:27:49 +0200] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"

...as supposed to, as it's 03:27:49 now. However, when I click the refresh button again, the new log entry is:

boogie.tontut.fi - - [27/Oct/2008:21:27:52 -0400] "GET /test HTTP/1.1" 404 457 "-" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3"

Offset has changed from +0200 to -0400 and I have no clue where this comes from.

How can I start troubleshooting this problem?

Answer:
Try and set your timezone explicitly in the
```
httpd.conf
```
:
```
```
SetEnv TZ GMT+2
```
```


Question: I would like to be able to drop to the python REPL from the debugger -- if this is not possible is there an easier way to evaluate python expressions in the context of the  current breakpoint other than manually adding them all as watch expressions?

Answer:
I don't use
pydev
, but to drop to python's interactive REPL from code:
```
```
import code
code.interact(local=locals())
```
```
To drop to python's debugger from code:
```
```
import pdb
pdb.set_trace()
```
```
Finally, to run a interactive REPL after running some code, you can use python's
```
-i
```
switch:
```
```
python -i script.py
```
```
That will give you a python prompt after the code, even if it throws an exception.
You may be able to hook some of those solutions into
pydev
, I think.


Question: Is there a way to get the directory of a project in Eclipse?  We are writing a plugin that will allow the user to select files, and then run some processes on those files.  I would ideally like to be able to get all the files with a certain extension, but that is not necessary.

Answer:
sure:
```
```
ResourcesPlugin.getWorkspace().getRoot().getProjects()
```
```
will get you a list of all the projects in the workspace.  you can easily iterate to find the one you want.  At that point, you can look for certain files by extensions, etc.


Question:
I have been enjoying learning the basics of python, but before I started reading things I tried to install various python versions and modules clumsily. Now that I have some ideas of what I want to do and how to do it I'm finding that various aspects are broken. For instance, 2.6 IDLE won't launch, and when I try to import modules they usually don't work.

My question is, how would you recommend I clean this up and start fresh? I have read information about modifying the 2.6 install, but I still can't get it to work.

IDLE 2.4 works, and when I launch python from the terminal I am running python 2.4.4.

Answer:
I had this problem so much when I first got my Mac. The best solution I found was to delete everything I'd installed and just go with the
pythonmac.org
version of Python (2.6). I then installed setuptools from the same site, and then used easy_install to install every other package.
Oh, and I got the GNU C Compiler from the Xcode developer tools CD (which you can download from Apple's website), so that I can compile C extensions.