Question:
How do I properly convert two columns from SQL (2008) using Linq into a Dictionary (for caching)?

I currently loop through the IQueryable b/c I can't get the ToDictionary method to work. Any ideas?
This works:

var query = from p in db.Table
            select p;

Dictionary<string, string> dic = new Dictionary<string, string>();

foreach (var p in query)
{
    dic.Add(sub.Key, sub.Value);
}

What I'd really like to do is something like this, which doesn't seem to work:

var dic = (from p in db.Table
             select new {p.Key, p.Value })
            .ToDictionary<string, string>(p => p.Key);

But I get this error:

Cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to
'System.Collections.Generic.IEnumerable'

Answer:
```
```
var dictionary = db
    .Table
    .Select(p => new { p.Key, p.Value })
    .AsEnumerable()
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;
```
```


Question:
I read some properties from an xml file, amongst which is a string that refers to an llblgen object for example 'article'. For now I have set up a rather long

Select Case myString
  Case "article"
    return New ArticleEntity()

Etc. which is getting rather ugly as it gets longer and longer ;). Is there a better way to do this ?

(the above is vb.net, but c# examples are fine as well)

Answer:
You could store the type names in the file and use:
```
```
return Activator.CreateInstance(Type.GetType("Some.Type.String"));
```
```
(that would work as long as
```
Some.Type.String
```
has a default parameterless constructor.)


Question:
I am writing a stored procedure where I have an input parameter called my_size that is an INTEGER. I want to be able to use it in a LIMIT clause in a SELECT statement. Apparently this is not supported, is there a way to work around this?

# I want something like:
SELECT * FROM some_table LIMIT my_size;

# Instead of hardcoding a permanent limit:
SELECT * FROM some_table LIMIT 100;

Answer:
A search turned up
this article
.  I've pasted the relevant text below.
Here's a forum post showing an example of prepared statements letting
  you assign a variable value to the limit clause:
http://forums.mysql.com/read.php?98,126379,133966#msg-133966
However, I think this bug should get some attention because I can't
  imagine that prepared statements within a procedure will allow for any
  procedure-compile-time optimizations.  I have a feeling that prepared
  statements are compiled and executed at the runtime of the procedure,
  which probaby has a negative impact on efficiency.  If the limit
  clause could accept normal procedure variables (say, a procedure
  argument), then the database could still perform compile-time
  optimizations on the rest of the query, within the procedure.  This
  would likely yield faster execution of the procedure.  I'm no expert
  though.


Question:
How do you go about verifying the type of an uploaded file reliably without using the extension? I'm guessing that you have to examine the header / read some of the bytes, but I really have no idea how to go about it. Im using c# and asp.net.

Thanks for any advice.

ok, so from the above links I now know that I am looking for 'ff d8 ff e0' to positively identify a .jpg file for example.

In my code I can read the first twenty bytes no problem:

                FileStream fs = File.Open(filePath, FileMode.Open);
                Byte[] b = new byte[20];
                fs.Read(b, 0, 20);

so (and please excuse my total inexperience here) but how do I check whether the byte array contains 'ff d8 ff e0'?

Answer:
The first few bytes of a file will often tell you the file type.  See, for example,
http://www.garykessler.net/library/file_sigs.html
http://www.astro.keele.ac.uk/oldusers/rno/Computing/File_magic.html
Use System.IO to read the byes as binary after the upload.
I'm curious, though, why you can't rely on on the ContentType header?


Question:
When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not?

When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"?

Answer:
In short, it means there are no restrictions on the object's use. It's the same as
any other object.
A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have.
Depending on the language, this can
  imply:
being expressible as an anonymous literal value
being storable in variables
being storable in data structures
having an intrinsic identity (independent of any given name)
being comparable for equality with other entities
being passable as a parameter to a procedure/function
being returnable as the result of a procedure/function
being constructible at runtime
being printable
being readable
being transmissible among distributed processes
being storable outside running processes
Source
.
In C++ functions themselves are not first class objects, however:
You can override the '()' operator making it possible to have an object function, which is first class.
Function pointers are first class.
boost bind, lambda and function do offer first class functions
In C++, classes are not first class objects but instances of those classes are.  In Python both the classes
and
the objects are first class objects.  (See
this answer
for more details about classes as objects).
Here is an example of Javascript first class functions:
```
```
// f: function that takes a number and returns a number
// deltaX: small positive number
// returns a function that is an approximate derivative of f
function makeDerivative( f, deltaX )
{
    var deriv = function(x)
    {
       return ( f(x + deltaX) - f(x) )/ deltaX;
    }
    return deriv;
}
var cos = makeDerivative( Math.sin, 0.000001);
// cos(0)     ~> 1
// cos(pi/2)  ~> 0
```
```
Source
.
Entities that are not first class objects are referred to as second-class objects.  Functions in C++ are second class because they can't be dynamically created.
Regarding the edit:
EDIT. When one says "everything is
  an object" (like in Python), does he
  indeed mean that "everything is
  first-class"?
The term object can be used loosely and doesn't imply being first class.  And it would probably make more sense to call the whole concept 'first class entities'.  But in Python they do aim to make everything first class.  I believe the intent of the person who made your statement meant first class.


Question:
I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called get()). jQuery's  is() only works with expressions, so this code would be ideal but will not work:

var someDiv = $('#div');

$('a').click(function() {
    if ($(this).parents().is(someDiv)) {
        alert('boo');
    }
}

Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.

Answer:
You can use the index() method to check if an element exists in a list, so would the following work?
```
```
var someDiv = $('#div');

$('a').click(function() {
    if ($(this).parents().index(someDiv) >= 0) {
        alert('boo');
    }
}
```
```
From
#index reference
.


Question:
I feel like I should know this, but I haven't been able to figure it out...

I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text.  I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.

Answer:
I think the
```
traceback
```
module might have what you're looking for. In particular, the
```
extract_stack
```
function looks like it will do the job.


Question:
This one has me scratching my head.

I'm running Subversion 1.3.1 (r19032) on Ubuntu. All was well until recently when I tried to run svnadmin verify prior to a dump. This is the error message:

svnadmin: Invalid diff stream: insn 0
  cannot be decoded

I have looked around for an explanation and fix but can't seem to find one. Subversion experts, I need your help.

Answer:
You should ensure that you are using the correct version of
```
svnadmin
```
for your repository version. It's possible to get errors like this by using the wrong version.
Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.
I also found through google that
some versions of SVNKit
can cause this problem.


Question:
Has anyone else had any problems using google's Domain Tracking API, I am specifically talking about the _link() method.

The documentation is here

The example provided shows that the _link() method should be used in the onclick event like this:

<a href="http://www.newsite.com" onclick="pageTracker._link('http://www.newsite.com');return false;">Go to our sister site</a>

However, this essentially just makes the link...do nothing (most probably because of the 'return false').

My understanding is that the pageTracker._link() method is 'supposed' to add additional parameters to the url and do it's own document.location style redirect.

Any ideas / catches / previous posts??

Answer:
You should ensure that you are using the correct version of
```
svnadmin
```
for your repository version. It's possible to get errors like this by using the wrong version.
Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.
I also found through google that
some versions of SVNKit
can cause this problem.


Question: After reading many of the replies to this thread, I see that many of those who dislike it cite the potential for abuse of the new keyword. My question is, what sort of abuse? How could this be abused so badly as to make people vehemently dislike it? Is it just about purism? Or is there a real pitfall that I'm just not seeing?

Answer:
Some see it as a tool that will be abused.  Like "Option Strict Off" and "On Error Resume Next" in VB which "pure" languages like C# and Java have never had.
Many said the same about the "var" keyword, yet I don't see it being abused, once it became understood that it wasn't the same as VB's "Variant"
It could be abused in places that lazy developers don't want type checking on classes and just try catch dynamic calls instead of writing "if blah is Blah ...".
I personally feel it could be used properly in situations like
this
recent question that I answered.
I think the ones really understanding it's power are those heavily into the dynamic .NET languages.


Question:
I'm using tortoise svn in Windows.

How can I branch in SVN and have it branch my svn:external folders as well?

Answer:
When you create a branch within Subversion you are simply creating a cheap copy of the trunk, branch, or tag that you are branching from. This cheap copy will contain all of the same files and properties as the trunk, branch, or tag that you branched from until you begin to modify the properties or files of the new branch.
However, you may be able to modify one of the 'commit' hooks to modify settings automatically once you commit your branch.
http://svnbook.red-bean.com/en/1.1/ch05s02.html
Otherwise if you want your externals to be modified on the branch you will need to do so manually.


Question:
I've been working on a SharePoint project and I have gone the route of loading User Controls through a custom web part.

I have several web controls where I need to dynamically generate hyperlinks (in a loop from a database) that will call certain functions of the User Control when clicked.

When I'm building my own ASP.NET sites, I just add parameters to the hyperlink and check on the page load to see if I need to run any other code when a hyperlink is click.

I'm starting to realize that this probably won't be very reliable inside the SharePoint environment because I don't control the way web page URLs are formed.

I would prefer to have it post back when the hyperlink is clicked and pass some values, but I'm not sure the best way to approach this.

Could someone point me in the right direction?

Thanks.

Answer:
When you create a branch within Subversion you are simply creating a cheap copy of the trunk, branch, or tag that you are branching from. This cheap copy will contain all of the same files and properties as the trunk, branch, or tag that you branched from until you begin to modify the properties or files of the new branch.
However, you may be able to modify one of the 'commit' hooks to modify settings automatically once you commit your branch.
http://svnbook.red-bean.com/en/1.1/ch05s02.html
Otherwise if you want your externals to be modified on the branch you will need to do so manually.


Question:
Does anybody know how to call the import data built-in dialog excel from a macro (vba)?

I've tried Application.Dialogs.Item(...).Show but I can´t find the right dialog.
Please help.

Thanks in advance.

Answer:
If you choose the Object Browser and search for say, xlDialogImportTextFile, you will get a list of possible dialogs.
EDIT:
Perhaps something on these lines would suit:
```
```
'Allow user to select text file
sf = Application _
    .GetOpenFilename("Text Files (*.txt), *.txt")
If sf <> False Then
    'Open text file
    Workbooks.OpenText sf
End If
```
```


Question:
I'd like to show an image in an iPhone app, but the image I'm using is too big.
I'd like to scale it to fit the iPhone screen, I can't find any class to handle it.

Answer:
```
```
UIImageView* view = [[UIImageView alloc] initWithImage: [UIImage imageNamed: @"your_image.png"]];
view.frame = CGRectMake(0, 0, width, height);
```
```
To get the frame of the iPhone screen you can use
```
```
CGRect frame = [[UIScreen mainScreen] bounds];
```
```


Question:
I have the following intentionally trivial function:

void ReplaceSome(ref string text)
{
    StringBuilder sb = new StringBuilder(text);
    sb[5] = 'a';
    text = sb.ToString();
}

It appears to be inefficient to convert this to a StringBuilder to index into and replace some of the characters only to copy it back to the ref'd param. Is it possible to index directly into the text param as an L-Value?

Or how else can I improve this?

Answer:
I don't know if this is more efficient, but it works. Either way you'll have to recreate the string after each change since they're immutable.
```
```
string test = "hello world";
    Console.WriteLine(test);

    test = test.Remove(5, 1);
    test = test.Insert(5, "z");

    Console.WriteLine(test);
```
```
Or if you want it more concise:
```
```
string test = "hello world".Remove(5, 1).Insert(5, "z");
```
```


Question:
I'm fairly new to Castle Windsor and am looking into the in's and out's of the logging facility. It seems fairly impressive but the only thing i can't work out is where Windsor sets the Logger property on my classes. As in the following code will set Logger to the nullLogger if the class hasn't been setup yet but when Resolve is finished running the Logger property is set.

private ILogger logger;

public ILogger Logger
{
    get
    {
        if (logger == null)
            logger = NullLogger.Instance;
        return logger;
    }
    set { logger = value; }
}

So what I am wondering is how and where windsor sets my Logger property.

Cheers
Anthony

Answer:
The logger is setup by the logging facility, which is in the
```
<facilities>
```
section of the configuration.  For example to use log4net your app or web.config would look something like this:
```
```
<?xml version="1.0"?>
<configuration>
    <configSections>
        <section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
    </configSections>
<Configuration>

<castle>

    <facilities>
        <facility id="loggingfacility"
             type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"
             loggingApi="log4net"
             configFile="logging.config" />
    </facilities>

</castle>
</configuration>
```
```


Question:
I have an application where I have a main.m that returns NSApplicationMain(argc,  (const char **) argv);.

I want to run code on -applicationDidFinishLaunching:, but I just dont see how to do it.

Can anyone help or have an example?

Thanks!
-Jason

Answer:
The applicationDidFinishLaunching: method of the NSApplication delegate will be called when the app has finished loading. Many of the project templates setup a delegate. If you are using one just add the appropriate method to it.
If your project does not have an app delegate set up you will need to do that yourself. First, make a new class to act as your delegate (you can use an exiting one if there is something logically appropriate). Now make sure that class is instantiated in your MainMenu.nib. Finally, hook the delegate property of the "File's Owner" object to the instantiate delegate in IB.


Question:
What are some of the lesser know, but important and useful features of Windows batch files?

Guidelines:

One feature per answer

Give both a short description of the feature and an example, not just a link to documentation

Limit answers to native funtionality, i.e., does not require additional software, like the Windows Resource Kit

Clarification: We refer here to scripts that are processed by cmd.exe, which is the default on WinNT variants.

(See also: Windows batch files: .bat vs .cmd?)

Answer:
I have always found it difficult to read comments that are marked by a keyword on each line:
```
```
REM blah blah blah
```
```
Easier to read:
```
```
:: blah blah blah
```
```


Question:
I have done this:

$ z() { echo 'hello world'; }

How do I get rid of it?

Answer:
```
```
unset -f z
```
```
Will unset the function named z.  A couple people have answered with:
```
```
unset z
```
```
but if you have a function and a variable named z only the variable will be unset, not the function.


Question:
Here's the situation - I've got a shell that loads an external .swf. Now, that .swf is 800x600, but it's an animation piece, and there are elements that extends off the stage. When I load the .swf into the shell and call its width attribute, it returns 1200 - because it's including the elements that break out of the stage.

This isn't what I want - ideally, there would be two properties, one to return the 'calculated width' and one to return the 'default width'. Do these properties exist, and if not, what's the best workaround?

Answer:
The width and height of the loaded SWF as defined by the FLA it was created with can be found in the
```
Loader
```
object in which you've loaded the SWF into.
```
```
swfLoader.contentLoaderInfo.width
swfLoader.contentLoaderInfo.height
```
```
This will always show you the dimensions as defined in the FLA properties. It makes no difference if any images, MovieClips, or what have you extend off the stage.
The
```
stage.stageWidth
```
and
```
stage.stageHeight
```
properties will always return the width of the stage, the stage is always the top most SWF. In other words, it will always represent the dimensions of the shell's stage. There is only ever one stage in a Flash application.


Question:
Using Python I want to be able to draw text at different angles using PIL.

For example, imagine you were drawing the number around the face of a clock.  The number 3 would appear as expected whereas 12 would we drawn rotated counter-clockwise 90 degrees.

Therefore, I need to be able to draw many different strings at many different angles.

Answer:
I'm not saying this is going to be easy, or that this solution will necessarily be perfect for you, but look at the documentation here:
http://effbot.org/imagingbook/pil-index.htm
and especially pay attention to the Image, ImageDraw, and ImageFont modules.
Here's an example to help you out:
```
```
import Image
im = Image.new("RGB", (100, 100))
import ImageDraw
draw = ImageDraw.Draw(im)
draw.text((50, 50), "hey")
im.rotate(45).show()
```
```
To do what you really want you may need to make a bunch of separate correctly rotated text images and then compose them all together with some more fancy manipulation.  And after all that it still may not look great.  I'm not sure how antialiasing and such is handled for instance, but it might not be good.  Good luck, and if anyone has an easier way, I'd be interested to know as well.


Question:
How do you connect to a remote server via IP address in the manner that TOAD, SqlDeveloper, are able to connect to databases with just the ip address, username, SID and password?

Whenever I try to specify and IP address, it seems to be taking it locally.

In other words, how should the string for cx_Oracle.connect() be formatted to a non local database?

There was a previous post which listed as an answer connecting to Oracle via cx_Oracle module with the following code:

#!/usr/bin/python

import cx_Oracle
connstr='scott/tiger'
conn = cx_Oracle.connect(connstr)
curs = conn.cursor()

curs.execute('select * from emp')
print curs.description
for row in curs:
    print row
conn.close()

Answer:
You can specify the server in the connection string, e.g.:
```
```
import cx_Oracle
connstr = 'scott/tiger@server:1521/orcl'
conn = cx_Oracle.connect(connstr)
```
```
"server" is the server, or the IP address if you want.
"1521" is the port that the database is listening on.
"orcl" is the name of the instance (or database service).


Question:
Having a vector containing pointers to objects then using the clear function doesn't call the destructors for the objects in the vector. I made a function to do this manually but I don't know how to make this a generic function for any kind of objects that might be in the vector.

void buttonVectorCleanup(vector<Button *> dVector){
    Button* tmpClass;
    for(int i = 0; i < (int)dVector.size(); i++){
        tmpClass = dVector[i];

        delete tmpClass;
    }
}

This is the function I have that works fine for a specific type of object in the vector but I'd like a single function that could take any kind of vector with object pointers.

Answer:
The best thing to do is use smart pointers, such as from
Boost
.  Then the objects will be deleted automatically.
Or you can make a template function
```
```
template <class T>
void vectorCleanup(vector<T *>& dVector){
    T* tmpClass;
    for(vector<T*>::size_type i = 0; i < dVector.size(); i++){
        tmpClass = dVector[i];

        delete tmpClass;
    }
```
```
}


Question:
I have form area in my view. If I click button A, I want to submit to /Books/1 and if I click button B, I want to submit to /Books/2

How do I achieve this with MVC?

Answer:
MVC Views can have multiple forms on a 'page', so just create separate  sections and give each one their own form action.
```
```
<form id="form1" name="form1" action="/Books/1" method="get">
<!--...form fields-->
</form>

<form id="form2" name="form2" action="/Books/2" method="get">
<!--...form fields-->
</form>
```
```


Question:
What's the best algorithm for comparing two arrays to see if they have the same members?

Assume there are no duplicates, the members can be in any order, and that neither is sorted.

compare(
    [a, b, c, d],
    [b, a, d, c]
) ==> true

compare(
    [a, b, e],
    [a, b, c]
) ==> false

compare(
    [a, b, c],
    [a, b]
) ==> false

Answer:
The best I can think of is O(n^2), I guess.
```
```
function compare($foo, $bar) {
    if (count($foo) != count($bar)) return false;

    foreach ($foo as $f) {
        foreach ($bar as $b) {
            if ($f == $b) {
                // $f exists in $bar, skip to the next $foo
                continue 2;
            }
        }
        return false;
    }
    return true;
}
```
```


Question:
Let's say I have two arrays:

int ArrayA[] = {5, 17, 150, 230, 285};

int ArrayB[] = {7, 11, 57, 110, 230, 250};

Both arrays are sorted and can be any size. I am looking for an efficient algorithm to find if the arrays contain any duplicated elements between them. I just want a true/false answer, I don't care which element is shared or how many.

The naive solution is to loop through each item in ArrayA, and do a binary search for it in ArrayB. I believe this complexity is O(m * log n).

Because both arrays are sorted, it seems like there should be a more efficient algorithm.

I would also like a generic solution that doesn't assume that the arrays hold numbers (i.e. the solution should also work for strings). However, the comparison operators are well defined and both arrays are sorted from least to greatest.

Answer:
Pretend that you are doing a mergesort, but don't send the results anywhere.  If you get to the end of either source, there is no intersection.  Each time you compare the next element of each, if they are equal, there is an intersection.
For example:
```
```
counterA = 0;
counterB = 0;
for(;;) {
    if(counterA == ArrayA.length || counterB == ArrayB.length)
        return false;
    else if(ArrayA[counterA] == ArrayB[counterB])
        return true;
    else if(ArrayA[counterA] < ArrayB[counterB])
        counterA++;
    else if(ArrayA[counterA] > ArrayB[counterB])
        counterB++;
    else
        halt_and_catch_fire();
}
```
```


Question: Most developers understand the concept of wicked problems. What's a good analogy to use when explaining this concept to project managers?

Answer:
Every changing requirements lead to an impossible to manage design. Just send him here:
Winchester Mystery House
. The house is filled with staircases to nowhere and doors that open to brick walls. It was built exactly as spec'd, but isn't really what you'd call usable.
Of course up here in New England a "wicked problem" is one that requires a wicked good engineer to come up with a wicked clever solution :)


Question:
Will their be a new release of the compact framework with VS2010 and .net 4.0 and if so what new features will it include?
WPF?
linq to SQL?
etc

Answer:
I'm not sure about 4.0 for compact devices (although it seems likely),
and I don't know about WPF either, but I can tell you they are going to provide Silverlight for mobile devices giving you access to a subset of WPF.
Haven't found any other references yet...


Question:
In DB2, you can name a column ORDER and write SQL like

SELECT ORDER FROM tblWHATEVER ORDER BY ORDER

without even needing to put any special characters around the column name.  This is causing me pain that I won't get into, but my question is:  why do databases allow the use of SQL keywords for object names?  Surely it would make more sense to just not allow this?

Answer:
Many SQL parsers (expecially DB2/z, which I use) are smarter than some of the regular parsers which sometimes separate lexical and semantic analysis totally (this separation is mostly a good thing).
The SQL parsers can figure out based on context whether a keyword is valid or should be treated as an identifier.
Hence you can get columns called ORDER or GROUP or DATE (that's a particularly common one).
It does annoy me with some of the syntax coloring editors when they brand an identifier with the keyword color. Their parsers aren't as 'smart' as the ones in DB2.


Question:
In an information security lab I'm working on, I've been tasked with executing multiple commands with a single call to "system()" (written in C, running on Fedora).  What is the syntax that will allow me to execute more than command through system()?  (The idea being you could execute arbitrary commands through a program running on a remote computer, if the program interacts with the OS through the system() call.)

I.e.:

char command[] = "????? \r\n";
system(command);

Answer:
That depends on the shell being invoked to execute the commands, but in general most shells use
```
;
```
to separate commands so something like this should work:
```
```
command1; command2; command3
```
```
[EDIT]
As @dicroce mentioned, you can use
```
&&
```
instead of
```
;
```
which will stop execution at the first command that returns a non-zero value.  This may or may not be desired (and some commands may return non-zero on success) but if you are trying to handle commands that can fail you should probably not string multiple commands together in a system() call as you don't have any way of determining where the failure occured.  In this case your best bet would either be to execute one command at a time or create a shell script that performs the appropriate error handling and call that instead.


Question:
I didn't attend PDC 2008, but I heard some news that C# 4.0 is announced to support Generic covariance and contra-variance. That is, List<string> can be assigned to List<object>. How could that be?

In Jon Skeet's book C# in Depth, it is explained why C# generics doesn't support covariance and contra-variance. It is mainly for writing secure code. Now, C# 4.0 changed to support them. Would it bring chaos?

Anybody know the details about C# 4.0 can give some explanation?

Answer:
Variance will only be supported in a
safe
way - in fact, using the abilities that the CLR already has. So the examples I give in the book of trying to use a
```
List<Banana>
```
as a
```
List<Fruit>
```
(or whatever it was) still won't work - but a few other scenarios will.
Firstly, it will only be supported for interfaces and delegates.
Secondly, it requires the author of the interface/delegate to decorate the type parameters as
```
in
```
(for contravariance) or
```
out
```
(for covariance). The most obvious example is
```
IEnumerable<T>
```
which only ever lets you take values "out" of it - it doesn't let you add new ones. That will become
```
IEnumerable<out T>
```
. That doesn't hurt type safety at all, but lets you return an
```
IEnumerable<string>
```
from a method declared to return
```
IEnumerable<object>
```
for instance.
Contravariance is harder to give concrete examples for using interfaces, but it's easy with a delegate. Consider
```
Action<T>
```
- that just represents a method which takes a
```
T
```
parameter. It would be nice to be able to convert seamlessly use an
```
Action<object>
```
as an
```
Action<string>
```
- any method which takes an
```
object
```
parameter is going to be fine when it's presented with a
```
string
```
instead. Of course, C# 2 already has covariance and contravariance of delegates to some extent, but via an actual conversion from one delegate type to another (creating a new instance) - see P141-144 for examples. C# 4 will make this more generic, and (I believe) will avoid creating a new instance for the conversion. (It'll be a reference conversion instead.)
Hope this clears it up a bit - please let me know if it doesn't make sense!


Question:
Are there any 'standard' plugins for detecting the CPU architecture in scons?

BTW, this question was asked already here in a more general form... just wondering if anyone has already taken the time to incorporate this information into scons.

Answer:
Something like this?
```
```
env = Environment()
conf = Configure(env)
if conf.CheckDeclaration("__i386__"):
    conf.Define("MY_ARCH", "blahblablah")
env = conf.Finish()
```
```


Question:
My database consists of 3 tables (one for storing all items, one for the tags, and one for the relation between the two):

Table: Post
Columns: PostID, Name, Desc

Table: Tag
Columns: TagID, Name

Table: PostTag
Columns: PostID, TagID

What is the best way to save a space separated string (e.g. "smart funny wonderful") into the 3 database tables shown above?

Ultimately I would also need to retrieve the tags and display it as a string again.    Thanks!

Answer:
If you have a Tag Table, wouldn't you have a row for each Tag?
```
```
tag.id = 1; tag.name = 'smart'
tag.id = 2; tag.name = 'funny'
tag.id = 3; tag.name = 'wonderful'
```
```
In Groovy/Grails, you'd retrieve them as a list, possibly concatenating them into a space separated list for display.
Unless I'm really misunderstanding the question, Groovy/Grails/GORM will handle this with little or no code with the default scaffolding, no real coding required.


Question: Many examples of macros seem to be about hiding lambdas, e.g. with-open-file in CL. I'm looking for some more exotic uses of macros, particularly in PLT Scheme. I'd like to get a feel for when to consider using a macro vs. using functions.

Answer:
I'll start answering the last question. When to use a macro instead of a function. The macros do things the functions can't, and the functions do thing the macros can't, so it'll be hard to mix them, but let's go deeper.
You use functions when you want the arguments evaluated and macros when you want the arguments un-evaluated. That's not very useful, is it? You use macros when you want to write something in a different way, when you see a pattern and you want to abstract. For example: I define three functions called foo-create, foo-process and foo-destroy for different values of foo and with similar bodies where the only change is foo. There's a pattern but a too-high level for a function, so you create a macro.
In my humble experience, macros in Scheme are to used as much as in other Lisps, like Common Lisp or
Clojure
. I suppose it's proof that maybe hygienic macros are not such a good idea, and here I would disagree with Paul Graham about why. It's not because sometimes you want to be dirty (un-hygienic) but because hygienic macros end up being complex or convoluted.


Question:
This is similar to this question, but I want to include the path relative to the current directory in unix. If I do the following:

ls -LR | grep .txt

It doesn't include the full paths. For example, I have the following directory structure:

test1/file.txt
test2/file1.txt
test2/file2.txt

The code above will return:

file.txt
file1.txt
file2.txt

How can I get it to include the paths relative to the current directory using standard Unix commands?

Answer:
Try
```
find
```
. You can look it up exactly in the man page, but it's sorta like this:
```
find [start directory] -name [what to find]
```
so for your example
```
find . -name "*.txt"
```
should give you what you want.


Question:
When running PHP in CLI mode, most of the time (not always), the script will hang at the end of execution for about 5 seconds and then output this:

Error in my_thread_global_end(): 1 threads didn't exit

It doesn't seem to actually have any effect on the script itself.

Some web searches turned up blogs which suggest replacing the php_mysql.dll with a different version, however this has not solved the issue for me, and I suspect the info from those blogs is now out of date.

My setup:

PHP Version 5.2.4

Apache/2.2.4 (Win32)

Windows Vista Home Premium SP1

Answer:
Did you take a look at
this resource
? You may want to double check that you got a specific libmysql.dll (5.2.1) that is unaffected by this, and also to double check that you don't have any stray mysql libraries lying around that PHP could be picking up instead. Or, switch from FastCGI if that's an option for you.
For interests sake, the bug appears to be best detailed
here
. The general idea of the problem (from the mysql bug link) appears to be:
```
```
Whenever a new thread is created libmysql is told about that by Windows. It then
increases a thread counter and initializes some data. When libmysql is being unloaded
it checks whether all threads have finished, if not it tries to tell them "close now"
and gives them 5 seconds for that. In general this works in a nice way.
```
```


Question:
Is it possible for the .NET CLR to support Objective-C? Are there any reasons (either from a legal or implementational) standpoint why this wouldn't be possible?

In the spirit of cross-platform application development, it would be nice to be able to write and run Objective-C applications on Windows machines. At least I think it would.

Answer:
No, there really aren't.  .NET compiles to
IL
(or CIL or MSIL) which is basically machine code for a virtual machine.  You can program in IL like you do in assembly (not that I've seen anyone do it).  If you had the experience, knowledge, and gumption there would be no problem writing an Objective-C to IL compiler.  Hell, there are even
functional programming languages (F#)
for .NET.  Besides the messaging capabilities and the libraries, it's not too different from C#, VB.NET, etc.
What an awesome idea!  Objective-C# or some such.
Here's where you might start:
Wikipedia on Microsoft's IL


Question:
For example, when I'm dividing two ints and want a float returned, I superstitiously write something like this:

int a = 2, b = 3;
float c = (float)a / (float)b;

If I do not cast a and b to floats, it'll do integer division and return an int.

Similarly, if I want to multiply a signed 8-bit number with an unsigned 8-bit number, I will cast them to signed 16-bit numbers before multiplying for fear of overflow:

u8 a = 255;
s8 b = -127;
s16 = (s16)a * (s16)b;

How exactly does the compiler behave in these situations when not casting at all or when only casting one of the variables? Do I really need to explicitly cast all of the variables, or just the one on the left, or the one on the right?

Answer:
Division of integers:  cast any one of the operands, no need to cast them both.  If both operands are integers the division operation is an integer division, otherwise it is a floating-point division.
As for the overflow question, there is no need to explicitly cast, as the compiler implicitly does that for you:
```
```
#include <iostream>
#include <limits>

using namespace std;
int main()
{
    signed int a = numeric_limits<signed int>::max();
    unsigned int b = a + 1; // implicit cast, no overflow here
    cout << a << ' ' <<  b << endl;
    return 0;
}
```
```


Question:
In SQL Server given a Table/View how can you generate a definition of the Table/View in the form:

C1 int,

  C2 varchar(20),

  C3 double

The information required to do it is contained in the meta-tables of SQL Server but is there a standard script / IDE faciltity to output the data contained there in the form described above ?.

For the curious I want this as I have to maintain a number of SP's which contain Table objects (that is a form of temporary table used by SQL Server). The Table objects need to match the definition of Tables or Views already in the database - it would make life a lot easier if these definitions could be generated automatically.

Answer:
If you want to duplpicate a table definition you could use:
```
```
select top 0
  *
into
  newtable
from
  mytable
```
```
Edit: Sorry, just re-read your question, and realised this might not answer it. Could you be clear on what you are after, do you want an exact duplicate of the table definition, or a table that contains information about the tables definition?


Question:
For example, using the answer for this question:

How to select all users who made more than 10 submissions
"How to select all users who made more than 10 submissions."

select userId
from submission
group by userId
having count(submissionGuid) > 10

Let's say now I want to know many rows this sql statement outputted. How scalable is the solution for counting the rows of counting the rows?

Answer:
In SQL Server you could do
```
```
select @@ROWCOUNT
```
```
immediately following the query you posted.


Question:
What I want to do is scroll down the window when I expand elements in my page.

The effect I am trying to achieve is like the Stack Overflow comments. If it expands beyond the page, it scrolls down to fit all the comments in the window.

What is the best way of doing this?

Edit: I am using JQuery.

Answer:
If you have the advantage of using Prototype, you can use
```
$(element).scrollTo()
```
.
Otherwise, the general idea is to calculate the cumulative offset of the element, then set
```
window.scrollTop
```
(and
```
window.scrollLeft
```
) accordingly.


Question:
Like, let's say I had a tree structure, then I would use, naturally a tree control, since that GUI element maps perfectly to the structure.

But what I have is a graph, potentially too wide to fit in one web page.  I can't think of examples of GUIs that really match the structure.  Some ideas I have that don't quite fit are, the web itself, with hyperlinks, the browser back button, and the forward button.   But that just shows you one node at a time.  I would like to display as many nodes as I can, and allow navigation to a new area of the graph.   Something like Google maps might be a good model, in that you have full freedom to scroll in any direction.

Answer:
Facebook used to do this,
way
back in the day, to visualize your friends. They drew nodes as little boxes, with lines connecting them, as expected. They drew the graphs into an SVG image, so you could easily zoom in and out.
Another option might be to draw into a
```
<canvas>
```
tag and scale that somehow. I imagine that's possible, but I don't know much about
```
<canvas>
```
Another option would be to draw it into an inline frame or other box that allows the user to scroll horizontally and vertically.


Question:
I use screen to persist my work session and connect to the same session from multiple machines. How can I setup SSH and screen such that the XDISPLAY variable inside my persistent screen session is always set to the machine I am currently connecting from?

ie. I start the screen session at work and use gvim, which uses the X server running on my work machine. Later, I connect to the same session from home and also want to use gvim. But this time, I want gvim to use the X server on my home machine. I realize I could manually update XDISPLAY every time I connect from a different machine but I'd rather have an automated system.

Bonus points if I can actually move gvim from my work machine to my home machine while it is running. I tried xmove but could never get it to play nice.

Answer:
There is no "trivial" way to change environment variables in foreign processes.
A straightforward solution might be to persist your
```
XDISPLAY
```
into a file on login and use a
```
PROMPT_COMMAND
```
to read this file before printing the next prompt.
For moving X applications around look at something like
```
X11vnc
```
or
```
Xvnc
```
.


Question:
As a second interview I get people to sit down and write code...I try to make the problem really technology independent.

My programming problems that I have don't really exercise peoples OO abilities.  I tend to try and keep the coding problem solvable within 2 hours ish.  So, I've struggled to find a problem small enough and involved enough that it exposes peoples OO design skills.

Any suggestions?

Answer:
These aren't specifically OO Questions, but check out the other questions tagged
interview-questions
Edit: What about implementing some
design patterns
? I don't have the best knowledge in the area but it seems as if you would be getting two questions for the price of one. You can test for both OO and Design pattens in the one question.


Question:
I have recently discovered the incredibly useful Eclipse Memory Analysis Tool, which makes quick work of finding memory leaks in Java applications.  Unfortunately, after switching my JDK to 1.6 (under Mac OS 10.5), the JVM terminates immediately upon startup.  All that appears is a dialog stating "JVM terminated" with "Exit code = -1".

Anyone else encounter this one? Perhaps there is a way to configure it to use a different JDK?  (such as 1.5: which it was shown to be compatible with)

Answer:
The official Java 6 for the Mac only has a 64 bit data model. Unfortunately, Eclipse uses Carbon on the Mac which is only available in 32 bits. In short, it is impossible to run Eclipse with the official Java 6 distribution.
The classical solution to this is to set the default VM to Java 5, and then choose Java 6 as the JRE/JDK within Eclipse.
If you really need to run Eclipse with Java 6, then you could take a look at
SoyLatte
which is a build of OpenJDK which both supports 32 and 64 bit modes.


Question:
What does InitializeComponent() do, and how does it work in WPF?

In general first, but I would especially be interested to know the gory details of order of construction, and what happens when there are Attached Properties.

Answer:
The call to
```
InitializeComponent()
```
(which is usually called in the default constructor of at least
```
Window
```
and
```
UserControl
```
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the
```
Window
```
/
```
UserControl
```
that is loading, and passes it to the
```
System.Windows.Application.LoadComponent()
```
static method.
```
LoadComponent()
```
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail,
```
LoadComponent
```
creates an instance of the
```
XamlParser
```
, and builds a tree of the XAML. Each node is parsed by the
```
XamlParser.ProcessXamlNode()
```
. This gets passed to the
```
BamlRecordWriter
```
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the
```
InitializeComponent
```
is a method on the
```
System.Windows.Markup.IComponentConnector
```
interface, of which
```
Window
```
/
```
UserControl
```
implement in the partial generated class.
Hope this helps!


Question: I have a legacy app where it reads message from a client program from file descriptor 3. This is an external app so I cannot change this. The client is written in C#. How can we open a connection to a specific file descriptor in C#? Can we use something like AnonymousPipeClientStream()? But how do we specify the file descriptor to connect to?

Answer:
Unfortunately, you won't be able to do that without P/Invoking to the native Windows API first.
First, you will need to open your file descriptor with a native P/Invoke call. This is done by the OpenFileById WINAPI function.
Here's how to use it
on MSDN,
here's an other link
explaining it in detail on the MSDN forums, and
here's some help (pinvoke.net)
on how to construct your P/Invoke call.
Once you got the file handle, you need to wrap it in a SafeFileHandle, this time in safe, managed C#:
```
```
// nativeHandle is the WINAPI handle you have acquired with the P/Invoke call
SafeFileHandle safeHandle = new SafeFileHandle(nativeHandle, true);
```
```
Now you can open the file stream directly:
```
```
Stream stream = new FileStream(safeHandle, FileAccess.ReadWrite);
```
```
And from this point you can use it as any other file or stream in C#. Don't forget to dispose your objects once you're done.


Question:
I have a site behind basic authentication (IIS6).

Part of this site calls a web service that is also part of the site and thus behind basic authentication as well.

However, when this happens the calling code receives a 401 Authentication Error.

I've tried a couple of things, with the general recommendation being code like this:

Service.ServiceName s = new Service.ServiceName();
s.PreAuthenticate = true;
s.Credentials = System.Net.CredentialCache.DefaultCredentials;
s.Method("Test");

However, this does not seem to resolve my problem.

Any advice?

Edit

This seems to be a not uncommon issue but so far I have found no solutions.
Here is one thread on the topic.

Answer:
The Line:
```
```
s.Credentials = System.Net.CredentialCache.DefaultCredentials();
```
```
Maybe you should try :
```
```
s.Credentials = HttpContext.Current.User.Identity;
```
```


Question: For general code, do I really need to dispose an object?  Can I just ignore it for the most part or is it a good idea to always dispose an object when your 100% sure you don't need it anymore?

Answer:
If the object implements IDisposable, you should dispose of it as soon as you are done with it. The easiest way is to surround it with a
using
block:
```
```
using (SqlCommand cmd = new SqlCommand(conn)) {
    cmd.ExecuteNonQuery();
}
```
```


Question:
I have a vba macro which runs a loop for about 200 iterations, using up the ram page file as it runs.

I need some kind of quick fix to clear the page file after every iteration. I know the best fix would be to clean up the code, but time is a constraint here.

Answer:
At the end of each loop iteration set any objects that will be re-created to
```
Nothing
```
.
This
article
explains it in detail.


Question:
If I were to include .Net Framework setup file along with my apps (installation process is done by our own technician), to be install on a clean Windows (XP SP2/SP3 or Vista SP1) without prior installation of any framework, which of the .Net Framework setup do I need to install in sequence, to get to 3.5 SP1?
Currently I have the setup file for:

.Net 2.0

.Net 2.0 SP1

.Net 3.0

.Net 3.5

.Net 3.5 SP1

All redistributable version.

EDIT : I need the full installation, client profile won't work as our client's machine might not have internet access. Basically I need a install-and-forget-it procedure, so when we decided to use anything new within 3.5 SP1 later, we can rest assure that we can just simple apply update our apps without having to install another pre-requisite

Answer:
NET 3.5 SP1 introduces a new setup package option for developers building .NET client applications called the "
.NET Framework Client Profile
".This provides a new setup installer that enables a smaller, faster, and simpler installation experience for .NET client applications on machines that do not already have the .NET Framework installed.
The .NET Framework Client Profile setup contains just those assemblies and files in the .NET Framework that are typically used for client application scenarios.  For example: it includes Windows Forms, WPF, and WCF.  It does not include ASP.NET and those libraries and components used primarily for server scenarios.  We expect this setup package to be about
26MB
in size, and it can be downloaded and installed much quicker than the full .NET Framework setup package.


Question:
What is the best way to extract the MAC address from ifconfig's output?

Sample output:

bash-3.00# ifconfig eth0
eth0      Link encap:Ethernet  HWaddr 1F:2E:19:10:3B:52
          inet addr:127.0.0.66  Bcast:127.255.255.255  Mask:255.0.0.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          ....
          ....

Should I use cut, AWK or anything else, and what are the merits and demerits of one method over the other.

Answer:
Not sure whether there really are any advantages, but you can simply use awk:
```
```
ifconfig eth0 | awk '/HWaddr/ {print $5}'
```
```


Question:
i would like to release a snapshot project 'foo-1.0-SNAPSHOT' using the maven release plugin. The project depends on a 3rd party module 'bar-1.0-SNAPSHOT' which is not released yet.
I use the option 'allowTimestampedSnapshots' in my project's pom.xml to allow timestamped snapshots but i assume that the 3rd party module (bar) is not timestamped unless i build it myself as maven still complains about unresolved SNAPSHOT dependencies.

Is there a way to release the project foo regardless of dependent SNAPSHOT projects and if not how could i add a timestamp to the 3rd party project?

Answer:
The short answer is see the
following answer
.... the long answer is you can work around it.
The only way I have coped in the past is to effectively fork the 3rd party library and cut a release myself. This of course is easier said than done and is just plain difficult if the library is large and complex and impossible if the 3rd party library is closed source. An easier route maybe to approach the 3rd party and ask them to cut a release.
Another option may be to copy their pom (ensure that it has no snapshots) change the version information and manually install the pom and artifact in your repository.


Question: How do you go about finding unused icons, images, strings in .resx files that may have become 'orphaned' and are no longer required?

Answer:
This is no information an algorithm can reliably compute. The inspected program could fetch a list of all resources and do something with them, like letting the user choose from several icons.
Your best bet is probably to search for all references to your resource-access API of choice and inspect those manually. Using
```
grep
```
/
```
sed
```
you might be able to reduce the sites you have to inspect manually by handling all "easy" ones where a simple string is used.


Question:
void f(cli::array<PointF> ^points){
    PointF& a = points[0];
    // and so on...
}

Compile error at line 2.

.\ndPanel.cpp(52) : error C2440: 'initializing' : cannot convert from 'System::Drawing::PointF' to 'System::Drawing::PointF &'
        An object from the gc heap (element of a managed array) cannot be converted to a native reference

What is the managed way to declare a reference variable?

Answer:
You need to use the
```
gcroot
```
template from
```
vcclr.h
```
file:
These are samples from MSDN:
```
```
// mcpp_gcroot.cpp
// compile with: /clr
#include <vcclr.h>
using namespace System;

class CppClass {
public:
   gcroot<String^> str;   // can use str as if it were String^
   CppClass() {}
};

int main() {
   CppClass c;
   c.str = gcnew String("hello");
   Console::WriteLine( c.str );   // no cast required
}

// mcpp_gcroot_2.cpp
// compile with: /clr
// compile with: /clr
#include <vcclr.h>
using namespace System;

struct CppClass {
   gcroot<String ^> * str;
   CppClass() : str(new gcroot<String ^>) {}

   ~CppClass() { delete str; }

};

int main() {
   CppClass c;
   *c.str = gcnew String("hello");
   Console::WriteLine( *c.str );
}

// mcpp_gcroot_3.cpp
// compile with: /clr
#include < vcclr.h >
using namespace System;

public value struct V {
   String^ str;
};

class Native {
public:
   gcroot< V^ > v_handle;
};

int main() {
   Native native;
   V v;
   native.v_handle = v;
   native.v_handle->str = "Hello";
   Console::WriteLine("String in V: {0}", native.v_handle->str);
}
```
```
You will find out more
here


Question:
Like many SO people, I'm in front of a computer almost all day. I like having a dark theme for Visual Studio (easier on the eyes), but since the rest of Windows and apps (explorer, dialogs, Outlook), have the full white background, it's even harder to switch between nice dark VS and sunshine bright Windows.

I tried a UXTheme.dll patch but couldn't find any dark themes that worked across Visual Studio and Windows apps in general. Any suggestions?

Edit: To be clear, I'd like no or almost no white. No scrollbars, menus, etc.

Answer:
May be not exactly what you are looking for, but
this is a dark color scheme
for visual Studio (2005 or 2008) you may use in complement of UXTheme.
Off course, they are other dar color schemes for Visual studio, like
this one
(Jeff
has one also
).
But I am not sure there is
one
tool that applies to all windows, including Visual Studio.


Question:
To implement "method-missing"-semantics and such in C# 4.0, you have to implement IDynamicObject:

public interface IDynamicObject
{
  MetaObject GetMetaObject(Expression parameter);
}

As far as I can figure out IDynamicObject is actually part of the DLR, so it is not new. But I have not been able to find much documentation on it.

There are some very simple example implementations out there (f.x. here and here), but could anyone point me to more complete implementations or some real documentation?

Especially, how exactly are you supposed to handle the "parameter"-parameter?

Answer:
Here is what I have figured out so far:
The Dynamic Language Runtime is currently maintained as part of the
IronPython project
. So that is the best place to go for information.
The easiest way to implement a class supporting IDynamicObject seems to be to derive from
Microsoft.Scripting.Actions.Dynamic
and override the relevant methods, for instance the Call-method to implement function call semantics. It looks like Microsoft.Scripting.Actions.Dynamic hasn't been included in the CTP, but the one from IronPython 2.0 looks like it will work.
I am still unclear on the exact meaning of the "parameter"-parameter, but it seems to provide context for the binding of the dynamic-object.


Question: what is the syntax for the sendkey for rightarrow  in .net?

Answer:
What you are looking for is called spatial search. I'm not sure if there are extensions to  Lucene.Net to do this but you could take a look at
NHibernate Spatial
. Other than that, these queries are often done within the database. At least PostGreSQL, MySQL and SQL Server 2008 have spatial query capabilities.


Question:
I'm rather confused about this.

And what's their relationship(e.g., how one can be used in the context of the other)? Much thanks!!

Answer:
The concept of symbols is a little bit hard to understand. (Even I'm not sure I got it :) )
You can look at symbols as special variables which behave like constants. There is only one instance in memory, no matter how often you used it.
The benefits are conserving memory and one can see if a value is used in a constant-like manner. (Improves code readability)
You can do
similar
things in C/C++ with
```
typdef
```
, in Java with
```
static final
```
or in Delphi/Pascal/VB with
```
const
```
, but be careful, in those and many other languages "symbol" means something different.


Question: I have an oc4j installation bereft of any release notes or version documentation. In the absence of such documents, how do I know for sure, which version of oc4j I am using?

Answer:
Check Server header in HTTP headers. For example with wget or curl;
```
```
wget -S <url-to-server>
curl -I <url-to-server>
```
```
or with browser, which can show HTTP headers.
There should be a header something like
```
```
Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-Server
```
```


Question: I'm using the MVP pattern in a windows form app. I need to change a radio button on the view. I can do this by exposing a Boolean property on the view, but should I be using events to manipulate the view instead?

Answer:
Using "plain language" analysis, I would say that "whether or not the radio button is displayed is a
property
of the view" and therefore use an actual property to communicate this to the View.
The other (technical) possibility would be to have a event on the Presenter, i.e.
```
RadioButtonVisibilityChanged
```
, which is listened to by the View and passes the new visibility through the
```
EventArgs
```
. This runs contrary to the View being independent and ignorant of the Presenter and therefore undermines the MVP pattern. I advise against such nonsense.


Question:
Actually I try to find a subclass of InputStream which is also Serializable. I think that doesn't exist. Since both Interfaces have many sublclasses it is hard to find one that is a subclass of both.

Until now I haven't found anything to help my search in Eclipse. Anyone ideas?

Edit: I understand now that serializing a Stream isn't really what one should do. But the essence of the Question is: how can I find a common subclass of two Interfaces.

Answer:
Serializing an InputStream is not a very viable solution. To illustrate this, imagine if you have an InputStream from a socket and you serialize that. Before you deserialize it, the socket is closed. Now when you actually do deserialize it, the resource has vanished and you have a nasty exception in your hands.
What you should rather do, if you need to serialize a resource, is to serialize the location of it or how to obtain it. In the socket example: host name and port, for files: the file path, etc.


Question:
I got this error when trying to update an image.
It was a cross-thread update, but I used .Invoke(), so that shouldn't be the problem, should it.

Answer:
(Answering my own question, for others, and for future reference)
I
think
(not yet entirely sure) that this is because InvokeRequired will always return false if the control has not yet been loaded/shown. I have done a workaround which seems to work for the moment, which is to simple reference the handle of the associated control in its creator, like so:
```
```
var x = this.Handle;
```
```
(See
http://ikriv.com:8765/en/prog/info/dotnet/MysteriousHang.html
- down?
cached version
)
(Related question:
Boiler plate code replacement - is there anything bad about this code?
)


Question: I know about "class having a single reason to change". Now, what is that exactly? Are there some smells/signs that could tell that class does not have a single responsibility? Or could the real answer hide in YAGNI and only refactor to a single responsibility the first time your class changes?

Answer:
the methods in your class should be cohesive...they should work together and make use of the same data structures internally. If you find you have too many methods that don't seem entirely well related, or seem to operate on different things, then quite likely you don't have a good single responsibility.
Often it's hard to initially find responsibilities, and sometimes you need to use the class in several different contexts and then refactor the class into two classes as you start to see the distinctions. Sometimes you find that it's because you are mixing an abstract and concrete concept together. They tend to be harder to see, and, again, use in different contexts will help clarify.


Question:
For example VK_LEFT, VK_DELETE, VK_ESCAPE, VK_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from?

If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.

Answer:
These are declared using
```
#define
```
in the file
```
winuser.h
```
in the Platform SDK. In my installation of Visual Studio 2008, the full path is
```
```
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h
```
```


Question:
We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Function]). The exception was thrown inside the dynamic method generated by LINQ.

Is there any easy way to debug such dynamic methods? Or do I have to sacrifice myself to learning WinDBG? :-)

Answer:
If you're using LINQ to Objects, I wouldn't expect to see dynamic methods being created. I'd expect them with LINQ to SQL etc. Could you give an example where you're seeing this?
I don't really have any good debugging tips when it comes to LINQ, but I'm pretty sure MS know about this as a pain point. Could I suggest you try the
VS2010 CTP
and see if that's better? More for the sake of improving VS than for solving your immediate problem, admittedly.


Question:
I have an Ant script that needs to checkout a directory from Subversion. This works using svnant/svnkit. However, Subversion access is authenticated, and I do not want to store my user password in a file.

Can I make svnkit pop up a password dialog?
Or even better, make it use the same credential caching that subversive/svnkit inside of Eclipse uses (the username can be read from the build.properties)?

I cannot switch to public key based authentication, as I do not control the subversion server.

Right now, it just says "svn: authentication cancelled".

Answer:
To answer my own question, I can use the Ant [input] task to ask the user for a password and store it in a property that can be passed to the [svn] task.
```
```
<target name="checkout">
    <input
        message="Please enter subversion password for ${username}:"
        addproperty="password"
      />

    <svn svnkit="${svnkit}" username="${username}" password="${password}">
        <checkout url="${urlRepos}/project" destPath="web/" />
    </svn>
</target>
```
```
Unfortunately, this does not mask the password with * * * * *, and I still want to read from the credential cache...


Question: Why is volatile needed in C? What is it used for? What will it do?

Answer:
```
volatile
```
tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.


Question:
I'm working on a eclipse plug-in and I've tried to create another test project seperate from the plug-in. The reason I do this is to not let the plug-in depend on jUnit when it is exported. However, I can't access the Eclipse Plug-in API when I do the testing. Whenever I try to add Plug-in dependencies the import list to that is empty.

Does anyone know how to import Eclipse plug-in API to an existing project? The workspace layout looks like this at the moment:

+- com.foo.myplugin
|     |
|     +- JRE System Library
|     |
|     +- Plug-in Dependencies
|     |
|     +- src
|     |
|     +- icons, META-INF, plugin.xml, etc...
|
+- com.foo.myplugin.test
      |
      +- JRE System Library
      |
      +- JUnit 4
      |
      +- src

Answer:
You could try to add the plugin nature to your new myplugin.test project.
In your .project file:
```
```
<natures>

        <nature>org.eclipse.pde.PluginNature</nature>
        [...]
</natures>
```
```
Then in the .classpath, add:
```
```
<classpath>
        [...]
        <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
        [...]
</classpath>
```
```
Delete your myplugin.test from the workspace, re-import that project and see if that does the trick...


Question:
this is my old code

    protected override bool OnPreAction(string actionName, System.Reflection.MethodInfo methodInfo)
    {
        if ("|Register|RegisterPage|Login|LoginPage|Logout|Service".ToLower().Contains(actionName.ToLower()))
        {
            return base.OnPreAction(actionName, methodInfo);
        }

        Customer = CustomerHelper.GetCustomer();

        if (Customer.IsSeccessedLogin())
        {
            return base.OnPreAction(actionName, methodInfo);
        }

        Response.Redirect("Login.html");
        return false;
    }

Answer:
```
```
string actionName = (string)filterContext.RouteData.Values["action"];
```
```


Question:
In the recent project, we had an issue with the performance of few queries that relied heavily on ordering the results by datetime field (MSSQL 2008 database).

When we executed the queries with ORDER BY RecordDate DESC (or ASC) the queries executed 10x slower than without that. Ordering by any other field didn't produce such slow results.

We tried all the indexing options, used the tuning wizard, nothing really made any difference.

One of the suggested solutions was converting the datetime field to the integer field representing the number of seconds or miliseconds in that datetime field. It would be calculated by a simple algorithm, something like "get me the number of seconds from RecordDate to 1980-01-01". This value would be stored at insertion, and the all the sorting would be done on the integer field, and not on the datetime field.

We never tried it, but I'm curious what do you guys think?

Answer:
Are the inserts coming from .Net Code...
You could store the
DateTime.Ticks
value in a bigint column on the DB and index on that.
In terms of updating your existing Database, it should be relatively trivial to write a CLR Function for converting existing DateTimes to TickCount along the lines of
```
```
ALTER TABLE dbo.MyTable ADD TickCount BigInt Null

Update dbo.MyTable Set TickCount = CLRFunction(DateTimeColumn)
```
```
It definitely feasible and would dramatically improve your sorting abilility


Question:
can we output a .jpg image or .gif image in C?
I mean can we print a picture as output with the help of a C program?
Aslo can we write a script in C language for HTML pages as can be written in JavaScript?
Can the browsers operate on it?
If not possible is there any plugin for any of the browsers?

Any example code or links please?

Answer:
That's a lot of questions!
You can generate JPEG and PNG files from C using
libjpeg
and
libpng
, respectively. (Yes, I'm dodging your GIF question on purpose. You don't need to do that; PNG is well-supported by mainstream browsers now and
should be preferred
. :-P)
Browsers generally only support JavaScript for client-side scripting. Using anything else will only destroy the portability of your webpages. Yes, like you say you can use plugins, but some people are averse to installing plugins, and others are behind corporate policies that don't allow such things.


Question:
While working on a project, I came across a JS-script created by a former employee that basically creates a report in the form of

Name : Value
Name2 : Value2

etc.

The peoblem is that the values can sometimes be floats (with different precision), integers, or even in the form 2.20011E+17. What I want to output are pure integers. I don't know a lot of JavaScript, though.  How would I go about writing a method that takes these sometimes-floats and makes them integers?

Answer:
You can use
Math.round()
for rounding numbers to the nearest integer.
```
```
Math.round(532.24) => 532
```
```
Also, you can use
parseInt()
and
parseFloat()
to cast a variable to a certain type, in this case integer and floating point.


Question:
What is the default capacity of a StringBuilder?

And when should (or shouldn't) the default be used?

Answer:
[edit: at the time, the question asked about
```
StringList
```
]
Do you mean
```
StringCollection
```
? This uses an empty
```
ArrayList
```
initially, so the answer is 0. And you have no option to change it. When you first add an item, the capacity jumps to 4, then uses a doubling strategy when it fills.
If you mean
```
List<string>
```
, then it is similar (an empty
```
T[]
```
, not an
```
ArrayList
```
), but you can initialize a known size if you need (i.e. you know how much data you expect). Again, the first time you
```
Add
```
to a
```
List<T>
```
the size jumps to 4, then doubles every time it fills up.


Question:
I am writing a shell script that takes file paths as input.

For this reason, I need to generate recursive file listings with full paths. For example, the file bar has the path:

/home/ken/foo/bar

but, as far as I can see, both ls and find only give relative path listings:

./foo/bar   (from the folder ken)

It seems like an obvious requirement, but I can't see anything in the find or ls man pages.

How can I generate a list of files in the shell including their absolute paths?

Answer:
If you give
```
find
```
an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:
```
```
find "$(pwd)" -name .htaccess
```
```
or if your shell expands
```
$PWD
```
to the current directory:
```
```
find "$PWD" -name .htaccess
```
```
```
find
```
simply prepends the path it was given to a relative path to the file from that path.
Greg Hewgill
also suggested using
```
pwd -P
```
if you want to resolve symlinks in your current directory.


Question:
I need to create a midnight DateTime

I've just done this:

DateTime endTime = DateTime.Now;
endTime.Subtract(endTime.TimeOfDay);

Haven't test it yet, I'm assuming it works but is there a better/cleaner way?

Answer:
Just use
```
foo.Date
```
, or
```
DateTime.Today
```
for today's date


Question: Does anybody know about an Eclipse plug-in to analyze code coverage for TestNG unit tests?

Answer:
EclEmma
can be run on TestNG test suites.  You can also run a group of test or a given TestNG class with it.  It requires the
TestNg plug-in
On EclEmma plugin, choose "coverage configuration..." and select the TestNG tab.


Question: Does anyone know of a tool to take a T-SQL query and convert it into a LINQtoSQL query?

Answer:
I'm sorry that I don't know of any tools to do this.  If your problem is that you just don't know Linq well enough, you may want to consider this
tool
.  It will help you learn Linq and it's free (but not open source).


Question: Is there any way to add iCal event to the iPhone Calendar from the custom App?

Answer:
Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.
https://developer.apple.com/bugreporter/


Question:
I want to be able to run a function in my firefox sidebar js file when the selected tab in the main content window is reloaded or changed. So the sidebar can change depending on the site the user is looking at.

Anyone able to point me in the right direction?

Answer:
My solution pilfered from somewhere but can't remember where:
```
```
//add the load eventListener to the window object
window.addEventListener("load", function() { functioname.init(); }, true);

var functionname =  {
    //add the listener for the document load event
init: function() {
    var appcontent = document.getElementById("appcontent");   // browser
    if(appcontent)
        appcontent.addEventListener("DOMContentLoaded", functionname.onPageLoad, false);
    },
    //function called on document load
    onPageLoad: function(aEvent) {
        if(aEvent.originalTarget.nodeName == "#document"){
        }
     }
}
```
```


Question:
I have seen a function whose prototype is:

int myfunc(void** ppt)

This function is called in a C file as
    a = myfunc(mystruct **var1);

where mystruct is typedef for one of structure we have.

This works without any compilation errors in MSVC6.0, But when I compile it with some other C compiler, it gives an error at the place where this function is called with error message:

Argument of type mystruct ** is incompatible with parameter of type void **

The argument of myfunc() is kept as void** because it seems to be a generic malloc kind of function to be called with various structure variable types for memory allocation

Is there any type such as void ** allowed in C standard/any C compilers?

How do I fix this? [I tried casting the function call argument to mystruct**, but it didn't work]

-AD

Answer:
```
void**
```
is
valid but, based on your error message, you probably have to explicitly cast the argument as follows:
```
```
mystruct **var1;
x = myfunc ((void**) var1);
```
```
That's because the
```
myfunc
```
function is expecting the
```
void**
```
type. While
```
void*
```
can be implicitly cast to any other pointer, that is not so for the double pointer - you need to explicitly cast it.


Question:
I'm looking for a Report Designer that will allow me to connect to a RESTful webservice. Ideally I would like one that has a royalty-free End-User Report Designer. WE will be hosting it in an ASP.NET web site. So something compatable with that would be ideal ;)

We used to use Data Dynamics Active Reports. However this doesn't allow connections to webservices.

Any help, very much appreciated.

Thanks in advance.

Crafty

Answer:
I'm not sure what you mean by asking for a report generator that can connect to a web service.
Web services aren't something you can report on. They're just a source of data. What do you want to connect to and what data are you expecting to get back?
The problem with RESTful web services is you don't know what you're going to get back (there's no schema as with a DB table).
The good thing about RESTful web services is you're probably going to get back some XML, and the Active Reports product you mention seems to do things with XML files.
"ActiveReports for .NET 3.0 supports many XML-based files for data input."
Cam you call the web services for the information you need and squirrel it away in some files (or a DB) first?
Or are you in essence asking for something that can query a RESTful web service in some reasonably complex way and return the results of the query in some structured way that a report generator can then consume?
Do you have specific RESTful web services in mind, and if so do you know what format they will return data in? Then your question is really about report generators that can handle that returned format, perhaps.
Or something else and I've missed the point?


Question: How do I convert a keycode to a keychar in .NET?

Answer:
In VB.NET:
```
```
ChrW(70)
```
```
In C# you can cast:
```
```
(char) 70
```
```


Question:
I want to create a trigger to check what is being deleted against business rules and then cancel the deletion if needed. Any ideas?

The solution used the Instead of Delete trigger. The Rollback tran stopped the delete. I was afraid that I would have a cascade issue when I did the delete but that didn't seem to happen. Maybe a trigger cannot trigger itself.

Answer:
Use an
```
INSTEAD OF DELETE
```
(see
MSDN
) trigger and decide within the trigger what you really want to do.


Question:
Here's a very simple question. I have an SP that inserts a row into a table and at the end there's the statement RETURN @@IDENTITY. What I can't seem to find is a way to retrieve this value in C#. I'm using the Enterprise library and using the method:

db.ExecuteNonQuery(cmd);

I've tried cmd.Parameters[0].Value to get the value but that returns 0 all the time. Any ideas?

Answer:
```
```
Dim c as new sqlcommand("...")

Dim d As New SqlParameter()
d.Direction = ParameterDirection.ReturnValue
c.parameters.add(d)

c.executeNonQuery

(@@IDENTITY) = d.value
```
```
It is more or less like this...either this or just return the value from a stored procedure as an output parameter.


Question:
This might be a naive question. I have to manually edit a .WXS file to make it support select features from command line.

For example, there are 3 features in .WXS file.

<Feature Id="AllFeature" Level='1'>

    <Feature Id="Feature1" Level='1'> </Feature>

    <Feature Id="Feature2" Level='1'> </Feature>

    <Feature Id="Feature3" Level='1'> </Feature>

</Feature>

Now, I want to select features from command line. Say, if I type "msiexec /i install.msi FEATURE=A", then "Feature1" and "Feature2" is installed; if I type "msiexec/i install.msi FEATURE=B", then "Feature1" and "Feature3" is installed. In this case, "A" maps to Feature 1 and 2; "B" maps to Feature 1 and 3.

How to accomplish this in WIX?

Answer:
I would change Feature1, Feature2 and Feature3 to Components, then would declare something like this:
```
```
<Feature Id="FEATUREA" Title="Super" Level="1" >
  <ComponentRef Id="Component1" />
  <ComponentRef Id="Component2" />
</Feature>

<Feature Id="FEATUREB" Title="Super1" Level="1" >
  <ComponentRef Id="Component1" />
  <ComponentRef Id="Component3"/>
</Feature>
```
```
Then to Install either FeatureA or FeatureB
```
```
msiexec /i install.msi ADDLOCAL=[FEATUREA | FEATUREB]
```
```


Question:
I am reading WIX script written by others. There are some code really confuses me.

<Custom Action='UnLoadSchedulerPerfCounters' After='InstallInitialize'>
    <![CDATA[(Installed) AND (!Scheduler = 3)]]>
</Custom>
<Custom Action='RollbackSchedulerPerfCounters' After='WriteRegistryValues'>
        <![CDATA[(&Scheduler = 3)]]>
</Custom>

So, what's the difference between !Scheduler and &Scheduler?
Is any special meaning when property is prefix-ed by & or !?

Answer:
From
http://www.tramontana.co.hu/wix/lesson5.php#5.3
:
Prepending some special characters to
  the names will give them extra
  meaning:
```
```
%     environment variable (name is case insensitive)
$     action state of component
?     installed state of component
&     action state of feature
!     installed state of feature
```
```
The last four can return the following
  integer values:
```
```
-1   no action to be taken
1    advertised (only for components)
2    not present
3    on the local computer
4    run from the source
```
```


Question: I'm working on a piece of library code around IDisposable. The managed path (via using) is easily testable. I'm wondering about the finalizer though: Is calling System.GC.Collect() sufficient to force the finalizer to run?

Answer:
Could you mock out an
```
IDisposable
```
interface and expect a call to
```
Dispose
```
?  That would at least let you see when the object is actually disposed.


Question:
My programming environment includes scripts for setting up my autobuild on a clean machine.

One step uses a vbscript to configure a website on IIS that is used to monitor the build.

On a particular machine I will be running apache on port 80 for a separate task.

I would like my vbscript to set the port to 8080 for the new site that it is adding.

How can I do this?

Answer:
Could you mock out an
```
IDisposable
```
interface and expect a call to
```
Dispose
```
?  That would at least let you see when the object is actually disposed.


Question:
What is the best way of working with calculated fields of Propel objects?

Say I have an object "Customer" that has a corresponding table "customers" and each column corresponds to an attribute of my object. What I would like to do is: add a calculated attribute "Number of completed orders" to my object when using it on View A but not on Views B and C.

The calculated attribute is a COUNT() of "Order" objects linked to my "Customer" object via ID.

What I can do now is to first select all Customer objects, then iteratively count Orders for all of them, but I'd think doing it in a single query would improve performance. But I cannot properly "hydrate" my Propel object since it does not contain the definition of the calculated field(s).

How would you approach it?

Answer:
Add an attribute "orders_count" to a Customer, and then write something like this:
```
```
class Order {
...
  public function save($conn = null) {
    $customer = $this->getCustomer();
    $customer->setOrdersCount($customer->getOrdersCount() + 1);
    $custoner->save();
    parent::save();
  }
...
}
```
```
You can use not only the "save" method, but the idea stays the same. Unfortunately, Propel doesn't support any "magic" for such fields.


Question:
Does anyone know how could I programatically disable/enable sleep mode on Windows Mobile?

Thanks!

Answer:
Probably by modifying the "System Power States" as
described here
(but in c#)
That article also describes a way to prevent the mobile device to sleep (which is not exactly what you may want), by calling the native function SystemIdleTimerReset() periodically (to prevent the device from powering down).


Answer:
From the Unix / cygwin command line, you can use bc.
```
```
$ bc
ibase=16
34363932353433373538323038353135353439
1164362276596472215941024063897591129839055929
```
```
There is also
an online version
.  If you want to do it in code you should use an arbitrary precision library facility, like Java's BigInteger, Perl's Math::BigInt, Tcl's  math::bignum, or of the many multiple precision arithmetic libraries that are available for C, like
GNU GMP
, or
MPI
.


Question:
Possible Duplicate:

  How can I use a carriage return in a HTML tooltip?

I'd like to know if it's possible to force a newline to show in the tooltip when using title property of a TD.
something like

<td title="lineone \n linetwo \n etc...">

Can this be done?

Answer:
This should be OK, but is Internet Explorer specific:
```
```
<td title="lineone
linetwo
etc...">
```
```
As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.


Question: I want to draw spinner controls, such as those found on a NumericUpDown, on a custom component.  If I want to draw a drop-down button, I can use ComboBoxRenderer.  Is there an equivalent of ComboBoxRenderer for NumericUpDown?

Answer:
I do not think a ComboBoxRenderer exists in the Windows Forms namespace. You need to directly draw the UpDown control arrows (spin buttons) using interop and the Theme API. I don't have a complete sample for you, but you'll need
```
```
[DllImport("uxtheme.dll", ExactSpelling = true, CharSet = CharSet.Unicode)]
public static extern IntPtr OpenThemeData(IntPtr hWnd, String classList);

[DllImport("uxtheme", ExactSpelling = true)]
public extern static Int32 DrawThemeBackground(IntPtr hTheme, IntPtr hdc, int iPartId, int iStateId, ref RECT pRect, IntPtr pClipRect);

[DllImport("uxtheme.dll", ExactSpelling = true)]
public extern static Int32 CloseThemeData(IntPtr hTheme);
```
```
and you can find the required parts and states in
this page
(look for the SPIN style class and its associated parts and states).


Question:
I have a char* p, which points to a \0-terminated string. How do I create a C++ string from it in an exception-safe way?

Here is an unsafe version:

string foo()
{
  char *p = get_string();

  string str( p );
  free( p );
  return str;
}

An obvious solution would be to try-catch - any easier ways?

Answer:
You can use
```
shared_ptr
```
from
C++11
or
Boost
:
```
```
string
foo()
{
    shared_ptr<char> p(get_string(), &free);
    string str(p.get());
    return str;
}
```
```
This uses a very specific feature of
```
shared_ptr
```
not available in
```
auto_ptr
```
or anything else, namely the ability to specify a custom deleter; in this case, I'm using
```
free
```
as the deleter.


Question:
I am implementing replication for a project I am developing, and would like to replicate changes in the Write database to the Read database.

While this isn't a problem, I want to tune one database for reading from, and the other to writing to, so they would have different settings.

Is there any resource/guide which will tell me what concepts to look into? I'm not looking for a how to guide (then again, at this level, these tasks are very involved to have guides to).

Thanks

Answer:
Index your databases differently.   You probably need different indexes (maybe fewer indexes) to suppor the process of writing to the Write database than you do with the read database.   If an index is only used for reading, then leave it off the Write database.
I'm no expert on this, and my thinking might be fuzzy, but consider the hardware/memory/and even RAID configurations.   I can't remember.... would one RAID configuration be more suited for writing and another for reading, or is that wrong...?


Question:
Please give me the advantages and disadvantages of using the particular framework.

Can give me examples of successes where you have used AOP in you .net applications?

Answer:
Index your databases differently.   You probably need different indexes (maybe fewer indexes) to suppor the process of writing to the Write database than you do with the read database.   If an index is only used for reading, then leave it off the Write database.
I'm no expert on this, and my thinking might be fuzzy, but consider the hardware/memory/and even RAID configurations.   I can't remember.... would one RAID configuration be more suited for writing and another for reading, or is that wrong...?


Question:
In the Render method of an ASP.NET web-control, I need to alter the output of the Html based on whether JavaScript is enabled or disabled on the clients browser,

Does anyone know the right incantation to figure that out?

Answer:
The
noscript
tag is used to define an alternate content (text) if a script is NOT executed.
EDIT: Hi Kieron, take a look at this link:
Creating a Server Control for JavaScript Testing
, and
Detect if JavaScript is enabled in ASPX


Question: How do I convert TIS-620 (the extended ASCII Thai Character code page) string to UTF-8 string in Java?

Answer:
The
noscript
tag is used to define an alternate content (text) if a script is NOT executed.
EDIT: Hi Kieron, take a look at this link:
Creating a Server Control for JavaScript Testing
, and
Detect if JavaScript is enabled in ASPX


Question:
OK, I am trying to generate the rDoc for paperclip, but the rake task is choking on another plugin before it gets to it, so this is out of the question:

rake doc:plugins

I could go and fix up the broken plugin, but I'm busy and lazy, so I just want to generate the docs for paperclip. Is there any way of doing this?

Answer:
Unbelievably, I've just figured it out!
```
```
rake doc:plugins:paperclip
```
```
That was simple.


Question:
I'm writing a web application which uses windows authentication and I can happily get the user's login name using something like:

 string login = User.Identity.Name.ToString();

But I don't need their login name I want their DisplayName. I've been banging my head for a couple hours now...

Can I access my organisation's AD via a web application?

Answer:
See related question:
Active Directory: Retrieve User information
See also:
Howto: (Almost) Everything In Active Directory via C#
and more specifically section "
Enumerate an object's properties
".
If you have a path to connect to a group in a domain, the following snippet may be helpful:
```
```
GetUserProperty("<myaccount>", "DisplayName");

public static string GetUserProperty(string accountName, string propertyName)
{
    DirectoryEntry entry = new DirectoryEntry();
    // "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
    entry.Path = "LDAP://...";
    entry.AuthenticationType = AuthenticationTypes.Secure;

    DirectorySearcher search = new DirectorySearcher(entry);
    search.Filter = "(SAMAccountName=" + accountName + ")";
    search.PropertiesToLoad.Add(propertyName);

    SearchResultCollection results = search.FindAll();
    if (results != null && results.Count > 0)
    {
        return results[0].Properties[propertyName][0].ToString();
    }
    else
    {
            return "Unknown User";
    }
}
```
```


Question:
I'm using Python's Imaging Library and I would like to draw some bezier curves.
I guess I could calculate pixel by pixel but I'm hoping there is something simpler.

Answer:
A bezier curve isn't that hard to draw yourself. Given three points
```
A
```
,
```
B
```
,
```
C
```
you require three linear interpolations in order to draw the curve. We use the scalar
```
t
```
as the parameter for the linear interpolation:
```
```
P0 = A * t + (1 - t) * B
P1 = B * t + (1 - t) * C
```
```
This interpolates between two edges we've created, edge AB and edge BC. The only thing we now have to do to calculate the point we have to draw is interpolate between P0 and P1 using the same t like so:
```
```
Pfinal = P0 * t + (1 - t) * P1
```
```
There are a couple of things that need to be done before we actually draw the curve. First off we have will walk some
```
dt
```
(delta t) and we need to be aware that
```
0 <= t <= 1
```
. As you might be able to imagine, this will not give us a smooth curve, instead it yields only a discrete set of positions at which to plot. The easiest way to solve this is to simply draw a line between the current point and the previous point.


Question: Such as deleting the output file during run, directing two instances of the sw to the same IO etc ?

Answer:
There isn't much you can do to prevent the user from doing that, but what you can do is to apply
defensive programming
.
In your two examples you'd have to, every time you access a resource, detect failure conditions and react appropriately either throwing exceptions and dying or continuing without access to that resource.
Never assume a resource allocation will succeed, always check what you don't control. In short,
assume as little as possible and verify everything
.
'I'm told to access this file to write to it. Is it already open? Do I have permissions? Does it have the expected format? Does the disk have enough space? etc.'
There is many more about this. Just Google for defensive programming and you'll get a lot to read about.


Question:
I just posted the question how-to-determine-why-the-browser-keeps-trying-to-load-a-page and discovered that my problem is with Gravatar.

I also noticed that StackOverflow is suffering from the same outage.

Does anyone know of a graceful way to determine if Gravatar, or any third party website for that matter, is up or not, before trying to retrieve avatar icons from them?

This would eliminate the long page load and the never ending busy cursor ... I shouldn't say never ending ... it just takes a long time to go away and is very confusing to the user as they sit there and wait ... for nothing.

Answer:
You can have a different process that is periodically checking the status of the site. Set a rule about what is down for you, for instance you could say: "ping time > 1500 ms = down". Have this process to leave a note in a database table or config file. Then you check this value on each page rendering at almost no cost.
Depending on how critical is this external site, you can do the check more or less often.
This process could be an out of the web stack program, or a page only accessible through localhost that gets executed via Scheduled Tasks or an ASP.NET facility like mentioned in the comments.


Question:
I recently started to develop using Flex 3 and Adobe Air and I wanted to know what features you want to be in futures releases of Adobe Air ?

The ones that I miss are:

Cross-systems way of launching a local file (shellExec) right from an Air application (although you can do this using workaround at least under Windows)

Ability to setup dynamic paths for Embed statement (e.g. Embed[(variable+"/path/to/file")] ). I didn't find any way to do this properly.

Some way of setting Flex object's positions with absolute values from CSS (that sounds more Flex related by the way)

Don't hesitate to add your workarounds to theses limitations if you know somes.

Answer:
Ability to call out to native code - you currently have to ship a server written in another language and make calls to that to do anything more than Air gives you.
Modal windows. There's a hack you can do which involves setting Application.application.enabled = false, setting dialog.nativeWindow.alwaysInFront = true and then re-enabling the application when the dialog closes, but this is long-winded and doesn't disable any native menus you may have! It's crazy that something so simple is made so difficult.
A usable way to set the application's icon. I spent 2 hours trying to do this the other day and gave up after persistent "303" errors that gave me no idea of what I was doing wrong. Again, really basic stuff.


Question:
I want do something like this:

Result = 'MyString' in [string1, string2, string3, string4];

This can't be used with strings and I don't want to do something like this:

Result = (('MyString' = string1) or ('MyString' = string2));

Also I think that creating a StringList to do just this is too complex.

Is there some other way to achieve this?

Thanks.

Answer:
Here is a function that does the job:
```
```
function StringInArray(Value: string; Strings: array of string): Boolean;
var I: Integer;
begin
  Result := False;
  for I := Low(Strings) to High(Strings) do
  Result := Result or (Value = Strings[I]);
end;
```
```
In fact, you do compare MyString with each string in Strings. As soon as you find one matching you can exit the for loop.


Question:
I have client application that uses WCF service to insert some data to backend database. Client application is going to call service on per event basis (it can be every hour or every second).

I'm wondering what's the best way of calling that service.

Should I create communication channel and keep it open all the time, or should I close channel after each call and create it again?

Answer:
The first question is whether your server needs to maintain any state about the client directly (i.e. are you doing session-like transactions?)  If you are, you will need to be able to manage how the server holds the information between communications.
My initial feeling of your question is that if there is no need to leave a connection open, then close it each time and recreate a new connection on demand.  This will avoid issues where a connection can be placed into a faulted state between calls.  The overhead of creating and destroying connections is minimal, and it will (probably) save you a lot of time in debugging
when
something goes wrong.


Question:
Here is a simplified version of my database model.  I have two tables: "Image", and "HostingProvider" which look like this:

[Image]

id

filename

hostingprovider_id

[HostingProvider]

id

base_url

Image HostingproviderId is a many-to-one foreign key relationship to the HostingProvider table. (Each image has one hosting provider).

Essentially I want to be able to have my Image class look like this:

[Image]

Id

base_url

filename

In NHibernate, how can I create a mapping file that will combine the base_url from the HostingProvider table, into the Image class?

Answer:
```
```
public class Image {
    public virtual HostingProvider HostingProvider { get; set; } // NHibernate takes care of this
    public virtual string BaseUrl { get { return HostingProvider.BaseUrl; } }
}
```
```


Question:
Currently we have mutiple projects sharing a JIRA instances. We want to make it such that the users only view the projects that they are doing testing.

But however we are currently groupging these users to the standard grouping jira-users.

What is the best way to filter out JIRA project that only certain users can see and access

Answer:
You should create special Groups of users for each project you have... you can have more than one group, something like "project1_developers", "project2_observers" for better organization.
You alson combine these groups with the Project Roles to define into each project what kind of access each group should have.
Make a Permission Scheme to set of permissions to one project. Something like this:
Browse Projects -> Group (project1_admins, project1_developers, project1_users, project1_observers)
Create Issues -> Group (project1_admins, project1_developers, project1_users)
Move Issues -> Group (project1_admins)
You can use your Project Roles here too... but I prefer to set everything with groups.
Finally, you can use Issue security schemes to define who can and cannot view issues. Issue security schemes implement a number of security levels which can have users/groups assigned to them.
Hope that can help.


Question:
I am trying to match the folder name in a relative path using C#. I am using the expression: "/(.*)?/" and reversing the matching from left to right to right to left.
When I pass "images/gringo/" into the regular expression, it correctly gives me "gringo" in the first group - I'm only interested in what is between the brackets.
When I pass in "images/", it fails to pick up "images".
I have tried using [/^] and [/$] but neither work.

Thanks,
David

Answer:
You're probably better off using the
System.IO.DirectoryInfo
class to interpret your relative path. You can then pick off folder or file names using its members:
```
```
DirectoryInfo di = new DirectoryInfo("images/gringo/");
Console.Out.WriteLine(di.Name);
```
```
This will be much safer than any regexps you could use.