Question:
I know there are libraries out there for working with ZIP files. And, you can alternatively use the functionality built into Windows for working ZIP files.

But, I'm wondering if anyone has worked out how to use the tools built into the System.IO.Compression namespace within .NET for reading/writing ZIP files? Or, is it not possible using only this namespace?

UPDATED: I've seem someone comment that the System.IO.Packaging namespace might be usefull with this also. Does anyone know exactly how to do it?

Answer:
MSDN has a complete
example
http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx
using the ZipPackage class.   Requires .NET 3.5.


Question:
I have this .NET regex:

^(?<prefix>("[^"]*"))\s(?<attrgroup>(\([^\)]*\)))\s(?<suffix>("[^"]*"))$

It properly matches the following strings:

"some prefix" ("attribute 1" "value 1") "some suffix"
"some prefix" ("attribute 1" "value 1" "attribute 2" "value 2") "some suffix"

It fails on...

"some prefix" ("attribute 1" "value (fail) 1") "some suffix"

...due to the right paren after "fail".

How can I modify my regex so that the attrgroup match group will end up containing "("attribute 1" "value (fail) 1")"? I've been looking at it for too long and need some fresh eyes. Thanks!

Edit: attrgroup won't ever contain anything other than pairs of double-quoted strings.

Answer:
```
```
^(?<prefix>"[^"]*")\s+(?<attrgroup>\(.*\))\s+(?<suffix>"[^"]*")$
```
```
fixed it for me.
I removed the extraneous unnamed groups and simplified (down to "any character") the attribute group.
A
very
worthwhile investment would be JG Soft's RegexBuddy
Edit: This won't validate the attribute group as pairs of quoted strings, but that should/could be done in a separate regex/validation step.


Question:
I know that primary keys based on Guids do not have the best performance (due to the fragmentation), but they are globally unique and allow replication scenarios.

Integral identifiers, on the other side, have greater performance at the cost of scalability.

But in what scenarios would someone want to use sequential uniqueidentifier as the primary key? I think, that it beats the purpose of GUID, but still I see mentioning of the sequentals now and then.

What do I miss here?

Answer:
What is commonly known as a sequential guids in SQL Server 2005 (generated by NEWSEQUENTIALID()) are an attempt to overcome the issues with normal guids.
They
are
still universally unique but also are always ascending.  This means that they can be used for replication
and
have much better insert performance than traditional GUIDs.
The one drawback is that they are not "secure" because it is possible to guess the next sequential guid.
http://msdn.microsoft.com/en-us/library/ms189786.aspx


Question:
I display data into an html table, w/ a drop down box with a list of venues. Each volunteer will be assigned a venue. I envision being able to go down thru the html table and assigning each volunteer a venue. The drop down box contains all the possible venues that they can be assigned to.

<select>
<option value="1">Setup</option>
<option value="2">Check in</option>
etc...
</select>

Then once I am done assigning each volunteer, I want to hit submit and it will assign the appropriate value for each volunteer.

How would I go about doing that, I know how to do that, but only one at a time.

Answer:
I can't think of any way. You can put multiple SQL statements into 1 MySQL query:
```
```
UPDATE volunteer SET venue = 1 WHERE id = 2;
UPDATE volunteer SET venue = 2 WHERE id = 3;
...
```
```
I wish there was a way, but I'm thinking that the where will be too different in each query to make it into one.


Question: I am trying to retrieve an image stored in an oracle blob and place it in a new System.Drawing.Image instance. I know I can write the stream to a temp.bmp file on the disk and read it from there but thats just not l33t enough for me.  How do I convert the blob object directly to an image?

Answer:
I know this uses sql but it should be similar for your needs
```
```
Dim cn As SqlConnection = Nothing
        Dim cmd As SqlCommand = Nothing
        Dim da As SqlDataAdapter = Nothing
        Dim ms As MemoryStream = Nothing
        Dim dsImage As Data.DataSet = Nothing
        Dim myBytes() As Byte = Nothing
        Dim imgJPG As System.Drawing.Image = Nothing
        Dim msOut As MemoryStream = Nothing

        Try
            cn = New SqlConnection(ConnectionStrings("conImageDB").ToString)
            cmd = New SqlCommand(AppSettings("sprocGetImage").ToString, cn)
            cmd.CommandType = Data.CommandType.StoredProcedure

            cmd.Parameters.AddWithValue("@dmhiRowno", irowno)

            da = New SqlDataAdapter(cmd)

            dsImage = New Data.DataSet
            da.Fill(dsImage, "image")

            If dsImage.Tables(0).Rows.Count = 0 Then
                Throw New Exception("No results returned for rowno")
            End If
            myBytes = dsImage.Tables(0).Rows(0)("Frontimage")

            ms = New MemoryStream
            ms.Write(myBytes, 0, myBytes.Length)

            imgJPG = System.Drawing.Image.FromStream(ms)

            'Export to JPG Stream
            msOut = New MemoryStream
            imgJPG.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg)
            imgJPG.Dispose()
            imgJPG = Nothing
            ms.Close()
            sFrontImage = Convert.ToBase64String(msOut.ToArray())

            dsImage = New Data.DataSet
            da.Fill(dsImage, "image")
            myBytes = dsImage.Tables(0).Rows(0)("Backimage")

            ms = New MemoryStream
            ms.Write(myBytes, 0, myBytes.Length)

            imgJPG = System.Drawing.Image.FromStream(ms)
            sBackImage = Convert.ToBase64String(ms.ToArray)

        Catch ex As System.IO.IOException ' : An I/O error occurs.
            Throw ex
        Catch ex As System.ArgumentNullException ': buffer is null.
            Throw ex
        Catch ex As System.NotSupportedException ': The stream does not support writing. For additional information see System.IO.Stream.CanWrite.-or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.
            Throw ex
        Catch ex As System.ArgumentOutOfRangeException ': offset or count are negative.
            Throw ex
        Catch ex As System.ObjectDisposedException ' : The current stream instance is closed.
            Throw ex
        Catch ex As System.ArgumentException
            Throw ex
        Catch ex As System.Runtime.InteropServices.ExternalException ': The image was saved with the wrong image format
            Throw ex
        Catch ex As Exception
            Throw ex
        Finally
            If cn IsNot Nothing Then
                cn.Close()
                cn.Dispose()
                cn = Nothing
            End If

            If cmd IsNot Nothing Then
                cmd.Dispose()
                cmd = Nothing
            End If

            If da IsNot Nothing Then
                da.Dispose()
                da = Nothing
            End If

            If ms IsNot Nothing Then
                ms.Dispose()
                ms = Nothing
            End If

            If msOut IsNot Nothing Then
                msOut.Close()
                msOut.Dispose()
                msOut = Nothing
            End If

            If dsImage IsNot Nothing Then
                dsImage.Dispose()
                dsImage = Nothing
            End If

            If myBytes IsNot Nothing Then
                myBytes = Nothing
            End If

            If imgJPG IsNot Nothing Then
                imgJPG.Dispose()
                imgJPG = Nothing
            End If

        End Try
```
```
This code pulls back a tiff wrapped jpeg for the front image so the code is a bit different than for the back image.


Question:
I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on something that was created with the new operator), but I'm not clear on when I should use malloc/ free and when I should use new/ delete in my real world programs.

If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.

Answer:
Unless you are forced to use C, you should
never use
```
malloc
```
.  Always use
```
new
```
.
If you need a big chunk of data just do something like:
```
```
char *pBuffer = new char[1024];
```
```
Be careful though this is not correct:
```
```
//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;
```
```
Instead you should do this when deleting an array of data:
```
```
//This deletes all items in the array
delete[] pBuffer;
```
```
The
```
new
```
keyword is the C++ way of doing it, and it will ensure that your type will have its
constructor called
.  The
```
new
```
keyword is also more
type-safe
whereas
```
malloc
```
is not type-safe at all.
The only way I could think that would be beneficial to use
```
malloc
```
would be if you needed to
change the size of your buffer
of data.  The
```
new
```
keyword does not have an analogous way like
```
realloc
```
.  The
```
realloc
```
function might be able to extend the size of a chunk of memory for you more efficiently.
It is worth mentioning that you cannot mix
```
new
```
/
```
free
```
and
```
malloc
```
/
```
delete
```
.
Note: Some answers in this question are invalid.
```
```
int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements
```
```


Question: PNG images appear "fuzzy" in flash CS3. They are very blocky and appear unanti-aliased (if that is a word) Does anyone have a fix for this? Is there some setting I'm missing?

Answer:
Are you loading them into your SWF through a loader? Or are they imported into your library as bitmap symbols? If they are loaded in try calling Bitmap.smoothing = true; or if they are in your library go to the Bitmap's properties and click Allow smoothing.
Other than that I would check to make sure you don't have some crazy above 1 alpha setting or that you aren't messing with the scale of it in your code at any time. Those two options tend to mess with bitmap images fuzziness.
If all else fails you'd probably want to look into turning your images into vector based graphics, then they'd always look exactly how you'd want them to regardless of scaling.


Question:
I am currently using Rails 2.1.0 and want to upgrade to Rails 2.1.1. After issuing the following command

gem update rails

I suppose that I need to change this line

RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION

in environment.rb

What other actions should I take to ensure that my application is using the latest version? Are there some other files that need an update?

Answer:
As far as I know, that right there defines what version of rails your application as a whole will use. I know for a project I'm in right now I had to override that to 2.1.1 to work on my VM because I had installed the latest, and had not specified the 2.1.0 as required by the project.
The biggest thing you have to watch out for is plugins and extensions that may override this setting, as well as incompatibility that will likely arise from changing versions.
Also there are some known issues with 2.1.1, unless there is a feature you absolutely need now, you may want to wait.


Question:
I downloaded a VM image of a web application that uses MySQL.

How can I monitor its space consumption and know when additional space must be added?

Answer:
If only MySQL is available, use the SHOW TABLE STATUS command, and look at the Data_length column for each table, which is in bytes.
If you have other languages available on the machine, a script in any of them that runs regularly (cron), checks disk free space or size of database directory, and updates you over e-mail or otherwise. There are far too many options to suggest a particular solution -- it depends on your situation.


Question:
If I have two variables containing binary values, how do I append them together as one binary value?  For example, if I used WMI to read the registry of two REG_BINARY value, I then want to be able to concatenate the values.

VBScript complains of a type mismatch when you try to join with the '&' operator.

Answer:
Perhaps...
```
```
result = CStr(val1) & CStr(val2)
```
```


Question:
Is there a way to do this in one line?

$x =~ s/^\s+//;
$x =~ s/\s+$//;

In other words, remove all leading and trailing whitespace from a string.

Answer:
Here you go:
```
$x =~ s/\A\s*(.*?)\s*\z/$1/;
```


Question:
I have topics(id*) and tags(id*,name) and a linking table topic_tags(topicFk*,tagFk*).

Now I want to select every single topic, that has all of the good tags (a,b,c) but none of the bad tags (d,e,f).

How do I do that?

Answer:
Here's a solution that would work, but requires a join for every tag you require.
```
```
SELECT *
FROM topics
WHERE topic_id IN
    (SELECT topic_id
    FROM topic_tags a
    INNER JOIN topic_tags b
      on a.topic_id=b.topic_id
      and b.tag = 'b'
    INNER JOIN topic_tags c
      on b.topic_id=c.topic_d
      and c.tag = 'c'
    WHERE a.tag = 'a')
AND topic_id NOT IN
    (SELECT topic_id
    FROM topic_tags
    WHERE tag = 'd' or tag = 'e' or tag = 'f')
```
```


Question:
I have a situation where I have two models, companies and permissions, where companies is in a separate database from my permissions database.  This is a has and belongs to many relationship because each company can have many permissions and each permission can belong to many companies.

The reason the two databases are split is because the company database runs a high demand production application and the permissions database controls the permissions for another application.

With rails, it looks for the join table in the same database as the primary table.  For instance, if I do company.permissions, it looks in the company database for company_permissions.  If I do permission.companies it looks in the permissions database.

What is the best solution to using a has and belongs to many relationship with multiple databases?

Answer:
If the companies data does not change very often, perhaps you could synchronize the data into the permissions database, then do your join naturally. A CMS I inherited is doing something like that where the user authentication is in its own database, and the permissions and such are all stored there, and user accounts are synch'd to the local database for each site. This way user accounts could be shared (especially for administration) across multiple sites with 1 login.
May not be the best because a synch is involved. Ideally you should just store the company data in the permissions db if you can't move permissions out. Unless of course you are joining on company elsewhere.


Question: What is the best comment in source code you have ever encountered?

Answer:
```
```
//ALL YOUR BASE ARE BELONG TO US
```
```
...it made my boss think someone had hacked in. He didn't know the joke.


Question:
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?

lst = ['one', 2, 3]

lst1 = list(lst)

lst2 = lst[:]

import copy
lst3 = copy.copy(lst)

Answer:
If you want a shallow copy (elements aren't copied) use:
```
```
lst2=lst1[:]
```
```
If you want to make a deep copy then use the copy module:
```
```
import copy
lst2=copy.deepcopy(lst1)
```
```


Question: I've read (and re-read) Martin Fowler's Mocks Aren't Stubs.  In it, he defines two different approaches to TDD: "Classical" and "Mockist".  He attempts to answer the question "So should I be a classicist or a mockist?", but he admits that he has never tried mockist TDD on "anything more than toys."  So I thought I'd ask the question here.  Good answers may repeat Fowler's arguments (but hopefully more clearly) or add arguments that he didn't think of or that others have come up with since Fowler last updated the essay back in January 2007.

Answer:
I don't think you need to choose one over the other. Both have their advantages and disadvantages and both are tools for your toolbox.
"Mockist" tdd makes you a bit more flexible in what you can test while classical TDD makes your tests a bit less brittle because they tend to look more at the input/vs output instead of looking at the actual implementation. When doing mockist unit testing I seem to have more tests break when changing the implementation.
I try to use classical tdd whenever possible (although i often use a mocking framework to set up the stubs quickly). Sometimes I notice I start testing too much at one time or i need too many objects to set up a test. That's when mockist testing can often help you set up smaller tests.
This is all quite abstract so I hope i make sense


Question:
Let's say that you have a product that is written in Visual Studio and you provide your customers and users with an installer for that product.

Then, you have some minor changes that you want to deploy to your users; you don't want your users to have to go through an uninstall process, backing up the configuration and then reinstalling the product again and restoring the configuration.

Instead, you want to provide a "hot-fix" that the users can simply copy over the already installed product. Using Visual Studio or some Microsoft tools, how would you go about this?

I don't know if it matters, but lets say that the product is 1) partially a web application, 2) partially a windows service and 3) partially a windows application.

Answer:
Use
WiX
.
It can deal with all those things (installation web applications, services, etc), and it's very flexible, free, and it's what Microsoft uses to build their installers.
You can install
Votive
to work with WiX inside of Visual Studio.
The details of how to do exactly what you're asking is a bit complex, and depends on the specifics of the situation. In general, you need to build your initial MSI to have an upgrade code. Then, subsequent upgrade installers will use the same product code and  upgrade code, but change the version. You can read the details of how to do this with WiX as
part 4 of the tutorial
.
IF you have existing installs, they may or may not have an upgrade code already set. You can find out by examining them using
ORCA
(
MSDN how to here
).
This can also be done via the .Net Setup projects built into Visual Studio, but I advise against that. They are not as flexible as WiX. If you care about your installation, and have something as complicated as what you're describing to install, WiX is the best way to go.


Question:
I'm using SimpleDateFormat with the pattern EEE MM/dd  hh:mma, passing in the date String Thu 10/9  08:15PM and it's throwing an Unparseable date exception. Why? I've used various patterns with SimpleDateFormat before so I'm fairly familiar with its usage. Maybe I'm missing something obvious from staring at it too long.

The other possibility is funky (technical term) whitespace. The context is a screen-scraping app, where I'm using HtmlCleaner to tidy up the messy html.  While I've found HtmlCleaner to be pretty good overall, I've noticed strange issues with characters that look like whitespace but aren't recognized as such with a StringTokenizer, for example. I've mostly worked around it and haven't dug into the character encoding or anything like that but am starting to wonder.

Answer:
Try this instead for your pattern:
```
```
EEE MM/d hh:mma
```
```
The difference is the single
```
d
```
instead of double
```
dd
```
, since your date is for 10/9 instead of 10/09.


Question:
Which of these pieces of code is faster?

if (obj is ClassA) {}

if (obj.GetType() == typeof(ClassA)) {}

Edit:
I'm aware that they don't do the same thing.

Answer:
This should answer that question, and then some.
The second line,
```
if (obj.GetType() == typeof(ClassA)) {}
```
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)


Question:
Can someone give me step by step instructions or point to the correct references in the correct order

so that I can determine the root cause of this issue?

Answer:
You can get a memory dump of the process and look into it WinDbg. It will at least give you a list of exceptions and the threads' current state(s). Doing so will recycle the process though.  It is also possible to attach to a QA style machine in a remote debug mode from visual studio. However I've not done this, and it would hang every other request while you debug.
If w3wp is running locally, you can right click on the process in the task manager and select debug to get a look at in in WinDbg.
Otherwise you want something like Debug Diag on your production/test machine to create a full user dump. See:
http://msdnrss.thecoderblogs.com/2008/05/21/debugdiag-11-or-windbg-which-one-should-i-use-and-how-do-i-gather-memory-dumps/
I did all this back in February, and haven't needed to since. the full step by step is actually somewhat painful due to getting symbols for WinDbg and configuring environment variables for where they should be stored etc.
For information on setting up WinDbg for ASP.NET inspection look at this article:
http://support.microsoft.com/kb/892277


Question:
I have a form that is sending in sizes of things, and I need to see what the strings are equal to so that I can set the price accordingly. When i try to do this, it says that they are not equal, and i get no prices. This is the code i'm using:

if ($_POST['sizes'] == "Small ($30)"){$total = "30";}
if ($_POST['sizes'] == "Medium ($40)"){$total = "40";}
if ($_POST['sizes'] == "Large ($50)"){$total = "50";}
else {$total = $_POST['price'];}

What am i doing wrong here? I can echo $_POST['sizes'] and it gives me exactly one of those things.

Answer:
Try using single quotes
```
```
if ($_POST['sizes'] == 'Small ($30)'){$total = "30";}
elseif ($_POST['sizes'] == 'Medium ($40)'){$total = "40";}
elseif ($_POST['sizes'] == 'Large ($50)'){$total = "50";}
else {$total = $_POST['price'];}
```
```
Double quoted strings use variable interpolation, so the $ symbol becomes significant! See
this manual page
for the differences in how you can declare string literals in PHP.
(Edited to correct the logic error - as others noted, a switch would be much clearer here)


Question:
Like it is the case with jpeg images for example?
What's about mp3 or ogg vorbis audio files?

Answer:
It all depends on the definition of "loading" and "saving".
If the program in question actually decodes mp3/ogg upon loading and encodes in back when saving (this could be detected by noticeable time it takes to save a file), then yes - you could experience degradation in quality. Especially if the encoding uses different settings (lower bitrate, etc).
On the other hand, a loseless mp3 splitter, for example, could take mp3 and split it into several smaller mp3's without re-encoding them.
So you need to consult a manual of the software in question, there is no generic answer.


Question: What is the difference between a deep copy and a shallow copy?

Answer:
In short, it depends on what points to what. In a shallow copy, object B points to object A's location in memory. In deep copy, all things in object A's memory location get copied to object B's memory location.
This wiki article has a great diagram.
http://en.wikipedia.org/wiki/Object_copy


Question:
I have a windows c# application and I want to display a pdf file, located on a webserver, in an acrobat com object added to my form.

pdf.loadfile(@"http://somewhere.com/nowwhere.pdf")

As my pdf is large, the application seems to hang till the entire file is loaded.

I want to read the large file without the user being under the perception that the application is hung.

Answer:
Three suggestions.
the first would be to break it and load a page at a time like some online books do. This is a bit annoying but would save you the loading time. I think ItextSharp has some functionality to do this.
Second try compression. again itextsharp has tools that allow for this
My third suggestion would be to check out
This thread
. choose a few nerdy loading phrases and use an animated gif to distract your client from the long loading time. Obviously this is a last resort, but could useful.


Question: I have a (Wordpress powered) website, and Google is indexing some of the sub-directories. How can I stop Apache from showing users the directory listing? I know I can edit .htaccess to password-protect a directory, but I would prefer a 403 / custom redirect if possible.

Answer:
Look at your robots.txt rules, and make sure apache is not serving-up directory listings.
see
http://httpd.apache.org/docs/2.0/howto/htaccess.html
&&
http://www.webmasterworld.com/forum92/5272.htm


Question:
I swear there used to be a way in X to start capturing all terminal traffic to a file on your host. It may have been a HummingBird extension, but I thought it was standard. Now, I can't find the trick. Am I hallucinating (happens when you get old), or is it possible?

I'm not talking about 'tee'. I want to be able to send a xterm control-sequence to stdout, giving a file name, and have everthing shown in the window from that time onward saved to the file (until the bookend cancel is issued).

Answer:
I am a little bit confused by the way you asked your question. First you mention Xterm then X and then terminal, are you simply looking for the "tee" (
```
man tee
```
) command?


Question:
I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:

<a href="#" onclick="foo()">Click</a>

But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing.

Answer:
```
```
Click
```
```


Question: I just want to enable or disable the button inside a ControlTemplate for a WPF Editor that I'm using.

Answer:
You really shouldn't be doing that explicitly, but instead be setting it with Triggers in the
```
ControlTemplate
```
itself. These Triggers would be reacting to some other change, and would set the
```
Enabled
```
property of the
```
Button
```
.


Question:
I have a webapp which resizes its window to exactly fit its contents:

window.resizeTo(200,300)

People do like having the page fit its window in this way. However with Firefox the next browser window the user opens comes up at the same size, which is ridiculously small.

Is there a way to tell Firefox to resize the current window, but not change its notion of how large subsequent windows should be?

Answer:
People do like having the page fit its window in this way.
Which
people?! I'd be seriously annoyed if a web page did anything to the size of my browser window. Fortunately, FF also allows users to disable moving or resizing existing windows, a feature i've taken advantage of for several years.
You should be able to open a
new
window at a specific size using
```
window.open
```
, so you could use that... or better yet, just allow your document to resize / reflow to fit into whatever window size the user prefers.


Question:
I just noticed that java.beans.Introspector getBeanInfo does not pickup any superinterface's properties. Example:

public interface Person {
    String getName();
}
public interface Employee extends Person {
    int getSalary();
}

Introspecting on Employee only yields salary even though name is inherited from Person.

Why is this? I would rather not have to use reflection to get all the getters.

Answer:
Try using
```
```
public static BeanInfo getBeanInfo(Class<?> beanClass, Introspector.USE_ALL_BEANINFO);
```
```
and see if this yields the result you're looking for.


Question:
Is there a way to test the type of an element in JavaScript?

The answer may or may not require the prototype library, however the following setup does make use of the library.

function(event) {
  var element = event.element();
  // if the element is an anchor
  ...
  // if the element is a td
  ...
}

Answer:
```
```
if (element.nodeName == "A") {
 ...
} else if (element.nodeName == "TD") {
 ...
}
```
```


Question:
Environment:

Windows Server 2003 R2 Enterprise 64bit, SP2

.NET framework is supposedly installed (2.0 SP2, 3.0 SP2, 3.5 SP1)

I say "supposedly" because they are listed as installed under Add/Remove programs. I'm not sure it's properly installed, because the "ASP.NET" tab isn't added to any of the sites in IIS.

In the IIS Web Service Extensions section, I have both "ASP.NET v2.0.50727" (Allowed), and "ASP.NET v2.0.50727 (32-bit)" (Prohibited).

The site in question has script-execute enabled.

Problem:

I created a super-simple ASP.NET/C# website: Default.aspx with a label id="Label1", and a code-behind with: Label1.text = "Hello World"; and the error I'm getting is:

%1 is not a valid Win32 application.

Answer:
Have you tried running:
```
```
aspnet_regiis -i
```
```
from the command line?


Question:
In emacs there is a handy way to launch the gdb and gui options for gdb, the C debugger.

Is there a similar option in gvim?

Answer:
I don't think there is.  I use different windows.
The only thing I can think of is
```
```
!gdb blah blah blah
```
```
but that may not be what you are looking for.  It tends to be used to generate batch text that gets plugged back into the file you are editing.
Hope this helps.


Question:
I would like to be able to spawn a linux process that would only have access to stdin, stdout, and stderr (nothing more and nothing less). Can I do this at the process level itself? I am also implicitly stating (oxymoron) that I don't want the spawned process to be able to change the "thing" that the other end of the stream points to.

Metaphorically:

the process has a input pipe that comes from somewhere, it cannot change where the pipe starts from, so it cannot control where input comes from.

the process has output and error pipes that go somewhere, it cannot change where the other end of the output pipes point to, so it cannot control where output goes to.

it cannot create any new pipes.

I am also currently looking at SElinux. Would this allow me to create a process that only had access to these three streams? Thank you.

Answer:
If you're root, you can chroot to a directory, drop privileges so that you no longer have filesystem write access, then exec.  That will prevent a program from creating new files.  But there's no way to prevent a program from creating pipes and sockets (well, no-sockets is possible with SELinux), and there's no way to prevent a program from rearranging and closing its file descriptors.
Well, I suppose you could use
```
ptrace
```
to trap all syscalls, and only allow the ones that you approve of, so when I say "there's no way" I mean "there's no easy way".  This incurs a noticable overhead, but if you're careful enough you can make it secure.  The
```
strace
```
or
UMview
projects may be good starting points if you decide to go down this path.


Question:
Can you please let me know the SQL to split date ranges when they overlap?

Data (sample data with a date range and possibly other columns):

    Col1 FromDate ToDate
 1. 1    1/1/2008 31/12/2010
 2. 1    1/1/2009 31/12/2012
 3. 1    1/1/2009 31/12/2014

Output:

   Col1  From Date ToDate
1. 1     1/1/2008 31/12/2008 (from row 1 above)
2. 1     1/1/2009 31/12/2010 (from rows 1,2 and 3 above)
3. 1     1/1/2011 31/12/2012 (from rows 2 and 3 above)
4. 1     1/1/2013 31/12/2014 (from row 3 above)

Answer:
This should do the trick (MySQL dialect, but easily adaptable)
Initial setup
```
```
SQL query: SELECT * FROM `test` LIMIT 0, 30 ;
Rows: 3
start       end
2008-01-01  2010-12-31
2009-01-01  2012-12-31
2009-01-01  2014-12-31
```
```
Query
```
```
SELECT
  `start` , min( `end` )
FROM (
  SELECT t1.start, t2.end
  FROM test t1, test t2
  WHERE t1.start < t2.end
  UNION
  SELECT t1.end + INTERVAL 1 DAY , t2.end
  FROM test t1, test t2
  WHERE t1.end + INTERVAL 1 DAY < t2.end
  UNION
  SELECT t1.start, t2.start - INTERVAL 1 DAY
  FROM test t1, test t2
  WHERE t1.start < t2.start - INTERVAL 1 DAY
) allRanges
GROUP BY `start`
```
```
Result
```
```
start       min( `end` )
2008-01-01  2008-12-31
2009-01-01  2010-12-31
2011-01-01  2012-12-31
2013-01-01  2014-12-31
```
```


Question:
I have a bit of html like so:

<a href="#somthing" id="a1"><img src="something" /></a>
<a href="#somthing" id="a2"><img src="something" /></a>

I need to strip off the links so I'm just left with a couple of image tags. What would be the most efficient way to do this with jQuery?

Answer:
```
```
$("a > img").parent()   // match all , select  parents
   .each( function()    // for each link
   {
      $(this).replaceWith(              // replace the
         $(this).children().remove() ); // with its detached children.
   });
```
```


Question:
I have a module in the parent directory of my script and I would like to 'use' it.

If I do

use '../Foo.pm';

I get syntax errors.

I tried to do:

push @INC, '..';
use EPMS;

and .. apparently doesn't show up in @INC

I'm going crazy!  What's wrong here?

Answer:
You have to have the
```
push
```
processed before the
```
use
```
is -- and
```
use
```
is processed early.  So, you'll need a
```
BEGIN { push @INC, ".."; }
```
to have a chance, I believe.


Question:
Say if I have a dropdown in a form and I have another nested class inside of this class .
Now what's the best way to access this dropdown from the nested class?

Answer:
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference.  Raymond Chen has an example describing the differences here :
C# nested classes are like C++ nested classes, not Java inner classes
.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
```
```
// C#
class OuterClass
{
    string s;
    // ...
    class InnerClass
    {
       OuterClass o_;
       public InnerClass(OuterClass o) { o_ = o; }
       public string GetOuterString() { return o_.s; }
    }
    void SomeFunction() {
        InnerClass i = new InnerClass(this);
        i.GetOuterString();
    }

}
```
```
Note that the InnerClass can access the "
```
s
```
" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "
```
string s;
```
" is
```
private
```
because no other access permission was specified.


Question: How can I get Environnment variables and if something is missing, set the value?

Answer:
Use the
System.Environment
class.
The methods
```
```
var value = System.Environment.GetEnvironmentVariable(variable [, Target])
```
```
and
```
```
System.Environment.SetEnvironmentVariable(variable, value [, Target])
```
```
will do the job for you.
The optional parameter
```
Target
```
is an enum of type
```
EnvironmentVariableTarget
```
and it can be one of:
```
Machine
```
,
```
Process
```
, or
```
User
```
. If you omit it, the default target is the
current process.


Question: I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later.  When users upload files to my server, PHP tells me what filetype it is based on the extension.  However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keeping a zip file on my server.  Is there any reasonable way to open an uploaded file and "check" to see if it truly is of the said filetype?

Answer:
Sort of. Most file types have some bytes reserved for marking them so that you don't have to rely on the extension.  The site
http://wotsit.org
is a great resource for finding this out for a particular type.
If you are on a unix system, I believe that the file command doesn't rely on the extension, so you could shell out to it if you don't want to write the byte checking code.
For PNG (
http://www.w3.org/TR/PNG-Rationale.html
)
The first eight bytes of a PNG file always contain the following values:
(decimal)              137  80  78  71  13  10  26  10
(hexadecimal)           89  50  4e  47  0d  0a  1a  0a
(ASCII C notation)    \211   P   N   G  \r  \n \032 \n


Question:
I would like to access a class everywhere in my application, how can I do this?

To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.

Answer:
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (
Concrete instance or Static access
to that class)
Or
You can have a
Singleton class
to use it everywhere but some people won't recommend you this way to proceed.


Question:
RDBMS packages today offer a tremendous amount of functionality beyond standard data storage and retrieval.  SQL Server for example can send emails, expose web service methods, and execute CLR code amongst other capabilities.  However, I have always tried to limit the amount of processing my database server does to just data storage and retrieval as much as possible, for the following reasons:

A database server is harder to scale than web servers

In a lot of projects I've worked on, the DB server is a lot busier than the web servers, and thus has less spare capacity

It potentially exposes your database server to a security attack (web services for example)

My question is, how do you decide how much functionality or code should be implemented directly on your database server versus other servers in your architecture?  What recommendations do you have for people starting new projects?

Answer:
The vendors have one set of best practices.  You, however, voice concerns with that.
Years ago I supported a
Major Software Product
. Major.
They said "The database is relational storage.  Nothing more."  Every user conference people would ask about stored procedure, triggers, and all that malarkey.
Their architect was firm.  As soon as you get away from plain-old-SQL, you've got a support and maintenance nightmare.  They did object-relational mapping from the DB into their product, and everything else was in their product.
This scales well.  Multiple application servers can easily share a single database server.


Question:
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?

The regular expression should match any of the following:

RunFoo.py
RunBar.py
Run42.py

It should not match:

myRunFoo.py
RunBar.py1
Run42.txt

The SQL equivalent of what I am looking for is ... LIKE 'Run%.py' ....

Answer:
This probably doesn't fully comply with file-naming standards, but here it goes:
```
```
/^Run[\w]*?\.py$/
```
```


Question:
I have some System.Diagnotics.Processes to run.  I'd like to call the close method on them automatically.  Apparently the "using" keyword does this for me.

Is this the way to use the using keyword?

foreach(string command in S) // command is something like "c:\a.exe"
{
    try
    {
        using(p = Process.Start(command))
        {
            // I literally put nothing in here.
        }
    }
    catch (Exception e)
    {
        // notify of process failure
    }
}

I'd like to start multiple processes to run concurrently.

Answer:
```
```
try
{
   foreach(string command in S) // command is something like "c:\a.exe"
   {
      using(p = Process.Start(command))
      {
        // I literally put nothing in here.
      }

    }
}
catch (Exception e)
{
    // notify of process failure
}
```
```
The reason it works is because when the exception happens, the variable p falls out of scope and thus it's Dispose method is called that closes the process is how that would go.  Additionally, I would think you'd want to spin a thread off for each command rather than wait for an executable to finish before going on to the next one.


Question:
While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:

static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };

Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this?

Edit: (re: Panos) In a file lexical order seems to be king? what about across files?

In looking I tried a cyclical dependency like this:

static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { a[0] };

and the program didn't run the same (the test suit failed across the board and I didn't look further).

Answer:
It seems to depend on the sequence of lines. This code works:
```
```
static private List<int> a = new List<int>() { 1 };
static private List<int> b = new List<int>() { a[0] };
```
```
while this code does not work (it throws a
```
NullReferenceException
```
)
```
```
static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { 1 };
```
```
So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain...
EDIT - What's happening "across files"? If we declare these two classes:
```
```
public class A {
    public static List<int> a = new List<int>() { B.b[0] };
}
public class B {
    public static List<int> b = new List<int>() { A.a[0] };
}
```
```
and try to access them with this code:
```
```
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }
try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
```
```
we are getting this output:
```
```
The type initializer for 'A' threw an exception.
Object reference not set to an instance of an object.
The type initializer for 'A' threw an exception.
```
```
So the initialization of
```
B
```
causes an exception in static constructor
```
A
```
and lefts field
```
a
```
with the default value (null). Since
```
a
```
is
```
null
```
,
```
b
```
can not also be initialized properly.
If we do not have cyclical dependencies, everything works fine.
EDIT: Just in case you didn't read the comments,
Jon Skeet
provides a very interesting reading:
The differences between static constructors and type initializers
.


Question:
In ASP.NET, I have an XML file (within my project) that I would like to deserialize.  FileStream objects do not allow you to open a file via URL.

What is the easiest way to open the file so that I can deserialize it?

Answer:
Generally, we put it all in one file. This isn't Java or C++.
Start with a single file until you get some more experience with Python.  Unless your files are gargantuan, it will work fine.
For example, Django encourages this style, so copy their formula for success.  One module for the model.  A module for each application; each application imports a common model.
Your Database and superclass stuff can be in your
```
__init__.py
```
file, since it applies to the entire package.  That may reduce some of the circularity.


Question:
I am working on a web application that was recently converted from Visual Studio 2003 to Visual Studio 2008.  The application contained some web services that were written using the .NET 1.1 Framework and Web Service Enhancements 2.0.  They were converted to the .NET 3.5 framework using the VS 2008 Conversion Wizard Tool.

A client application which is still written using the .NET 1.1 framework has a reference to the updated web service and try to consume the web service and received the following error:

System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: (web service URI)

The URL Behavior is set to static for the reference and the proxy class inheritance was changed from System.Web.Services.Protocols.SoapHttpClientProtocol namespace to Microsoft.Web.Services2.WebServicesExtension namespace

If you need additional information or need to see some source code, please let me know.

Answer:
Does the web service work otherwise?  Is it possible your new updated 2.0 web service exists in the same application domain as a 1.1 application?  In that case you'll want to make your own app-domain.
If its not local try using Fiddler to see everything that is going back and forth.


Question:
There's a lot of interest these days in Erlang as a language for writing parallel programs on multicore. I've heard people argue that Erlang's message-passing model is easier to program than the dominant shared-memory models such as threads.

Conversely, in the high-performance computing community the dominant parallel programming model has been MPI, which also implements a message-passing model. But in the HPC world, this message-passing model is generally considered very difficult to program in, and people argue that shared memory models such as OpenMP or UPC are easier to program in.

Does anybody know why there is such a difference in the perception of message-passing vs. shared memory in the IT and HPC worlds? Is it due to some fundamental difference in how Erlang and MPI implement message passing that makes Erlang-style message-passing much easier than MPI? Or is there some other reason?

Answer: Regarding MPI vs OpenMP/UPC: MPI forces you to slice the problem in small pieces and take responsibility for moving data around.  With OpenMP/UPC, "all the data is there", you just have to dereference a pointer.  The MPI advantage is that 32-512 CPU clusters are much cheaper than 32-512 CPU single machines.  Also, with MPI the expense is upfront, when you design the algorithm.  OpenMP/UPC can hide the latencies that you'll get at runtime, if your system uses NUMA (and all big systems do) - your program won't scale and it will take a while to figure out why.


Question:
My company has login integration with GroupWise, and Exchange 5.5/2000+.  The Exchange 5.5/GroupWise logic is done using wldap32.dll (win32), and so the login code is in a managed c++ class.  When the configuration tool (or the backend service) tries to load the dll built off this managed c++ project on my XP development box, it works fine.  On QA/Customer Windows 2003 boxes, a FileLoadException is thrown.

First off, this used to work fine.  Secondly, I've validated the same working code on my box fails on the qa box.

How can I track down the cause of this exception?

Answer:
Not to answer my own question, but support just updated the bug with the text following this paragraph.  I'm still interested in thoughts on tracking down situations like this.
Resolved by downloading and installing the Visual C++ 2008 Redistributable
Package for Windows on the IMS:
http://www.microsoft.com/downloads/details.aspx?FamilyID=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&DisplayLang=en


Question: I would like MATLAB to tell me if I have an input file (.m file) that contains some variables with their numbers (i.e., a = 5, b = 6, c = 7) so that I can then use that .m file in another program (main .m file) that uses these variables to calculate S = a + b + c. How can I then read the input file from the main file? Assume the input file is called INP and the main MAIN.

Answer:
If your "input" file is an m-file, just use the name of the file in your "main" m-file.  For example you might have a file called input.m that looks like this:
```
```
% File: inputs.m
a = 5;
b = 6;
c = 7;
```
```
Then, you can use it in the file main.m like this:
```
```
% File: main.m
inputs;
S = a + b + c;
```
```


Question:
I have a view that supports landscape and portrait viewing, with the controls all moving around when you switch from one to the other. I'm currently doing this by setting the .center of each one of my controls when the user rotates the phone. The problem is that this is tedious, and requires a lot of code, and seems to defeat the purpose of using Interface Builder in the first place.

My question is: is there a way in Interface Builder for one view to support multiple looks (one for landscape one for portrait)? If not how do other people do this with IB? Do you set up 2 views?

Edit: Just to clarify my landscape and portrait views look different, I don't want a straight transform, I actually display the data differently in landscape mode

Answer: I'm not 100% sure if it's possible, but have you considered using different view controllers for landscape and portrait?


Question:
Anyone know of a good memory/disk caching library for AIR? Extra points for being compatible with Flash CS3, and being free (as in beer).

I'd like to cache results of http requests: both binary and text (xml).

Answer:
The
bulk-loader
project might have what you're looking for. I haven't used it myself but in the description it says (among other things):
Cache management
Various asset types (XML, NetStreams, Swfs, Images, Sound, Text Files)
From quickly looking at the code and some of the examples in the wiki it looks like it has memory (but not disk) caching capabilities.


Question:
Is it possible to do something like this?

var pattern = /some regex segment/ + /* comment here */
    /another segment/;

Or do I have to use new RegExp() syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.

Answer:
Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:
```
```
var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
              segment_part + /* that was defined just now */
              "another segment");
```
```
If you have two regular expression literals, you can in fact concatenate them using this technique:
```
```
var regex1 = /foo/g;
var regex2 = /bar/y;
var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
var regex3 = new RegExp(expression_one.source + expression_two.source, flags);
// regex3 is now /foobar/gy
```
```
It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.


Question: I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.

Answer:
A little hacky but should work:
```
```
SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))
```
```


Question: What is the largest heap you have personally used in a managed environment such as Java or .NET?  What were some of the performance issues you ran into, and did you end up getting a diminishing returns the larger the heap was?

Answer:
I am unsure what you mean by heap,  but if you mean memory used, I have used quite a bit, 2GB+. I have a web app that does image processing and it requires loading 2 large scan files into memory to do analysis.
There were performance issues. Windows would swap out lots of ram, and then that would create a lot of page faults. There was never any need for anymore than 2 images at a time as all requests were gainst those images (I only allowed  1 session per image set at a time)
For instance, to setup the files for initial viewing would take about 5 seconds. Doing simple analysis and zooming would be fairly fast once in memory, in the order of .1 to .5 seconds.
I still had to optimize, so I ended up preparsung the files and chopping into smaller peices and worked only with the peices that were required by the user at the time.


Question:
I would like to remove the domain/computer information from a login id in C#.  So, I would like to make either "Domain\me" or "Domain\me" just "me".  I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact.

Worse case scenario:

int startIndex = 0;
int indexOfSlashesSingle = ResourceLoginName.IndexOf("\");
int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\");
if (indexOfSlashesSingle != -1)
    startIndex = indexOfSlashesSingle;
else
    startIndex = indexOfSlashesDouble;
string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1);

Answer:
I always do it this way:
```
```
string[] domainuser;
    string Auth_User = Request.ServerVariables["AUTH_USER"].ToString().ToLower();
    domainuser = Auth_User.Split('\\');
```
```
Now you can look at domainuser.Length to see how many parts are there and domainuser[0] for the domain and domainuser[1] for the username.


Question:
This is an age-old question where given a table with attributes 'type', 'variety' and 'price', that you fetch the record with the minimum price for each type there is.

In SQL, we can do this by:

select f.type, f.variety, f.price
from (  select type, min(price) as minprice from table group by type ) as x
inner join table as f on f.type = x.type and f.price = x.minprice;`

We could perhaps imitate this by:

minprices = Table.minimum(:price, :group => type)
result = []
minprices.each_pair do |t, p|
   result << Table.find(:first, :conditions => ["type = ? and price = ?", t, p])
end

Is there a better implementation than this?

Answer:
```
```
Table.minimum(:price, :group => :type)
```
```
See
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum
for more.


Question:
I couldn't really find this in Rails documentation but it seems like 'mattr_accessor' is the Module corollary for 'attr_accessor' (getter & setter) in a normal Ruby class.

Eg. in a class

class User
  attr_accessor :name

  def set_fullname
    @name = "#{self.first_name} #{self.last_name}"
  end
end

Eg. in a module

module Authentication
  mattr_accessor :current_user

  def login
    @current_user = session[:user_id] || nil
  end
end

This helper method is provided by ActiveSupport.

Answer:
Rails extends Ruby with both
```
mattr_accessor
```
(Module accessor) and
```
cattr_accessor
```
(as well as _
```
reader
```
/
```
_writer
```
versions).  As Ruby's
```
attr_accessor
```
generates getter/setter methods for
instances
,
```
cattr/mattr_accessor
```
provide getter/setter methods at the
class
or
module
level.  Thus:
```
```
module Config
  mattr_accessor :hostname
  mattr_accessor :admin_email
end
```
```
is short for:
```
```
module Config
  def self.hostname
    @hostname
  end
  def self.hostname=(hostname)
    @hostname = hostname
  end
  def self.admin_email
    @admin_email
  end
  def self.admin_email=(admin_email)
    @admin_email = admin_email
  end
end
```
```
Both versions allow you to access the module-level variables like so:
```
```
>> Config.hostname = "example.com"
>> Config.admin_email = "admin@example.com"
>> Config.hostname # => "example.com"
>> Config.admin_email # => "admin@example.com"
```
```


Question:
I wonder if this would be doable ? To insert an array into one field in the database.

For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website.

It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id.

I just want to have something like this

ID      TITLE
1       Array("english title", "nederlandse titel");

I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.

Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)

Answer:
There's really only two reasonable choices here:
Join with another table
pros: unlimited titles in unlimited languages
cons: join overhead is more computationally expensive, SQL is marginally more complex to update/insert etc
Multiple columns
eg: TITLE_EN, TITLE_NL, TITLE_DE
pros: fast to insert, select, etc
cons: limited number of languages, adding more is an ALTER TABLE
Given our two choices, you usually should should pick the first one.  Unless you're dealing with just an obscene amount of transactions that cannot be parallelized, or you absosmurfly can ensure that you will never add languages, the extra flexibility in schema layout will save you headaches in the long run.


Question:
I am having a doubt in page_init, page preinit, load.
I need to know when we use this also where we need to call our objects in different stages of our life cycle.

Please let me know how they will process for each events raised

Answer:
Its called the Page lifecycle because at different stages of the page request, different objects are populated with different information.
Here are some good links to read up on:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://www.15seconds.com/issue/020102.htm


Question:
Has anybody been successful in integrating the Enterprise Library v4.0 with SharePoint WSS 3.0?  I created a very simple .ASPX page.  It's only purpose will to be to connect to an Oracle database and display some values in a DropDownList.  But right now, all it does is displays Hello World.  I've added the necessary references and everything compiles fine.  When I test the page, it displays Hello World.  But once I add the using Microsoft.Practices.EnterprisesLibrary.Data, the page no longer works. I just get the standard Unknown Error message.  Is there a log file I can check?

I'm looking for any steps or tips that I can use to get this up and running.  I use this Enterprise Library in all my ASP.NET applications and it works great.  Trying to get this to work in SharePoint seems like a natural fit.  But why does it seem so difficult?  And why does there seem to be a lack of information?

Anyways, thank you so much for any information anybody can provide.

Answer:
Are you able to debug and see where the failure is occurring in your code?  Is it occurring on an Enterprise Library related call?  If so I would capture the exception that is being thrown and evaluate the message that it provides using; try {} catch (Exception ex) {}.
One thing I have seen with Enterprise Library that if it is not properly configured it will sometimes log messages to the Event Log on the server.
I'm sorry I can't get much more information without more technical details about your implementation.  I can assure you though that Enterprise Library works very well with SharePoint and that for the past few years I have used Enterprise Library in all of my SharePoint solution work.


Question:
I have a UIImageView and the objective is to scale it down proportionally by giving it either a height or width.

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

//Add image view
[self.view addSubview:imageView];

//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;

//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;

The image did get resized but the position is not at the top left. What is the best approach to scaling image/imageView and how do I correct the position?

Answer:
I think you can do something like
```
```
image.center = [[imageView window] center];
```
```


Question:
I'd like to know if Flash/AS3 has any nice way to convert an AS3 'Date' object to/from rfc-850 timestamp format (as used by HTTP date and last-modified).

This question is very similar to this question about rfc 3339, except it's specific to AS3 and rfc-850.

RFC-850 is like: Thu, 09 Oct 2008 01:09:43 GMT

Answer:
The
as3corelib
libraries have DateUtil.toRFC822() and DateUtil.parseRFC822() methods (among others). Don't know if these are exactly what you are looking for.
The specific docs for the DateUtil class is here:
http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/utils/DateUtil.html


Question:
I'm trying to create a user control that allows users to make something like the following:

  <uc1:MyControl id="controlThing" runat="server">

    <uc1:BoundColumn id="column1" Column="Name" runat="server" />
    <uc1:CheckBoxBoundColumn id="column2" Column="Selector" runat="server" />
    <uc1:BoundColumn id="column3" Column="Description" runat="server" />

     ...etc

  </uc1:MyControl>

There are only certain controls I would allow, in addition to the fact that you can have many of any type. I can picture this in XSD, but I'm not entirely sure for ASP.NET.

My ASP.NET voodoo is drawing a blank right now.. any thoughts?

Answer:
Is it possible for you to override an existing control such as a ListView or GridView? That's your simplest option.
But to create your own custom templated control you need to use ITemplate.
I haven't done one but a quick google returned this:
http://www.developerfusion.com/article/4410/in-depth-aspnet-using-adonet/2/
it looked good.
I have a book "Developing Microsoft ASP.NET Server Controls and Components" which covers it but I haven't read through it indepth yet (
http://www.amazon.com/exec/obidos/ASIN/0735615829/nikhilkothari-20
)


Question:
How to parse the DOM and determine what row is selected in an ASP.NET ListView? I'm able to interact with the DOM via the HtmlElement in Silverlight, but I have not been able to locate a property indicating the row is selected.

For reference, this managed method works fine for an ASP.NET ListBox

var elm = HtmlPage.Document.GetElementById(ListBoxId);

foreach (var childElm in elm.Children)
{
    if (!((bool)childElm.GetProperty("Selected")))
    {
       continue;
    }
}

Answer:
I don't have my dev environment up to test this, but could you call GetProperty('selectedIndex') on the ListBoxID element? Then from that you figure out which child is selected and return that child using the elm.Children.
Edit:
Got my dev environment up this morning and did some testing. Here is a code snippet that worked for me:
```
```
HtmlElement elem = HtmlPage.Document.GetElementById("testSelect");
int index = Convert.ToInt32(elem.GetProperty("selectedIndex"));
var options = (from c in elem.Children
              let he = c as HtmlElement
              where he.TagName == "option"
              select he).ToList();

output.Text = (string)options[index].GetProperty("innerText");
```
```
Of course, you'll have to change "textSelect" to the name of your html select element. The linq query is needed since the Children property is made up of ScriptableObjects and only about half of them are the option elements which is what you care about.


Question:
I'm using the zlib.NET library to try and inflate files that are compressed by zlib (on a Linux box, perhaps).  Here's what I'm doing:

zlib.ZInputStream zinput =
    new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));

while (stopByte != (data = zinput.ReadByte()))
{
  // check data here
}

zinput.Close();

The data bytes match the compressed data bytes, so I must be doing something wrong.

Answer:
Other than failing to use a "using" statement to close the stream even in the face of an exception, that looks okay to me. Is the data definitely compressed? Are you able to decompress it with zlib on the linux box?
Having looked at the source code, it's pretty ghastly - a call to
```
int Read(buffer, offset, length)
```
will end up calling its internal
```
int Read()
```
method
```
length
```
times for example. Given that sort of shaky start, I'm not sure I'd trust the code particularly heavily, but I'd have expected it to work at least
slightly
! Have you tried using
SharpZipLib
?


Question:
I have a directory with several subdirectories with files.

How can I copy all files in the subdirectories to a new location?

Edit: I do not want to copy the directories, just the files...

As this is still on XP, I chose the below solution:

 for /D %S IN ("src\*.*") DO  @COPY "%S\" "dest\"

Thanks!

Answer:
The Xcopy command should help here.
```
```
XCOPY /E SrcDir\*.* DestDir\
```
```
Or if you don't want any of the files in SrcDir, just the sub directories, you can use XCOPY in conjunction with the FOR command:
```
```
FOR /D %s IN (SrcDir\*) DO @XCOPY /E %s DestDir\%~ns\
```
```


Question:
Is there a Winform caching library out there? I need to pass a few datasets aroung in a Winform Application, and probably persist to storage upon close.

I've seen some samples around via Google, using System.Web.

What's the recommendation and where can I get some details. I am using VS 2008 for 2.0. 3.0 Framework.

Thanks

Answer: Starting with .NET 2.0 you can use the System.Web.Caching.Cache class with non-ASP.NET apps. The Microsoft recommended approach these days though is to use the Enterprise Library Caching Application Block.


Question:
We can use Bitmapsource object as the content of a Image control, However if I only have Bitmap object, can I use it directly, if I convert Bitmap to Bitmapsouce using the following method:

        Bitmap bitmap = imageObjToBeConvert;
        IntPtr HBitmap = bitmap.GetHbitmap();
        result = Imaging.CreateBitmapSourceFromHBitmap
            (HBitmap,
            IntPtr.Zero,
            Int32Rect.Empty,
            BitmapSizeOptions.FromEmptyOptions());
        DeleteObject(HBitmap);
        bitmap.Dispose();

It take some time. Is there any way to use Bitmap directly?

And I found BitmapSource seems can't be released directly, Is there a sample method to release the memory immediately, after the Bitmapsouce is not used again.

Answer:
I think REST would make more sense than traditional RPC. Even the
Micorosft Robotics Studio runtime application model
uses REST.
The robot can consist of different resources that are identified by URI, including one for each sensor and actuator or composite abstractions thereof.
REST puts emphasis on guaranteeing what the side effects of certain methods are and also it facilitates caching, both of which can be useful for something like controlling and monitoring a distant robot. And just because you can use REST it
doesn't
have to be the HTTP protocol.
A SAFE and IDEMPOTENT method like GET, though, is good for tracking the state of the robot and polling its sensor data. You can use something like the Last-Modified header to retrieve cached sensor data that doesn't change often (e.g., humidity or light levels).
For long distances you can use relay proxies for caching.
For commands that move the robot, something like POST would be used where every such message will change the robot (e.g., turn right ). A status code can be returned indicating whether the command was immediately executed or queued for processing.
The absolute state of any resources can be set using something like PUT where multiple messages will not change things any more than just a single message (e.g., point to north pole or dim front lights to 10% brightness). This allows for reliable messaging in case of probablity of messages getting lost en route.
A new resource may be created via a POST-like operation as well, e.g., a data-collection routine and a set of parameters. The POST request can send back a CREATED result with a URI for the new resource, which can be used to DELETE when no longer needed.
A group of robots may also speak to each other using the same REST based protocol and can enjoy the same benefits.
Granted, for something simple like one person controlling a single isolated local robot, a REST API may be overkill. But for multi-user and/or unreliable-communications-channels and/or Web-scale-networking, REST is something to consider.


Question:
I am trying to convert an int into three bytes representing that int (big endian).

I'm sure it has something to do with bit-wise and and bit shifting.  But I have no idea how to go about doing it.

For example:

int myInt;

// some code

byte b1, b2 , b3; // b1 is most significant, then b2 then b3.

*Note, I am aware that an int is 4 bytes and the three bytes have a chance of over/underflowing.

Answer:
An int doesn't fit into 3 bytes.  However, assuming that you know these particular ones do:
```
```
byte b1 = (myInt & 0xff);
   myInt >>= 8;
   byte b2 = (myInt & 0xff);
   myInt >>= 8;
   byte b3 = (myInt & 0xff);
```
```


Question: It seems redundant to have zlib compress a web page during every request. It is also the bottleneck of my files' response times. Is there a way to cache the zlib'd file so that it is compressed only once at each modification? Or should I just keep wishing?

Answer:
Hm, I think mod_cache will do the job.
http://httpd.apache.org/docs/2.0/mod/mod_cache.html


Question:
What is the best way to initialize a private, static data member in C++?  I tried this in my header file, but it gives me weird linker errors:

class foo
{
    private:
        static int i;
};

int foo::i = 0;

I'm guessing this is because I can't initialize a private member from outside the class.  So what's the best way to do this?

Answer:
The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h
```
```
class foo
{
    private:
        static int i;
};
```
```
But the initialization should be in source file.
File: foo.cpp
```
```
int foo::i = 0;
```
```
If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files.
The initialisation of the
```
static int i
```
must be done outside of any function.
Note:
Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of
const integer type
(
```
bool
```
,
```
char
```
,
```
char8_t
```
[since C++20],
```
char16_t
```
,
```
char32_t
```
,
```
wchar_t
```
,
```
short
```
,
```
int
```
,
```
long
```
,
```
long long
```
, or any implementation-defined extended integer types, including any signed, unsigned, and cv-qualified variants.
). You can then declare and initialize the member variable directly inside the class declaration in the header file:
```
```
class foo
{
    private:
        static int const i = 42;
};
```
```


Question:
Using the Qt Visual studio integration, adding a new Qt class adds two separate moc.exe generated files - one for debug and one for release (and one for any other configuration currently existing). Yet the two eventual generated files seem to be identical.

On the other hand when adding a UI class, the uic.exe generated files don't have this separation and are the same file for all configurations.

Does anybody have an idea why there's a need for a separate moc file for every configuration? When is there a difference between the two?

Answer:
My guess would be that separate debug and release versions are needed because the moc output is generated from user-defined source code. So the moc output might be different between debug and release builds if the preprocessed class source differs between debug and release (for example, a signal that exists only in the debug build).
This doesn't apply to the uic-generated files because those are generated from the .ui XML, which can't vary between debug and release configurations.


Question:
I have a production server running with the following flag: -XX:+HeapDumpOnOutOfMemoryError

Last night it generated a java-38942.hprof file when our server encountered a heap error. It turns out that the developers of the system knew of the flag but no way to get any useful information from it.

Any ideas?

Answer:
You can use
JHAT
, The Java Heap Analysis Tool provided by default with the JDK.  It's command line but starts a web server/browser you use to examine the memory.  Not the most user friendly, but at least it's already installed most places you'll go.  A very useful view is the "heap histogram" link at the very bottom.
ex:
```
jhat -port 7401 -J-Xmx4G dump.hprof
```
```
jhat
```
can execute OQL "these days" as well (bottom link "execute OQL")


Question: Recently I was asked this during a job interview. I was honest and said I knew how a symbolic link behaves and how to create one, but do not understand the use of a hard link and how it differs from a symbolic one.

Answer:
Underneath the file system, files are represented by inodes. (Or is it multiple inodes?  Not sure.)
A file in the file system is basically a link to an inode.
A hard link, then, just creates another file with a link to the same underlying inode.
When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.
A symbolic link is a link to another name in the file system.
Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.
Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.


Question:
It appears that in PHP objects are passed by reference. Even assignment operators do not appear to be creating a copy of the Object.

Here's a simple, contrived proof:

<?php

class A {
    public $b;
}

function set_b($obj) { $obj->b = "after"; }

$a = new A();
$a->b = "before";
$c = $a; //i would especially expect this to create a copy.

set_b($a);

print $a->b; //i would expect this to show 'before'
print $c->b; //i would ESPECIALLY expect this to show 'before'

?>

In both print cases I am getting 'after'

So, how do I pass $a to set_b() by value, not by reference?

Answer:
According to the docs (
http://ca3.php.net/language.oop5.cloning
):
```
```
$a = clone $b;
```
```


Question:
How can I delete the contents of a local folder in Python?

The current project is for Windows, but I would like to see *nix also.

Answer:
```
```
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
    file_path = os.path.join(folder, filename)
    try:
        if os.path.isfile(file_path) or os.path.islink(file_path):
            os.unlink(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
    except Exception as e:
        print('Failed to delete %s. Reason: %s' % (file_path, e))
```
```


Question: I know this can be done in IE by creating an ActiveX object, but how do I do it in FF. The navigator.plugins['Adobe Acrobat'] object lets me know if it's installed or not, but it doesn't contain the version number. Any ideas?

Answer:
```
navigator.plugins[n].name
```
where
```
n
```
is the index of the Acrobat plugin is supposed have the version number in it. Unfortunately, starting with Adobe Reader 8, they changed the name to
```
"Adobe PDF Plug-In for Firefox and Netscape"
```
, with no version information. So, if this is the name you've detected at least Reader 8, but can't tell versions 8 from 9.
Also, make sure you take into account that Macs don't need Acrobat Reader to render PDF files. (I booted my Windows partition just to test this.)


Question: What is the best way to create a custom title for pages in a Rails app without using a plug-in?

Answer:
Look into
```
content_for
```
:
http://railscasts.com/episodes/8


Question:
In javascript, we can do:

["a string", 10, {x : 1}, function() {}].push("another value");

What is the Scala equivalent?

Answer:
Arrays in Scala are very much homogeneous.  This is because Scala is a statically typed language.  If you really need pseudo-heterogeneous features, you need to use an immutable data structure that is parametrized covariantly (most immutable data structures are).
```
List
```
is the canonical example there, but
```
Vector
```
is also an option.  Then you can do something like this:
```
```
Vector("a string", 10, Map("x" -> 1), ()=>()) + "another value"
```
```
The result will be of type
```
Vector[Any]
```
.  Not very useful in terms of static typing, but everything will be in there as promised.
Incidentally, the "literal syntax" for
arrays
in Scala is as follows:
```
```
Array(1, 2, 3, 4)     // => Array[Int] containing [1, 2, 3, 4]
```
```
See also
:
More info on persistent vectors


Question:
My friend accidentally bought a laptop with Windows Vista Home Basic Edition. He figured out how to install IIS on it, but it doesn't seem to have either the management console or the admin tools. Is there any way for him to configure a site or import an IIS 6 config file?

EDIT: "Windows Vista Home Edition" --> "Windows Vista Home Basic Edition".

Answer:
Okay, not being on Vista I don't know for sure, but on XP the application which controls IIS is
```
%SystemRoot%\system32\inetsrv\iis.msc
```
. Perhaps hunting around for
```
iis.msc
```
would be a first step.


Question: I use log4net in just about every code project. I was wondering what other generally useful code projects are available?

Answer:
I like the C5 collection classes, from the IT University of Copenhagen:
http://www.itu.dk/research/c5/
It's one of the most well-designed libraries, of any kind, I've ever used.


Question:
I have had to do this several times, usually when trying to find in what files a variable or a function is used.

I remember using xargs with grep in the past to do this, but I am wondering if there are any easier ways.

Answer:
```
```
grep -r REGEX .
```
```
Replace
```
.
```
with whatever directory you want to search from.


Question:
(function()
 {
     //codehere
 }
)();

What is special about this kind of syntax?
What does ()(); imply?

Answer:
The creates an anonymous function, closure and all, and the final () tells it to execute itself.
It is basically the same as:
```
```
function name (){...}
name();
```
```
So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it.
This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.


Question:
I was developing a web page, where I was laying out a board for a Chess-like game, along with a couple of piece trays. It's all done using HTML (with jQuery for dynamic updating as the game is played). Somewhere I'd got the notion that using absolute positioning of elements within a page was considered a bad practice, and that it was preferable to use relative positioning.

After struggling with relative positioning for too long, I realized that absolute positioning of the board elements would be much, much easier to get right... and it was.

Is anyone aware of a reason that relative positioning is preferable over absolute? Are there any guidelines or rules of thumb that you apply when deciding which approach to take?

Answer:
For a chess like game such as you are developing, there is nothing inherently wrong with using absolute positioning.  As you said, relative positioning and normal flow layout make this sort of task quite difficult.
Of course, if you were developing a more standard website, such as a site providing some public service, absolute positioning overrides the default flow layout of browsers and so will reduce accessibility for many users.  In this case I would avoid it.
Having said that, a lesser known benefit of absolute positioning is that it allows localized absolute positioning
within
the nearest "positioned" parent element.
Note:
A "positioned" element can be any of the following: relative, fixed, absolute, or sticky.
To explain:
```
```

          I'm absolutely positioned within parentDIV.

```
```
Here,
```
childDIV
```
is actually positioned 20px from the left and 20px from the top of
```
parentDIV
```
,
NOT
the overall document.  This gives a nice precise control over nested elements on a page, without sacrificing the overall page flow-layout.
So to answer your question (relative positioning being preferred over absolute): I don't believe there is a correct answer, it depends on what you are needing to build.  However in general positioning (absolute or relative) versus default flow layout, my approach is as described above.


Question: I'd like to create a sparse file such that all-zero blocks don't take up actual disk space until I write data to them.  Is it possible?

Answer:
As in other Unixes, it's a feature of the filesystem.  Either the filesystem supports it for ALL files or it doesn't.  Unlike Win32, you don't have to do anything special to make it happen.  Also unlike Win32, there is no performance penalty for using a sparse file.
On MacOS, the default filesystem is HFS+ which does
not
support sparse files.
Update:
MacOS used to support UFS volumes with sparse file support, but that has been removed. None of the currently supported filesystems feature sparse file support.


Question: Just this - How do you add a timer to a C# console application? It would be great if you could supply some example coding.

Answer:
Use the System.Threading.Timer class.
System.Windows.Forms.Timer is designed primarily for use in a single thread usually the Windows Forms UI thread.
There is also a System.Timers class added early on in the development of the .NET framework. However it is generally recommended to use the System.Threading.Timer class instead as this is just a wrapper around System.Threading.Timer anyway.
It is also recommended to always use a static (shared in VB.NET) System.Threading.Timer if you are developing a Windows Service and require a timer to run periodically.  This will avoid possibly premature garbage collection of your timer object.
Here's an example of a timer in a console application:
```
```
using System;
using System.Threading;
public static class Program
{
    public static void Main()
    {
       Console.WriteLine("Main thread: starting a timer");
       Timer t = new Timer(ComputeBoundOp, 5, 0, 2000);
       Console.WriteLine("Main thread: Doing other work here...");
       Thread.Sleep(10000); // Simulating other work (10 seconds)
       t.Dispose(); // Cancel the timer now
    }
    // This method's signature must match the TimerCallback delegate
    private static void ComputeBoundOp(Object state)
    {
       // This method is executed by a thread pool thread
       Console.WriteLine("In ComputeBoundOp: state={0}", state);
       Thread.Sleep(1000); // Simulates other work (1 second)
       // When this method returns, the thread goes back
       // to the pool and waits for another task
    }
}
```
```
From the book
CLR Via C#
by Jeff Richter.  By the way this book describes the rationale behind the 3 types of timers in Chapter 23, highly recommended.


Question: My boss thinks the VS 2008 IDE Window Manager(autohiding, docking of Solution Explorer, Properties, etc) is the best thing since sliced bread.  I can't find a control that resembles that functionality in the Toolbox.  Is there a control like that available that you know of?  Or should I go ahead and implement it myself?  Btw, we're using VS 2008 Express.

Answer:
You should check out
SandDock
. The older versions were freely licenced (dunno if they are still available) and the newer versions are relatively cheap, especially considering the amount of time/money/sanity they would save you.
I would strongly recommend against trying to roll your own VM component. There is just too much work involved, and it wouldn't be worth it, if it wasn't your primary product.


Question:
I have been trying to change the background color of Eclipse's windows to black and customize the font colors. There doesn't seem to be a way to do this, at least not in an obvious way. I am using version 3.3.

How do I do this or are there any plugin's that might be able to assist in doing this?

Answer:
If you go to Windows, Preferences then select General, Editors, Text editors, you can set colors on that property page (and there's a link for setting MORE colors - General, Appearance, Colors and fonts).
That's with an Eclipse 3.3 build anyway.


Question:
I would like to use a secure SSL login on my website! I have not used SSL before, so I am looking for some good reading. Can anyone tell me where I can find some sample code of SSL snippets or page code. (Not too technical)

I do have a static IP

My host is set-up to handle SSL Pages.

Interested in: Basic page code. / Tree structure. / Other

Paul

Answer:
My first thought would be to simply call a function to redirect to the https: version of the current page when you need to be secure.
Some code like this:
```
```
if($requireSSL && $_SERVER['SERVER_PORT'] != 443)
{
   header("HTTP/1.1 301 Moved Permanently");
   header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
   exit();
}
```
```
Reference


Question:
He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings {'id': id, 'url': url}. Some ids in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:

def unique_mapping(map):
    d = {}
    for res in map:
        d[res['id']] = res['url']

    return [{'id': id, 'url': d[id]} for id in d]

I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?

Answer:
Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:
```
```
def unique_mapping(mappings):
    return dict((m['id'], m) for m in mappings).values()
```
```
Although this came out as a one-liner, I still think it's quite readable.
There are two things you have to keep in mind when using your original solution and mine:
the items will not always be returned in the same order they were originally
the later entry will overwrite previous entries with the same id
If you don't mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority:
```
```
def unique_mapping(mappings):
    addedIds = set()
    for m in mappings:
        mId = m['id']
        if mId not in addedIds:
            addedIds.add(mId)
            yield m
```
```
You might need to call it with
```
list(unique_mappings(mappings))
```
if you need a list and not a generator.


Question:
I want to use implicit linking in my project , and nmake really wants a .def file . The problem is , that this is a class , and I don't know what to write in the exports section .
Could anyone point me in the right direction ?

The error message is the following :

NMAKE :  U1073: don't know how to make 'DLLCLASS.def'

P.S: I'm trying to build using Windows CE Platform Builder .

Answer:
If I recall correctly, you can use
```
__declspec(dllexport)
```
on the
class
, and VC++ will automatically create exports for all the symbols related to the class (constructors/destructor, methods, vtable, typeinfo, etc).
Microsoft has more information on this
here
.


Question: Are there any "all-in-one" installers for php + mysql on iis? Preferably with a gui configuration interface.

Answer:
I don't know of any all-in-one installers for both MySql and PHP, but PHP itself comes with an automated installer that will attach itself to IIS - but the preferred method is still manual (the automated procedure only uses CGI). There are plenty of how-to pages on the web that give you the step-by-step procedure required to get setup (and these differ based on your version of IIS) - I suggest you use one of those instead.
Some links to get you started:
PHP Documentation
Installing PHP 5 on IIS in 5 simple steps


Question:
A project I'm working on will pull XML from a web-server and build a data store from it. The data will have certain core fields but needs to be extendable... for example I have a  and later might want to have  which adds extra fields.

In the Flex app, I don't want the central data store to be working on XML objects or simply putting the properties into Objects. I want to have strong types, e.g a Person class, which are created/populated from the XML.

How can this be done in a flexible way? Is Flex able to automatically build a Person from an XML  if the attribute names match, or do I need to write conversion functionality for , , etc?

Answer:
I don't think this can be done automatically. I generally create the a class to mirror the XML structure I have and then create a static class method to create an instance of the object given an XML node. For example:
```
```
package {

  public class Foo{

     public function Foo(barparam1:String, barparam2:uint, barparam3:String, barparam4:Number){
       this._bar1 = barparam1;
       this._bar2 = barparam2;
       this._bar3 = barparam3;
       this._bar4 = barparam4;
       }

     protected var _bar1:String;
     protected var _bar2:uint;
     protected var _bar3:String;
     protected var _bar4:Number;

     public function get bar1():String{ return this._bar1; }
     public function get bar2():uint    { return this._bar2; }
     public function get bar3():String  { return this._bar3; }
     public function get bar4():Number  { return this._bar4; }

     public function toString():String{
        return "[Foo bar1:\"" + this.bar1 + "\", bar3:\"" + this.bar3 + "\", bar2:" + this.bar2 + ", bar4:" + this.bar4 + "]";
        }

     public static function createFromXml(xmlParam:XML):Foo{

        /* XML Format:
          <foo bar1="bar1value" bar2="5">
            <bar3>bar3 data</bar3>
            <bar4>10</bar4>
          </foo>
        */

       return new Foo(xmlParam.@bar1, xmlParam.@bar2, xmlParam.bar3[0], xmlParam.bar4[0]);
       }
    }
  }
```
```


Question:
I have a list of Date objects, and a target Date. I want to find the date in the list that's nearest to the target date, but only dates that are before the target date.

Example:
2008-10-1
2008-10-2
2008-10-4

With a target date of 2008-10-3, I want to get 2008-10-2

What is the best way to do it?

Answer:
I currently use the following method, but I'm not sure it's the most effective one, because this assumes an already sorted list, and (potentially) iterates over every single date in the list.
```
```
private Date getDateNearest(List<Date> dates, Date targetDate){
  for (Date date : dates) {
    if (date.compareTo(targetDate) <= 0) return date;
  }

  return targetDate;
}
```
```


Question:
I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command.

I want to do this so that I can have a system where I can add users to without having to create a system wide account, so that they can then, for example, commit to a VCS branch, or similar.

While I can work out how to do this with conch to get it to a "custom" shell... I can't figure out how to make it so that the SSH stream works as if it were a real one (I'm preferably wanting to limit to /bin/bzr so that bzr+ssh will work.

It needs to be in python (which i can get to do the authorisation) but don't know how to do the linking to the app.

This needs to be in python to work within the app its designed for, and to be able to be used for those without access to add new users

Answer:
While Python really is my favorite language, I think you need not create you own server for this. When you look at the
OpenSSH Manualpage for sshd
you'll find the "command" options for the authorized keys file that lets you define a specific command to run on login.
Using keys, you can use one system account to allow many user to log in, just put their public keys in the account's authorized keys file.
We are using this to create SSH tunnels for SVN and it works just great.


Question:
Is there an event like onLoad?

just at closing the Site (onClose)?

Answer:
The closest you can get it UnLoad.
http://msdn.microsoft.com/en-us/library/ms178472.aspx


Question:
I have a HTML select list with quite a few (1000+) names. I have a javascript in place which will select the first matching name if someone starts typing. This matching looks at the start of the item:

var optionsLength = dropdownlist.options.length;
  for (var n=0; n < optionsLength; n++)
  {
    var optionText = dropdownlist.options[n].text;
    if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
    {
      dropdownlist.selectedIndex = n;
      return false;
    }
  }

The customer would like to have a suggest or autofilter: typing part of a name should 'find' all names containing that part. I've seen a few Google Suggest like options, most using Ajax, but I'd like a pure javascript option, since the select list is already loaded anyway. Pointers anyone?

Answer:
Change
```
```
if (optionText.indexOf(dropdownlist.keypressBuffer,0) == 0)
```
```
to
```
```
if (optionText.indexOf(dropdownlist.keypressBuffer) > 0)
```
```
To find
```
dropdownlist.keypressBuffer
```
anywhere in the
```
optionText
```
.


Question:
While designing a table my colleague here says that I should avoid identity column as it is specific to SQL Server and MS Access, But I differ with his views as it makes my coding simpler.

Should I use identity column or not? If not what is best way to create the identity columns from application code?

Answer:
You can't completely divorce an application from the database vendor. If you do you won't be able to take advantages of whatever features your database provides you.
I'd say use the identity column. If you move over to Oracle (for example), you can use a Sequence. Hardly a big change.
I don't know what technology you're using, but one thing that would help is using a tool such as Hibernate or iBATIS (I think they're both available for Java and .NET) which separates you a bit from the database implementation details. Then if you change database vendor you won't need to change application code, just configuration. (In theory, at least!)


Question:
Which is the best timer approach for a C# console batch application that has to process as follows:

Connect to datasources

process batch until timeout occurs or processing complete. "Do something with datasources"

stop console app gracefully.

related question: How do you add a timer to a C# console application

Answer:
When you say "until timeout occurs" do you mean "keep processing for an hour and then stop"? If so, I'd probably just make it very explicit - work out at the start when you want to finish, then in your processing loop, do a check for whether you've reached that time or not. It's incredibly simple, easy to test etc. In terms of testability, you may want a fake clock which would let you programmatically set the time.
EDIT: Here's some pseudocode to try to clarify:
```
```
List<DataSource> dataSources = ConnectToDataSources();
TimeSpan timeout = GetTimeoutFromConfiguration(); // Or have it passed in!
DateTime endTime = DateTime.UtcNow + timeout;

bool finished = false;
while (DateTime.UtcNow < endTime && !finished)
{
    // This method should do a small amount of work and then return
    // whether or not it's finished everything
    finished = ProcessDataSources(dataSources);
}

// Done - return up the stack and the console app will close.
```
```
That's just using the built-in clock rather than a clock interface which can be mocked, etc - but it probably makes the general appropriate simpler to understand.


Question:
When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example

create or replace procedure testproc(arg1 in varchar2) is
begin
  null;
end;

Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ?

Answer:
In PL/SQL procedure it may be up to 32KB
Futher information here:
http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804


Question:
This is a very basic problem that's frustrating me at the moment. Let's say within a single solution, I have two projects. Let's call the first project SimpleMath. It has one header file "Add.h" which has

int add(int i, int j)

and the implementation "Add.cpp" which has

int add(int i, int j) {
  return i+j;
}

Now let's say in a second project I want to use the add function. However, this code:

#include "..\SimpleMath\Add.h"

int main() {

    add(1, 2);

}

results in "unresolved external symbol". How do I get the second program to "know" about the actual implementation in the .cpp file. As a side note all code is fictional this is not how I actually program.

Answer:
You either have to make Add.cpp part of a library and include it in both projects. or you have to add Add.cpp to your second project too.
Edit: to make SimpleMath a library go into the project settings on General and change the Configuration Type to Static Lib.
Then go into your solution settings, click on Project Dependencies, then select your second project in the drop down list, and put a check mark next to SimpleMath. That will automatically link SimpleMath to your second project, and will also make sure that any changes to SimpleMath will be rebuilt when you rebuild your second project.


Question:
I need to add a xml:lang attribute on the root xml node in the outbound document from BizTalk.

This is a fixed value, so it may be set in the schema or something.

This is what I want to get out:

<Catalog xml:lang="NB-NO">
...
</Catalog>

I've tried to define the attribute "xml:lang", but it doesn't allow me to use ":" in the schema.

This is the error message I get:

Invalid 'name' attribute value
  'xml:lang': The ':' character,
  hexadecimal value 0x3A, at position 3
  within the name, cannot be included in
  a name.

Is there another way to insert a ':' as part of the attribute name in BizTalk?

Can anyone tell me how to do this?

I'm using BizTalk 2006 and no orchestration.

Answer:
Try to add the xml namespace declaration to the schema
```
```
xmlns:xml="http://www.w3.org/XML/1998/namespace"
```
```
Beware that this addition will be removed when the schema file is recreated.


Question:
we're running in this issue. We're using a web service (using soap4r) to run some kind of searches and the problem appears when the webservice server is down and our aplication is trying to connect to it.
At that point the application is unreachable, and all the customers are blocked.

What can we do to avoid that? Is possibile to block the routing to a mongrel that it is blocked? (I suppose that the apache's proxy uses a round-robin algohritm)

Thanks
Roberto

Answer:
This sounds to me like it may be more of a mod_proxy problem than one with Mongrel or Apache - are you setting Proxy Timeouts as described
here
?