q:
I've created a MATLAB class, something like:

classdef myclass

  properties
      x_array = [];
  end

  methods
    function increment(obj,value)
       obj.x_array = [obj.x_array ; value);
    end
  end
end

The problem is, the property x_array is never modified when I invoke the increment() function:
ex:

>>s = myclass
>>increment(s,5)

>>s.x_array
ans = []

I did some research, and I reached a conclusion that this is because of MATLAB using Lazy Copy for objects, making my class inherit the HANDLE class should have solved this, but it didn't, does anybody know why this is happening? And if extending the handle class is indeen the solution, isn't this the right way to do it:

classdef myclass < handle

or are there any extra steps?

[A]
This is similar to
this question
. In short all you should have to do is inherit from handle class.
Quick example
Contents of file myclass.m
```
```
classdef myclass<handle
    properties
        x_array = []
    end
    methods
        function obj=increment(obj,val)
            obj.x_array=[obj.x_array val];
        end
    end
end
```
```
Now from the Matlab command prompt, you can do the following
```
```
>> s=myclass;
>> s.increment(5)
>> s.increment(6)
>> s

s =

myclass handle

properties:
    x_array: [5 6]

lists of methods, events, superclasses
```
```


q:
I'm desperately searching for a tool allowing me to copy documents with their old versions from a SharePoint 2003 to a SharePoint 2007 site.

Do you know about any simple (and preferably free) tool which does this?

[A]
We recently did a migration from SPS 2003 to MOSS 2007, and I was trying to figure out how to do this. Sadly, there didn't seem to be a great way. What I ended up doing was using a back up of my SPS 2003 content database and a MOSS 2007 VM to do a database attach upgrade of the whole SPS 2003 portal. Then, I used the content migration commands (stsadm -o export, stsadm -o import) to move the lists with all of their versions to the "real" MOSS 2007 site collection.
This
page
gave me the steps for doing the database migration.
There are also some nice commands you can potentially use for moving just a list
here
. For the record, the migration commands (e.g. gl-exportlist, gl-importlist) only work between two MOSS 2007 installations.
I definitely had to try it both with the stsadm extensions and the built-in commands a couple of times before the results were acceptable. The real key was doing the database migration to a VM to get everything into MOSS so I could use those tools.
I know this seems like a crazy amount of work, but it's the only way I found to get it done without dropping thousands of dollars for something like AvePoint's DocAve Migrators. And it really wasn't
that
bad.
One thing to watch out for is that, if you include user security when you do the export and import, you will get a lot of SharePoint groups and users added to your production site collection.

s: huggingface

c: devops

d: intermediate


q:
Given the string "ThisStringHasNoSpacesButItDoesHaveCapitals" what is the best way to add spaces before the capital letters. So the end string would be "This String Has No Spaces But It Does Have Capitals"

Here is my attempt with a RegEx

System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0")

[A]
What you have works perfectly.  Just remember to reassign
```
value
```
to the return value of this function.
```
```
value = System.Text.RegularExpressions.Regex.Replace(value, "[A-Z]", " $0");
```
```


q:
Below is what I'm trying to achieve. The problem is "errors" is not defined. If I remove my match logic, the errors are displayed on the web page. Is there anyway of evaluating the text the error contains?

<logic:messagesPresent>
    <tr>
        <td class="errorcicon"><img src="images/icon_caution.gif" width="18" height="18" alt="Caution" /></td>
        <td></td>
        <td colspan="4"><html:errors /></td>
    </tr>
</logic:messagesPresent>

<logic:match name="errors" property="text" value="Service Start date is required" >
    <% pageContext.setAttribute("NOORIGIONALSERVICEDATE", "-1");%>
</logic:match>

[A]
Have you tried the .siblings() method?
```
```
$(this).siblings('img.expander').attr('src','img/content/info-close.gif');
```
```


q:
Do I really have to learn Objective-C to develop solid Mac Apps?

As Mac users tend to use only applications that have a nice (native) GUI, i don't think that Mono and GTK+ or any Java GUI (Swing) will fit their needs.

There are projects like Cocoa#, PyObjC and RubyCocoa, but are they ready for primetime?

So do I really have to learn Objective-C ?
I would prefer a dynamic language.

[A]
Objective-C
is
a dynamic language, as far as the Objective-C parts go.  Here's a little summary article:
http://www.macdevcenter.com/pub/a/mac/2003/04/28/objective-c.html
The syntax is scary at first, but it grows on you.  I suggest biting the bullet and slogging through it.
If you want to work at a "real job" doing Mac programming with other people, you're going to need to know Objective-C (in my opinion, anyway).


q:
Is there any way of pulling in a CSS stylesheet into FireFox 2 or 3 that is not a static file?

Bellow is the code we are using to pull in a stylesheet dynamically generated by a CGI script.

<link rel="stylesheet" href="/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css" type="text/css">

/cgi-bin/Xebra?ShowIt&s=LH4X6I2l4fSYwf4pky4k&shw=795430-0&path=customer/DEMO/demo1.css

Note that the URL above that pulls in the CSS does not end with .css rather the parameters do.

[A]
Is the Content Type from the server the correct one for the file that is served up?
```
```
Content-type: text/css
```
```


q:
I've created a c# webservice that allows our front end support teams to view and update a few selected Active Directory values using system.directoryservices

Fields that I want to update are [job] title, department, telephone and employeeid.

I can use a service account with "delegates rights" to update [job] title, department, telephone etc. but when I try to update employeeid I get an "not authorised" error message.

If I use a domain admin account then the same code works fine.

I don't want to use a domain admin account for this webservice, so what privileges do I need?

[A]
A sample of the code (the moving parts at least)
```
```
string distinguishedname = "CN=Wicks\, Guy,OU=Users,DC=ad,DC=com"
using (DirectoryEntry myDirectoryEntry = new DirectoryEntry(string.Format("LDAP://{0}", distinguishedname), null, null, AuthenticationTypes.Secure))
{
    try
    {
        myDirectoryEntry.Username   = "serviceaccount";
        myDirectoryEntry.Password   = "pa55word";

        myDirectoryEntry.Properties["employeeid"][0]    = employeeID;
        myDirectoryEntry.CommitChanges();
        setresult.result        = myDirectoryEntry.Properties["employeeid"][0].ToString();
    }
    catch   ( Exception ex )
    {
        setresult.result        = ex.Message;
    }
} // end using
```
```
(I do apologise for my c#)


q:
My company uses StarTeam for source control and CR management, but I would really like to switch to Subversion for source control.  For those of you that know ClearQuest and ClearCase, StarTeam has the ability to create tickets, which can later be associated with code changes.

Are there any similar products that integrate nicely with Subversion (preferably free, but I'm not necessarily against the idea of a commercial app)?  I played around with trac a while back, but I wasn't overly impressed with it.

[A]
Jira
integrates well, with a little effort, with Subversion.
Using
Bamboo
together with Subversion and
Jira
can help integrate your whole release management cycle - See
A good strategy for implementing a versioning system


q:
I have a NotifyIcon control that appears in the system tray.  How can I find the location (x, y) of the icon on the screen?

Thanks

[A]
You can't.  It isn't hard to get the window handle for the system tray, GetClassName() returns "ToolbarWindow32", the class name of the standard TOOLBAR common control.  Beware that a 64-bit OS has two of them.  Then you can send messages to it like TB_GETBUTTONINFO.  Chief hang-ups are that you won't know what button ID to choose and the returned info does not include the button position.
Which is for the better, buttons move around without you being able to lock them.


q:
There are several similar Oracle technologies - Oracle Streams, Oracle Change Data Capture and Database Change Notification.

What are the differences between these?

Are they related to Oracle Advanced Queueing?

[A]
Oracle CDC is all about capturing changes in DB tables and the changes are stored in special Oracle tables. There are two modes of CDC operation: asynchronous (based on Java) or synchronous (based on DB triggers, more performance overhead).
Oracle Streams sits on top of Oracle CDC and it's a full transport mechanism (over e.g. HTTP) for data synchronization between 2 servers. It's based on Oracle Advanced Queues technology and it's designed for high performance and reliability.
Both Oracle CDC and Streams are generally used for data synchronization between Oracle DB servers... With Oracle CDC, you don't have to use Oracle Streams for, e.g. you could write your own data export routines which create flat files for the purpose of synchronization between 2 DB servers, whereas with Streams you must have a network link between the 2 servers.
Database Change Notification is something else again, it's not used for server-to-server synch but instead more for server notification of resultset changes to clients, mostly in the context of data caches on the client side.


q:
I have a delphi (Win32) web application that can run either as a CGI app, ISAPI or Apache DLL. I want to be able to generate a unique filename prefix (unique for all current requests at a given moment), and figure that the best way to do this would be to use processID (to handle CGI mode) as well as threadID (to handle dll mode).

How would I get a unique Process ID and Thread ID in Delphi?

Will these be unique in a Multi-Core/Multi-Processor situation (on a single webserver machine)?

Edit: please note that I was advised against this approach, and thus the accepted answer uses a different method to generate temporary filenames

[A]
Could you not use a
GUID
instead?
Edit: Should have said first time around, check out the following two functions
```
```
CreateGuid
GuidToString
```
```


q:
I'm not that familiar with WCF, but I thought I'll learn while trying to consume an existing service.

One of the REST APIs I thought of was the Twitter API. I thought of developing a WPF client that will just output to the screen the last 5 tweets by a certain Twitter user.

I was wondering if someone could please briefly outline the steps I need to take in Visual Studio to consume these services, using WCF (classes, wizards, proxies etc.).I already know how to just call them using a web request and parse the XML that returns - I really want to see the WCF part at work.

Thanks in advance to anyoine who helps further my education :)

[A]
There is no benefit to using WCF to consume an Http based API like the Twitter API.  System.Net.HttpWebRequest is more than sufficient.  In fact I suspect that you will have some difficulty.  WCF is much easier to get working when you have WCF at both ends of the wire.
However, if the REST API is returning Atom content then you could using the System.ServiceModel.Syndication classes to help parse the response.
EDIT:
Since I wrote this post Microsoft released a preview of a new HTTP client library that does an even better job of consuming RESTful services.
Here is how you would use it to POST to twitter:
```
```
var client = new HttpClient();
client.DefaultHeaders.Authorization = Credential.CreateBasic("username","password");
var form = new HttpUrlEncodedForm();
form.Add("status","Test tweet using Microsoft.Http.HttpClient");
var content = HttpContent.Create(form);
var resp = client.Post("http://www.twitter.com/statuses/update.xml", content);
```
```
If you want more more details on this client library,  I am in the process of writing some blog posts about it
here
.


q:
Is there a (portable) way to rotate text in a HTML table cell by 90°?

(I have a table with many columns and much text for the headings, so I'd like to write it vertically to save space.)

[A]
Alternate Solution?
Instead of rotating the text, would it work to have it written "top to bottom?"
Like this:
```
```
S
O
M
E

T
E
X
T
```
```
I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.
This could be done via JavaScript in the browser like this:
```
```
"SOME TEXT".split("").join("\n")
```
```
... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by "portable?")
Also the user doesn't have to turn his/her head sideways to read it. :)
Update
This thread
is about doing this with jQuery.


q: Does anyone know how I can get a list of products belonging to a specific category from within a view file in Magento?

[A]
It all depends on which view you're in. ;-)
First off, I hope you stayed within your template set (default in my example).
Use this as an
example
:
```
```
<?php
$_cat         = $this->getCurrentCategory();
$_parent      = $_cat->getParentCategory();
$_categories  = $_parent->getChildren();

/* @var $category Mage_Catalog_Model_Category */
$collection = Mage::getModel('catalog/category')->getCollection();
/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */
$collection->addAttributeToSelect('url_key')
    ->addAttributeToSelect('name')
    ->addAttributeToSelect('is_anchor')
    ->addAttributeToFilter('is_active', 1)
    ->addIdFilter($_categories)
    ->setOrder('position', 'ASC')
    ->joinUrlRewrite()
    ->load();

$productCollection = Mage::getResourceModel('catalog/product_collection');
$layer             = Mage::getSingleton('catalog/layer');
$layer->prepareProductCollection($productCollection);
$productCollection->addCountToCategories($collection);
// $productCollection should be ready here ;-)
?>
```
```
I'm using the above code to display sister categories in my template - it's not ideal but it works.
It's sort of a hack because I did not yet have time to learn all the layout XML madness. Otherwise if you use the XMLs you need to keep in mind - it all depends on where you are at.
Where
means the template file and essentially also the layout (in terms of app/design/frontend/default/default/layout/*).
I know it's not much, but I hope it helps to get you started.


q:
What is the best way to get the application name (i.e MyApplication.exe) of the executing assembly from a referenced class library in C#?

I need to open the application's app.config to retrieve some appSettings variables for the referenced DLL.

[A]
To get the answer to the question title:
```
```
// Full-name, e.g. MyApplication, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
string exeAssembly = Assembly.GetEntryAssembly().FullName;

// or just the "assembly name" part (e.g. "MyApplication")
string exeAssemblyName = Assembly.GetEntryAssembly().GetName().Name;
```
```
As mentioned by @Ben, since you mention wanting to get the configuration information, use the
```
ConfigurationManager
```
class.


q: Is there a better way to keep the domain name unaltered in the adress bar besides using a main frame?

[A]
You can use AJAX to change the content of the page without changing the address.
However, if the data is located on another domain then the address should change to point to that domain.  Also, it is recommended that the address can be bookmarked so user's can easily return to the data.  The address should reflect the content of the resource it points to.


q:
I thought that it would be fun to present some classic CS problems and let people show their algorithm optimization skills. The hope is that we get to see some clever techniques to solve abstract problems that we may be able to implement in practice.

Ideally solutions would be presented in pseudo code with a big O classification. Proof of that classification is gravy. On to the problem:

There are N closed lockers and N students present. The first student opens each locker. The second student opens or closes every second locker. This continues where the nth student opens and closes every nth locker. After N students what lockers are open? How many lockers are open?

[A]
Students will only flip the state of those lockers that their number is a divisor of (student 2 flips the even lockers, student 3 flips the lockers divisible by 3, so on and so forth...).  So, the only lockers that will remain open after N rounds are those that have an odd number of divisors (because they start closed, an odd number of flips will leave it open).  The only numbers that have an odd number of divisors are perfect squares, so all of the perfect-square-numbered lockers will be left open.  So after N rounds, the number of lockers left open will be the square root (floored) of N.
This solution would be O(sqrt(N)) to know
exactly which
lockers are open, but O(1) if you only need to know
how many
lockers are open.


q:
char *strtok(char *s1, const char *s2)

repeated calls to this function break string s1 into "tokens"--that is
  the string is broken into substrings,
  each terminating with a '\0', where
  the '\0' replaces any characters
  contained in string s2. The first call
  uses the string to be tokenized as s1;
  subsequent calls use NULL as the first
  argument. A pointer to the beginning
  of the current token is returned; NULL
  is returned if there are no more
  tokens.

Hi,

I have been trying to use strtok just now and found out that if I pass in a char* into s1, I get a segmentation fault. If I pass in a char[], strtok works fine.

Why is this?

I googled around and the reason seems to be something about how char* is read only and char[] is writeable. A more thorough explanation would be much appreciated.

[A]
What did you initialize the
```
char *
```
to?
If something like
```
```
char *text = "foobar";
```
```
then you have a pointer to some read-only characters
For
```
```
char text[7] = "foobar";
```
```
then you have a seven element array of characters that you can do what you like with.
```
strtok
```
writes into the string you give it - overwriting the separator character with
```
null
```
and keeping a pointer to the rest of the string.
Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault.
Also, becasue
```
strtok
```
keeps a reference to the rest of the string, it's not reeentrant - you can use it only on one string at a time. It's best avoided, really - consider strsep(3) instead - see, for example, here:
http://www.rt.com/man/strsep.3.html
(although that still writes into the string so has the same read-only/segfault issue)


q:
I've got a iSeries to .Net compact framework project.  It includes rgple programs exposed as web services and a Windows mobile app that uses the webservices.  Each iSeries program has a specific webservice wrapper and the .net app reference each.  I would like to come up with a more generic messaging service using XML.

I am fairly familiar with procesing XML in .Net.  But have no experience with XML on the iSeries.  What iSeries XML tools would you recommend?  And how best to get started/learn XML processing on the iSeries?

[A]
IBM provides the
XML Toolkit for IBM System i5
.
You can also run Java which has an
XML parser
.
RPG also has some
support for XML
built into the langage.
You can get started by reading the IBM documentation at those links.


q:
Can anyone explain why following code won't compile? At least on g++ 4.2.4.

And more interesting, why it will compile when I cast MEMBER to int?

#include <vector>

class Foo {
public:
    static const int MEMBER = 1;
};

int main(){
    vector<int> v;
    v.push_back( Foo::MEMBER );       // undefined reference to `Foo::MEMBER'
    v.push_back( (int) Foo::MEMBER ); // OK
    return 0;
}

[A]
You need to actually define the static member somewhere (after the class definition).  Try this:
```
```
class Foo { /* ... */ };

const int Foo::MEMBER;

int main() { /* ... */ }
```
```
That should get rid of the undefined reference.


q:
I'm trying to install RSpec as a gem after having it installed as a plugin.  I've gone ahead and followed the directions found here http://github.com/dchelimsky/rspec-rails/wikis for the section titled rspec and rspec-rails gems.  When I run ruby script/generate rspec, I get the error Couldn't find 'rspec' generator.  Do only the plugins work?  If so, why do they even offer the gems for rspec and rspec-rails?  I'm running a frozen copy of Rails 2.1.2, and the version of rpsec and rspec-rails I'm using is the newest for today (Nov 7, 2008) 1.1.11.

EDIT Nov 12, 2008
I have both the rspec and rspec-rails gems installed. I've unpacked the gems into the vender/gems folder. Both are version 1.1.11.

[A]
Is there supposed to be an 'rspec' generator?  I've only used the following:
```
```
script/generate rspec_model mymodel
script/generate rspec_controller mycontroller
```
```


q:
When does java let go of a connections to a URL? I don't see a close() method on either URL or URLConnection so does it free up the connection as soon as the request finishes? I'm mainly asking to see if I need to do any clean up in an exception handler.

try {
  URL url = new URL("http://foo.bar");
  URLConnection conn = url.openConnection();
  // use the connection
}
catch (Exception e) {
  // any clean up here?
}

[A]
It depends on the specific protocol specified in the protocol. Some maintain persistent connections, other close their connections when your call close in the input or outputstream given by the connection. But other than remembering to closing the streams you opened from the URLConnection, there is nothing else you can do.
From the javadoc for java.net.URLConnection
Invoking the close() methods on the
  InputStream or OutputStream of an
  URLConnection after a request may free
  network resources associated with this
  instance, unless particular protocol
  specifications specify different
  behaviours for it.


q:
I have a pseudo-realtime data processing application where I would like to use LazyInit<double> so I don't do calculations I don't need, but LazyInit<T> restricts  T to classes.  I can work around it, but I'd obviously prefer not to.

Does anybody know why this is?

[A]
I believe it is because value types are automatically initialized and LazyInit determines if something needs initializing based on if it is null or not. You can get around it by using nullable types.
```
```
LazyInit<double?>
```
```


q:
I've done development in both VB6 and VB.NET, and I've used ADODB objects in VB6 to handle recordset navigation (i.e. the MoveFirst, MoveNext, etc. methods), and I have used ADO.NET to handle queries in a row-by-row nature (i.e For Each Row In Table.Rows ...)

But now I seem to have come to a dilemma.  I am now building a program in VB.NET where I need to use the equivalent functionality of the Move commands of the old Recordset object.  Does VB.NET have some sort of object that supports this functionality, or do I have to resort to using the old ADODB COM object?

Edit: Just for clarification, I want the user to be able to navigate through the query moving forwards or backwards.  Looping through the rows is a simple task.

[A]
In .Net, there are many ways to do this. One that I like is to use a DataReader, which can return multiple recordsets. You can loop through its records using While DataReader.Read.
One of the advantages of using DataReader is that it is a forward-only, read-only object, so it's fast and light-weight.
To allow the user to navigate through all of the records, one at a time, you do not want to hold a DataReader open while the user navigates. you can read the DataReader records into objects. Or, you can retrieve the records into a DataSet, and display the DataRows from the DataTable one at a time.
I would suggest that, if possible, you retrieve all of the records at once if there are not too many. This will save repeated calls to the database.
On the other hand, if there are a lot of records, you could retrieve the first few (say, 10 or 20) and only retrieve the next set of records with a new database call if the user clicks beyond the initial set. This is lazy loading.


q:
We are currently using unit tests to test our project.  We have the majority of functionality covered but I think our tests are too brittle.

I was wondering if there are any specific things we can be doing to make the unit tests more flexible so they don't break for the wrong reasons.

A couple answers have mentioned being careful of mocking too much... So what are legitimate reasons for mocking?  I think that may be one of our main problems, but when your application is mostly a dynamic, database-driven site, how do you get away from mocking?

[A]
This is a somewhat simplistic answer, but shows the right mindset:
A test should break if the behaviour changes in a way that you care about.
A test should continue to work if the behaviour changes in a way that you don't care about.
So as far as is possible - without going
hugely
out of your way - make sure you're testing the "end result" of the method without caring how it got there. One thing to watch  out for is mocking - it's incredibly useful, but can easily make your tests brittle.


q:
It seems that all of the documentation I can find about OpenGL-ES says something to the effect of "OpenGL-ES is just like OpenGL, but without a lot of stuff.  For example, there's no glBegin or glEnd."

Ok, that's great.  So, what ELSE isn't there any of?  Or is there a list of what's in?  Or maybe a porting guide?

(Specifically, I'm trying to move an existing GL app to the iPhone, although I don't want to necessarily limit my Q to the iPhone.)

[A]
The
"OpenGL ES 1.1.12 Difference Specification"
(PDF) linked to from
the OpenGL ES 1.X info page at Khronos.org
goes through the differences between OpenGL ES 1.X and OpenGL 1.5.  OpenGL ES 1.1 is the version used on the iPhone.
The difference specification is not the simplest document I've ever seen, but it is easier reading than the OpenGL specs in general.  I recommend getting a list of OpenGL functions you call and then searching through the difference document for them.  It will show you if they are supported in OpenGL ES, and if support is only partial you can go to the full spec for more information.


q:
I have a rails template (.rhtml file) generating a Javascript object. It looks something like the following:

var volumes = {
  <% for volume in @volumes %>
    <%= volume.id %> : <%= volume.data %>
    <%= ',' unless volume === @volumes.last %>
  <% end %>
};

Note the unless statement modifier to suppress printing the comma after the last element (to satisfy Internet Explorer, which incredibly doesn't support trailing commas in JSON properties declarations).

This appears to work, but as a matter of style, do people think it is reasonable to rely on <%= value unless condition %> in the template generating an appropriate render call?

[A]
I don't see why not, but generally if you find yourself conditionalizing a comma on the last member, you probably want to use
```
join
```
instead:
```
```
<%= @volumes.map {|v| "#{v.id} : #{v.data}"}.join "," %>
```
```


q: I need to select a datetime column in a table. However, I want the select statement to return the datetime as a nvarchar with the format DD/MM/YYYY.

[A]
This should help.  It contains all (or most anyway) the different date formats
http://wiki.lessthandot.com/index.php/Formatting_Dates
I think you'd be better off handling the string conversion in client if possible.


q:
In converting from short to a byte array I found the following solution on the web but could not quite understand the logic involved.

//buffer is an array of bytes, bytes[]
buffer[position] = (byte)(sample & 0xff);
buffer[position+1] = (byte)((sample >> 8) & 0xff);

Can someone tell me why 0xff (256) is being anded to the sample which is a short?

[A]
This code probably comes from C code (or was written by a C programmer who don't parse Java as well as erickson does). This is because in Java a cast from a type with more information to a type with less information will discard the higher order bits and thus the & 0xff is unnecessary in both cases.
A short has 16 bits, two bytes. So it needs to take two slots in the byte array, because if we just casted a short into a byte one byte would be lost.
So, the code you have does
```
```
1110001100001111 sample
0000000011111111 0xff
0000000000001111 sample & 0xff => first byte`
```
```
Then, displaces the sample to get the second byte
```
```
0000000011100011 sample >> 8
0000000011111111 0xff
0000000011100011 (sample >> 8 ) & 0xff => second byte
```
```
Which can be a lot better written as erickson shows below (hopefully it'll be above soon).


q: It seems pretty silly to me. What don't I get?

[A] Business logic should be in your BLL.  If you end up with "2 liner functions" in your BLL, did you accidentally put that business logic in your DAL or UI?


q:
We have a Linux application that makes use of OpenSSL's Python bindings and I suspect it is causing random crashes. Occasionally, we see it crash with the message:

Python Fatal Error: GC Object already tracked

which would appear to be either a programming error on the part of the library, or a symptom of memory corruption. Is there any way to know the last line of Python source code it executed, given a core file? Or if it is attached in GDB? I realize it is probably all compiled bytecode, but I'm hoping there someone out there may have dealt with this. Currently it is running with the trace module active and we're hoping it will happen again, but it could be a long while.

[A]
If you have mac or sun box kicking around you could use
dtrace
and a version of python compiled with dtrace to figure out what the application was doing at the time. Note: in 10.5 python is pre-compiled with dtrace which is really nice and handy.
If that isn't available to you, then you can
import gc
and enable debugging which you can then put out to a log file.
To specifically answer your question regarding debugging with GDB you might want to read "
Debugging With GDB
" on the python wiki.


q: How can I calculate the last business day of the month in .NET?

[A] First, get the last day of the month.  Then keep decrementing until you're either past the beginning of the month, or have hit a date that validates as a "business day".


q:
I'm building the HTML code within an XML DOM object to be used as the contents of the innerHTML of a div element using an XSL template. Traditionally we create a new XML DOM document and add the input parameters as XML Elements for the transform via javascript. This is all very time-consuming as we are basically hand picking the data from another XML document that represents our current account and copying the data into a transient XML DOM document.

What I'd like to do is clone the relevant node of the account document (i.e. customer info) and use it as the basis for the transform. I don't want to use the account document directly as I'd like to be able to add transform specific input, without making changes to the account object.

How efficient is using .cloneNode(true) for a desired node of about typically less than 200 elements from a document of typically 2000+ elements? The target platform is IE6 with no external tools (i.e. ActiveX).

[A]
IE will fail on certain things.
e.g. checked radio/checkboxes will not be checked when you add your copy to the DOM.
Example:
http://webbugtrack.blogspot.com/2008/03/bug-199-cant-clone-form-element-in-ie.html
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
To see what IE will actually return, try replacing the url with this in the Address Bar of one of your pages, and press enter.
```
```
javascript:'<xmp>'+window.document.body.outerHTML+'</xmp>';
```
```
If you are happy with the results, great!, but I think you'll end up less than satisfied at what IE returns (both in the DOM, and this "string" value equivelant.


q:
Sometimes, my UIWebView will have a grey box over part or all of the content. I can't make heads or tails of why it's happening.  It happens regularly for certain content.

Thanks!

--Update--

It seems to occur when the webview is not immediately viewable on the screen -- ie i've got a scrollview, and the webview is below the fold.

--Update #2--

When I bring the content above the fold, it loads fine most of the time. There are still instances when the grey box is still showing up. The weird part is if i double-tap it, it finishes loading the content just fine.  bizarre

--Update #3--

Okay, so it seems to be that if my uiwebview has a height greater than 1000px, a grey box appears on the rest of the content below 1000px. A double-tap reveals the actual content.

[A]
I have been dealing with this glitch as well, and have opened a bug report at apple.
I would have commented above, but I don't have the 50 rep yet.
For anyone else encountering this glitch, send them a report, I included a full project demonstrating it, with a few screenshots from another app I am working on.
The more bug reports they get on a topic, the more likely they are to address it, apparently.
https://bugreport.apple.com/


q:
I've been spoiled by ActiveRecords.  So I'm on the lookout for migration system that can be applied to SQL Server, and either is executed as Java application, or a Win32 Executable.  (Of course further compatibility with other DB's and host OS's is welcome.)

The real desire is having a clear schema change application with roll back, ideally in something nicer then SQL so it can be DB system agnostic.

The hitch I've found for alternatives that are Java based, is lack of clean support for the Microsoft JDBC.

Looking forward to any suggestions.

[A]
OpenNETCF's NetworkInformation namespace is not going to help - it's a wrapper around NDIS and WZC, which is not of much use for telephony.  What is probebly relevent here is the
Telephony API (TAPI)
, though I have doubts whether even TAPI is going to give all of this info (it's been a while since I fought with TAPI).
My guess is that you'll be able to get some of the info through TAPI, but a lot of it i probably retrieved through a proprietary API that the radio vendor provides, and without info on that API (from the radio vendor or the device OEM) you're probably out of luck.


q:
I am wondering how the HttpContext is maintained given that the request-response nature of the web is essentially stateless.

Is an identifier being for the HttpContext object being sent as part of the __EVENTTarget / __EVENTARGUMENTS hidden fields so that the HttpRuntime class can create the HttpContext class by reading this section from the request (HttpWorkerRequest)?  I don't think

Please let me know as I am trying to fill some holes in my understanding of the http pipeline and I was unable to find any information about this.

I understand something like
HttpContext.Current.Session["myKey"] = Value;

just works but if I had to do something similar in a different language (say perl), I would have to use hidden fields for the same, wouldn't I?

Thanks
-Venu

[A]
I don't think there is one answer to your question, because I don't think everything under the HttpContext umbrella works the same way.  In the example you chose, session state, both the key and value are stored on the server side.  The way it knows how to hook up future requests to that session state is by using a cookie that has a (totally different) key in it. When the browser makes another request, it sends this cookie with the request and the server uses it to figure out which session to map to. Once it figures it out, you've again got access to your dictionary, across responses.
So, to do it in perl, you'd want to manually create a cookie and store a unique key in it, have a server-side mapping of those unique keys to session state dictionaries, and pretty much do what I described above.


q:
I haven't used regular expressions at all, so I'm having difficulty troubleshooting. I want the regex to match only when the contained string is all numbers; but with the two examples below it is matching a string that contains all numbers plus an equals sign like "1234=4321". I'm sure there's a way to change this behavior, but as I said, I've never really done much with regular expressions.

string compare = "1234=4321";
Regex regex = new Regex(@"[\d]");

if (regex.IsMatch(compare))
{
    //true
}

regex = new Regex("[0-9]");

if (regex.IsMatch(compare))
{
    //true
}

In case it matters, I'm using C# and .NET2.0.

[A]
Use the beginning and end anchors.
```
```
Regex regex = new Regex(@"^\d$");
```
```
Use
```
"^\d+$"
```
if you need to match more than one digit.
Note that
```
"\d"
```
will match
```
[0-9]
```
and other digit characters like the Eastern Arabic numerals
```
٠١٢٣٤٥٦٧٨٩
```
.  Use
```
"^[0-9]+$"
```
to restrict matches to just the Arabic numerals 0 - 9.
If you need to include any numeric representations other than just digits (like decimal values for starters), then see
@tchrist
's
comprehensive guide to parsing numbers with regular expressions
.


q: What is the purpose/meaning of the Version property on a FormsAuthenticationTicket?

[A]
The
docs
are less than enlightening on this one, though the default version number did change
from 1
to 2 with ASP.NET 2.0.
Reflector didn't turn up any interesting uses of it either, other than keeping it alive on renews. My guess is that it's for "future use".


q:
How can I dynamically invoke a class method in PHP? The class method is not static. It appears that

call_user_func(...)

only works with static functions?

Thanks.

[A]
```
```
call_user_func(array($object, 'methodName'));
```
```
For more details, see the
php callback documentation.


q: How do I check if the directory into which a file is going to be written does exist, and if it does not, create the directory using Python?

[A]
Try the
```
os.path.exists
```
function
```
```
if not os.path.exists(dir):
    os.mkdir(dir)
```
```


q:
Is it ever acceptable to have a memory leak in your C or C++ application?

What if you allocate some memory and use it until the very last line of code in your application (for example, a global object's destructor)? As long as the memory consumption doesn't grow over time, is it OK to trust the OS to free your memory for you when your application terminates (on Windows, Mac, and Linux)? Would you even consider this a real memory leak if the memory was being used continuously until it was freed by the OS.

What if a third party library forced this situation on you? Would refuse to use that third party library no matter how great it otherwise might be?

I only see one practical disadvantage, and that is that these benign leaks will show up with memory leak detection tools as false positives.

[A]
In theory no, in practise
it depends
.
It really depends on how much data the program is working on, how often the program is run and whether or not it is running constantly.
If I have a quick program that reads a small amount of data makes a calculation and exits, a small memory leak will never be noticed. Because the program is not running for very long and only uses a small amount of memory, the leak will be small and freed when the program exists.
On the other hand if I have a program that processes millions of records and runs for a long time, a small memory leak might bring down the machine given enough time.
As for third party libraries that have leaks, if they cause a problem either fix the library or find a better alternative.  If it doesn't cause a problem, does it really matter?


q:
I have only been working with sharepoint for three months but right from the start I was told that the SharePoint content db was off limits as MS could change the schema at any time. The recommended route is to use the object model, and in most case I kind of understands that.

Now I need to join some lists in order to present the content grouped by some specific fields. Rather then iterating through each and every list I would prefer to link our own db which resides on the same DB server, to the WSS content DB and just create a view on the tables. This view should be on our DB in order to make such that we don't change ANYTHING on the WSS content DB.

Am I on the route to eternal damnation or not?

[A]
Yes, you are. Microsoft is
very
clear that any modifications to the SharePoint tables renders you unsupportable.
Direct modification of the SharePoint database or its data is not recommended because it puts the environment in an unsupported state.
Now, creating a link on your own DB which queries the SharePoint DB is shaky ground. Personally I'd do one of two things:
If this is a mission-critical application, run it past MSFT support.
If it is anything else, just make sure that your view is not locking the DB during querying.
A better strategy might be to iterate the lists and sync it to your own table so you can do whatever kind of data-mining you'd like - if you don't mind whatever lag time your sync routine would need.


q: In layman's terms, what's a RDF triple?

[A]
An RDF file should parse down to a
  list of triples.
A triple consists of a subject, a
  predicate, and an object. But what do
  these actually mean?
The subject is, well, the subject. It
  identifies what object the triple is
  describing.
The predicate defines the piece of
  data in the object we are giving a
  value to.
The object is the actual value.
From:
http://www.robertprice.co.uk/robblog/archive/2004/10/What_Is_An_RDF_Triple_.shtml


q: I want to create a library with a modified version of printf and then call LD_PRELOAD so when my program calls printf it uses my version. Can someone explain to me how to use LD_PRELOAD and if there is a something special I need to do in my code or my library?

[A]
That seems like a bad idea. Why not name your version of
```
printf
```
something else?


q:
The title sort of explains itself. I am making some 'genrative' artwork in flash. Now I want to save the frame without making a screenshot so-on and sofort. And perhaps one day i would like to save a batch of frames.

Is there an AS3 class/library out there that could help me out ?

[A]
Do you want to save the file to a hard-drive or to a website?
If to a hard-drive, you might have a hard time unless you're open to using Air. Because of the security sandbox of Flash, you can't write arbitrary files to the user's hard disk.
If you absolutely must save it to a user's hard-drive using Flash and not Air, you'll probably have to send the bitmap data to a server-side PHP (or similar) script which will then allow the user to download and save the image in one location or another.


q:
How do I get:

id       Name       Value
1          A          4
1          B          8
2          C          9

to

id          Column
1          A:4, B:8
2          C:9

[A]
This kind of question is asked here very often, and the solution is going to depend a lot on the underlying requirements:
https://stackoverflow.com/search?q=sql+pivot
and
https://stackoverflow.com/search?q=sql+concatenate
Typically, there is no SQL-only way to do this without either dynamic sql, a user-defined function, or a cursor.


q:
I have an application where I accept a socket connection from a telnet client and put up a simple, keyboard driven character GUI.

The telnet client, at least on Linux, defaults into line-at-a-time mode, so I always have to do ^]mode char manually.

A skim of the relevant RFCs suggests that if my application simply sent the characters IAC DONT LINEMODE (\377\376\042) as soon as the client connects, the client should be forced into character mode.  However, it doesn't make any difference.

What's the simplest bit of code that would do the job?  Ideally just a string to be sent. My application can absorb whatever junk the client sends back.

[A]
For what it's worth, solved it myself.
```
```
// IAC WONT LINEMODE IAC WILL ECHO

write(s,"\377\375\042\377\373\001",6);
```
```
gets the remote (at least telnet from an Xterm on a Linux box) into the right state.


q:
I want to deal with the command line input in Ruby:

> cat input.txt | myprog.rb
> myprog.rb < input.txt
> myprog.rb arg1 arg2 arg3 ...

What is the best way to do it? In particular I want to deal with blank STDIN, and I hope for an elegant solution.

#!/usr/bin/env ruby

STDIN.read.split("\n").each do |a|
   puts a
end

ARGV.each do |b|
    puts b
end

[A]
I am not quite sure what you need, but I would use something like this:
```
```
#!/usr/bin/env ruby

until ARGV.empty? do
  puts "From arguments: #{ARGV.shift}"
end

while a = gets
  puts "From stdin: #{a}"
end
```
```
Note that because ARGV array is empty before first
```
gets
```
, Ruby won't try to interpret argument as text file from which to read (behaviour inherited from Perl).
If stdin is empty or there is no arguments, nothing is printed.
Few test cases:
```
```
$ cat input.txt | ./myprog.rb
From stdin: line 1
From stdin: line 2

$ ./myprog.rb arg1 arg2 arg3
From arguments: arg1
From arguments: arg2
From arguments: arg3
hi!
From stdin: hi!
```
```


q:
Rails has an awesome way of looking up column names and expected datatypes from the DB, alleviating a lot of programming.

I'm trying to build something like this in C#.NET, because we have large tables that are ever changing. I'll be adding parameters like so:

SqlParameter param = new SqlParameter("parametername", *SqlDbType.Int*);
param.Direction = ParameterDirection.Input;
param.Value = 0;
comm.Parameters.Add(param);

Notice the SqlDbType.  How can I get that?  If I get DataColumns from the DataSet, all I can get is System types like System.string.

[A]
why not just let ADO.NET detect it automatically:
```
```
SqlParameter param = new SqlParameter("parametername", value);
```
```
'course, you don't actually need Direction, either:
```
```
comm.Parameters.Add(new SqlParameter("parametername",value));
```
```
I'm kind of a fan of doing things in one line :)


q:
I just added printing capability to a web site using a style sheet (ie. @media print, etc.) and was wondering if I could use a similar method for adding support for mobile devices.

If not, how do I detect a mobile device?  My pages are C# (.aspx) and I'd like to scale back the pages for ease of use on a mobile device.

Any advice for me?

EDIT: My wife has a BlackBerry, so at a miminum I'd like to enable our company's web site for that.

[A]
I'm not sure how the IPhone/iPod Touch declare themselves when requesting the stylesheet, but for most, using
```
```
<style type="text/css">
    @media handheld
    {
      /* handheld styles */
    }
</style>
```
```
should do the trick. It works in the same way @media print does (or doesn't).
For a complete list of media types, see
here.


q:
Few of us would deny the awesomeness of debuggers, but to make it more useful, some tricks can be used.

For example in Python, you can use pass to do absolutely nothing except to leave you room to put a break point and allow you to observe the values in the Watch window.

In C#, I used to do GC.Collect(), but now I use if (false){}

What's your most playful dummy line?

[A]
In C#, you can use this:
```
```
System.Diagnostics.Debugger.Break();
```
```
It will force a breakpoint.


q:
What are differences between CallContext and ThreadStatic?

I've understood that in an ASP.NET environment data stored in CallContext could be persisted throughout the request until it ends while ThreadStatic may or may not work since the request may switch threads. I've also learned that the HttpContext is internally stored using the CallContext.

In a regular application they both seem to persist throughout the same thread call. When isn't this the case?

Edit: In the comments I learned that the call context is an abstraction over a thread static store. The ASP.NET framework explicitly moves the data from one thread to the next that is to handle one request. Other framework that wants to provide thread agility could do the same to for contextual storage.

[A]
Very often a request will use the same thread throughout, but it certainly won't always be the case - ASP.NET exhibits
thread agility
. There's an old
in-depth blog article about the matter
from 2005, but as of .NET 4.5
things are rather better
.


q:
We have an internal application that is using a service account and fine-grained table and field control is controlled by permissions tables in the application.

If we wanted to use pass-through security with Active Directory,  we have a problem in that a user with odbc access could modify tables outside of business rules that exist in the application.

Is there a way to enable pass-through security,  but disable odbc access.

[A] You could use stored procedures and only give the rights to the stored procedures, ensuring either that the basic business rules cannot be violated (if they are simple and unchanging, they can go in the SPs) or at the very least (if they are complex or changing, they don't work well in SPs), all modifications have to go through stored procs.  If they make an ODBC connection to the database, they could execute the stored procs to make changes, but if you give select-only rights to the tables or views, then they cannot do it through an Access linked-table for instance.


q:
I am a big time user of using double quotes in PHP so that I can interpolate variables rather than concatenating strings. As a result, when I am generating HTML I often use single quotes for setting tag fields. For example:

$html = "<input type='text' name='address' value='$address'>";

Now this is far more readable to me than either

$html = "<input type=\"text\" name=\"address\" value=\"$address\">";

or

$html = '<input type="text" name="address" values="' . $address . '">' ;

From brief searches I have heard people saying that single quotes for HTML fields is not recognized by EVERY browser. Thus I am wondering what browsers would have problems recognizing single quote HTML?

[A]
This is similar to
When did single quotes in HTML become so popular?
. Single quotes around attributes in HTML are and always have been permitted by
the specification
. I don't think any browsers wouldn't understand them.


q:
How can I find out the number of dimensions in an array in Classic ASP ( VBScript ) .

I am being passed an Array with multiple dimensions but I only want to look at the last. Seems easy in other languages.

[A]
```
```
Ubound(MySingleDimensionalArray, 2) ' Number of Array Elements

Ubound(MyMultiDimensionalArray, 1)  ' Number of Columns
Ubound(MyMultiDimensionalArray, 2)  ' Number of Rows
```
```


q:
I have a server with .Net 2.0 sp1 installed and have no ability to  install the AJAX extensions on the server.

Is there anyway I could work around this to incorporate ASP.NET AJAX functionality?

[A]
If you can't install AJAX extensions, you will have to manage the AJAX calls yourself.  It's absolutely possible, since AJAX Extensions just wrap the meat of AJAX.  Read up on XMLHttpRequest and you'll find many examples.
Here's a good site with examples.
http://www.fiftyfoureleven.com/resources/programming/xmlhttprequest/examples


q:
I've been Googling around for .htaccess redirection information, but nothing I find is quite what I'm looking for.

Basically, I want a solution that will take a site example.com and allow you to enter URL's like:

 123.example.com
 ksdfkjds.example.com
 dsf38jif348.example.com

and this would redirect them to:

 example.com/123
 example.com/ksdfkjds
 example.com/dsf38jif348

So basically accept any subdomain and automatically redirect to a folder on the root of the domain with the name of that subdomain.

[A]
Try something like this:
```
```
# If we're not on http://example.com
RewriteCond %{HTTP_HOST} .+\.example.com

# Add the host to the front of the URL and chain with the next rule
RewriteRule ^(.*)$ ${HOST}$1 [C,QSA]

# Make the host a directory
RewriteRule ^(.*)\.example\.com(.*)$ http://example.com/$1$2 [QSA]
```
```
You don't say what should happen to
http://foo.example.com/bar?moo
- I've made it go to
http://example.com/foo/bar?moo
Change the last line if that's not what you want.


q:
Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I'm trying to figure out the best way to do that.

There's this somewhat-related method in UIApplication:

[UIApplication sharedApplication].idleTimerDisabled;

It'd be nice if you instead had something like this:

NSTimeInterval timeElapsed = [UIApplication sharedApplication].idleTimeElapsed;

Then I could set up a timer and periodically check this value, and take some action when it exceeds a threshold.

Hopefully that explains what I'm looking for. Has anyone tackled this issue already, or have any thoughts on how you would do it? Thanks.

[A] Ultimately you need to define what you consider to be idle - is idle the result of the user not touching the screen or is it the state of the system if no computing resources are being used? It is possible, in many applications, for the user to be doing something even if not actively interacting with the device through the touch screen.  While the user is probably familiar with the concept of the device going to sleep and the notice that it will happen via screen dimming, it is not necessarily the case that they'll expect something to happen if they are idle - you need to be careful about what you would do.  But going back to the original statement - if you consider the 1st case to be your definition, there is no really easy way to do this. You'd need to receive each touch event, passing it along on the responder chain as needed while noting the time it was received. That will give you some basis for making the idle calculation.  If you consider the second case to be your definition, you can play with an NSPostWhenIdle notification to try and perform your logic at that time.


q: I want to develop a windows application. If I use native C++ and MFC for user interface then the application will be very fast and tiny. But using MFC is very complicated. Also If I use C# then the application will be slower than the native code and It reqiures .NET framework to run. But developing GUI is very easy by using WinForm. Which one do you prefer?

[A]
"fast" and "slow" are subjective, especially with today's PC's. I'm not saying deliberately make the thing slow, but there isn't
nearly
as much overhead in writing a managed application as you might think. The JIT etc work very well to make the code execute very fast. And you can also NGEN for extra start-up speed if you really need.
Actually, if you have time to learn it, you might want to consider WPF rather than winform - this is a different skill-set, but allows you to make very good use of graphics hardware etc.
Also - .NET framework comes with new OS installs, and is still very common on those that pre-date it. So for me it would be a fairly clear choice to develop with C#/.NET. The time to develop a
robust and fully tested
C++ app (with no leaks, etc) is (for me at least) much greater than the same with C#.


q:
I can't seem to find a nice clean example of using AES 128 bit encryption.

Does anyone have some sample code?

[A]
If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):
http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx
And just in case you need the sample in a hurry, here it is in all its plagiarized glory:
```
```
using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged
                // class.  This generates a new key and initialization
                // vector (IV).
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {

                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    // Encrypt the string to an array of bytes.
                    byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                    // Decrypt the bytes to a string.
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an RijndaelManaged object
            // with the specified key and IV.
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            return encrypted;

        }

        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an RijndaelManaged object
            // with the specified key and IV.
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}
```
```


q:
When designing a wiki application, what things should I take into consideration?

So far I have:

revisions

parsing some sort of markup text

keeping track of links in wikis, and pages that link to other pages.

related wikis i.e. wikis are related to others.

What else goes into building a Wiki?

[A]
User interface -- one of the most frustrating things for users is that they have to learn one user interface for MediaWiki, one for TikiWiki, and one for any of the other myriad of wiki's out there.
The most important part of wikis is not the technical feasibility -- it's getting users to contribute and edit in a convenient and effective way. You can have the most technically robust wiki in the world, but if it's not easy to use, it will be useless as the community tool that a wiki is supposed to be.
Either copy an existing and familiar wiki syntax (such as MediaWiki), or be prepared to invest heavily in creating a WYSIWYG editor.


q:
Seems likes it might be useful to have the assert display a message when an assertion fails.

Currently an AssertionError gets thrown, can you specify a custom message for it?

Can you show an example mechanism for doing this (other than creating your own exception type and throwing it)?

[A]
You certainly can:
```
```
assert x > 0 : "x must be greater than zero, but x = " + x;
```
```
See
Programming with Assertions
for more information.


q: Is there a way to install all versions of all browsers on one machine?

[A] Yes. I have IE8 Beta2, FF3, Chrome Beta, and Safari 3.1.2 with the applicable developer plugins.


q:
If a company often requires users to be created in a partner's active directory, and vice versa, does it make sense to set up a federated / trusted relationship between the AD instances? If so, what should be considered? Does the ACL for users in the partner AD still work the same way? What security risks does this expose?

Thanks!

KA

Update:

I've learned that there's a better way to do this by having the application itself check user stores. The best way to do this is by moving the application into a domain trusted by both user stores. I've provided more detail in my answer below.

[A]
I've been researching this a bit more, and I've found a good solution. Since both companies both need to use the same system, the system itself just needs to verify if a user exists in either of the user stores(authentication), and then to the authorization at the system level.
The idea behind giving both companies access is solid - If we are working together and didn't have a way to do this, we'd need to re-create all the users from the company without access in the connected user store. Obviously, this would be a total mess and a maintenance nightmare.
I found out that in my case, even though both ADs are on the same WAN, it's necessary to have a formal federation or trust. Thankfully, we already have a domain that's trusted between both companies, so I just have to move the applications used by the partners into this domain. After that, it's simply a matter of fully-qualifying the DNS suffix to indicate the AD being used. Application-specific ACLs then reference the desired user store.


q:
What is copyright licence type to select in order to make the code free for the public in all possible ways.

Is "The MIT License" the best option?

[A]
Releasing your code as
public domain
is the best way to make it free for
all
possible ways.
SQLite
is a well-known public domain library (they have
a page
that explains their license).
Having said that, code that is in the public domain can be simply taken by anybody else and they can call it their own. This is why there exist free licenses like GPL/BSD/MIT/etc where you retain some semblance of ownership over the work.
Personally, I prefer licenses like BSD or MIT because they aren't as restrictive as the GPL. The GPL has a lot to say about what the user of the code can and can't do with it.


q: How do I make an activeX control in a C# library project and then reference it in another ASP.NET wet site project?

[A]
If you're using C#/.NET to build your control and consuming it from ASP.NET you would get better performance (and cause yourself much less pain) by referencing it as a standard .NET assembly, bypassing ActiveX altogether.  Hope this helps!
Adam


q:
Python 3.0 breaks backwards compatibility with previous versions and splits the language into two paths (at least temporarily). Do you know of any other language that went through such a major design phase while in maturity?

Also, do you believe that this is how programming languages should evolve or is the price to pay simply too high?

[A]
C# and the .NET framework broke compatibility between versions 1.0 and 1.1 as well as between 1.1 and 2.0.  Running applications in different versions required having multiple versions of the .NET runtime installed.
At least they did include an upgrade wizard to upgrade source from one version to the next (it worked for most of our code).


q: Does anybody have a suggestion for a java library that performs automatic cropping and deskewing of images (like those retrieved from a flatbed scanner)?

[A]
ImageMagick
can do that; you can use the
ImageMagick Java bindings
.  The
auto-crop
operator is probably what you're looking for.  Automatic deskewing is a much harder problem and involves some significant image processing; I'm not sure if ImageMagick can handle that.  If you can figure out the skewing parameters using something else, ImageMagick can definitely unskew it for you.


q:
Hey all, I need some advice on this...

We have certain permissions setup in the database for certain levels of control a user can have over the application. Disabled, ReadOnly and Edit.

My question is: Are there more generic/better ways to handle permissions applied to a form element on the page than writing a security method/check per page to enable/disable/hide/show proper controls depending on the permissions allowed?

Anyone have any experience handling this in different ways?

Edit:

I just thought about the possibility of adding constants for each layer that needs security and then adding an IsAuthorized function in the user class that would accept a constant from the form that the control is on, and return boolean to enable/disable controls, this would really reduce the amount of places I'd have to hit when/if I ever need to modify the security for all forms.

Cheers!

[A]
I think there are more possibilities than you are considering.
Hidden/Visible - is the field visible or not
Blanked/System/Unchanged - does the system initially set the value to blank, or to some business-rule-provided value, or is it left as-is
ReadOnly/Editable - can the user change the value
Required/LeaveBlank/Optional - is the field required to not be blank, or can it be left blank assuming it was blank to begin with, or is it optional and can be blank in any case
Also you need to consider a lot of factors that go into making the decision
Role - usually the user has 1 or more roles, and those roles can allow or disallow different possibilities
Status - the status of the object in question often controls which fields are editable, regardless of role
Object - often the values of the object itself determine what is allowed when, beyond just's it's status
Task - you might break down editing things into more than just read and edit
Section - I often want to control the settings for an entire section of the object or screen, and all the controls inherit those settings, but can override them on an individual basis if needed
Implementation?
First, make sure you have a clear vision of how the page lifecycle is handled. Mine usually goes something like this.
Get the object they are editing, usually from session state, sometimes if they are doing a "new" operation you may need to create a stub data structure for them to work on
If this is the first time the page is loading up, populate choices into dropdowns, this is usually a generic process, done only once
If this is a postback, update the object being edited by reading in values off the controls
Process events such as button clicks
Run through all your business edits, these should alter the data structure they are editing
Update the visibility and editability of the controls based on all the data you have on hand
Populate the controls with the data from the object being edited, including validation messages, or error messages


q:
What are some helpful things that ASP.NET MVC developers could suggest that would help us ASP.NET WebForms developers to write better code/web apps?

I'm a WebForms guy but with all the new hype around MVC I'd value some comments on helpful tips, tricks and strategies that might be able to be used in a webforms app.

[A]
I'm also coming from webforms, but have been learning asp.net MVC since around preview 3.
I'm not exactly sure how to bring anything from MVC into webforms, they are two entirely different frameworks.  I'm probably too new with it to understand how any of it could be applied to webforms, but right now it seems they have very little in common.
Some of the strengths of MVC are it's rigid structure on how you need to do things and where you put code.  It also does away with the form runat=server and I believe does not promote the usage of any of the asp.net server controls (you need to write all the HTML yourself).  That is pretty much the definition of webforms right there.  MVC pretty much replaces webforms with it's own framework.
If you ever did Classic ASP or PHP, I would call ASP.net MVC a more structured framework for what people might do with those older scripting languages.  It's kind of like the FuseBox framework, but even more structured and evolved.


q: The company I work for is thinking of developing a LAMP SaaS Web application that would be plan based. We want to monitor usage because it involves external references, and would draw bandwidth through the placement of an iframe or JavaScript snippet on a third-party site. My first thought was relying only on a page impression algorithm, but since this is really a bandwidth issue, I wonder if monitoring that is a better approach. What is the best way to do this monitoring in a fashion that would allow me to message the third-party site that the cap has been exceeded?

[A]
I think a web service gateway would be a good option. Most of them (IBM, Layer 7, Vordel) offer throttling and contract management features. They'll allow you to set thresholds on access to whatever is behind them.
If you're using authorization and authentication for users and service, you can easily configure them to send a notification if the usage gets too high (from abuse, exceeding the SLA for requests, or whatever else you configure.
Best of all, they'll work with whatever is consuming your application / data, be it users, batch processes, or services.


q:
I am designing a WCF service which a client will call to get a list of GUID's from a server.

How should I define my endpoint contract?

Should I just return an Array?

If so, will the array just be serialized by WCF?

[A]
The Guids, if you're going for SOA oriented services, will need to be set as strings. The client will be responsible for turning them back into whatever. As for the listing of the Guids, they'd be returned as an array. If you have a contract with a regular Generics List Object of Guids like this
```
```
[DataMember] List<Guid> SomeGuidsGoInHere {get;set;}
```
```
then you'll get an array of Guids back.  Which could cause compatability issues.  What you'll want to do is setup a List of strings like this.
```
```
[DataMember] List<String> SomeGuidsAsStringsGoInHere {get;set;}
```
```


q: Does anyone know the official method for submitting feedback on C# 4.0 so that Anders and his team will get the feedback and be able to respond to the submission?

[A]
Probably the forums
here
, or (for bugs)
connect
(they've added options for .NET 4.0 CTP and VS2010 CTP)


q:
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;

"loop again? y/n"

[A]
```
```
while True:
    func()
    answer = raw_input( "Loop again? " )
    if answer != 'y':
        break
```
```


q:
I have a list of numbers, say {2,4,5,6,7}
I have a table, foos, with foos.ID, including say, {1,2,3,4,8,9}

Id like to take my list of numbers, and find those without a counterpart in the ID field of my table.

One way to achieve this would be to create a table bars, loaded with {2,4,5,6,7} in the ID field.
Then, I would do

SELECT bars.* FROM bars LEFT JOIN foos ON bars.ID = foos.ID WHERE foos.ID IS NULL

However, I'd like to accomplish this sans temp table.

Anyone have any input on how it might happen?

[A]
I can't find a solution to your precise problem that doesn't use a temporary table, but an alternate way of doing your query using a sub-select instead of a join is:
```
```
SELECT bars.* FROM bars WHERE bars.ID NOT IN (SELECT ID FROM foos)
```
```
Like the other posters I originally wrote:
```
```
SELECT * FROM foos WHERE foos.ID NOT IN (2, 4, 5, 6, 7)
```
```
but then I realised that this is producing the opposite to what you want.


q:
How do you create a 1 bit per pixel mask from an image using GDI in C#?  The image I am trying to create the mask from is held in a System.Drawing.Graphics object.

I have seen examples that use Get/SetPixel in a loop, which are too slow. The method that interests me is one that uses only BitBlits, like this. I just can't get it to work in C#, any help is much appreciated.

[A]
Try this:
```
```
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
```
```
...
```
```
public static Bitmap BitmapTo1Bpp(Bitmap img) {
      int w = img.Width;
      int h = img.Height;
      Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
      BitmapData data = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadWrite, PixelFormat.Format1bppIndexed);
      for (int y = 0; y < h; y++) {
        byte[] scan = new byte[(w + 7) / 8];
        for (int x = 0; x < w; x++) {
          Color c = img.GetPixel(x, y);
          if (c.GetBrightness() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
        }
        Marshal.Copy(scan, 0, (IntPtr)((int)data.Scan0 + data.Stride * y), scan.Length);
      }
      bmp.UnlockBits(data);
      return bmp;
    }
```
```
GetPixel() is slow, you can speed it up with an unsafe byte*.


q:
Actually my question is all in the title.

Anyway:

I have a class and I use explicit constructor:

.h

class MyClass
{
  public:
    explicit MyClass(const string& s): query(s) {}
  private:
   string query;
}

Is it obligatory or not to put explicit keyword in implementation(.cpp) file?

[A]
No, it is not. The
```
explicit
```
keyword is only permitted in the header. My gcc says:
```
```
test.cpp:6: error: only declarations of constructors can be 'explicit'
```
```
for the following code:
```
```
class foo {
public:
    explicit foo(int);
};

explicit foo::foo(int) {}
```
```


q:
I am designing a error logging feature so our servers (each donig different things) can have a central data store for logging errors.

Would it be a good idea to have the various applications writing to the error log file using a WCF service, or is that a bad idea?

they can do it just by ADO.NET to the database, which I think is the simpler route.

[A]
I'd say just log to your local data store.  The advantages are :
Speed - it's pretty rapid to just
dump your chosen error report to an
existing data connection.
Tracability - What happens if you
have an error in your service?  You
lose all ability to chase down
errors on all servers.
Simplicity - If you change the
endpoint for your errors service,
you have to update every other
application that uses the error
service.
Reporting - Do you really want to
trawl through error reports from
tens / hundreds of applications in
one place when you could easily find
them in the data store local to the
app?
Of course, any of these points could be viewed from the other side, these are just my opinions.


q:
With multiple developers working on the same Tomcat application, I'd like to tell the application to install to a different path, based on the current user and revision control client/view.

So, if Bob is building, the app should be installed in Bob's test environment, maybe /bob1 or something like that.  Bob might have several revision control clients/views/workspaces he works with so he could have /bob1, /bob2, /bob3, etc.

The install location is specified in the build.properties file.  Is there a way to avoid checking that file out and changing it for each specific user and revision control view?

Can "ant install" take arguments or be configured to consider environment variables for the install target?

[A]
You can override ant properties from the command line.
```
```
ant -Dinstall.location=/bob1 install
```
```
See
Running Ant
for more information.


q:
In an attempt to hide the Safari UI components for an web-app bookmarked as a Homescreen Icon. I am using this meta tag

<meta name="apple-mobile-web-app-capable" content="yes" />

as specified on iPhone Dev Center but the address bar and toolbar are still there when launched from the home screen icon.  What do I need to do different? Does anyone have an example?

[A]
Is it being launched from the home screen? The documentation on the linked page does not mention but I found this @
Configuring Web Applications
:
For example, you can specify an icon for your web application used to represent it when added to the Home screen, as described in “Specifying a Webpage Icon for Web Clip.”
You can also minimize the Safari on iPhone user interface
, as described in “Changing the Status Bar Appearance” and “Hiding Safari User Interface Components,”
when your web application is launched from the Home screen
. These are all optional settings that when added to your web content are ignored by other platforms


q: In the C / Unix environment I work in, I see some developers using __progname instead of argv[0] for usage messages. Is there some advantage to this? What's the difference between __progname and argv[0].  Is it portable?

[A]
```
__progname
```
isn't standard and therefore not portable, prefer
```
argv[0]
```
. I suppose
```
__progname
```
could lookup a string resource to get the name which isn't dependent on the filename you ran it as. But
```
argv[0]
```
will give you the name they
actually
ran it as which I would find more useful.


q: I wonder if there is an example which html files and java files are resides in different folders.

[A]
I don't recommend using a separate page directory unless you are quite comfortable with how resource streams work, which I am not.
The vast majority of wicket projects I have seen keep class and html files in the source directory.  I tried separating them myself but then found that getting my hands on other resources, like images and such, was a hassle; so, I wound up putting those resources in the package directory - in the end I had resources in several different places and it was more of a mess than putting everything in package directory would have been.
That said, here's the code I used to put my html templates in a separate folder.  It should be added to Init() in your application class.
```
```
IResourceSettings resourceSettings = getResourceSettings();
resourceSettings.addResourceFolder("pages"); //the full path to your folder, relative to the context root
resourceSettings.setResourceStreamLocator((IResourceStreamLocator) new PathStripperLocator());
```
```
https://cwiki.apache.org/confluence/display/WICKET/Control+where+HTML+files+are+loaded+from
has a tutorial on this.


q:
I have an application where, in the course of using the application, a user might click from

virginia.usa.com

to

newyork.usa.com

Since I'd rather not create a new session each time a user crosses from one subdomain to another, what's a good way to share session info across multiple subdomains?

[A]
If you're using PHP, one hack would be to make a little include script (or two) to do the following:
1 Serialize your $_SESSION array
  2 Pass that string as a hidden input, making all your links to those buttons in separate forms using POST.
  3 Also include a boolean hidden input to let your script know whether it needs to use the current session or unserialize $_POST['session']
  4 Deploy this across your site, calling things where appropriate
I wouldn't do this if there's actually a sanctioned way to transfer a session.  I hope you've at least considered using cookies.


q:
I have a web directory where I store some config files. I'd like to use wget to pull those files down and maintain their current structure. For instance, the remote directory looks like:

http://mysite.com/configs/.vim/

.vim holds multiple files and directories. I want to replicate that on the client using wget. Can't seem to find the right combo of wget flags to get this done. Any ideas?

[A]
```
```
wget -r http://mysite.com/configs/.vim/
```
```
works for me.
Perhaps you have a .wgetrc which is interfering with it?


q:
I have a SSIS package that eventually I would like to pass parameters too, these parameters will come from a .NET application (VB or C#) so I was curious if anyone knows of how to do this, or better yet a website with helpful hints on how to do it.

So basically I want to execute a SSIS package from .NET passing the SSIS package parameters that it can use within it.

For instance, the SSIS package will use flat file importing into a SQL db however the Path and name of the file could be the parameter that is passed from the .Net application.

[A]
Here is how to set variables in the package from code -
```
```
using Microsoft.SqlServer.Dts.Runtime;

private void Execute_Package()
    {
        string pkgLocation = @"c:\test.dtsx";

        Package pkg;
        Application app;
        DTSExecResult pkgResults;
        Variables vars;

        app = new Application();
        pkg = app.LoadPackage(pkgLocation, null);

        vars = pkg.Variables;
        vars["A_Variable"].Value = "Some value";

        pkgResults = pkg.Execute(null, vars, null, null, null);

        if (pkgResults == DTSExecResult.Success)
            Console.WriteLine("Package ran successfully");
        else
            Console.WriteLine("Package failed");
    }
```
```


q:
Similar to this question but for MySQL....

How can I programmatically determine foreign key references in MySQL (assuming InnoDB)?  I can almost get them with:

SHOW TABLE STATUS WHERE Name = 'MyTableName';

...but alas, the comment column which seems to contain some of this info gets truncated so I can't rely on it.  There must be some other way...

I'd be happy with a C API call, a SQL statement, anything--I just need something that consistently works.

Note:  I've also considered parsing the results of a "SHOW CREATE TABLE MyTableName" statement, but I'm really hoping there's something simpler.

[A]
Try
```
INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
```


q:
I have a bunch of controls on my window.  One of them is a refresh button that performs a cumbersome task on a background thread.

When the user clicks the refresh button, I put the cursor in a wait (hourglass) status and disable the whole window -- Me.IsEnabled = False.

I'd like to support cancellation of the refresh action by letting the user click a cancel button, but I can't facilitate this while the whole window is disabled.

Is there a way to do this besides disabling each control (except for the cancel button) one by one and then re-enabling them one by one when the user clicks cancel?

[A]
You can data bind each controls IsEnabled property to your custom boolean dependency property that signals when your application is in lock down.  Just don't bind the cancel button.
As  Donnelle mentioned You can setup multi binding with a converter. Here are a couple examples you can refer to.
WPF MultiBinding with Converter
Implementing Parameterized MultiBinding Sample


q:
I am developing a HTML form designer that needs to generate static HTML and show this to the user. I keep writing ugly code like this:

public string GetCheckboxHtml()
{
    return ("&lt;input type="checkbox" name="somename" /&gt;");
}

Isn't there a set of strongly typed classes that describe html elements and allow me to write code like this instead:

var checkbox = new HtmlCheckbox(attributes);
return checkbox.Html();

I just can't think of the correct namespace to look for this or the correct search term to use in Google.

[A]
One option is to use
XElement
functional construction
. See
this blog post
for an example calendar generator.
In your case, your Html could be generated with:
```
```
var input = new XElement("input",
    new XAttribute("type", "checkbox"),
    new XAttribute("name", "somename"));

return input.ToString();
```
```


q:
The topic generically says it all. Basically in a situation like this:

boost::scoped_array<int> p(new int[10]);

Is there any appreciable difference in performance between doing: &p[0] and p.get()?

I ask because I prefer the first one, it has a more natural pointer like syntax. In fact, it makes it so you could replace p with a native pointer or array and not have to change anything else.

I am guessing since get is a one liner "return ptr;" that the compiler will inline that, and I hope that it is smart enough to to inline operator[] in such a way that it is able to not dereference and then immediately reference.

Anyone know?

[A]
The only way to know is to actually measure it!
But if you have the source of the boost:scoped_array you could llok at the code and see what it does. I am sure it is pretty similar.
```
```
T * scoped_array::get() const // never throws
{
    return ptr;
}

T & scoped_array::operator[](std::ptrdiff_t i) const // never throws
{
    BOOST_ASSERT(ptr != 0);
    BOOST_ASSERT(i >= 0);
    return ptr[i];
}
```
```
Write two versions of the code (one using get() the other using operator[]). Compile to assembley with optimizations turned on. See if your compiler actually manages to optimize away the ptr+0.


q: Currently it's a big PITA to create timesheet report for say a week or month in FogBugz... maybe someone knows about a plugin to that for you?

[A] If you have FogBugz hosted on your own server, you can query the database manually and get timesheet results that way. If its hosted by FogBugz, then you can download the database, do the same query, or, use the API to get all the time entries. Some programs already exists for that, one of them is TimeSprite, but its not free.


q:
I have two forms in microsoft access, one called Bill and the other one called Payment. They both have Total amount as a field in both of the forms. I am trying to reference the Bill total amount to the Payment total amount.

I have tried in the Payment total amount control source : =Forms!Bill![Total Amount]

but this doesnt seem to work. In Design view it says '#Name?' in the text box.

How would you do this?

[A]
Is either of the forms a subform? If so, you need to reference the subform control or the parent property:
```
```
Me.Parent.[Total order]
Me.[Subform Control name Here].form.[Total order]
```
```
Note that the Subform Control name  is not always the same as the form contained.
EDIT: Either omit Me or use Form!FormName in a control.
EDIT2: Please note that the usual way of referencing forms, subform and controls is with either bang (!) or dot (.). parentheses and quotes are rarely used. This can be seen in both the Microsoft Access MVPs site (
http://www.mvps.org/access/forms/frm0031.htm
) and Microsoft's own site (
http://support.microsoft.com/kb/209099
), as mentioned by Knox.
If not, have you tried the Expression builder? It will help ensure that you have the correct names.
As an aside, it is best to avoid spaces in the names of fields and controls, it will save you a good deal of work. It is also best to rename controls so they do not have the same name as the fields they contain, txtOrderTotal, for example.


q: I want to send a message to a thread and handle it in the thread. How can I do this in Delphi? I guess PostMessage is the way to go, but the examples I've seen so far are describing the other way, i.e. from the thread to main thread.

[A]
I won't even try and explain or write any code. Just look at this tutorial. It's a little old, but very good imho.
Multithreading - The Delphi Way


q:
I am trying to write a function that will pull the name of a property and the type using syntax like below:

private class SomeClass
{
    Public string Col1;
}

PropertyMapper<Somewhere> propertyMapper = new PropertyMapper<Somewhere>();
propertyMapper.MapProperty(x => x.Col1)

Is there any way to pass the property through to the function without any major changes to this syntax?

I would like to get the property name and the property type.

So in the example below i would want to retrieve

Name = "Col1" and Type = "System.String"

Can anyone help?

[A]
Here's enough of an example of using
Expressions
to get the name of a property or field to get you started:
```
```
public static MemberInfo GetMemberInfo<T, U>(Expression<Func<T, U>> expression)
{
    var member = expression.Body as MemberExpression;
    if (member != null)
        return member.Member;

    throw new ArgumentException("Expression is not a member access", "expression");
}
```
```
Calling code would look like this:
```
```
public class Program
{
    public string Name
    {
        get { return "My Program"; }
    }

    static void Main()
    {
        MemberInfo member = ReflectionUtility.GetMemberInfo((Program p) => p.Name);
        Console.WriteLine(member.Name);
    }
}
```
```
A word of caution, though: the simple statment of
```
(Program p) => p.Name
```
actually involves quite a bit of work (and can take measurable amounts of time). Consider caching the result rather than calling the method frequently.


q: Is there an obvious way to do this that I'm missing?  I'm just trying to make thumbnails.

[A]
Define a maximum size.
Then, compute a resize ratio by taking
```
min(maxwidth/width, maxheight/height)
```
.
The proper size is
```
oldsize*ratio
```
.
There is of course also a library method to do this: the method
```
Image.thumbnail
```
.
Below is an (edited) example from the
PIL documentation
.
```
```
import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.Resampling.LANCZOS)
            im.save(outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile
```
```


q:
For some reason I'm not getting this. (Example model below) If I write:

var property = typeof(sedan).GetProperty("TurningRadius");
Attribute.GetCustomAttributes(property,typeof(MyAttribute), false)

the call will return MyAttribute(2) despite indicating I don't want to search the inheritance chain. Does anyone know what code I can write so that calling

MagicAttributeSearcher(typeof(Sedan).GetProperty("TurningRadius"))

returns nothing while calling

MagicAttributeSearcher(typeof(Vehicle).GetProperty("TurningRadius"))

returns MyAttribute(1)?

Example Model:

public class Sedan : Car
{
    // ...
}

public class Car : Vehicle
{
    [MyAttribute(2)]
    public override int TurningRadius { get; set; }
}

public abstract class Vehicle
{
    [MyAttribute(1)]
    public virtual int TurningRadius { get; set; }
}

[A]
I think this is what you're after - note that I had to make TurningRadius abstract in Vehicle and overridden in Car. Is that okay?
```
```
using System;
using System.Reflection;

public class MyAttribute : Attribute
{
    public MyAttribute(int x) {}
}

public class Sedan : Car
{
    // ...
}

public class Car : Vehicle
{
    public override int TurningRadius { get; set; }
}

public abstract class Vehicle
{
    [MyAttribute(1)]
    public virtual int TurningRadius { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        MagicAttributeSearcher(typeof(Sedan));
        MagicAttributeSearcher(typeof(Vehicle));
    }

    static void MagicAttributeSearcher(Type type)
    {
        PropertyInfo prop = type.GetProperty("TurningRadius");
        var attr = Attribute.GetCustomAttribute(prop, typeof(MyAttribute), false);
        Console.WriteLine("{0}: {1}", type, attr);
    }
}
```
```
Output:
```
```
Sedan:
Vehicle: MyAttribute
```
```


q:
I'm having a little bit of trouble making a sticky form that will remember what is entered in it on form submission if the value has double quotes. The problem is that the HTML is supposed to read something like:

<input type="text" name="something" value="Whatever value you entered" />

However, if the phrase: "How do I do this?" is typed in with quotes, the resulting HTML is similar to:

<input type="text" this?="" do="" i="" how="" value="" name="something"/>

How would I have to filter the double quotes? I've tried it with magic quotes on and off, I've used stripslashes and addslashes, but so far I haven't come across the right solution. What's the best way to get around this problem for PHP?

[A]
You want
htmlentities()
.
```
<input type="text" value="<?php echo htmlentities($myValue); ?>">
```


q:
Right now we've got web pages that show UI elements, and web pages that just process form submissions, and then redirect back to the UI pages.  They do this using PHP's header() function:

header("Location: /other_page.php");

This causes a 302 Found response to be sent; according to the HTTP 1.1 spec, 302 is for cases where "The requested resource resides temporarily under a different URI." [HTTP 1.1 spec]

Functionally, this is fine, but it doens't seem like this is the proper status code for what we're doing.  It looks like 303 ("See Other") is the appropriate status here, so I'm wondering if there's any reason not to use it.  We'd have to be more explicit in our use of header(), since we'd have to specify that status line rather than just a Location: field.  Thoughts?

[A]
I've never used it myself... as it says in your link:
Note: Many pre-HTTP/1.1 user agents do
  not understand the 303
        status. When interoperability with such clients is a concern, the
        302 status code may be used instead, since most user agents react
        to a 302 response as described here for 303.
This seems a good enough reason to me to stick with 302.
FYI
header()
takes extra parameters in which you can set the status code:
```
header('Location: /foo.php', true, 303);
```


q:
How does one prevent an inclusion cycle in C? ie. You shouldn't have a.h #include "b.h", which #include's "c.h" which #include's "a.h". I'm looking for a way of preventing this from happening using some sort of C directive.

I had originally thought this would've prevented this from happening:

Contents of a.h:

#ifndef __A_H
#define __A_H

#include "b.h"

#endif // __A_H

Contents of b.h:

#ifndef __B_H
#define __B_H

#include "c.h"

#endif // __B_H

Contents of c.h:

#ifndef __C_H
#define __C_H

#include "a.h"

#endif // __C_H

But it doesn't seem to work.

[A]
It does work allright: the files
are
repeatedly included, but the sections protected by #ifdndef/#define/#endif
are not
repeated, and that breaks the cycle.
Use your compiler to produce the preprocessed output and look at it for yourself.  With GNU CC, you need to use "-E" option on the .c[pp] file, like this:
```
```
gcc -E $(CFLAGS) -o foo.i foo.cpp
```
```


q:
I would like to know if there is software that, given a regex and of course some other constraints like length, produces random text that always matches the given regex.
Thanks

[A] Instead of starting from a regexp, you should be looking into writing a small context free grammer, this will allow you to easily generate such random text. Unfortunately, I know of no tool which will do it directly for you, so you would need to do a bit of code yourself to actually generate the text. If you have not worked with grammers before, I suggest you read a bit about bnf format and "compiler compilers" before proceeding...


q:
I very rarely meet any other programmers!

My thought when I first saw the token was "implies that" since that's what it would read it as in a mathematical proof but that clearly isn't its sense.

So how do I say or read "=>" as in:-

IEnumerable<Person> Adults = people.Where(p => p.Age > 16)

Or is there even an agreed way of saying it?

[A]
I usually say 'such that' when reading that operator.
In your example, p => p.Age > 16 reads as "P, such that p.Age is greater than 16."
In fact, I asked this very question on the official linq pre-release forums, and Anders Hejlsberg responded by saying
I usually read the => operator as "becomes" or "for which". For example,
Func f = x => x * 2;
Func test = c => c.City == "London";
reads as "x becomes x * 2" and "c for which c.City equals London"
As far as 'goes to' - that's never made sense to me. 'p' isn't going anywhere.
In the case of reading code to someone, say, over the phone, then as long as they're a fellow C# programmer, I'd just use the word 'lambda' - that is, "p lambda p dot age greater-than sixteen."
In comments Steve Jessop mentioned 'maps to' in the case of transformations - so taking Anders' example:
```
```
x => x * 2;
```
```
would read
x maps to x times 2.
That does seem much closer to the actual intention of the code than 'becomes' for this case.


q:
I'm increasingly becoming aware that there must be major differences in the ways that regular expressions will be interpreted by browsers.

As an example, a co-worker had written this regular expression, to validate that a file being uploaded would have a PDF extension:

^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$

This works in Internet Explorer, and in Google Chrome, but does NOT work in Firefox.  The test always fails, even for an actual PDF.  So I decided that the extra stuff was irrelevant and simplified it to:

^.+\.pdf$

and now it works fine in Firefox, as well as continuing to work in IE and Chrome.

Is this a quirk specific to asp:FileUpload and RegularExpressionValidator controls in ASP.NET, or is it simply due to different browsers supporting regex in different ways?  Either way, what are some of the latter that you've encountered?

[A]
If you're using javascript, not enclosing the regex with slashes causes error in Firefox.
Try doing
```
var regex = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$/;
```