q:
After installing the VSTS Database GDR and importing a SQL Server 2005 database that includes the ASP.NET provider schema tables, I get the following warnings:

TSD04151: Procedure: [dbo].[aspnet_Users_DeleteUser] has an unresolved reference to object [dbo].[sysobjects].[name].

TSD04151: Procedure: [dbo].[aspnet_Users_DeleteUser] has an unresolved reference to object [dbo].[sysobjects].

TSD04151: Procedure: [dbo].[aspnet_AnyDataInTables] has an unresolved reference to object [dbo].[sysobjects].[type].

TSD04151: Procedure: [dbo].[aspnet_Users_DeleteUser] has an unresolved reference to object [dbo].[sysobjects].[type].

TSD04151: Procedure: [dbo].[aspnet_AnyDataInTables] has an unresolved reference to object [dbo].[sysobjects].

TSD04151: Procedure: [dbo].[aspnet_AnyDataInTables] has an unresolved reference to object [dbo].[sysobjects].[name].

Does anyone know how to get rid of these warnings?

[A]
I'm not sure, but a quick look seems to reveal the following.
The offending line in the script seems to be:
Line 42 in procedure [dbo].[aspnet_Users_DeleteUser]
(how do you do underscores here?)
(like this: \_ )
(EXISTS (SELECT name FROM
sysobjects
WHERE (name = N'vw_aspnet_MembershipUsers') AND (type = 'V'))))
the system view sysobjects belongs to the built in system schema 'sys' which is not included in the database project. As a result the database project parser thinks (wrongly) that the reference is unresolved.
I don't think there is anything you can do but select to ignore the warning from the project settings. (Be aware that that will hide real errors from you as well.) I would probably just ignore the warnings.
Update:
Try to add a reference to:
C:\Program Files\Microsoft Visual Studio 9.0\VSTSDB\Extensions\SqlServer\2008\DBSchemas\master.dbschema


q:
I've seen some posts where jQuery has been favored vs ExtJS. I haven't looked at jQuery in detail, but from what I read so far, jQuery doesn't provide the kind of UI which comes with ExtJS. Am I correct? Why would some of you prefer jQuery in ASP.NET?

Thanks

[A]
There are two schools of javascript frameworks, ones that focus on widgets (Yui, ext, etc) , and ones that focus on behavior (jquery, prototype, moo, etc)
JQuery just makes life easier to build dynamic, sexy sites. If you are just doing system.draggy.droppy asp development, you can ignore both, since you probably aren't really touching javascript at all. But if you do use javascript, it is worth your time to learn one of the frameworks that are out there, and jquery is currently the most popular.

s: huggingface

c: devops

d: intermediate


q:
Is it possible for a JPA entity class to contain two embedded (@Embedded) fields? An example would be:

@Entity
public class Person {
    @Embedded
    public Address home;

    @Embedded
    public Address work;
}

public class Address {
    public String street;
    ...
}

In this case a Person can contain two Address instances - home and work. I'm using JPA with Hibernate's implementation. When I generate the schema using Hibernate Tools, it only embeds one Address. What I'd like is two embedded Address instances, each with its column names distinguished or pre-pended with some prefix (such as home and work). I know of @AttributeOverrides, but this requires that each attribute be individually overridden. This can get cumbersome if the embedded object (Address) gets big as each column needs to be individually overridden.

[A]
If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy. DefaultComponentSafeNamingStrategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be defaulted even if used twice in the same entity.
From Hibernate Annotations Doc:
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714


q:
How do I setup TeamCity 4.0 so that I can access it over port 443 on the internet?  e.g. https://teamcity.mydomain.com

I am running IIS 7 on the same server that TeamCity is installed.  I see two options:

Setup TeamCity to use port 8443 and
create a reverse proxy in IIS that
routes requests to the TeamCity
public IP address to the Tomcat port
on the internal IP address.

Setup Tomcat to run on a different
IP address than IIS 7, and configure
TeamCity to run on port 443.

I'm not sure on the details of either of these steps.

[A]
It requires configuring the bundled Tomcat server for https.  See here:
http://confluence.jetbrains.net/display/TCD65/Using+HTTPS+to+access+TeamCity+server
and here:
http://tomcat.apache.org/tomcat-6.0-doc/ssl-howto.html
I also setup Tomcat to listen on just one IP Address.  All of this turned out to be a real pain, and I still am not able to run TeamCity as a service.  I can only run it at the command line.  If I were going to do this over, I would install TeamCity to run on the default port, and reverse proxy to it using
IIS7 Application Request Routing
or Apache Virtual Directories.
[Edit]
I have done this over, and I used IIS Application Request Routing to set up a reverse proxy. It works perfectly, and Team City upgrades are painless as well.


q:
I've created a small python script to toggle between two files I'm using for testing.

My question is, what is a good Python format style for the following code:

import filecmp
import shutil

local = "local.txt"
remote = "remote.txt"
config_file = "C:\some\path\file.txt"

shutil.copyfile( remote if( filecmp.cmp(local, config_file ) ) else local, config_file  )

Or

shutil.copyfile( remote
                     if( filecmp.cmp(local, config_file ) )
                     else local,
                 config_file  )

Or

tocopy = remote if( filecmp.cmp( local, config_file ) ) else local
shutil.copyfile( tocopy, config_file )

Or what?

Also, what is the preferred way to name var in python for many-word names, is it "to_copy", "tocopy", "toCopy", "ToCopy"

[A]
The most common naming I've seen is underscode separated words, to_copy.
As for the format style, I've seen no such agreement. I find
```
```
source = remote if filecmp.cmp(local, config_file) else local

shutil.copyfile(source, config_file)
```
```
to be the clearest among your options.
And seeing that everyone prefers to split the if I'd, at the very least, encapsulate the copyfile call in case you someday wish to change it:
```
```
def copy_to(source, destination):
    shutil.copyfile(source,destination)

if filecmp.cmp(local, config_file):
    copy_to(remote, config_file)
else:
    copy_to(local, config_file)
```
```


q:
SELECT
  avg(con_hits) as avg_hits
FROM
  content
WHERE
  con_type = 1
  AND con_posttime < $twelve_hrs_ago
  AND con_refresh = 0
ORDER BY
  con_posttime DESC
LIMIT 100

I would like it to go to the first record that was posted at least 12 hours ago (denoted by the $twelve_hrs_ago variable which has the suitable timestamp), and take the average of the con_hits column, for the next 100 records. In my example, it disregards the LIMIT, and takes the average of every record in the table.

Is there a way to bypass that?

[A]
```
LIMIT
```
is applied to the resultset, after
```
AVG
```
is calculated. You can do what you want, with a subselect:
```
```
SELECT avg(con_hits) as avg_hits
FROM (
  SELECT con_hits
  FROM content
  WHERE
    con_type = 1
    AND con_posttime < $twelve_hrs_ago
    AND con_refresh = 0
  ORDER BY con_posttime DESC
  LIMIT 100
) x;
```
```
You can use the database to calculate the time offset too. Replace
```
$twelve_hrs_ago
```
above with:
```
```
date_add(now(), interval -12 hour)
```
```


q:
I've recently updated an application to the 3.5 framework (from 2.0). The app links to Reporting Services (2005) remotely via an URL. This all works fine locally but when deployed to the dev server (win 2003) I'm getting a 403 error when attempting to call the report server.

"You are not authorized to view this page
...

HTTP Error 403 - Forbidden "

This just started happening after the 3.5 framework was installed, I've tried various security settings but can't get this to work again.

Does anyone know what security needs to be set or what I need to change?

Thanks.

[A]
When you say call the report server, what do you mean specifically? Access the Report Manager using this url: www.myserver.com/reports   ?
The main reason is, that locally you are authenticated implicitly as the user you're logged on to the server. Accessing the server remotely in the browser, does not necessarily authenticate you. Do you have anonymous authentication enabled in IIS on the server? If so, you are authenticated as a public anonymous/guest user and have not access to the report server. By disabling anonymous authentication, you will be prompted for username/password to authenticate.


q:
What is the best practices regarding storing files uploaded from users?

Currently, I am during the following method for storing files:

<web_app_root>/course_material/<term_id>/<course_id>/<file_id>

As you can see, the files are stored according to the keys in the database. I thought this was safer, since I wouldn't have to filter filenames and turn unsafe characters into safe characters.

However, I am starting a new project and wanted to know if it was a bad idea to tie a web app's filesystem so closely with a database. Should I store files in a more human readable format?

<web_app_root>/course_material/<term_name_underscored>/<course_name_underscored>/<file_name_underscored>

If so, what are the best ways to filter out filenames to be safe? Or is the way I am currently doing it a best practice?

[A]
I've always just stored the files in a directory with unique GUID based filenames, and mapped the guid to the file in the DB.  As long as you're not manually browsing the files and such, this is probably the easiest solution (also gets around invalid chars).
Another option is storing them as BLOBS in the database.  I've also done this - but it was to fill a replicated DR scenario, which modern NAS devices should handle.
If you see the need to manually browse the files outside of the app for some reason, then using the long or short name (however you'd like to browse them) would be cleaner.


q:
I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python?
Thanks!

[A]
When you open the URL with
```
urllib2
```
, and you're redirected, you get a status 30x for redirection.  Check the info to see the location to which you're redirected.  You don't need to read the page to read the
```
info()
```
that's part of the response.


q:
I'm switching between different Java SDKs (1.4.2, 1.5.0 and 1.6.0) for various projects.  I would like to set the JAVA_HOME environment variable on my Windows XP machine without going through the tedious My Computer -> Advanced -> [Select System Variable] -> Edit -> Ok -> Ok

Is it possible to do this from the command line, or is there a utility that can do this?

(Note that I am not referring to the standard batch file "SET" command - I want to set the environment variable "globally," not just for the life of a console window).

[A]
From
http://vlaurie.com/computers2/Articles/environment.htm
:
Using the add-on tool Setx.exe
It is not part of the standard Windows
  XP setup but a command-line tool
  called setx.exe is included in the
Windows XP Service Pack 2 Support Tools
. This tool extends the set
  command so that permanent changes in
  the environment variables can be made.
  For example, to add a folder C:\New
  Folder to the path, the command would
  be setx path "%PATH%;C:\New Folder"


q: How do I create a Web Application Project in VS 2008? How is it different from a "WebSite" project?

[A]
File--New--Project
instead of File--New--Web Site
It acts as a different container all together and the compile model is different.
ScottGu provided some details when they were first launched:
http://weblogs.asp.net/scottgu/archive/2006/05/08/445742.aspx


q:
This question is about "best use" scenarios in projects with ORMs like NHibernate, Subsonic, Linq2SQL, etc...

All of these tools generate basic entity classes, some with attributes, others without.  Do people use these classes as their business classes?  Or is there wholesale copying of data from ORM generated classes to manually created business classes?

Thanks.

[A]
I tend to work the opposite way.  I create the business objects the way I need them, and create NHibernate mappings from my objects to data.  You can have NHibernate generate a schema for you based on your mappings, or you can create your own schema, and create the mappings to go between the two.  Linq2Sql and Entity Framework do not support this.  I can't speak to Subsonic on this point.
I usually create my business classes, and get the application at least partially running without any database at all.  This way I can develop a better understanding of what it is the application is supposed to do, and how it should behave before making the decision of how to persist the objects.


q: Simple question, spurred on by the removal of the target attribute in HTML 4.0 Strict and XHTML 1.0 Strict.

[A]
I personally don't think so, as web users become more savvy, they'll ask for a new window from the browser.  It annoys me when a website does this a lot.
I think the question is sort of subjective.  It could be good if you're launching a javascript game or something.
Here's
Neil Turner's reasons not to do it
.


q: I'm working on a menu-generating HtmlHelper extension method. This method will need to know which Action is being executed. So if Home/Index is executing, the extension method would show all links to other actions that're "coordinated." In a sense, all I need to know during the execution of the Home controller's Index action is the name of the Controller and the name of the Action that are being executed so that other logic can be executed. Is this possible?

[A]
Try this
```
```
var action = HtmlHelper.ViewContext.RouteData.Values["action"];
var controller = HtmlHelper.ViewContext.RouteData.Values["controller"];
```
```


q:
I'm attempting to use the following code to serialize an anonymous type to JSON:

var serializer = new DataContractJsonSerializer(thing.GetType());
var ms = new MemoryStream();
serializer.WriteObject(ms, thing);
var json = Encoding.Default.GetString(ms.ToArray());

However, I get the following exception when this is executed:

Type
  '<>f__AnonymousType1`3[System.Int32,System.Int32,System.Object[]]'
  cannot be serialized. Consider marking
  it with the DataContractAttribute
  attribute, and marking all of its
  members you want serialized with the
  DataMemberAttribute attribute.  See
  the Microsoft .NET Framework
  documentation for other supported
  types.

I can't apply attributes to an anonymous type (as far as I know).  Is there another way to do this serialization or am I missing something?

[A]
Try the JavaScriptSerializer instead of the DataContractJsonSerializer
```
```
JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);
```
```


q:
My list (@degree) is built from a SQL command. The NVL command in the SQL isn't working, neither are tests such as:

if (@degree[$i] == "")
if (@degree[$i] == " ")
if (@degree[$i] == '')
if (@degree[$i] == -1)
if (@degree[$i] == 0)
if (@degree[$i] == ())
if (@degree[$i] == undef)

$i is a counter variable in a for loop. Basically it goes through and grabs unique degrees from a table and ends up creating ("AFA", "AS", "AAS", "", "BS"). The list is not always this long, and the empty element is not always in that position 3.

Can anyone help?

I want to either test during the for loop, or after the loop completes for where this empty element is and then replace it with the word, "OTHER".

Thanks for anything
-Ken

[A]
First of all, the ith element in an array is $degree[$i], not @degree[$i].  Second, "==" is for numerical comparisons - use "eq" for lexical comparisons.  Third of all, try
```
if (defined($degree[$i]))
```


q:
When I look at a directory in Windows Explorer, I can see a ProductName and ProductVersion property for the DLL's in that directory.

I need to export this DLL list with ProductName and ProductVersion into a text file.

If I do c:\>dir *.dll > test.log, the test.log does not have the ProductName and ProductVersion.

Could someone help me to get these properties exported to a file along with the filename?

Even if it is a freeware tool or some other dir switch, that will be useful.

[A]
Using VBScript you could do the following:
```
```
Set objShell = CreateObject ("Shell.Application")
Set objFolder = objShell.Namespace ("C:\Scripts")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim arrHeaders(40)

For i = 0 to 40
    arrHeaders(i) = objFolder.GetDetailsOf (objFolder.Items, i)
Next

For Each strFileName in objFolder.Items
    For i = 0 to 40
        Wscript.echo arrHeaders(i) & ": " & objFolder.GetDetailsOf (strFileName, i)
    Next
    Wscript.Echo
Next
```
```


q:
What are the proper uses of:

static_cast

dynamic_cast

const_cast

reinterpret_cast

(type)value (C-style cast)

type(value) (function-style cast)

How does one decide which to use in which specific cases?

[A]
Does
this
answer your question?
I have never used
```
reinterpret_cast
```
, and wonder whether running into a case that needs it isn't a smell of bad design. In the code base I work on
```
dynamic_cast
```
is used a lot. The difference with
```
static_cast
```
is that a
```
dynamic_cast
```
does runtime checking which may (safer) or may not (more overhead) be what you want (see
msdn
).


q:
I've been trying to add a swf over a swf on a html page, it's working fine in Firefox, but in IE, the one that's added first is always on top of the other one. I used z-index but it's not working, does anyone know how to solve this? Thanks.

I already added wmode:transparent, it is working in firefox but not in IE 6.


q:
Im trying to create an app to control a pc remotely using java , i want to use red5  to let the admin control desktops using a flash movie
so i need to find java classes to :

capture desktop as live video

-control mouse and keyboard

[A]
TightVNC
has a Java viewer so you can easily manage your server through VNC protocol and use a Java client (usable as an applet too).
There are tools, though not in Java, such as
vncrec
to record VNC sessions. I don't know if this is exactly what you are looking for since to distribute video a better choice would be to set up a streaming server.


q:
My application's context root is /foobar and I am running an exploded deployment with maven-jetty-plugin.

I need to dynamically remap requets for /images/* to /foobar/images/*, and I cannot remap my application's context root to /.

For weblogic I have a halfwit solution where I deploy an additional war containing a proxy to context root /images.

The problem is that I cannot get this to work with maven-jetty-plugin, because I dont see how it can deploy two apps.

Anyone know how to do this  ?

[A]
I don't think it can be done since TryUpdateModel, which UpdateModel uses, references the ControllerContext which is null when invoked from a unit test.  I use RhinoMocks to mock or stub the various components needed by the controller.
```
```
var routeData = new RouteData();
var httpContext = MockRepository.GenerateStub<HttpContextBase>();
FormCollection formParameters = new FormCollection();

EventController controller = new EventController();
ControllerContext controllerContext =
    MockRepository.GenerateStub<ControllerContext>( httpContext,
                                                    routeData,
                                                    controller );
controller.ControllerContext = controllerContext;

ViewResult result = controller.Create( formParameters ) as ViewResult;

Assert.AreEqual( "Event", result.Values["controller"] );
Assert.AreEqual( "Show", result.Values["action"] );
Assert.AreEqual( 0, result.Values["id"] );
```
```
Here's the relevant bit from the Controller.cs source on www.codeplex.com/aspnet:
```
```
protected internal bool TryUpdateModel<TModel>( ... ) where TModel : class
{

     ....

    ModelBindingContext bindingContext =
           new ModelBindingContext( ControllerContext,
                                    valueProvider,
                                    typeof(TModel),
                                    prefix,
                                    () => model,
                                    ModelState,
                                    propertyFilter );

     ...
}
```
```


q:
I'm working with some example java code for making md5 hashes. One part converts the results from bytes to a string of hex digits:

byte messageDigest[] = algorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i=0;i<messageDigest.length;i++) {
    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
    }

However, it doesn't quite work since toHexString apparently drops off leading zeros. So, what's the simplest way to go from byte array to hex string that maintains the leading zeros?

[A]
This what I am using for MD5 hashes:
```
```
public static String getMD5(String filename)
        throws NoSuchAlgorithmException, IOException {
    MessageDigest messageDigest =
        java.security.MessageDigest.getInstance("MD5");

    InputStream in = new FileInputStream(filename);

    byte [] buffer = new byte[8192];
    int len = in.read(buffer, 0, buffer.length);

    while (len > 0) {
        messageDigest.update(buffer, 0, len);
        len = in.read(buffer, 0, buffer.length);
    }
    in.close();

    return new BigInteger(1, messageDigest.digest()).toString(16);
}
```
```
EDIT: I've tested and I've noticed that with this also trailing zeros are cut. But this can only happen in the beginning, so you can compare with the expected length and pad accordingly.


q:
In Django 1.0, what is the best way to catch and show an error if user enters only whitespace (" ") in a form field?

class Item(models.Model):
    description = models.CharField(max_length=100)

class ItemForm(ModelForm):
    class Meta:
        model = Item

if user enters only whitespace (" ") in description CharField, what change needs to done to class Item or class ItemForm so that form.is_valid() fails and shows an error?

After form.is_valid(), I could write the code to check for only whitespaces in description field and raise a validation error but there has to be a better way. Can RegexField be used to specify description entered should not be just whitespaces. Any suggestions?

[A]
```
```
class ItemForm(forms.ModelForm):
    class Meta:
        model = Item

    def clean_description(self):
        if not self.cleaned_data['description'].strip():
            raise forms.ValidationError('Your error message here')
```
```
The
forms validation documentation
might provide a good read.


q:
I have a website that employs a generic mod_rewrite rule to push all requests to the index.php page, with the exception of certain file extensions:

RewriteRule !\.(js|ico|gif|jpg|JPG|png|css|php|phtml|pdf|txt|xml)$ index.php

What I need to be able to do is also exclude a certain directory (including any files or sub-directories contained within) from this rule - what is the best solution?

Here is my full .htaccess file, in case something else within it is intefering:

RewriteEngine ON
RewriteCond %{HTTP_HOST} !^www\..*
RewriteCond %{HTTP_HOST}   !^$
RewriteCond %{HTTP_HOST} ^([^.]*)\.(co\.uk)
RewriteRule ^.*$     http://www.%1.%2%{REQUEST_URI} [R=permanent,L]

AddHandler application/x-httpd-php .phtml

RewriteRule !\.(js|ico|gif|jpg|JPG|png|css|php|phtml|pdf|txt|xml)$ index.phtml

php_value display_errors "On"

[A]
You could check with
```
RewriteCond %{REQUEST_FILENAME} !-f
```
for any request that doesn't match to an existing filename.


q: I need to store a double as a string.  I know I  can use printf if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the value, not the key).

[A]
Take a look at
```
sprintf()
```
and family.


q: I need to deploy a few .net dlls. They need to be put in the GAC and the required entries need to be in the registry. On my machine I have both the SDK and Visual Studio running, so currently I am utilizing .net sdk tools like gacutil and regasm. However, when I need to install these dlls on a customer machine, how should I go about it. Can I accomplish this by just having the .net runtime. I am currently using .net 2.0.

[A]
Well, the easiest way, for the person that's going to be sitting in front of that other machine that is, is of course an installation program.
I believe most VS editions have some sort of installer support where you can create a setup project that ends up as a .exe and .msi file that you can use to install your software with, and then you'll get basically all you need, things like desktop/start menu shortcuts, GAC-support, uninstall, downloading the .NET runtime if needed, etc.
Check the new project dialog box in your Visual Studio and I'm sure you'll find something useful there, if not then I'm pretty sure someone here can point you in the right direction.
On the other hand, if you want to go the manual route, then some of the .NET tools is installed in the .NET directory beneath C:\Windows\Microsoft.NET\Framework\version.


q:
What is the most appropriate media type (formally MIME type) to use when sending data structured with YAML over HTTP and why?

There is no registered application type or text type that I can see.

Example:

> GET /example.yaml

< Content-Type: ????
<
< --- # Favorite movies
< - Casablanca
< - North by Northwest
< - Notorious

Possible options:

text/x-yaml

text/yaml

text/yml

application/x-yaml

application/x-yml

application/yaml

application/yml

[A]
Ruby on Rails uses
```
application/x-yaml
```
with an alternative of
```
text/yaml
```
(
source
).
I think it's just a matter of convention, there is no
technical
why, as far as I can tell.


q: Is it possible to change a sql server instance name?  Or is it something that can only be set during installation?

[A]
To the best of my knowledge, they can only be changed at install time.  You might be able to change the name with the installer package while keeping the current info.  I would make backups of all of your databases and then try this.
On another note, changing instance names will just cause you so many headaches.  Even if you can do it, I would strongly reccomend leaving well enough alone.


q:
What is the best method of hiding php errors from being displayed on the browser?

Would it be to use the following:

ini_set("display_errors", 1);

Any best practice tips would be appreciated as well!

I am logging the errors, I just want to make sure that setting the display_errors value to off (or 0) will not prevent errors from being logged.

[A]
The best way is to log your errors instead of displaying or ignoring them.
This example will log the errors to syslog instead of displaying them in the browser.
```
```
ini_set("display_errors", 0);
ini_set("log_errors", 1);

//Define where do you want the log to go, syslog or a file of your liking with
ini_set("error_log", "syslog"); // or ini_set("error_log", "/path/to/syslog/file");
```
```


q:
I have an OpenGl program in which I am displaying an image using textures. I want to be able to load a new image to be displayed.

In my Init function I call:

Gl.glGenTextures(1, mTextures);

Since only one image will be displayed at time, I am using the same texture name for each image.

Each time a new image is loaded I call the following:

Gl.glBindTexture(Gl.GL_TEXTURE_2D, mTexture[0]);

Gl.glTexImage2D(Gl.GL_TEXTURE_2D, 0, Gl.GL_LUMINANCE, mTexSizeX, mTexSizeY, 0, Gl.GL_LUMINANCE, Gl.GL_UNSIGNED_SHORT, mTexBuffer);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MIN_FILTER, Gl.GL_LINEAR);
Gl.glTexParameteri(Gl.GL_TEXTURE_2D, Gl.GL_TEXTURE_MAG_FILTER, Gl.GL_LINEAR);

The first image will display as expected. However, all images load after the first, display as all black.

What am I doing wrong?

[A]
When do you submit the geometry using these textures? I assume that is interleaved with the texture loading, although you don't show that. Of course, if you are going to replace the texture name with different images, you don't need to use texture names at all, do  you? You could just do the
```
glTextImage2D
```
call when you need to set a new texture, and then use that for as long as necessary, never involving
```
glBindTexture()
```
at all.
An obvious thing to do is of course to insert error-checking code, OpenGL stores an error code when an operation fails and this code is not overwritten until read by the application. See
glGetError()
for more on this.


q: I know class foo(object) is an old school way of defining a class. But I would like to understand in more detail the difference between these two.

[A]
```
class foo(object):
```
is the 'new' way of declaring classes.
This change was made in python 2.2, see
this PEP for an explanation
of the differences.


q:
Hello I am compiling a program with make but I get the error of No such file or directory but the file is in a directory of the path.

I have this #include "genetic.h", that file is in a directory called /home/myuser/toolbox/lib/genalg and in the PATH I have ...:/home/myuser/toolbox/lib/genalg, so I do not why make cannot find the library. Any ideas?. Thanks


q: I'm trying to setup the Entity Framework with SQL Server 2008.  I'm using Guids for the keys on my tables.  Is there a way to set it up so the keys are automatically generated by the database?  I tried setting "RowGuid" to true and also set the column's default value to be "(newid())".  Either way the mapped class still needs me to give it a Guid on the C# side.  Any ideas?

[A]
Since a Guid is a structure, a null value is never passed so the defaults don't kick in. You could consider a
nullable Guid
: Guid?, though this may cause headaches as mentioned in this post:
Nullable GUID
I found it easier to just initialize the Guid with a new value:
```
```
private Guid _identifier = Guid.NewGuid();
```
```
If it's an existing record, it will be replaced when the object is populated. If not, the initialized value will be inserted.


q: How do I change the size of figure drawn with Matplotlib?

[A]
Deprecation note:
As per the
official Matplotlib guide
, usage of the
```
pylab
```
module is no longer recommended. Please consider using the
```
matplotlib.pyplot
```
module instead, as described by
this other answer
.
The following seems to work:
```
```
from pylab import rcParams
rcParams['figure.figsize'] = 5, 10
```
```
This makes the figure's width 5 inches, and its height 10
inches
.
The Figure class then uses this as the default value for one of its arguments.


q:
Is there a measurable performance difference between using INT vs. VARCHAR as a primary key in MySQL? I'd like to use VARCHAR as the primary key for reference lists (think US States, Country Codes) and a coworker won't budge on the INT AUTO_INCREMENT as a primary key for all tables.

My argument, as detailed here, is that the performance difference between INT and VARCHAR is negligible, since every INT foreign key reference will require a JOIN to make sense of the reference, a VARCHAR key will directly present the information.

So, does anyone have experience with this particular use-case and the performance concerns associated with it?

[A]
For short codes, there's probably no difference.  This is especially true as the table holding these codes are likely to be very small (a couple thousand rows at most) and not change often (when is the last time we added a new US State).
For larger tables with a wider variation among the key, this can be dangerous.  Think about using e-mail address/user name from a User table, for example.  What happens when you have a few million users and some of those users have long names or e-mail addresses.   Now any time you need to join this table using that key it becomes much more expensive.


q:
Is it possible to embed the Windows Explorer file/folder browser view in a WPF or a WinForms window?

I basically want to host the file/folder browser as part of my app window.  I don't want to re-implement what the shell provides, especially the shell extensions such as TortoiseSVN.

[A]
As far as I know, there isn't any File/Folder browser control out of the box in Windows Forms nor WPF.
However there are commercial third-party controls that offer a Windows Explorer-like interface to browse files and folders on disk. Take a look at these products from LogicNP:
FileView Control
FolderView Control
Alternatively, you could host the
Windows Forms WebBrowser control
in WPF and use it to browse the filesystem, since it is integrated with the Windows shell.
In XAML you could do something like this:
```
```
<Window x:Class="Samples.FilesystemBrowser"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    Title="Filesystem Browser">
    <StackPanel>
        <WindowsFormsHost>
            <wf:WebBrowser Url="C:\" />
        </WindowsFormsHost>
    </StackPanel>
</Window>
```
```
Note, that with
.NET 3.5 SP1
Microsoft added a
native WPF WebBrowser control
, so you can optionally use that instead:
```
```
<Window x:Class="Samples.FilesystemBrowser"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Filesystem Browser">
    <StackPanel>
        <WebBrowser Source="C:\" />
    </StackPanel>
</Window>
```
```


q:
Just looking at:

(Source: https://xkcd.com/327/)

What does this SQL do:

Robert'); DROP TABLE STUDENTS; --

I know both ' and -- are for comments, but doesn't the word DROP get commented as well since it is part of the same line?

[A]
It drops the students table.
The original code in the school's program probably looks something like
```
```
q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')";
```
```
This is the naive way to add text input into a query, and is
very bad
, as you will see.
After the values from the first name, middle name textbox
FNMName.Text
(which is
```
Robert'); DROP TABLE STUDENTS; --
```
) and the last name textbox
LName.Text
(let's call it
```
Derper
```
) are concatenated with the rest of the query, the result is now actually
two queries
separated by the
statement terminator
(semicolon).  The second query has been
injected
into the first.  When the code executes this query against the database, it will look like this
```
```
INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')
```
```
which, in plain English, roughly translates to the two queries:
Add a new record to the Students table with a Name value of 'Robert'
and
Delete the Students table
Everything past the second query is
marked as a comment
:
```
--', 'Derper')
```
The
```
'
```
in the student's name is not a comment, it's the closing
string delimiter
.  Since the student's name is a string, it's needed syntactically to complete the hypothetical query.  Injection attacks only work
when the SQL query they inject results in valid SQL
.
Edited
again
as per
dan04
's astute comment


q:
I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:

SerialTestDataContext db = new SerialTestDataContext();

relation_table row = db.relation_tables.First();

MemoryStream memStream = new MemoryStream();
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(memStream, row);
Console.WriteLine("Serilized successfully");

TestTable tt = new testTable();
tt.data = new System.Data.Linq.Binary(memStream.ToArray());
db.testTables.InsertOnSubmit(tt);
db.SubmitChanges();
Console.WriteLine("Inserted successfully");

Currently that fails even though I've marked the generated classes as [Serializable] because one of the LINQ inherited classes is not. Is it even possible to do this?

[A]
Linq classes are partial classes.  You can change the definition to mark the classes as implementing
ISerializable
and then provide the code...
```
```
public partial class User : ISerializable
{
  // implement GetObjectData here
}
```
```
There might still be issues with deserialization, however (I'm not 100% on this).  An alternative is to use xml serialization and implement
IXmlSerializable
, which has methods for serializing and deserializing, allowing you to control the entire process...


q: Is there a JavaScript equivalent of Java's class.getName()?

[A]
Is there a JavaScript equivalent of Java's
```
class.getName()
```
?
No
.
ES2015 Update
:
the name of
```
class Foo {}
```
is
```
Foo.name
```
.  The name of
```
thing
```
's class, regardless of
```
thing
```
's type, is
```
thing.constructor.name
```
. Builtin constructors in an ES2015 environment have the correct
```
name
```
property; for instance
```
(2).constructor.name
```
is
```
"Number"
```
.
But here are various hacks that all fall down in one way or another:
Here is a hack that will do what you need - be aware that it modifies the Object's prototype, something people frown upon (usually for good reason)
```
```
Object.prototype.getName = function() {
   var funcNameRegex = /function (.{1,})\(/;
   var results = (funcNameRegex).exec((this).constructor.toString());
   return (results && results.length > 1) ? results[1] : "";
};
```
```
Now, all of your objects will have the function,
```
getName()
```
, that will return the name of the constructor as a string. I have tested this in
```
FF3
```
and
```
IE7
```
, I can't speak for other implementations.
If you don't want to do that, here is a discussion on the various ways of determining types in JavaScript...
I recently updated this to be a bit more exhaustive, though it is hardly that. Corrections welcome...
Using the
```
constructor
```
property...
Every
```
object
```
has a value for its
```
constructor
```
property, but depending on how that
```
object
```
was constructed as well as what you want to do with that value, it may or may not be useful.
Generally speaking, you can use the
```
constructor
```
property to test the type of the object like so:
```
```
var myArray = [1,2,3];
(myArray.constructor == Array); // true
```
```
So, that works well enough for most needs. That said...
Caveats
Will not work
AT ALL
in many cases
This pattern, though broken, is quite common:
```
```
function Thingy() {
}
Thingy.prototype = {
    method1: function() {
    },
    method2: function() {
    }
};
```
```
```
Objects
```
constructed via
```
new Thingy
```
will have a
```
constructor
```
property that points to
```
Object
```
, not
```
Thingy
```
. So we fall right at the outset; you simply cannot trust
```
constructor
```
in a codebase that you don't control.
Multiple Inheritance
An example where it isn't as obvious is using multiple inheritance:
```
```
function a() { this.foo = 1;}
function b() { this.bar = 2; }
b.prototype = new a(); // b inherits from a
```
```
Things now don't work as you might expect them to:
```
```
var f = new b(); // instantiate a new object with the b constructor
(f.constructor == b); // false
(f.constructor == a); // true
```
```
So, you might get unexpected results if the
```
object
```
your testing has a different
```
object
```
set as its
```
prototype
```
. There are ways around this outside the scope of this discussion.
There are other uses for the
```
constructor
```
property, some of them interesting, others not so much; for now we will not delve into those uses since it isn't relevant to this discussion.
Will not work cross-frame and cross-window
Using
```
.constructor
```
for type checking will break when you want to check the type of objects coming from different
```
window
```
objects, say that of an iframe or a popup window. This is because there's a different version of each core type
```
constructor
```
in each `window', i.e.
```
```
iframe.contentWindow.Array === Array // false
```
```
Using the
```
instanceof
```
operator...
The
```
instanceof
```
operator is a clean way of testing
```
object
```
type as well, but has its own potential issues, just like the
```
constructor
```
property.
```
```
var myArray = [1,2,3];
(myArray instanceof Array); // true
(myArray instanceof Object); // true
```
```
But
```
instanceof
```
fails to work for literal values (because literals are not
```
Objects
```
)
```
```
3 instanceof Number // false
'abc' instanceof String // false
true instanceof Boolean // false
```
```
The literals need to be wrapped in an
```
Object
```
in order for
```
instanceof
```
to work, for example
```
```
new Number(3) instanceof Number // true
```
```
The
```
.constructor
```
check works fine for literals because the
```
.
```
method invocation implicitly wraps the literals in their respective object type
```
```
3..constructor === Number // true
'abc'.constructor === String // true
true.constructor === Boolean // true
```
```
Why two dots for the 3? Because Javascript interprets the first dot as a decimal point ;)
Will not work cross-frame and cross-window
```
instanceof
```
also will not work across different windows, for the same reason as the
```
constructor
```
property check.
Using the
```
name
```
property of the
```
constructor
```
property...
Does not work
AT ALL
in many cases
Again, see above; it's quite common for
```
constructor
```
to be utterly and completely wrong and useless.
Does NOT work in <IE9
Using
```
myObjectInstance.constructor.name
```
will give you a string containing the name of the
```
constructor
```
function used, but is subject to the caveats about the
```
constructor
```
property that were mentioned earlier.
For IE9 and above, you can
monkey-patch in support
:
```
```
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s+([^\s(]+)\s*\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1] : "";
        },
        set: function(value) {}
    });
}
```
```
Updated version
from the article in question. This was added 3 months after the article was published, this is the recommended version to use by the article's author Matthew Scharley. This change was inspired by
comments pointing out potential pitfalls
in the previous code.
```
```
if (Function.prototype.name === undefined && Object.defineProperty !== undefined) {
    Object.defineProperty(Function.prototype, 'name', {
        get: function() {
            var funcNameRegex = /function\s([^(]{1,})\(/;
            var results = (funcNameRegex).exec((this).toString());
            return (results && results.length > 1) ? results[1].trim() : "";
        },
        set: function(value) {}
    });
}
```
```
Using Object.prototype.toString
It turns out, as
this post details
, you can use
```
Object.prototype.toString
```
- the low level and generic implementation of
```
toString
```
- to get the type for all built-in types
```
```
Object.prototype.toString.call('abc') // [object String]
Object.prototype.toString.call(/abc/) // [object RegExp]
Object.prototype.toString.call([1,2,3]) // [object Array]
```
```
One could write a short helper function such as
```
```
function type(obj){
    return Object.prototype.toString.call(obj).slice(8, -1);
}
```
```
to remove the cruft and get at just the type name
```
```
type('abc') // String
```
```
However, it will return
```
Object
```
for all user-defined types.
Caveats for all...
All of these are subject to one potential problem, and that is the question of how the object in question was constructed. Here are various ways of building objects and the values that the different methods of type checking will return:
```
```
// using a named function:
function Foo() { this.a = 1; }
var obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // true
(obj.constructor.name == "Foo");  // true

// let's add some prototypical inheritance
function Bar() { this.b = 2; }
Foo.prototype = new Bar();
obj = new Foo();
(obj instanceof Object);          // true
(obj instanceof Foo);             // true
(obj.constructor == Foo);         // false
(obj.constructor.name == "Foo");  // false

// using an anonymous function:
obj = new (function() { this.a = 1; })();
(obj instanceof Object);              // true
(obj.constructor == obj.constructor); // true
(obj.constructor.name == "");         // true

// using an anonymous function assigned to a variable
var Foo = function() { this.a = 1; };
obj = new Foo();
(obj instanceof Object);      // true
(obj instanceof Foo);         // true
(obj.constructor == Foo);     // true
(obj.constructor.name == ""); // true

// using object literal syntax
obj = { foo : 1 };
(obj instanceof Object);            // true
(obj.constructor == Object);        // true
(obj.constructor.name == "Object"); // true
```
```
While not all permutations are present in this set of examples, hopefully there are enough to provide you with an idea about how messy things might get depending on your needs. Don't assume anything, if you don't understand exactly what you are after, you may end up with code breaking where you don't expect it to because of a lack of grokking the subtleties.
NOTE:
Discussion of the
```
typeof
```
operator may appear to be a glaring omission, but it really isn't useful in helping to identify whether an
```
object
```
is a given type, since it is very simplistic. Understanding where
```
typeof
```
is useful is important, but I don't currently feel that it is terribly relevant to this discussion. My mind is open to change though. :)


q: Lets say you need to attach some JavaScript functionality to an ASP.NET User Control of which there might be multiple instances on any given page.  Because JavaScript has shared global state, what techniques can you use to keep the client state and behavior for each instance of a control separate?

[A]
Well, the main thing you can do is make sure your JavaScript functions are abstract enough that they are not coupled to specific instances of HTML controls - have them accept parameters that allow you to pass various instances of objects in.
The JavaScript that does whatever magic you need to be done should only exist once in your page regardless of how many instances of a user control you have on a given page, thus your functions need to be ignorant of that fact.
Without more information about what you are trying to do, there is little more I can offer in the way of help; it would depend on your circumstance.
EDIT: One way I have dealt with particular aspects of this problem is to create a static property on the user control (thus it is the same variable across multiple instances) that tracks the client-side IDs of the various user control elements (the user control adds the client IDs to this list in the
control's
OnLoad event); then, in the
page's
OnPreRender event (IIRC), render those out in a JavaScript variable that my code knows to look for on the client and operate on. I don't know if that makes sense, but it might help someone...


q:
I want to do this C# code in F#

  string[] a = new string[5];
    string b = string.Empty;
    a[0] = "Line 1";
    a[2] = "Line 2";

    foreach (string c in a)
    {
        b = c + Environment.NewLine;
    }

[A]
Its a lot better to use the built-in String.Join method than rolling your own function based on repeated string concatting. Here's the code in F#:
```
```
open System
let a = [| "Line 1"; null; "Line 2"; null; null;|]
let b = String.Join(Environment.NewLine, a)
```
```


q: How can I programmatically change my browser's default home page with C#?

[A]
See this, which is not in C#, but you should be able to work out the registry stuff in C# pretty easily.
http://www.microsoft.com/technet/scriptcenter/resources/qanda/nov04/hey1108.mspx
Please don't arrange for this code to run on my machine!


q:
When using TFS with a tool outside of Visual Studio (Specifially ORMS), modifications to the project file to include a new file will not cause the file to be added to source control.

Does anything exist that could potentially say "Warning: You are about to check in change to a project file which include a file which is not versioned"

[A]
Not quite, however you might want to download the
TFS Power Tools
and check out the command line utility tfpt.exe.
The "tfpt online" and "tfpt treeclean" might be most useful to you when working outside of an integrated TFS client.  tfpt online will look for files in your local directory that are not under version control, treeclean will show you files in your local directory that are not under version control so that you can remove then if they are not required.
Good luck,
Martin.


q: I dictate SQL using speech recognition, and lining things up is a pain. If I could see where the tab stops are it would save me a lot of time.

[A]
Management Studio supports an undocumented feature that
Visual Studio has as well
. It adds vertical guide lines to the editor window at specific column locations.
Create a .reg file using the text below and open it to merge it with your registry. This will add a line every 8 characters (up to column 96) in SQL Server 2005. Modify as needed to suit your tab size. It does not appear to support more than 12 lines. The RGB portion of the string is supposed to set the color, but it always displays as black for me. You'll quickly notice why this is an undocumented feature - the lines appear in unwanted locations such as the Messages output window.
```
```
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Microsoft SQL Server\90\Tools\Shell\Text Editor]
"Guides"="RGB(128,0,0) 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88, 96"
```
```


q:
I was curious if anyone had any hard numbers around the performance difference between annotating Entities using private fields instead of public getter methods.  I've heard people say that fields are slower because they're called "through reflection" but then again so are the getter methods, no?  Hibernate needs to set the accessibility of the field to true before it tries to read it which I can see having some slight overhead.  However wouldn't that be done at the Class-level in the scope of a Session or perhaps only once when the Configuration is read and SessionFactory is built?

Just curious if this is a myth or if there's really truth to it; I personally find annotating the fields to be a bit more readable.

[A]
ok, I can't give numbers haha, but I would guess that accessing the fields through reflection wouldn't be a 'one time' thing.  Each object has its own private members.
I honestly don't know much about reflection but the getter/setters should be straight forward.  In fact you can try setting one of the methods to private and I think it won't work because it can't find the method it needs.
There are other issues like proxies that will affect getter methods though depending on how you load your entities.
This is all I see in the documentation:
The access attribute lets you control
  how Hibernate will access the property
  at runtime. By default, Hibernate will
  call the property get/set pair. If you
  specify access="field", Hibernate will
  bypass the get/set pair and access the
  field directly, using reflection. You
  may specify your own strategy for
  property access by naming a class that
  implements the interface
  org.hibernate.property.PropertyAccessor.
My guess is that reflection in general is going to be a higher cost though, but sorry.. no numbers :(


q: I have a set of divs that I want to make collapsible/expandable using jQuery's slideToggle() method. How do I make all of these divs collapsed by default? I'd like to avoid explicitly calling slideToggle() on each element during/after page rendering.

[A]
you probably can do something like this:
```
```
$(document).ready(function(){
  $('div').hide();
});
```
```


q:
When I get AuthenticationStatus.Authenticated (DotNetOpenId library)
response from myopenid provider, i'd like to redirect user from login page
to another one using MVC Redirect(myurl). But unfortunately, instead of
getting to myurl, user is redirected to empty page:

myurl?token=AWSe9PSLwx0RnymcW0q.... (+ several kilobytes of
myopenid-specific query string)

I also tried FormsAuthentication.RedirectFromLoginPage(), but it redirects
to original login page again instead of the myurl.

Could anybody suggest proper redirection to myurl?

Thanks

[A]
First of all you should set authorization cookie:
```
```
FormsAuth.SetAuthCookie(UserName, RememberMe);
```
```
After this you should return RedirectToAction result:
```
```
return RedirectToAction(actionName, controllerName);
```
```
Or Redirect result:
```
```
return Redirect(url);
```
```
When you use "return Redirect(url);" it uses Response.Redirect(url, false) method for redirecting so it must work. May be you not returning this action result, please check this.
"FormsAuthentication.RedirectFromLoginPage()" will redirect to login page when you didn't set authorization cookie or when your login page is a home (default) page of the application -
The RedirectFromLoginPage method redirects to the URL specified in the query string using the ReturnURL variable name. For example, in the URL
http://www.contoso.com/login.aspx?ReturnUrl=caller.aspx
, the RedirectFromLoginPage method redirects tothe return URL caller.aspx. If the ReturnURL variable does not exist, the RedirectFromLoginPage method redirects to the URL in the DefaultUrl property.
Via MSDN


q:
I would like to implement a search engine which should crawl a set of web sites, extract specific information from the pages and create full-text index of that specific information.

It seems to me that Xapian could be a good choice for the search engine library.

What are the options for a crawler/parser to integrate with Xapian?

Would Solr be a better choice than Xapian to integrate with open source crawlers/parsers?


q:
I've got a whole host of values stored in a .net 2.0 hashtable.  What I would really like to find is a way to, essentially, do a SQL select statement  on the table.

Meaning, I'd like to get a list of keys whose associated values match a very simple text pattern (along the lines of "starts with a number".)

The final goal will be to remove these records from the hashtable for further processing.

I've been beating my head against this for a while now, and I can't seem to come up with anything.

Any ideas?

(On the off chance this matters: due to the realities of this project, any 3rd party widgets or upgrading to a more recent version of .net are off the table.)

[A]
You could use a regex against every key in the hashtable.  This is very dirty but it works:
```
```
static void Main(string[] args)
    {
        Hashtable myhashtable = new Hashtable();
        myhashtable.Add("Teststring", "Hello");
        myhashtable.Add("1TestString1", "World");
        myhashtable.Add("2TestString2", "Test");

        List<String> newht = new List<String>;

        //match all strings with a number at the front
        Regex rx = new Regex("^[1-9]");
        foreach (string key in myhashtable.Keys)
        {
            if (rx.IsMatch(key) == true)
            {
                newht.Add(key);
            }
        }

        //Loop through all the keys in the new collection and remove them from
        //them from the main hashtable.
        foreach (string key in newht)
        {
            myhashtable.Remove(key);
        }
    }
```
```
EDIT: And just for fun, here is the LINQ version (sorry I just had too).
```
```
Hashtable myhashtable = new Hashtable();
            myhashtable.Add("Teststring", "Hello");
            myhashtable.Add("1TestString1", "World");
            myhashtable.Add("2TestString2", "Test");

            Regex rx = new Regex("^[1-9]");
            var k = (from string key in myhashtable.Keys
                     where rx.IsMatch(key)
                     select key).ToList();

            k.ForEach(s => myhashtable.Remove(s));
```
```
EDIT: I have just added list of sting rather then a hashtable, I couldn't remember which .net version had generic lists in it ***slaps forehead


q:
I'm dealing with a large group of entities that store locations. They are displayed on a map. I'm trying to come up with an efficient way to group near located entities into one entity when viewed from a higher location. So, for example, if you are very high, when looking down, you will see one entity that represents a group of closely located entities in an area. Zooming in close enough would split that entity out into its contained entities.

Is there an efficient algorithm for doing this? I thought about just griding off the view based on height and dropping entities into grid boxes based on location then rendering the box point. My only concern is if all the entities are in the upper right of that box, the entity rendered to represent them might be centered in the middle instead of the location of the group of entities.

Any thoughts or ideas?


q:
I have double (or float) variables that might be "empty", as in holding no valid value. How can I represent this condition with the built in types float and double?

One option would be a wrapper that has a float and a boolean, but that can´t work, as my libraries have containers that store doubles and not objects that behave as doubles. Another would be using NaN (std::numeric_limits). But I see no way to check for a variable being NaN.

How can I solve the problem of needing a "special" float value to mean something other than the number?

[A]
We have done that by using NaN:
```
```
double d = std::numeric_limits<double>::signaling_NaN();
bool isNaN = (d != d);
```
```
NaN values compared for equality against itself will yield false. That's the way you test for NaN, but which seems to be only valid if
```
std::numeric_limits<double>::is_iec559
```
is true (if so, it conforms to ieee754 too).
In C99 there is a macro called
```
isnan
```
for this in
```
math.h
```
, which checks a floating point number for a NaN value too.


q:
This is for my DB class. I am new to OO, been a procedural lad for some time, so I'm still a bit murky.

My first idea was using a bunch of setter functions/methods.. but after writing a whole bunch, I thought about using PHP's define function, like so.

define('MYSQL_USERNAME', 'jimbo');

Is this an accepted practice? What is the best practice? Should I really clutter my class with a bunch of setter functions (I am currently the only developer using these classes). What are your solutions?

Thank you!

[A]
there are probably a few options to deal with this:
just use setters, it's perfectly acceptable, but can get a bit "wordy" with a lot of config options.
use a config object to pass in:
```
```
$config = (object) array(
   'prop1' => 'somevalue',
   'prop2' => 'somevalue2',
   'prop3' => 'somevalue3',
);

$db = new DB($config);
```
```
if you want to use constants, you could restrict them to the class to avoid global namespace pollution:
```
```
class DB {
    const USER = 'mysqluser';
}

echo DB::USER; // for example
```
```


q:
Generally speaking what do you get out of extending an artificial neural net by adding more nodes to a hidden layer or more hidden layers?

Does it allow for more precision in the mapping, or does it allow for more subtlety in the relationships it can identify, or something else?

[A]
This is very interesting question but it's not so easy to answer. It depends on the problem you try to resolve and what neural network you try to use. There are several neural network types.
I general it's not so clear that more nodes equals more precision. Research show that you need mostly only one hidden layer. The numer of nodes should be the minimal numer of nodes that are required to resolve a problem. If you don't have enough of them - you will not reach solution.
From the other hand - if you have reached the number of nodes that is good to resolve solution - you can add more and more of them and you will not see any further progress in result estimation.
That's why there are so many types of neural networks. They try to resolve different types of problems. So you have NN to resolve static problems, to resolve time related problems and so one. The number of nodes is not so important like the design of them.


q:
I'm using a UITableView to show some data from an array. This array can be changed at any time by other threads. (I believe that whether the array is mutable, or just replaced entirely, doesn't make a difference.) Access to the array itself is threadsafe.

What's the proper way to ensure thread safety with regard to the tableview? I'm worried, for example, that I might change the array to be shorter just before cellForRowAtIndexPath is called, leading to an NSRangeException.

Should I...

Enforce that the array is only changed on the main thread? (Seems ugly.)

Maintain a shadow array and update this on the main thread through KVO observing?

??? There must be a better solution...

[A]
From your description, you really have TWO different data sets:
The actual data, as it exists in your model
The data that's displayed to the user
Thus, you already have, in effect, a 'shadow' array (virtual shadow, which may be stretching the metaphor too far). I'd say your best bet is to formalize this arrangement, and keep a 'display' array that only gets modified in the main thread. In it, you can have objects from your 'real' array; since they're only pointers, you won't be giving up too much memory.
Threading is evil.


q:
The software base I am developing for uses a signficant amount of yacc which I don't need to deal with. Some times I think it would be helpful in understanding some problems I find but most of the time I can get away with my complete ignorance of yacc.

My question are there enough new projects out there that still use yacc to warrant the time I'll need to learn it?

Edit: Given the response is mostly in favour of learning Yacc, is there a similar language that you would recommend over yacc?

[A]
Yes, these tools are worth learning if you ever need to create or modify code that parses a grammar.
For many years the de facto tool for generating code to parse a grammar was yacc, or its GNU cousin, bison.
Lately I've heard there are a couple of new kids on the block, but the principle is the same:  you write a declarative grammar in a format that is more or less in Backus-Naur Form (
BNF
) and yacc/bison/whatever generates some code for you that would be extremely tedious to write by hand.
Also, the principles behind grammars can be very useful to learn even if you don't need to work on such code directly.  I haven't worked with parsers much since taking a course on Compiler Design in college, but understanding runtime stacks, lookahead parsers, expression evaluation, and a lot of other related things has helped me immensely to write and debug my code effectively.
edit:
Given your followup question about other tools, Yacc/Bison of course are best for C/C++ projects, since they generate C code.  There are similar tools for other languages.  Not all grammars are equivalent, and some parser generators can only grok grammars of a certain complexity.  So you might need to find a tool that can parse your grammar.  See
http://en.wikipedia.org/wiki/Comparison_of_parser_generators


q:
I get a 404 response from .Net MVC when I try to make a request where my search term ends with a . (period). This is the route that I'm using:

routes.MapRoute(
                "Json",
                "Remote.mvc/{action}/{searchTerm}/{count}",
                new { controller="Remote", count=10}
            );

The search works fine with a . inside the search term, it just cannot end with it.  Any thoughts on how to route this search request?

[A]
If you are using .NET 4.0, you can set this flag in the system.web section of your web.config and it will be allowed:
```
```
<httpRuntime relaxedUrlToFileSystemMapping="true" />
```
```
I've tested it and it works.
Haack
has an explanation of it.


q:
I have a desktop application having heavyweight components (JxBrowser) in a JFrame. How can I make a snapshot from the GUI and save it to for example a png file?

Note: The method using Graphics2d and Component.paint()/paintAll()/print/printAll works only for lightweight components.

Any answers appreciated!

EDIT

I have already tried this:

robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));

But I want the inner component to be captured...

EDIT

The situation seems to converge to this solution: if I have a bigger heavyweight component in my JFrame, so it is rendered on a JScrollPane then there exist no other method to get a snapshot of it programatically then to scroll it/screenshot it with screencapture?

[A]
You mean programmatically?
What about
```
```
Point p = yourAwtComponent.getLocationOnScreen();
int w   = yourAwtComponent.getWidth();
int h   = yourAwtComponent.getHeight();

Rectangle rectangle = new Rectangle( p.x, p.y, w, h );

Image image = robot.createScreenCapture(rectangle);
```
```
And then something like this:
```
```
ImageIO.write( image, "png", file );
```
```


q:
Here's a code snippet. . .

<form name="FinalAccept" method="get"><br>

<input type="radio" name="YesNo" value="Yes" onclick="/accept"> Yes<br>

<input type="radio" name="YesNo" value="No" onclick="/accept"> No<br>

Clearly, what I'm trying to do is call the routine linked to /accept when the user clicks on the radio button.

I know the routine is working because I call the same routine from another place in the program.

I'm trying to run it locally using google appserver. Is there something I'm missing?

Thanks

[A]
Your onClick event is expecting some javascript code:
```
```
onclick="SomeJavaScriptCode"
```
```
More here:
http://www.w3schools.com/jsref/jsref_onClick.asp
So, you should be doing something like this:
```
```
onClick="myfunction('my value');"
```
```
EDIT: It looks like you want to go to a URL when the user clicks either "yes" or "no".  To do that, you can try this little bit of javascript code:
```
```
onClick="location.href='http://www.example.com/accept';"
onClick="location.href='http://www.example.com/decline';"
```
```
Now, if you want to submit the form automatically when the user clicks either "yes" or "no", then do what Benry suggests:
```
```
onClick="this.form.submit();"
```
```
Hope this helps.


q:
How can I maintain the scroll position of a treeview control in .NET application? For example, I have a treeview control and go through a process of adding various nodes to it tacking them on to the bottom. During this process, I can scroll through the treeview and view different nodes. The problem is when the process completes, the treeview scrolls to the very bottom.

It appears that calling treenode.Expand() is what is throwing me off track here. When a parent node is expanded, it gets the focus.

Is there a way around this? If I'm looking at a specific node while the process is running, I don't want it to jump around on me when the process is done.

[A]
I think I figured it out:
Get the node at the top of the treeview.
Expand the parent node.
Make the node that was previously at the top visible.
```
```
If treeNodeParent.IsExpanded = False Then
    Dim currentNode As TreeNode = TreeViewHosts.GetNodeAt(0, 0)
    treeNodeParent.Expand()
    currentNode.EnsureVisible()
End If
```
```
Is the a better way to do this?


q:
I'm thinking about exploring the idea of having our client software run as a service on a high port and listen for simple http GET requests from 127.0.0.1.  The theory is that I would be able to access this service via js from a web page that is served from my site.

1) User installs client software that installs itself as a service and waits for authenticated requests on 127.0.0.1:8080

2) When the user hits my home page js on the page makes an xhtml request to 127.0.0.1:8080 and asks for the status

3) The home page then makes another js request back to my web server sending the status that it received.

This would allow my users to upload/download and edit files on a USB attached device in real-time from a browser.  Polling could be the fallback method which is close to what we do today.

Has anyone done this and what potential pitfalls are there? Will this even work?

[A]
I can't see any potential pitfalls. I do have a couple of points however.
1/ You probably want to make sure your service only accepts incoming connection from the local machine (127.0.0.1).  Otherwise, anyone could look at your JavaScript and figure out that it's talking to [your-ip]:8080. They could then try that themselves from a remote site (security hole).
2/ I wouldn't use port 8080 as it's commonly used for other things (alternate HTTP servers, etc.). Make it configurable and choose a nice high random-type value.
3/ I'm not sure what you're trying to do with point 3 but I
think
you're trying to send the status back to the user. In which case, why wouldn't the JavaScript on your home page just get the status in a single session and output/update the HTML to be presented to the user?  Your "another js request back to my web server" doesn't make sense to me.


q: What is the equivalent of varchar(max) in MySQL?

[A]
The max length of a varchar is subject to the max row size in MySQL, which is 64KB (not counting BLOBs):
```
```
VARCHAR(65535)
```
```
However, note that the limit is lower if you use a multi-byte character set:
```
```
VARCHAR(21844) CHARACTER SET utf8
```
```
Here are some examples:
The maximum row size is 65535, but a varchar also includes a byte or two to encode the length of a given string. So you actually can't declare a varchar of the maximum row size, even if it's the only column in the table.
```
```
mysql> CREATE TABLE foo ( v VARCHAR(65534) );
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
```
```
But if we try decreasing lengths, we find the greatest length that works:
```
```
mysql> CREATE TABLE foo ( v VARCHAR(65532) );
Query OK, 0 rows affected (0.01 sec)
```
```
Now if we try to use a multibyte charset at the table level, we find that it counts each character as multiple bytes. UTF8 strings don't
necessarily
use multiple bytes per string, but MySQL can't assume you'll restrict all your future inserts to single-byte characters.
```
```
mysql> CREATE TABLE foo ( v VARCHAR(65532) ) CHARSET=utf8;
ERROR 1074 (42000): Column length too big for column 'v' (max = 21845); use BLOB or TEXT instead
```
```
In spite of what the last error told us, InnoDB still doesn't like a length of 21845.
```
```
mysql> CREATE TABLE foo ( v VARCHAR(21845) ) CHARSET=utf8;
ERROR 1118 (42000): Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs
```
```
This makes perfect sense, if you calculate that 21845*3 = 65535, which wouldn't have worked anyway. Whereas 21844*3 = 65532, which does work.
```
```
mysql> CREATE TABLE foo ( v VARCHAR(21844) ) CHARSET=utf8;
Query OK, 0 rows affected (0.32 sec)
```
```


q: Is there a good tutorial on using regular expressions, especially with grep? I tried googling for some, but most tutorials are too basic and cover things I already know.

[A]
Here
is an introductory article.
Here
are some other tutorials.
The definitive book is
Mastering Regular Expressions
by J. Friedl:
alt text http://ecx.images-amazon.com/images/I/51fSgodb1uL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg


q:
I come from a fairly strong OO background, the benefits of OOD & OOP are second nature to me, but recently I've found myself in a development shop tied to a procedural programming habits. The implementation language has some OOP features, they are not used in optimal ways.

Update: everyone seems to have an opinion about this topic, as do I, but the question was:

Have there been any good comparative studies contrasting the cost of software development using procedural programming languages versus Object Oriented languages?

Some commenters have pointed out the dubious nature of trying to compare apples to oranges, and I agree that it would be very difficult to accurately measure, however not entirely impossible perhaps.

[A]
Good idea.  A head-to-head comparison.  Write application X in a procedural style, and in an OO style and measure something.  Cost to develop.  Return on Investment.
What does it mean to write the same application in two styles?  It would be a different application, wouldn't it?  The procedural people would balk that the OO folks were cheating when they used inheritance or messaging or encapsulation.
There can't be such a comparison.  There's no basis for comparing two "versions" of an application.  It's like asking if apples or oranges are more cost-effective at being fruit.
Having said that, you have to focus on things other folks can actually see.
Time to build something that works.
Rate of bugs and problems.
If your approach is better, you'll be successful, and people will want to know why.
When you explain that OO leads to your success... well... you've won the argument.


q: I have signed up with BizSpark and it is a great deal, especially for people like myself in perennial startup mode. As part of BizSpark you get 3 year deployment licenses for software such as Windows Server and SQL Server. Is there any dedicated hosting companies that will allow you to use these licenses without having to pay for licenses built into typically hosting accounts? For example, normally to get SQL Server Standard installed on a dedicated server at a host can cost a fair bit of extra money, but as I already have a license I shouldn't have to pay.

[A]
As far as I know you have a few options.
BizSpark has a hosting company agreement, you could contact them
Most hosting companies with dedicated systems will sell you a basic configuration and allow you to install your own software.  (However, windows might be the only tricky one).
I personally recommend both
RackSpace
and
HostMySite
for hosting, if you contact their sales people they will let you know what is possible.


q:
Many databases I've encountered (Like SQL Server) use a single file to store the entire database.  This seems to be a pretty common approach. What are the advantages to storing the entire database in a single file, as opposed to breaking up the data into more logical units, such as a single table per file.

Also, how does a database work internally. How does it handle concurrent writes to the same file by different threads.  In most applications I've seen you can only have 1 open write handle on a file at a time. How do the various database engines handle the concurrent writes.

[A]
A single non-fragmented large file can be treated by the server application much like a raw disk is treated by the operating system: a random-seekable block of bytes. The database server could, if it chose to, implement an entire file system on top of that block of bytes, if there was a benefit to implementing tables as separate files.
Concurrent writes to different sections of the same file are not a problem. The database uses locking strategies to make sure that multiple threads aren't trying to access the same section of the file, and this is one of the main reasons that database transactions exist: to isolate the visible effects of one transaction from another.
For example, a database server might keep track of which rows in which tables have been accessed by which in-flight transactions; when a transaction retires, the rows which it had touched are released so that they can be freely accessed by other transactions. In this scenario, other transactions might simply block - i.e. wait - when they try to access rows that are currently being part of another transaction. If the other transaction doesn't complete within a reasonable (configurable) time, then the waiting transaction might be aborted. Often the reason for this is a deadlock. The application using the database can then choose, if it wants, to retry the transaction.
This locking could be implemented using semaphores or other synchronization mechanisms, depending on the performance tradeoffs.


q:
Informed options needed about the merits of flat file database.  I'm considering using a flat file database scheme to manage data for a custom blog.  It would be deployed on Linux OS variant and written in Java.

What are the possible negatives or positives regarding performance for reading and writing of both articles and comments?

Would article retrieval crap out because of it being a flat file rather than a RDBMS if it were to get slash-doted? (Wishful thinking)

I'm not against using a RDBMS, just asking the community their opinion on the viability of such a software architecture scheme.

Follow Up:
In the case of this question I would see “Flat file == file system–based” For example each blog entry and its accompanying metadata would be in a single file. Making for many files organized by date structure of the file folders (blogs\testblog2\2008\12\01) == 12/01/2008

[A]
(answer copied and modified from
here
)
I would advise against using a flat file for anything besides read-only access, because then you'd have to deal with concurrency issues like making sure only one process is writing to the file at once. Instead, I recommend
SQLite
, a fully functional SQL database that's stored in a file. SQLite already has built-in concurrency, so you don't have to worry about things like file locking, and it's really fast for reads.
If, however, you are doing lots of database changes, it's best to do them all at once inside a
transaction
. This will only write the changes to the file once, as opposed to every time an change query is issued. This dramatically increases the speed of doing multiple changes.
When a change query is issued, whether it's inside a tranasction or not, the whole database is locked until that query finishes. This means that extremely large transactions could adversely affect the performance of other processes because they must wait for the transaction to finish before they can access the database. In practice, I haven't found this to be that noticeable, but it's always good practice to try to minimize the number of database modifying queries you issue, and it's certainly faster then trying to use a flat file.


q:
How can I parse integers passed to an application as command line arguments if the app is unicode?

Unicode apps have a main like this:

int _tmain(int argc, _TCHAR* argv[])

argv[?] is a wchar_t*. That means i can't use atoi. How can I convert it to an integer? Is stringstream the best option?

[A]
if you have a TCHAR array or a pointer to the begin of it, you can use
```
std::basic_istringstream
```
to work with it:
```
```
std::basic_istringstream<_TCHAR> ss(argv[x]);
int number;
ss >> number;
```
```
Now,
```
number
```
is the converted number. This will work in ANSI mode (_TCHAR is typedef'ed to
```
char
```
) and in Unicode (_TCHAR is typedef`ed to wchar_t as you say) mode.


q: Is it possible to have a WPF window/element detect the drag'n'dropping of a file from windows explorer in C# .Net 3.5? I've found solutions for WinForms, but none for WPF.

[A]
Turns out I couldn't drop onto my TextBox for some reason, but dropping onto buttons works fine. Got it working by adding 'AllowDrop="True"' to my window and adding drop event handler to button consisting of:
```
```
private void btnFindType_Drop(object sender, DragEventArgs e)
{
  if (e.Data is System.Windows.DataObject &&
    ((System.Windows.DataObject)e.Data).ContainsFileDropList())
  {
    foreach (string filePath in ((System.Windows.DataObject)e.Data).GetFileDropList())
    {
      // Processing here
    }
  }
}
```
```


q:
this c# code is probably not the most efficient but gets what I want done.

How do I accomplish the same thing in F# code?

    string xml = " <EmailList> " +
               "      <Email>test@email.com</Email> " +
               "      <Email>test2@email.com</Email> " +
               " </EmailList> ";

    XmlDocument xdoc = new XmlDocument();
    XmlNodeList nodeList;
    String emailList = string.Empty;
    xdoc.LoadXml(xml);
    nodeList = xdoc.SelectNodes("//EmailList");
    foreach (XmlNode item in nodeList)
    {
        foreach (XmlNode email in item)
        {
             emailList +=  email.InnerText.ToString() +  Environment.NewLine ;
        }
    }

[A]
If you look at your code, you have a couple of things going on. The first is loading the collection for the Email nodes, and the second is actually doing something meaningful with them.
First, you'd want to have your function return a collection. Something like (and I'm on my Mac, so this may not work):
```
```
List<string> EmailAddresses(string xml)
{
    XmlDocument xdoc = new XmlDocument();
    XmlNodeList nodeList;
    String emailList = string.Empty;
    xdoc.LoadXml(xml);
    nodeList = xdoc.SelectNodes("//EmailList");
    foreach (XmlNode item in nodeList)
    {
        foreach (XmlNode email in item)
        {
             yield email.InnerText.ToString();
        }
    }
}
```
```
Now the question comes around what you want to do with that collection. In your example above, you were concatenating it, or basically storing state.
From a C# perspective, you can then start using things like the answers from
this question
(using LINQ) and
this one
.
From an F# perspective, you now have a list and can simply use the normal procedures for a list like
this one
or
here
.
You can also look at
LINQ to XML
(or at the
5 minute overview
) to get some more ideas.


q:
How do you safely encode a URL using JavaScript such that it can be put into a GET string?

var myUrl = "http://example.com/index.html?param=1&anotherParam=2";
var myOtherUrl = "http://example.com/index.html?url=" + myUrl;

I assume that you need to encode the myUrl variable on that second line?

[A]
Check out the built-in function
encodeURIComponent(str)
and
encodeURI(str)
.
In your case, this should work:
```
```
var myOtherUrl =
       "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
```
```


q:
I just installed the SharePoint SDK on my machine, but I can't seem to find the location of Microsoft.Sharepoint.dll so I can add a reference to it.

It's not in the GAC or C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\ and a search comes up with nothing.

Any suggestions?

[A]
It might show up in the "add reference" dialog anyway - 99% of the time you don't reed to know the physical location.  Look in the ".Net" list, which is sorted alphabetically.
I assume the SDK installer would assert this, but Sharepoint development also requires a server OS.


q:
I'm administering a svn repo for a project where the source wasn't imported with a single top level directory. As a result, there are about 15 separate 'projects' instead of one. How can I merge these into one folder while maintaining the change history?

*hint: svn move doesn't work in this case.

[edit]
whoops, dupe of Combining multiple SVN repositories into one

[A]
If you don't care about retaining all the history of one of the repositories, you can just create a new directory under one project's repository, then import the other.
If you care about retaining the history of both, then you can use 'svnadmin dump' to dump one repository, and 'svnadmin load' to load it into the other repository. The revision numbers will be off, but you'll still have the history.
Copied from here:
http://subversion.tigris.org/faq.html#multi-merge


q:
Any idea on how to check whether that list is a subset of another?

Specifically, I have

List<double> t1 = new List<double> { 1, 3, 5 };
List<double> t2 = new List<double> { 1, 5 };

How to check that t2 is a subset of t1, using LINQ?

[A]
Try this
```
```
static bool IsSubSet<A>(A[] set, A[] toCheck) {
  return set.Length == (toCheck.Intersect(set)).Count();
}
```
```
The idea here is that Intersect will only return the values that are in both Arrays.  At this point if the length of the resulting set is the same as the original set, then all elements in "set" are also in "check" and therefore "set" is a subset of "toCheck"
Note: My solution does not work if "set" has duplicates.  I'm not changing it because I don't want to steal other people's votes.
Hint: I voted for Cameron's answer.


q:
how do i get a list of user that have completed or not completed or not responded to a survey.

so i have a survey, lets say "survey A". in this survey i have a list of people or groups that must fill the survey. sharepoint already gives us a list of respondents, but i want to make a list of people that have not responded or not completed the survey.

i'm using c#, thanks..


q: Trying to build a dashboard using Oracle's Brio.  I have to access 6 different databases to grab the same type of data, aggregate it and display it.  Except that when I do it, Brio grabs the data from the first source just fine.  When I grab the data from the second data source, Brio replaces the original data with the second set.  So I am not able to aggregate the data.  Can anyone help me figure out how I can do this in Brio please?


q:
I'm working on a site now that have to fetch users feeds. But how can I best optimize fetching if I have a database with, lets say, 300 feeds. I'm going to set up a cron-job to which fetches the feeds, but should I do it like 5 every second minute or something?

Any ideas on how to do this the best way in PHP?

[A]
Based on the new information I think I would do something like this:
Let the "first" client initiate the updatework and store timestamp with it.
Everey other clients that will ask for the information get a cashed information until that information are to old. Next hit from a client will then refresh the cashe that then will be used by all clients till next time its to old.
The client that will actually initiate the updatework should not have to wait for it to finnish, just serv the old cashed version and continue to do it till the work is done.
That way you dont have to update
anything
if no clients are requesting it.


q:
I'll phrase this in the form of an example to make it more clear.

Say I have a vector of animals and I want to go through the array and see if the elements are either dogs or cats?

class Dog: public Animal{/*...*/};
class Cat: public Animal{/*...*/};

int main()
{
vector<Animal*> stuff;
//cramming the dogs and cats in...

for(/*all elements in stuff*/)
//Something to the effect of:  if(stuff[i].getClass()==Dog) {/*do something*/}

}

I hope that's sort of clear. I know about typeid, but I don't really have any Dog object to compare it to and I would like to avoid creating a Dog object if I can.

Is there a way to do this? Thanks in advance.

[A]
You can use
```
dynamic_cast
```
, as long as the vector contains Animal pointers.
```
```
vector <Animal *> stuff;

for(int i=0;i<stuff.size();i++) {
    Dog *pDog = dynamic_cast <Dog *> (stuff[i]);
    if(pDog) {
        // do whatever with the dog
    }

    Cat *pCat = dynamic_cast <Cat *> (stuff[i]);
    if(pCat) {
        // and so on
    }
}
```
```
but you should be aware that this is generally not the best practice. You should try to work with polymorphism, not against it. In other words, try to write a virtual
```
Animal
```
function that
```
Dog
```
and
```
Cat
```
override, and let the compiler automagically call the right one.
(Also,
```
dynamic_cast
```
is relatively slow, so too many of them will hinder performance; whereas a virtual function call is general just a single instruction.)


q: I'm looking for something containing similar functions to Matlab’s financial and financial derivatives toolbox but don’t have the cash to spend on matlab. I would appreciate any info on free or open source libraries or programs that will let me easily calculate interest rates, risk etc.

[A]
How about the
Octave
financial functions?
http://www.gnu.org/software/octave/doc/interpreter/Financial-Functions.html#Financial-Functions
I'm not familiar with the Matlab toolbox, so you'll have to judge for yourself.
GNU Octave is a high-level language,
  primarily intended for numerical
  computations. It provides a convenient
  command line interface for solving
  linear and nonlinear problems
  numerically, and for performing other
  numerical experiments using a language
  that is mostly compatible with Matlab.
  It may also be used as a
  batch-oriented language.


q:
I was thinking it would be nice to create a base class for NUnit test fixtures that opens a TransactionScope during the SetUp phase, then rolls back the transaction during tear down.
Something like this:

    public abstract class TestFixtureBase
{
    private TransactionScope _transaction;

    [TestFixtureSetUp]
    public void TestFixtureSetup()
    {
        _transaction = new TransactionScope();
    }

    [TestFixtureTearDown]
    public void TestFixtureTearDown()
    {
        if (_transaction != null)
        {
            _transaction.Dispose();
        }
    }
}

Do you think this is a good idea?

Obviously the database is just a test database, not a live database, but it would still be annoying if it filled up with junk data from the unit tests.

What do other people do when running unit tests that involve a lot of data access?

[A]
You want to be careful here.  TransactionScope is going to promote the transaction to a distributed transaction if you open up more than one connection to the database.  I find that it is easier just to write some simple SQL that clears out the tables of interest to my test class before I start running the test.
EDIT:
Normally I would call any test that touches the database an integration test since it involves another system.  Typically, I will mock out the database when unit testing my code.
```
```
[TestSetup]
public void Setup()
{
   foreach (string table in new string[] { "table1", "table2" })
   {
        ClearTable( table );
   }
}

private void ClearTable( string table )
{
     ...standard stuff to set up connection...
     SqlCommand command = connection.CreateCommand() );
     command.CommandText = "delete from " + table;
     command.ExecuteNonQuery();
     ... stuff to clean up connection...
}
```
```


q: I have around 8-9 parameters to pass in a function which returns an array. I would like to know that its better to pass those parameters directly in the function or pass an array instead? Which will be a better way and why?

[A]
Pass them individually, because:
that is the type-safe way.
IntelliSense will pick it up in Visual Studio and when you write your calling functions, you will know what's what.
It is faster to execute that way.
If the parameter really IS the array, though, then pass the array.  Example:
For functions which look like this, use this notation:
```
```
Array FireEmployee(string first, string middle, string last, int id) {...}
```
```
For functions that look like this, use the array:
```
```
Array FireEmployees(Employee[] unionWorkers) {...}
```
```


q:
I'm working on a P2P application, and I need to get it to communicate through NAT Routers / Firewalls using UPnP. However, it doesn't seem that the .NET Framework includes support for UPnP.

Is there a UPnP Library for .NET? C# or VB.NET?

UPDATE: I have since found the NATUPnP 1.0 Type Library (NATUPNP.DLL) COM Component that is part of Windows (since Windows XP) that allows you to easily setup/maintain Port Forwarding using UPnP.

I wrote an article with code samples here:
.NET Framework: Communicate through NAT Router via UPnP (Universal Plug and Play)

[A]
There is a COM library that's easy enough to access:
UPnP APIs
Purpose
The UPnP™ framework enables dynamic
  networking of intelligent appliances,
  wireless devices, and PCs. There are
  two APIs for working with
  UPnP-certified devices:
The
Control Point API
, which consists
  of a set of COM interfaces used to
  find and control devices. The
Device
  Host API
, which consists of a set of
  COM interfaces used to implement
  devices that are hosted by a computer.


q:
I have a page which work like a navigation and a iframe in this page which show the content.

Now there are some situation when the inner page is directly shown in the browser.
eg: if somebody types the inner page's url in the browser address bar, the page is displayed in the window.

I want to prevent this.

Better still, I would like to redirect to any other page.

[A]
```
```
<script language="Javascript"><!--
if (top.location == self.location) {
  top.location = "index.html" // must be viewed in main index
}
//--></script>
```
```
modified it from a situation where an an iframe decides to become the main frame.


q:
I have a goal to build an application with UI that would run on both Windows Mobile and "normal" desktop Windows. The priority is for it to "look good" under Windows Mobile, and for desktop Windows it is OK if it distorted. Before I invest days trying, I would like to hear if that is possible to begin with. There are several parts to this question:

Is .NET Compact Framework a subset of "normal" (please, edit) .NET Framework? If not, does MSDN have any information anywhere on classes that are in .NET Compact Framework, but not in "normal" (again, please, edit) framework?

Is behavior of shared classes same in both frameworks?

Is it possible to have a single Visual Studio 2005 solution / project for both platforms? If yes, how do to set it up?

Any other comments and advice? Any relevant links?

[A]
CF, in general contains a subset of the
classes
from the regular framework - but you can't directly execute code from one on t'other. Additionally, rather than just being a subset, there are probably a few things in compact that aren't in the regular version, such as the GUI things specific for mobile devices (soft keys, etc) - assuming you are writing a winform exe, and not a web page (which might be the simplest way to get compatibility).
With some effort, it it possible to share
logic
code, in particular utility dlls - but they need different csproj files (since they have completely different compile-time "targets"). To reduce maintenance, you can often cheat by hacking the csproj to use wildcards, like from
here
:
```
```
<ItemGroup>
  <Compile Include="..\protobuf-net\**\*.cs" />
</ItemGroup>
```
```
For UI, things get a lot tricker. In general the expectation would be to have shared business logic and separate UI for different target devices.


q:
I would like to know how to setup an SVN repository with LDAP authentication.
I do not want to use Apache DAV though.

[A]
There are two options:
Run svnserve as a server, and authenticate using
SASL
. Configure
SASL to authenticate against LDAP
.
Access the repository over ssh. Create ssh accounts for all users (perhaps automatically), and have these accounts authenticate against LDAP using PAM. Put all users into a single group, and make the repository files owned by that group.