q:
Let's say we're tracking the end-user IP for a web service:

ip = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
If ip = "" Then
    ip = Request.ServerVariables("REMOTE_ADDR")
End If

I've read that this is the best method of retrieving end-user IP because it works even for users on a transparent proxy.

If we're using the end-user IP address to filter malicious users, are there are any security implications with the above method instead of, say, just using Request.ServerVariables("REMOTE_ADDR")?

For example, if we banned a malicious user by end-user IP, could they easily change their IP via a proxy and continue using our web service?

Thanks in advance for your help.

[A]
```
REMOTE_ADDR
```
is generated by the web server based on the connection from the client.
```
HTTP_X_FORWARDED_FOR
```
is based on a HTTP header sent by the client.
You can't trust input from the client, particularly input that is easily faked, such as HTTP headers.  Clients can stick
anything
into that
```
HTTP_X_FORWARDED_FOR
```
header.


q:
Simple question:

How do I do this on one line:

my $foo = $bar->{baz};
fizz(\$foo);

I've tried \$bar->{baz}, \${$bar->{baz}}, and numerous others.  Is this even possible?

-fREW

Update: Ok, the hashref is coming from DBI and I am passing the scalar ref into template toolkit.  I guess now that I look more closely the issue is something to do with how TT does all of this.  Effectively I want to say:

$template->process(\$row->{body}, $data);

But TT doesn't work that way, TT takes a scalar ref and puts the data there, so I'd have to do this:

$template->process(\$row->{body}, $shopdata, \$row->{data});

Anyway, thanks for the help.  I'll at least only have one reference instead of two.

[A]
I am not even sure what you are doing.
You also should put quotes around baz.
Now let's consider that you assign a scalar to the scalar in the first line then the second line should work.
However I don't really know if this is what you are trying here and it does not really make sense in Perl.
Using references is often used in other languages to
speed up a function call
allow multiple values to be returned.
Now the first is usually not needed with scalars and anyway Perl is a script language so if you are really concerned about speed write C.
The second is not needed in Perl as you can return lists and references to anonymous hashes quite easy.
Have you looked at "man perlref"?

s: huggingface

c: devops

d: intermediate


q:
I have a generic list of objects in C#, for example sake, here's what the object might be.

public class Thing {
    public string Name { get; set; }
    public DateTime EditDate { get; set; }
}

var things = new List<Thing>();

Now I want to call:

thing.Sort((t1, t2) => t1.EditDate.CompareTo(t2.EditDate));

However, some of my EditDate properties are null.  I want these objects with a null EditDate property to show up at the top of my list (i.e. closer to the zero index).  How can I do this?

[A]
List has a
sort function
that takes a delegate.
Now that I've read the question
```
```
TheList.Sort(int delegate(Type a, Type b)
{
    if (a.memeber == null) return -1;
    if (b.memeber == null) return 1;
    if (a.memeber<b.memeber) return -1;
    if (b.memeber<a.memeber) return 1;
    return 0;
}
```
```


q:
I have to do some work for college and my professor likes to torture us with Nassi-Shneiderman diagrams.

Has anyone a good editor/graphcial tool to draw these? Requirements:

cross platform (or able to run within wine)

open source (or a least free to for private use)

--

After considering some editors, I ended up by using Strutorizer from http://structorizer.fisch.lu/

It hasn't the best usability but it's good enough. And it's written in Java.

[A]
You can download a free trial copy of
SmartDraw
, which can edit Nassi-Schneiderman diagrams, or there's the free
Nassi-Shneiderman Diagram-Editor
.
EDIT:
How to draw Nassi-Shneiderman diagrams with SmartDraw


q:
I have developed a web application using internationalization best practices such as putting all my displayable strings in property files, etc, etc.

I would like to have the strings in the property files translated into 5 different languages.

Does anyone have any experience using Mechanical Turk or another crowd sourcing service for language translation?

The reason I don't want to just hire a translation company or service is because I want to eventually have ongoing content fed into the translation service via an API.

My Google results for more information on this topic were surprisingly dismal.  Any links or pointers are appreciated.

[A]
I don't have any experience crowd-sourcing translations, but my advice would be to find some dependable freelance translators in your target languages (check out Proz.com), and keep going back to them every time you have new content. Application UIs are notoriously difficult to localize because of lack of context in the resource files, and so you want someone who understands the application and is able/willing to test the localized version. Each of the localizations will undoubtedly reveal i18n bugs as well, so there is likely to be a bit of back and forth the first time around. I guess my point is that you don't want arms-length relationships with your translators; they should feel like an extension of your team.
Anyway, bravo for internationalizing your application. Good luck!


q:
I have a list control in Flex that has been data bound to an e4x xml object from an HTTPService.

I would now like to have a button that clears the list, how can I do this?

I have tried:

list.dataProvider = null;

which does not seem to work, I have also tried:

list.dataProvider = {};

which clears the items but leaves [object,object] as the first item in the list...


q:
As I continue my quest of learning functional programming, I've come
to wonder if there may be alternatives to my default "procedural" way
of thinking. To be more specific, I'm looking at a function I
wrote. Here is what it does:

Swap two elements of an unordered list of numbers, such that one of the elements
 is now in the right place
Add the sum of the swapped values to an accumulated total
Repeat until list is sorted

So, right now I'm using a standard loop* with an accum variable to do
the above. It works fine and all, and there's certainly nothing wrong
with iteration in real life, but as the point of this exercise is to
expand my way of thinking, I'm curious if there is a more functional
approach to the above algorithm.

Thanks!

*(Actually recursion, but whatever)


q: Sometimes software installers force you to scroll to the end of the EULA before the “I agree” box is enabled.  How can I produce the same effect on a web page?

[A]
```
```

        <form>
            <textarea id="agreetext" rows="8" cols="40">Long agreement</textarea>

            <input type="checkbox" id="agreebox" value="true"/> I agree

            <input type="submit" value="Continue"/>
        </form>

```
```


q:
My question is similar to "What is the difference between include and extend in Ruby?".

What's the difference between require and include in Ruby?  If I just want to use the methods from a module in my class, should I require it or include it?

[A]
What's the difference between
  "include" and "require" in Ruby?
Answer:
The include and require methods do
  very different things.
The require method does what include
  does in most other programming
  languages: run another file. It also
  tracks what you've required in the
  past and won't require the same file
  twice. To run another file without
  this added functionality, you can use
  the load method.
The include method takes all the
  methods from another module and
  includes them into the current module.
  This is a language-level thing as
  opposed to a file-level thing as with
  require. The include method is the
  primary way to "extend" classes with
  other modules (usually referred to as
  mix-ins). For example, if your class
  defines the method "each", you can
  include the mixin module Enumerable
  and it can act as a collection. This
  can be confusing as the include verb
  is used very differently in other
  languages.
Source
So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use
```
require
```
.
Oddly enough, Ruby's
```
require
```
is analogous to C's
```
include
```
, while Ruby's
```
include
```
is almost nothing like C's
```
include
```
.


q:
How do I setup an Ant task to generate a Findbugs report when the source folder has many jars in it?

I'm looking for a worked example of the ant task required to output the fancy HTML from a folder containing multiple jars


q: what is the best way to track and lower GDI windows handles . .

[A]
Personally I use
IARSN TaskInfo
to see the number of handles my program uses, GDI included. As for lowering the number of active handles, then I would look at what in your application is using handles.
Things like (but not limited to):
Pens
Bitmaps
Controls (I don't think all of them uses handles)
Do you have a specific problem with too many handles, or perhaps even a handle leak?


q:
I'm trying to get distinct results using the Criteria API in NHibernate. I know this is possible using HQL, but I would prefer to do this using the Criteria API, because the rest of my app is written using only this method. I found this forum post, but haven't been able to get it to work. Is there a way with the criteria API to get distinct result sets?

Edit: In doing this, I also wanted to exclude the Primary Key column, which is also an identity, and get the remaining distinct records. Is there a way to do this? As it is, the distinct records are returning duplicates because the primary key is unique for each row, but all other fields are the same.

[A]
Cannot see the forum post at this moment (broken link?), so maybe this is not the answer, but you can add a DistinctRootEntityResultTransformer:
```
```
session.CreateCriteria(typeof(Product)
    .Add(...)
    .SetResultTransformer(new DistinctEntityRootTransformer())
```
```


q:
I am trying to set the margin of an object from JavaScript. I am able to do it in Opera & Firefox, but the code doesn't work in Internet Explorer.

Here is the JavaScript I have:

function SetTopMargin (ObjectID, Value)
{
    document.getElementById(ObjectID).style.marginTop =  Value.toString() + "px";
}

And it is called like this:

SetTopMargin("test_div_id", 100);

So does anyone know some code that will work in Internet Explorer?

[A]
[Updated in 2016] On all current browsers (including IE8+), your code
```
```
document.getElementById(ObjectId).style.marginTop = Value.ToString() + 'px';
```
```
works fine.
On
very old
IE (< 8) versions, you must use this non-standard contraption instead:
```
```
document.getElementById(ObjectId).style.setAttribute(
   'marginTop', Value.ToString() + 'px');
```
```
EDIT
- From deleted comment by OP:
Note that while you can use style.setAttribute('margin-top', ..) in current IEs, 8 and older require style.setAttribute('marginTop', ..)


q:
The two key event argument classes KeyEventArgs and PreviewKeyDownEventArgs each have two properties, KeyCode and KeyData, which are both of the enumeration type Keys.

What is the difference between these two properties? Do the values in them ever differ from each other?  If so, when and why?

[A]
```
KeyCode
```
is an enumeration that represents all the possible keys on the keyboard.
```
KeyData
```
is the
```
KeyCode
```
combined with the modifiers (Ctrl, Alt and/or Shift).
Use
```
KeyCode
```
when you don't care about the modifiers,
```
KeyData
```
when you do.


q: Server 2008 machine with SP1, Visual Studio 2008 with SP1. My user; Developer, is in the local Administrators group. That said, some actions I perform in Visual Studio (use the properties window of a web application to invoke the creation of a virtual directory in local IIS) tell me that Admin privileges are required. It is an annoyance more than anything, I can just launch VS with right click (Run As Administrator) to perform the action -  but I was curious if anyone knows why this happens?

[A]
Because that's how it works, I guess... It doesn't matter the group your user is in, what matters is if the application is running with admin privileges or not. If it is, than you will be able to perform admin actions, otherwise you won't.
All applications that use UAC to perform admin actions (when you see the security badge) they will either a) restart the application with admin privileges or b) launch a process with admin privileges to perform the respective action. They will never be able to grant you admin privileges without launching a process with them.
That's just the way it works really. As far as I know, this is how it works...


q:
I need to display 2d images in opengl using textures.

The image dimensions are not necessarily powers of 2.

I thought of creating a larger texture and restricting the display to the part I was using but the image data will be shared with openCV so I don't want to copy data a pixel at a time into a larger texture.

EDIT - it turns out that even the simplest Intel on board graphics under Windows supports none-power-of-2 textures.

EDIT2 - and even if you don't have arb texture size, then making your image smaller and rescaling to the window size it is very fast even on low end hardware

[A]
First of all, most modern videocards actually support texture dimensions that are both non-square and non-power-of-two sized. But for maximum compatibility, using only power of two textures is probably recommended.
Start off by determining the closest power of two that is larger for each of the image dimensions (width and height) and creating a texture of that size.
Then you have two options. The first one is to do a software resize of the pixel data to fit the image, and then size your quad according to the original aspect ration when you need to display it. Or, you can just fill part of the texture with your image data and put transparent pixels in the rest.


q:
I'm generating titles out of a few other fields, and want the "right" way to do:

Me.Title.Value = Join(Array([Conference], [Speaker], partstr), " - ")

Except any of [conference], [speaker] or partstr might be null, and I don't want the extra "-"'s.  Are there any functions that'll make this job straightforward?

[A]
Nope - you'll have to check each one and then cleanup at the end
```
```
Dim Temp As String

If Not IsNull([Conference]) Then
  Temp = Temp & [Conference] & " - "
End If

If Not IsNull([Speaker]) Then
  Temp = Temp & [Speaker] & " - "
End If

If Not IsNull(partstr) Then
  Temp = Temp & partstr & " - "
End If

If Temp > "" then
  Me.Title.Value = Left(Temp, Len(Temp) - 3)
Else
  Me.Title.Value = Null
End If
```
```
Revised with generic function:
```
```
Public Function JoinEx(ByVal pArray As Variant, ByVal pDelimiter As String) As String

  Dim sTemp As String
  Dim iCtr As Integer

  For iCtr = 0 To UBound(pArray)
    If Not IsNull(pArray(iCtr)) Then
      sTemp = sTemp & pArray(iCtr) & pDelimiter
    End If
  Next

  If sTemp > "" Then
   JoinEx = Left(sTemp, Len(sTemp) - Len(pDelimiter))
  End If

End Function
```
```
Calling Example:
```
```
JoinEx(Array("one","two","three"), " - ")  'Returns "One - Two - Three"
 JoinEx(Array(null,"two","three"), " - ")  'Returns "Two - Three"
```
```


q:
Is it possible to cast an object in Java to a combined generic type?

I have a method like:

public static <T extends Foo & Bar> void doSomething(T object) {
    //do stuff
}

Calling this method is no problem if I have a class that implements both interfaces (Foo & Bar).

The problem is when I need to call this method the object I need to pass to it is received as java.lang.Object and I need to cast it to make the compiler happy. But I can't figure out how to make this cast.

edit:

The problem lies in a function like this:

public void problemFunction (Object o) {
  if ( o instanceof Foo && o instanceof Bar) {
      doSomething((Problematic cast) o);
  }
}

}

[A]
Unfortunately, there is no legal cast that you can make to satisfy this situation. There must be a single type known to implement all of the interfaces that you need as bounds, so that you can cast to it. The might be a type you create for the purpose, or some existing type.
```
```
interface Baz extends Foo, Bar { }

public void caller(Object w) {
  doSomething((Baz) w);
}
```
```
If other types are known, like
```
Baz
```
, to meet the bounds, you could test for those types, and have a branch in your caller that calls
```
doSomething
```
with a cast to those types. It's not pretty.
You could also use delegation, creating your own class
```
Baz
```
that meets the bounds required by
```
doSomething
```
. Then wrap the object you are passed in an instance of your
```
Baz
```
class, and pass that wrapper to
```
doSomething
```
.
```
```
private static class FooBarAdapter implements Foo, Bar {
  private final Object adaptee;
  FooBarAdapter(Object o) {
    adaptee = (Foo) (Bar) o;
  }
  public int flip() { return ((Foo) adaptee).flip(); }
  public void flop(int x) { ((Foo) adaptee).flop(x); }
  public void blort() { ((Bar) adaptee).blort(); }
}

public void problemFunction (Object o) {
  doSomething(new FooBarAdapter(o));
}
```
```


q:
I'm trying to assert that one object is "equal" to another object.

The objects are just instances of a class with a bunch of public properties. Is there an easy way to have NUnit assert equality based on the properties?

This is my current solution but I think there may be something better:

Assert.AreEqual(LeftObject.Property1, RightObject.Property1)
Assert.AreEqual(LeftObject.Property2, RightObject.Property2)
Assert.AreEqual(LeftObject.Property3, RightObject.Property3)
...
Assert.AreEqual(LeftObject.PropertyN, RightObject.PropertyN)

What I'm going for would be in the same spirit as the CollectionEquivalentConstraint wherein NUnit verifies that the contents of two collections are identical.

[A]
Override .Equals for your object and in the unit test you can then simply do this:
```
```
Assert.AreEqual(LeftObject, RightObject);
```
```
Of course, this might mean you just move all the individual comparisons to the .Equals method, but it would allow you to reuse that implementation for multiple tests, and probably makes sense to have if objects should be able to compare themselves with siblings anyway.


q:
is it possible to create something like this i ASP.NET MVC beta 1

i have tried but the

override bool OnPreAction(string actionName,
                          System.Reflection.MethodInfo methodInfo)

does not exsist anymore and

override void OnActionExecuting(ActionExecutingContext filterContext)

don't give me access to the action name

[A]
In the blogpost you are referring to, the author states that
One way to solve this problem is by using the attribute based security as shown on this post. But then you will have to decorate your actions with the security attribute which is not a good idea.
I think it's a perfectly fine way to go about it and it is supported by the framework. It will give you a nice declarative implementation. Check out the AuthorizeAttribute in System.Web.Mvc. It will allow you to do something like this:
```
```
[Authorize(Roles="Admin, Editor")]
public ActionResult Delete(int id){
    (...)
}
```
```
Since the Delete action alters the state of your system, I would also add an AcceptVerbs attribute like so:
```
```
[AcceptVerbs(HttpVerbs.Post)]
[Authorize(Roles="Admin, Editor")]
public ActionResult Delete(int id){
    (...)
}
```
```
This will make sure that the action will not accept GET requests.


q: I have a support environment where we connect to many of our customers' systems using VPN and Remote Desktop. Right now, support personnel have to manually set up the VPN connection on their workstation. Is there a way to programmatically create the VPN connection?

[A]
Look up the RAS API (Remote Access Service), it's a win32 dll, but you can call it from C#. Here are some links that may help you get started:
http://msdn.microsoft.com/en-us/library/aa446741(VS.85).aspx
http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/28125f40-9c3b-4e77-9bfb-8a975e9b3457/


q:
We have hosted our web applications on Tomcat 6.0.18 and experienced the following problem:

There are two web apps WebApp1 and WebApp2, both are same system but of different versions.

Now the problem is when the tomcat has been running for a week or longer time then sometimes system gives NoClassDefFoundError ! also we got some strange issue where the Class Loader of WebApp1 has loaded the class present in the jar of WebApp2 ! The same jar is also present in WebApp1 but the versions are different.

When we restarted the Tomcat everything started working fine ! Our JRE is 1.5.10

Please let me know if you have encountered such issues.

Regards,
Jatan Porecha

[A]
I've encountered many, many flavors of classloader weirdness with Tomcat - even if you don't perform any classloader code yourself, it's very easy for Tomcat itself to produce problems. The most common problem appears to be repeatedly unloading and reloading a webapp leaks classloaders and eventually runs Tomcat out of memory.
The most common reason I've seen for version mismatches is that Tomcat makes sure some classes and jars (part of Tomcat itself) are ahead of any others in your webapp classpath - commons-logging seems to be the most common example - and it's possible for classloaders to be loaded, unloaded, or kept around when you wouldn't expect.
Can you provide a few more details - if the jar is from a third-party there is a good chance someone has seen the issue before. If it's your own jar, then do you have any of your own classloader code in the application?


q: how do i define a named_scope to return all the records that were created within the last 7 days, and then how do i use that named scope in a controller?

[A]
You need to pass named_scope a proc so it will be evaluated every time the call to named_scope is run.  Otherwise if you specify Time.now it will run once (on first call) and be "cached" until the app is restarted.
```
```
named_scope \
    :this_week,
    :conditions =>  [
      %created_at > :time!,
      proc {{:time => Time.now}}
    ]
```
```
You can call the named_scope like
@ar_object.this_week


q:
I have a string like "1234567890". Now I need to store/print out this with the following format,
                     123-456-7890

What is the best method to implement this in C?

Thanks for comments/answers.

[A]
There will be two schools of thought on this as far as what is "best".
One school says that, as long as it's functional and secure, whatever method uses the fewest resources (memory and processor cycles) is "best".
One school says that, as long as it's functional and secure, whatever method is easiest to read and maintain (though it may be inefficient) is "best".
Edit:
Redacted my answer as I don't like giving code answers to homework questions
As other answers and comments have suggested, you'll do best if you read the documentation for string.h and printf / sprintf.


q:
Where is .mobi headed? Will the mobile devices use proprietary browsers that simplify a .com site or are they going to use browsers on a .mobi basis? I have a feeling it will be a flop... not sure though.

Thanks

[A]
My feeling is that smart phone browsers are getting more and more like desktop browsers, so the whole concept of .mobi is flawed from the start.  Plus, a lot of sites can now detect that you're using an inferior browser and redirect you automatically to a less functional version of their web site - no special domains required.
If you're programming a web site, wouldn't it be simpler just to have an internal redirection for mobile phone browsers than to have to maintain a whole different domain?  Especially if you can programattically derive the mobile version from the non-mobile version, either on the fly or whenever you delivery content?


q:
I have a table with a credit and debit column.

I need to get the highest balance out of that, and I think a stored procedure is the way to do it, but I have no idea how.

I need to start with the first row, add the debits, subtract the credits and store the value A.

Second row is A+debit-credit=B; A = max(A,B)
Repeat last step till the end.

Remember, I'm looking for the highest EVER, not the current, which would just be
sum(debit-credit)

[A]
May
```
```
select max(debit-credit) from yourtable
```
```
work?
Try to test it.


q: The iPhone SDK docs claim fopen() is a supported method of file access but I am unable to get it to return a FILE handle.  I am accessing a directory which is included in my project.  I have tried fopen "filename","dir/filename","./filename","./dir/filename","/dir/filename" all returning with a null pointer.  Some people report using it with no issue so I am sure it is something simple!

[A]
if you're trying to access a file within your application bundle, you need to get the full path to it:
```
[[NSBundle mainBundle] pathForResource: FILENAME ofType: FILEEXTENSION]
```
This returns an NSString, which you can pull a UTF8String out of and pass to fopen.


q:
I'd like to make a video tutorial for my SDK--one of those videos that shows the screen while some dude talks about what he's doing. Can someone direct me to easy and preferably free tools for doing so?

Desired features:
- Cuts (recording several snippets of video and putting them together afterward)
- Subtitles (not only for user convenience but because I'd rather not disturb the other cubicles by talking in a microphone at work :))

(who doesn't like video tutorials?)

Update: I'm using Windows.

[A]
Jing
. Free, very easy to use, Windows version requires .NET 3.0 framework. Also, there is Mac version available.


q:
I am doing a join on two tables. One is a user's table and the other a list of premium users. I need to have the premium members show up first in my query. However, just because they are in the premium user table doesn't mean they are still a premium member - there is an IsActive field that also needs to be checked.

So basically I need to return the results in the following order:

Active Premium Users

Regular and Inactive Premium Users

Right now I have it as the following:

SELECT Users.MemberId, PremiumUsers.IsActive FROM Users
LEFT JOIN PremiumUsers ON PremiumUsers.UserId = Users.Id
ORDER BY PremiumUsers.IsActive DESC

The problem with this is that it places non-active premium members above non-premium members.

(I'm using MS SQL Server 2005 for this)

[A]
```
```
ORDER BY COALESCE(PremiumUsers.IsActive, 0) DESC
```
```
That will group the NULLs with not-actives.


q:
I want to create a scrollable list of pictures fetched from the internet and give the user the ability to click on it. How do i go about doing it in WinForms/C#? Is it possible to add picturebox control/ controls to the listBox?

I tried adding a list of picturebox into UserControl with AutoScroll set to true, which will give me a feel like using a listBox, Is this a right approach?

I also tried setting the ImageLocation of the pictureBox to a URI of the image and then called Load() to load the image, it did work, however my Form is freezing up! How do i go on updating each of the picturebox in a sequential way without freezing my form?

Thank you,
Azlam

[A]
I'll answer your third question first, becuase that's the only one I REALLY know the answer to. There's a LoadAsync() method on the picture box that will load the image in a seperate thread and won't hang your app.
As for the other questions, I too would most likely start with a user control and put the images there. The only thing I can suggest would be to first create a user control that has a picture box, and maybe a multiline textbox or richtextbox next to it. Turn off the border on the textbox, and have a slight border around the entire control. This will allow you to display the image, with some text next to it. Then, your actual final control will just be a collection of these controls with the ability to add them as needed.
--my 2 cents...


q:
GCC supports Setjump-longjump (sjlj) and Dwarf2 table-based unwinding (dw2) exception handling models. What is the difference between the two models and how to choose the appropriate model? Why is Dwarf2 table-based unwinding (dw2) the more efficient model? I understand that the two models cannot be mixed.

Reference: Technology Preview: gcc-4.2.1-sjlj -2

[A]
Well, dwarf2 builds up tables for every function, that contain what the callee saved registers are and where in the stack they are saved, and where the frame pointer/return address in the callstack is, and some other stuff. If you use dwarf2, the compiler can use those information and effectively restore registers, and jump back to callers in the event of an exception. The backends need to provide information in their implementations' prologue generating code, to tell GCC which registers are callee-saved, and when the frame pointer was saved and such stuff.
Using setjmp/longjmp is just a hack. Since setjmp/longjmp does not know about the structure of the function throwing, it will restore all registers saved in the jump-buffer by setjmp, even if they were not overridden by the throwing function. I'm not really an expert for this, but i think it's obvious that this will not be efficient. Also, every time you start a try block, setjmp has to be called to set up the buffer containing the saved registers, while when using dwarf2, the compiler already provides all necessary information at compile time.
If the backends do not provide the necessary information, GCC will automatically fall-back to setjmp/longjmp based exception handling.
Note i'm not a GCC expert. I just ported the toolchain to some easy processor of my professor, including GCC. I hope i could help you a bit.


q:
I am trying to debug an intermittent error on the iPhone, a crash with a trace that looks like:

objc_message_send
__invoking__
[NSInvocation invoke]
HandleDelegateSource
MainRunLoop
....

When GDB stops, I'd like to be able to determine details about what selector the system is attempting to be invoked - I've set a break point now around [NSInvocation Invoke], but from that point cannot figure out how to examine details of the NSInvocation object I am stopped in.

[A]
If you look at the reference information for
objc_msgSend
you will see that the selector is the second argument. Now it should be easier to decipher the debugger output.
objc_msgSend
Sends a message with a simple return value to an instance of a class.
id objc_msgSend(id theReceiver, SEL theSelector, ...)
Parameters
theReceiver
A pointer that points to the instance of the class that is to receive the message.
theSelector
The selector of the method that handles the message.
...
A variable argument list containing the arguments to the method.


q:
Any good converter for GB, Big5, Unicode?

Convert GB to Unicode, Unicode to GB, Big5 to Unicode, Unicode to Big5, GB to Big5.

[A]
iconv should be able to do the job.  It's part of the GNU C Library.
```
```
http://en.wikipedia.org/wiki/Iconv
http://www.gnu.org/software/libiconv/
```
```


q: What's the difference between a keystore and a truststore?

[A]
A keystore contains private keys, and the certificates with their corresponding public keys.
A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.


q:
I'm trying to create some skinned forms (just the border and caption) with a different approach than you usually see but I'm having some issues with form flickering while I resize the form.

I don't know how else to explain the problem, so here's a video I created to demonstrate the problem:
http://www.screencast.com/t/AIqK9Szmz

Also, here's a VS2008 test solution with the whole code that repaints the form borders:http://stuff.nazgulled.net/misc/TestForm.zip

Hope someone can help me get rid of the flicker...

[A]
That's what I use in my base form's constructor:
```
```
this.SetStyle( ControlStyles.AllPaintingInWmPaint, true );
this.SetStyle( ControlStyles.UserPaint, true );
this.SetStyle( ControlStyles.OptimizedDoubleBuffer, true );
this.SetStyle( ControlStyles.ResizeRedraw, true );
```
```
I think the key is the use of "AllPaintingInWmPaint".


q:
How do you build a hierarchical set of tags with data in PHP?

For example, a nested list:

<div>
    <ul>
        <li>foo
        </li>
        <li>bar
            <ul>
                <li>sub-bar
                </li>
            </ul>
        </li>
    </ul>
</div>

This would be build from flat data like this:

nested_array = array();
nested_array[0] = array('name' => 'foo', 'depth' => 0)
nested_array[1] = array('name' => 'bar', 'depth' => 0)
nested_array[2] = array('name' => 'sub-bar', 'depth' => 1)

It would be nice if it were nicely formatted like the example, too.

[A]
You mean something like
```
```
function array_to_list(array $array, $width = 3, $type = 'ul', $separator = ' ', $depth = 0)
{
    $ulSpace = str_repeat($separator, $width * $depth++);
    $liSpace = str_repeat($separator, $width * $depth++);
    $subSpace = str_repeat($separator, $width * $depth);
    foreach ($array as $key=>$value) {
        if (is_array($value)) {
        $output[(isset($prev) ? $prev : $key)] .= "\n" . array_to_list($value, $width, $type, $separator, $depth);
        } else {
            $output[$key] = $value;
            $prev = $key;
        }
    }
    return "$ulSpace<$type>\n$liSpace
\n$subSpace" . implode("\n$liSpace
\n$liSpace
\n$subSpace", $output) . "\n$liSpace
\n$ulSpace</$type>";
}

echo array_to_list(array('gg', 'dsf', array(array('uhu'), 'df', array('sdf')), 'sdfsd', 'sdfd')) . "\n";
```
```
produces
```
```

      gg

      dsf

                  uhu

            df

                  sdf

      sdfsd

      sdfd

```
```
I know theres a little gap there if a sub list don't start with an explanation.
Personally I usually don't really care how the HTML looks as long as its easy to work with in PHP.
Edit: OK, it works if you run it through this first ... :P
```
```
function flat_array_to_hierarchical_array(array &$array, $depth = 0, $name = null, $toDepth = 0)
{
    if ($depth == 0) {
        $temp = $array;
        $array = array_values($array);
    }
    if (($name !== null) && ($depth == $toDepth)) {
        $output[] = $name;
    } else if ($depth < $toDepth) {
        $output[] = flat_array_to_hierarchical_array(&$array, $depth + 1, $name, $toDepth);
    }
    while ($item = array_shift($array)) {
        $newDepth = $item['depth'];
        $name = $item['name'];
        if ($depth == $newDepth) {
            $output[] = $name;
        } else if ($depth < $newDepth) {
            $output[] = flat_array_to_hierarchical_array(&$array, $depth + 1, $name, $newDepth);
        } else {
            array_unshift($array, $item);
            return $output;
        }
    }
    $array = $temp;
    return $output;
}

$arr = flat_array_to_hierarchical_array($nested_array);
echo array_to_list($arr);
```
```


q:
We're trying to decide between having all the devs on a particular team to use an absolute path for their code base or if relative paths are fine.

One reason I can think for an absolute path, meaning everyone has the same path, is because of IIS and functional tests.  Our asp.net functional test use Nunit and WatiN to fire up IE and go through various scenarios.  To have these run stand alone from the Nunit GUI, I have to check if Cassini is running and if not, start it.  It requires passing in the physical path.  So, only people using that particular path can run the functional tests this way.

Are there any deal breakers that argue for an absolute (common) path?

[A]
I too was faced with the situation where the dev server required an absolute path to launch. It was also for unit testing. After spending a couple of days dwelling on the issue, I decided to refactor as much as possible to make testing work without requiring the actual ASP.NET pages to be served. This meant abandoning automated UI testing of some packaged server controls, but in the end, I never found a good solution.
Absolute paths are one of the worst things I've ever encountered in almost any environment. They're a timebomb waiting to happen.
That said, I've often had an application that required an absolute UNC path as a "drop" location for uploaded files (when hosted in a web farm). I found it acceptable, in the end, for lack of a better solution.


q:
In .NET is it possible to convert a raw HTTP request to HTTPWebRequest object?

I'm sure .NET internally doing it. Any idea which part of the .NET is actually handling this? Can I call it or is there any external library which allows raw HTTP connections?

[A]
I dont believe there is an exposed method to do this. You may have to find or write a parser to break the request up and then write your own class that extends HttpWebRequest.
Here is what looks like a parser from CodeProject:
http://www.codeproject.com/KB/IP/CSHTTPServer.aspx
I looked at the rotor code for the HttpWebRequest (briefly) and I did not see anything that stood out as a silver bullet. Here is the link to the file:
http://www.123aspx.com/Rotor/RotorSrc.aspx?rot=40844
All of the rotor code is here for browsing online:
http://www.123aspx.com/Rotor/default.aspx
And here you can download it:
http://www.microsoft.com/downloads/details.aspx?FamilyId=8C09FD61-3F26-4555-AE17-3121B4F51D4D&displaylang=en
I know a bunch of links doesn't really answer your question, but I don't think the functionality that you are looking for is exposed in the framework. I would love to be proven wrong, so please update the post if you find a good way of doing it. I know tools out there must do it, anything written in .Net that logs raw requests and then lets you resubmit them is doing something similar. I believe
fiddler
(
http://www.fiddler2.com
) is written in .Net, you may want to shoot an email over to those guys and see if they can help.


q:
I've got a structure as follows:

typedef struct
{
    std::wstring DevAgentVersion;
    std::wstring SerialNumber;

} DeviceInfo;

But when I try to use it I get all sorts of memory allocation errors.

If I try to pass it into a function like this:

GetDeviceInfo(DeviceInfo *info);

I will get a runtime check error complaining that I didn't initialize it before using it, which I seemed to have fixed with:

DeviceInfo *info = (DeviceInfo*)malloc(sizeof(DeviceInfo));

But then, in the function, when I try to set either of the structures stings, it complains that I'm trying to access a bad pointer when trying to set a value to the string.

What is the best way to initialize this structure (and all of it's internal strings?

[A]
You should use
```
new
```
instead of
```
malloc
```
, to assure the constructor gets called for the
```
DeviceInfo
```
and its contained
```
wstring
```
s.
```
```
DeviceInfo *info = new DeviceInfo;
```
```
In general, it's best to avoid using
```
malloc
```
in C++.
Also, make sure to
```
delete
```
the pointer when you're done using it.
Edit: Of course if you only need
```
info
```
in the local scope, you shouldn't allocate it on the heap. Just do this instead:
```
```
DeviceInfo info; // constructed on the stack
GetDeviceInfo( &info ); // pass the address of the info
```
```


q:
We are developing in an embedded type environment and find ourselves needing to create our own UI framework.

I have done this before, but I am interested in doing a little bit of research around common design patterns for frameworks.

Types of things that I am thinking of as patterns (somewhat far reaching):

Widget Focus / defocus

Widget Animation

Data sharing between elements

Attaching commands to widgets

Saving state (MVC?)

What recommended reading do you have for GUI Framework patterns?

[A]
I have two for you, the callback or notification, maybe this is what you call "attaching commands to widgets", somehow you want to react to changes in state in your UI element. The controller needs to be informed that a change has occured.
Cocoa/UIKit has a pattern that is called "Delegation" and notifications to accomplish this, others use callback functions or objects (Java Swing) or  "signals and slots" (QT).
I very useful pattern that does not occur in the wild very often is the ability to
prevent
a state change, the easiest use case for this is input validation, you want to prevent the loss of focus from a widget when the text in the widget does not concur with what you would expect. Windows Forms used to have that on some elements, not all, Cocoa can do this. This can be accomplished by using return values or reference parameters (or pointers) in the callbacks where the callee can communicate back to the originating widget
These days applying styles to ui elements, i.e. changing the look without changing the functionality has also become very popular QT can do this and I am sure a lot of other libraries
The Gang of Four Decorator pattern is also used sometimes for enhancing the capabilities of a widget, making something scrollable could be done via a decorator. It all depends on how far you will need to go with your UI elements. Good Luck, it is not an easy task
EDT: Apply MVC wherever you can. The first candidates are any kind of list displays, don't make them responsible for keeping the items they are displaying. This definitely goes for the combo box, a list box, tables and trees, you could implement this for text inputs but that might not be worth the overhead.


q: I am using SQL Advantage and need to know what the SQL is to identify the triggers associated with a table.  I don't have the option to use another tool so the good old fashioned SQL solution is the ideal answer.

[A]
```
select *
from sysobjects
where type = 'TR'
```
Taken from
here
.


q:
Is it possible to create and initialise a System.Collections.Generic.Dictionary object with String key/value pairs in one statement?

I'm thinking along the lines of the constructor for an array of Strings..

e.g.

Private mStringArray As String() = {"String1", "String2", "etc"}

In case this is turns out to be a syntactic sugar kind of thing, I'd prefer an answer that I can use in .Net 2.0 (Visual Studio 2005), and Visual Basic - though I'm curious if it's possible at all so don't let that put you off ;o)

[A]
Try this syntax:
```
```
Dictionary<string, double> dict = new Dictionary<string, double>()
{
  { "pi", 3.14},
  { "e", 2.71 }
 };
```
```
But that may require C# 3 (.NET 3.5)


q:
I want to pass in the tType of a class to a function, and the class object to a generic function.

I need to be able to cast to that Type (of class) so I can access the class's methods.

Something like:

void GenericFunction(Object obj, Type type)
{
    (type)obj.someContainer.Add(1);
}

Would implementing an interface for these classes and then casting to that interface work?
If so, could someone give an example?

I've been Googling for the past few hours, and I've never had to do this before.

Can someone shed some light?

[A]
Can you use generics in your method call? Something like:
```
```
void GenericFunction<T>(Object obj)
  where T : class {
  obj.someContainer.Add(1) as T;
}
```
```
Hope that helps!


q:
there was a somewhat detailed thread (228684) on how to globally (using extern struct) declare a structure that could be seen in more than 1 c++ file, but I can not figure out exactly how to do it (there was a lot of discussion about do this, do that, maybe do this, try this, etc...).

couuld someone please post a very simple example of how to declare a structure that could be seen in 2 separate c++ files?  If I put all my functions in the same file as the main it works fine, but when I try to split the functions out in different files I cannot get it to compile.

Things I am unclear on...
Should I typedef the structure?
Do I define the structure in a header file and include that header in each c++ source file?
Do I need the #ifndef macro in the header file?
Do I declare the structure extern in the header?

[A]
It's called a header file.
in your header file (call it foo.h)
```
```
#ifndef FOO_H
#define FOO_H
class X {
};
#endif
```
```
Then, in any C files you have
```
```
#include "foo.h"
X x;
```
```
For C++ it's more common/preferred to use class, but you can use struct as well.  The extern keyword generally refers to variables, not class/struct declarations.  You would make a global variable extern in a header file (then declare it not-extern) in one of your .cpp files.


q:
I have a collection of collections, all the child collections have the same number of elements. The parent collection does nothing other than hold the child collections.

[0] [Child_0] [ID: 1]
[0] [Child_0] [Amount: 4]
[0] [Child_1] [ID: 2]
[0] [Child_1] [Amount: 7]
[1] [Child_0] [ID: 1]
[1] [Child_0] [Amount: 2]
[1] [Child_1] [ID: 2]
[1] [Child_1] [Amount: 4]
[2] [Child_0] [ID: 1]
[2] [Child_0] [Amount: 5]
[2] [Child_1] [ID: 2]
[2] [Child_1] [Amount: 3]

For my output I don't care about the parent collection. I just want an anonymous type of ID and average of amounts, so for the above it would be

ID     Avg
1      3.66
2      4.66

Language of the response does not matter.

Thanks.

[A]
you may be able to us this as a guide
```
```
var items = new[]
        {
            new { ID = 1, Amount = 4 },
            new { ID = 1, Amount = 5 },
            new { ID = 2, Amount = 5 },
            new { ID = 2, Amount = 3 },
        };

        var results = from item in items group item by item.ID into g select new { ID = g.Key, Avg = g.Average(item => item.Amount) };

        foreach (var result in results)
        {
            Console.WriteLine("{0} - {1}", result.ID, result.Avg);
        }
```
```


q: Is there a way to get drop_receiving_element to not generate "// ..

[A]
The code for the
```
drop_receiving_element
```
is
```
```
def drop_receiving_element(element_id, options = {})
  javascript_tag(drop_receiving_element_js(element_id, options).chop!)
end
```
```
```
javascript_tag
```
is what adds the script tags, so it looks like you should just be able to leave those out, and enter this yourself.
```
```
drop_receiving_element_js(element_id, options).chop!
```
```
Note: It might be a private method, in which case just use
```
```
send(:drop_receiving_element_js, element_id, options).chop!
```
```


q:
I have a database that hold's a user's optional profile. In the profile I have strings, char (for M or F) and ints.

I ran into an issue where I try to put the sex of the user into the property of my Profile object, and the application crashes because it doesn't know how to handle a returned null value.

I've tried casting the data to the appropriate type

char sex = (char)dt.Rows[0]["Sex"];

Which didn't fix my problem. I then tried changing the types to Nullable and Nullable and get conversion issues all the same. My current solution that I was able to find is the following:

object.sex = null;
if(dt.Rows[0]["Sex"] != DBNull.Value)
      object.sex = (char)dt.Rows[0]["Sex"];
object.WorkExt = null;
if(dt.Rows[0]["WorkExt"] != DBNull.Value)
      object.WorkExt = (int)dt.Rows[0]["WorkExt"];

Is there a simpler or better way to do this? Or am I pretty much on the right track?

[A]
I would do it pretty much like you did. I would write a function for it:
Something that does:
```
```
object.sex = handle(dt.Rows[0]["Sex"]);
```
```
And in handle you do the ==DBNull.Value check.


q:
Using MySQL syntax and having a table with a row like:

mydate DATETIME NULL,

Is there a way to do something like:

... WHERE mydate<='2008-11-25';

I'm trying but not really getting it to work.

[A]
Nevermind found an answer. Ty the same for anyone who was willing to reply.
```
```
WHERE DATEDIFF(mydata,'2008-11-20') >=0;
```
```


q:
I am creating a jQuery plugin.

How do I get the real image width and height with Javascript in Safari?

The following works with Firefox 3, IE7 and Opera 9:

var pic = $("img")

// need to remove these in of case img-element has set width and height
pic.removeAttr("width");
pic.removeAttr("height");

var pic_real_width = pic.width();
var pic_real_height = pic.height();

But in Webkit browsers like Safari and Google Chrome values are 0.

[A]
this works for me (safari 3.2), by firing from within the
```
window.onload
```
event:
```
```
$(window).load(function() {
  var pic = $('img');

  pic.removeAttr("width");
  pic.removeAttr("height");

  alert( pic.width() );
  alert( pic.height() );
});
```
```


q:
I am new with Linq and I would like to sort some data that are in the BindingList. Once I did my Linq query, I need to use back the BindingList collection to bind my data.

 var orderedList = //Here is linq query
 return (BindingList<MyObject>)orderedList;

This compiled but fails in execution, what is the trick?

[A]
```
```
new BindingList<MyObject>(orderedList.ToList())
```
```


q:
We have a server (written in C and C++) that currently catches a SEGV and dumps some internal info to a file. I would like to generate a core file and write it to disk at the time we catch the SEGV, so our support reps and customers don't have to fuss with ulimit and then wait for the crash to happen again in order to get a core file. We have used the abort function in the past, but it is subject to the ulimit rules and doesn't help.

We have some legacy code that reads /proc/pid/map and manually generates a core file, but it is out of date, and doesn't seem very portable (for example, I'm guessing it would not work in our 64 bit builds). What is the best way to generate and dump a core file in a Linux process?

[A]
Some possible solutions^W ways of dealing with this situation:
Fix the ulimit!!!
Accept that you don't get a core file and run inside gdb, scripted to do a "thread all apply bt" on SIGSEGV
Accept that you don't get a core file and acquired a stack trace from within the application. The
Stack Backtracing Inside Your Program
article is pretty old but it should be possible these days too.


q:
I recently watched this youtube tutorial on the Null Object design pattern. Even though there were some errors in it: such as the NullCar that doesn't do anything creates an infinite loop, the concept was well explained. My question is, what do you do when the objects that can be null have getters, and are used in your code? How do you know which value to return by default? Or should I implement this pattern inside all the objects? What if I need to return strings or primitives? I'm talking from a Java perspective.

EDIT: won't I be trading null objects testing for default value testing ? If not , why not ?

[A]
As far as I've understood it the idea is that the null object's value is as close to "nothing" as possible. That unfortunately means you have to define it yourself. As an example I personally use "" when I can't pass a null String, null object number for me is -1 (mostly because by default most database sequences start at 1 and we use those for item id:s a lot so -1 is dead giveaway it's a null object), with lists/maps/sets it's
```
Collections.EMPTY_SET
```
,
```
EMPTY_MAP
```
or
```
EMPTY_LIST
```
and so on and so forth. If I have custom class I have to create a null object from, I remove all actual data from it and see where that takes me and then apply what I just mentioned until it's "empty".
So you really don't "know" which value to return by default, you just have to decide it by yourself.


q:
I am using C# 3.0 / .NET 3.5 and planning to build an eCommerce website.

I've seen NHibernate, LLBLGEN, Genome, Linq to SQL, Entity Framework, SubSonic, etc.

I don't want to code everything by hand. If there is some specific bottleneck I'll manage to optimize the database/code.

Which ORM would be best? There is so much available those day that I don't even know where to start.

Which feature(s) should I be using?

Links, Screencast and Documentation are welcome.

[A]
I can only really speak for LINQ-SQL and can say that it is:
Easy to use
Quick to get you up and running
Good for simple schemas and object models
but it starts to fall down if:
You're using a disconnected (tiered) architecture because its datacontexts require the same object instances to perform tracking and concurrency (though there are ways around this).
You have a complex object model / database
Plus it has some other niggles and strange behaviour
I'm looking to try EF next myself and MS seem to be quietly dropping LINQ-SQL in favour of EF, which isn't exactly a ringing recommendation of LINQ-SQL :)


q:
Let's say I create a website like StackOverFlow and decide to use OpenID. What's to prevent me, or anyone else for that matter, from phishing the ID's? That is, how can you truly know that any website is using OpenID and not pretending to? And how do you protect myself against this?

Expanding on this, let's say one site did compromise your openID credentials, couldn't they use it on every other site using openID (a global password hack)? Wouldn't then the security of your openID then only be as strong as the weakest website/provider?

[A]
All you enter is the ID, no password. The ID is public, therefore "phishing" it is not a security hole. Some providers even use the same ID for all users, for instance the ID for a google account is always
```
https://www.google.com/accounts/o8/id
```
. See the
Wikipedia article
for a more detailed explanation.


q: I have one java program that has to be compiled as 1.4, and another program that could be anything (so, 1.4 or 1.6), and the two need to pass serialized objects back and forth. If I define a serializable class in a place where both programs can see it, will java's serialization still work, or do I need 1.6-1.6 or 1.4-1.4 only?

[A]
Make sure the classes to be serialized define and assign a value to
```
static final long serialVersionUID
```
and you should be ok.
That said, normally I would not do this.  My preference is to only use normal serialization either within a single process, or between two processes are on the same machine and getting the serialized classes out of the same jar file.  If that's not the case, serializing to XML is the better and safer choice.


q: Does anyone know of a good tool that converts .pst to .csv files through command line?

[A]
one time only? or programmatically?
if one time only, import into a mail program that handles mbox (e.g. Thunderbird), at which point you just have text files, manipulate as desired.
otherwise, no idea, best of luck.


q:
I was using jQuery plugins to create a rounded corner for my <li>, but it was not working on a lot of browsers and didn't support mouse over.

I am wondering what is the best way to use two images (left corner and right corner) as the left and right side with using <li>.

[A]
You could put Divs inside your li's like so:
```
```

Foo

```
```
That way you will both keep your semantics and will also have the cross-browser support of styling DIVs.


q:
Lets say you have a:

List<string> los = new List<string>();

In this crazy functional world we live in these days which one of these would be best for creating one string by concatenating these:

String.Join(String.Empty, los.ToArray());

StringBuilder builder = new StringBuilder();
los.ForEach(s => builder.Append(s));

string disp = los.Aggregate<string>((a, b) => a + b);

or Plain old StringBuilder foreach

OR is there a better way?

[A]
I would go with option A:
```
```
String.Join(String.Empty, los.ToArray());
```
```
My reasoning is because the Join method was written for that purpose. In fact if you look at Reflector, you'll see that unsafe code was used to really optimize it. The other two also WORK, but I think the Join function was written for this purpose, and I would guess, the most efficient. I could be wrong though...
As per @Nuri YILMAZ without
```
.ToArray()
```
, but this is .NET 4+:
```
```
String.Join(String.Empty, los);
```
```


q:
I have following POJOs:

class Month {
    long id;
    String description;
    List<Day> days; // always contains 29, 30 or 31 elements
}

class Day {
    byte nr; // possible values are 1-31
    String info;
}

Is there a way to store these objects into following DB structure using JPA+Hibernate:

Table MONTHS:

id;description;

Table DAYS:

id-of-month;nr-of-day;info;

Any better solution for this situation?

[A]
Here is one solution I found:
```
```
class Month {
    long id;
    String description;

    @CollectionOfElements(fetch = FetchType.EAGER)
    @IndexColumn(name = "nr-of-day")
    List<Day> days; // always contains 29, 30 or 31 elements
}

@Embeddable
class Day {
    byte nr; // possible values are 1-31
    String info;
}
```
```
@CollectionOfelements and @IndexColumn are Hibernate annotations. If I use @OneToMany annotation available in JPA, hibernate creates 3 tables instead of 2.
My only problem now is that Day.nr is saved twice: first as IndexColumn of the List (0-based counter) and second time as field of class Day (1-based counter).


q:
I am trying to map a virtual keycode to a char.

My code uses ProcessCmdKey to listen to WM_KEYDOWN which gives me access to the key pressed. For example, when I press single quote I get a key of 222 which I want to have it mapped to keychar 39 which represents... you guessed it... single quote.

My dev context is:
- .net Framework 2.0
- UserControl placed in a lot of places

Do you know the answer to the question?

[A]
Yes, I did use the
```
MapVirtualKey
```
method. But I was expecting more details on how to use it: what
```
DllImport
```
directive to use, what
```
enum
```
is specific for mapping to characters, etc.
I don't like these answers where you google for like 5 seconds and then just suggest a solution: the real challenge is to put all the pieces together and not have to waste your time with tons of sample-less MSDN pages or other coding forums in order to get your answer. No offense plinth, but your answer (even good) was worhtless since I had this answer even before posting my question on the forum!
So there you  go, I am going to post what I was looking for - an out-of-the-box C# solution:
1- Place this directive inside your class:
```
```
[DllImport("user32.dll")]
static extern int MapVirtualKey(uint uCode, uint uMapType);
```
```
2- Retrieve your char like this:
```
```
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
  {
     const int WM_KEYDOWN = 0x100;

     if (msg.Msg == WM_KEYDOWN)
     {
        // 2 is used to translate into an unshifted character value
        int nonVirtualKey = MapVirtualKey((uint)keyData, 2);

        char mappedChar = Convert.ToChar(nonVirtualKey);
     }

     return base.ProcessCmdKey(ref msg, keyData);
  }
```
```
Thanks for caring... and enjoy!


q: What is the Emacs mode or package that highlights Lisp forms changing the color of the backgrounds so that the form you are in has one color, the outer form another, the outer outer form another and so on?

[A]
You may want to try
mwe-color-box
(screenshot below) or read
Five approaches to s-expression highlighting
by
Lemondor
.
(source:
foldr.org
)


q: I'd like to programatically determine the encoding of a page via JavaScript, or some other API from a browser. The reason I want this information is because I am attempting to fuzz major browsers on what character encodings they support, and obviously just because I sent the appropriate "Content-Type" doesn't mean that the browser will do the right thing with the encoding. Any other possible methods would be welcome, but I would rather not click "Page Info" for 50+ character encodings.

[A]
Javascript can only report some of the things that are going on. Most browsers won't expose enough useful settings to you for you to base any hardcore tests on.
There are things such as
```
document.inputEncoding
```
,
```
document.characterSet
```
(non IE),
```
document.charset
```
, and
```
document.defaultCharset
```
(IE) which might get you some of the way there. But these might be as flaky as the actual support. That is, if a browser "thinks" it supports an encoding but really doesn't, isn't that something you want to know?
I think your best bet is to set up a dynamic test page with some fairly difficult characters on it (or a really large test set), load test in a browser, have the browser report back browser id string, encoding settings, original encoding request, and contents of
```
testElement.innerHTML
```
which you can then verify against expected results.


q: I've often heard Ruby's inject method criticized as being "slow." As I rather like the function, and see equivalents in other languages, I'm curious if it's merely Ruby's implementation of the method that's slow, or if it is inherently a slow way to do things (e.g. should be avoided for non-small collections)?

[A]
```
inject
```
is like
```
fold
```
, and can be very efficient in other languages,
```
fold_left
```
specifically, since it's tail-recursive.


q:
Is this right for When 4 < 5 and 1 < 2 ?

<xsl:when test="4 &lt; 5 AND 1 &lt; 2" >
<!-- do something -->
</xsl:when>

[A]
From
XML.com
:
Like xsl:if instructions, xsl:when
  elements can have more elaborate
  contents between their start- and
  end-tags—for example, literal result
  elements, xsl:element elements, or
  even xsl:if and xsl:choose elements—to
  add to the result tree. Their test
  expressions can also use all the
  tricks and operators that the xsl:if
  element's test attribute can use, such
  as and, or, and function calls, to
  build more complex boolean
  expressions.


q:
I have TFS installed on a single server and am running out of space on the disk. (We've been using the instance for about 2 years now.)

Looking at the tables in SQL Server what seems to be culprit is the tbl_content table, it is at 70 GB.  If I do a get on the entire source tree for all projects it is only about 8 GB of data.

Is this just all the histories of the files?  It seems like a 10:1 ratio just the histories...since I would think the deltas would be very small.

Does anyone know if that is a reasonable size given 8 GB of source (and 2 yrs of activity)?  And if not what to look at to 'fix' this?

Thanks

[A]
I can't help with the ratio question at the moment, sorry. For a short-term fix you might check to see if there is any space within the DB files that can be freed up. You may have already, but if not..
```
```
SELECT name ,size/128.0 - CAST(FILEPROPERTY(name, 'SpaceUsed') AS int)/128.0 AS AvailableSpaceInMB
FROM sys.database_files;
```
```
If the statement above returns some space you want to recover you can look into a one time  DBCC SHRINKDATABASE or DBCC SHRINKFILE along with scheduling routine SQL maintenance plan that may include defragmenting the database.
DBCC SHRINKDATABASE and DBCC SHRINKFILE aren't things you should do on a regular basis, because SQL Server needs some "swap" space to move things around for optimal performance. So neither should be relied upon as your long term fix, and both could cause some noticeable performance degradation of TFS response times.
JB


q:
I have a table with a binary column which stores files of a number of different possible filetypes (PDF, BMP, JPEG, WAV, MP3, DOC, MPEG, AVI etc.), but no columns that store either the name or the type of the original file.  Is there any easy way for me to process these rows and determine the type of each file stored in the binary column?  Preferably it would be a utility that only reads the file headers, so that I don't have to fully extract each file to determine its type.

Clarification:  I know that the approach here involves reading just the beginning of each file.  I'm looking for a good resource (aka links) that can do this for me without too much fuss.  Thanks.

Also, just C#/.NET on Windows, please.  I'm not using Linux and can't use Cygwin (doesn't work on Windows CE, among other reasons).

[A]
This is not a complete answer, but a place to start would be a "magic numbers" library. This examines the first few bytes of a file to determine a "magic number", which is compared against a known list of them.  This is (at least part) of how the
```
file
```
command on Linux systems works.


q:
Is there a way to set a maximum size for files that can be check in into source control under Team Foundation Server 2005 or 2008?

In the past, when we worked with SourceSafe there were several cases were developers decided to checkin a 500mb data file to source control.

I don't know what such a thing will do to TFS - and actually, I don't want to find out.

Edit: Custom checkin policy is not a viable solution for two reasons:

it is done in the client side - I want the server to protect itself from such an abuse

custom checkin policy can be overridden by the user.

[A]
I can only give a partial answer but I think the reason that
```
```
public void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
                libDataGrid.DataSource = this.manager.Lib.LibList;
                libDataGrid.Refresh();
        }
```
```
isn't working, is because you need to add this line where tabControl1 is being initialized.  I've had this problem where VS won't do this itself.
```
```
tabControl1.SelectedIndexChanged += new EventHandler(tabControl1_SelectedIndexChanged);
```
```


q:
i've populated a dropdownlist control with different text properties but each text properties had THE SAME value (text property was A, value properties is blah,text property was B, value properties is blahblah, etc... )

ASP.net only checks value properties on postback and because ALL values were the same (for
testing reason) this little annoying behavior happened. Is there a work around? does this mean you can't never have the value to be the same?

[A]
Sounds like you are working on the wrong event. Try
SelectedIndexChanged
.
Ensure you also have the
```
AutoPostBack
```
property set to
```
True
```
.
Resolved
OK, so I got digging on this since I was curious :)
There is a "problem" when databinding with non-unique values.
So, firstly, I publicly apologise for saying otherwise.
To replicate:
ASPX
```
```
<asp:DropDownList ID="myDDL" runat="server" AutoPostBack="True">
    </asp:DropDownList>
    <asp:Label ID="lblSelItem" runat="server"Text="Currently Selected Item: 0"></asp:Label>
    <asp:Label ID="lblSelVal" runat="server" Text="Currently Selected Value: X"></asp:Label>
```
```
Code-Behind
```
```
List<string> MyData()
    {
        List<string> rtn = new List<string>();
        rtn.Add("I am the same value!");
        rtn.Add("I am the same value!");
        rtn.Add("I am the same value!");
        rtn.Add("I am the same value!2");
        return rtn;
    }

    protected void Page_Init()
    {
        if (!Page.IsPostBack)
        {
            // Load the Data for the DDL.
            myDDL.DataSource = MyData();
            myDDL.DataBind();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        // Display the Currently Selected Item/Value.
        lblSelItem.Text = "Currently Selected Item: " + myDDL.SelectedIndex.ToString();
        lblSelVal.Text = "Currently Selected Value: " + myDDL.SelectedValue;
    }
```
```
Run, changing the values in the DropDownList. Note that a PostBack does not occur.
When looking at the Source, I realised that we need to explicitly set the "
```
value
```
" attribute for the
```
<option>
```
elements generated by the server control, which lead me to do something like:
New Code-Behind
```
```
Dictionary<string, string> MyTwoColData()
    {
        Dictionary<string, string> rtn = new Dictionary<string, string>();
        rtn.Add("1", "I am the same value!");
        rtn.Add("2", "I am the same value!");
        rtn.Add("3", "I am the same value!");
        return rtn;
    }

    protected void Page_Init()
    {
        if (!Page.IsPostBack)
        {
            // Load the Data for the DDL.
            Dictionary<string, string> data = MyTwoColData();

            foreach (KeyValuePair<string, string> pair in MyTwoColData())
            {
                myDDL.Items.Add(new ListItem(pair.Value, pair.Key));
            }

            myDDL.DataBind();
        }
    }
```
```
This explcitly sets the values to the "1", "2", "3" etc making them unique, while still displaying the correct data within the list.
Obviously, you can change this to work with single-column lists but just running through a for loop and using the value of
```
i
```
or something.
As to good workarounds with DataSets, not sure.
Realistically, would we present a list of options with the exact same values to the user?
I personally think not, which is probably why this "problem" hasn't been addressed :)
Enjoy!
PS:
Oh, I should also add, if you want to use the text value in the "fix" then change it to
```
SelectedItem
```
rather than
```
SelectedValue
```
.


q:
Testing:

return request.getCookies() == null;

is not an appropriate way test. Is there another way?

[A]
You generally want to use JavaScript to determine if the client's browser has cookies enabled:
```
```
<script type="text/javascript">
var cookieEnabled=(navigator.cookieEnabled)? true : false

//if not IE4+ nor NS6+
if (typeof navigator.cookieEnabled=="undefined" && !cookieEnabled){
document.cookie="testcookie"
cookieEnabled=(document.cookie.indexOf("testcookie")!=-1)? true : false
}

//if (cookieEnabled) //if cookies are enabled on client's browser
//do whatever

</script>
```
```


q:
I can't find a good way of putting Eclipse windows on two monitors. Currently I just detached (clicked on a header and dragged) a few windows to a secondary monitor (package explorer, console, and outline) while leaving primary monitor with maximized source editing window.

It works pretty well except few annoying issues. Detached windows are not in focus while you are editing your code. Which means that, for example, last build shortcut (Alt-Shift-X, Q) doesn't work because it can't find build file (because package explorer is not in focus). Also "Selected resources" option in a file search menu is not picking up current package selection.

So I was wondering is detaching windows a right way to go? Do you have any better solutions so at least package explorer stays in focus?

Thanks.

PS. Btw "unable to find build" error started showing up only in 3.4 ver for some reason.

[A]
I split the eclipse environment over two monitors (both running at 1600*1200)
on the left I have the main coding window maximised with the outline down the right hand side.
On the second monitor I have the Junit window, Problems, Console and the package explorer
I have the same layout duplicated for all the perspectives that I use.
I have never used the
Alt
-
Shift
-
Q
short cut but I have found the
Alt
-
Shift
-
X
,
T
shortcut for running junit works fine when I am focussed in the main coding window .
Possibly have the package explorer on the same monitor as the coding window?


q:
How do I convert a string into the corresponding code in PLT Scheme (which does not contain the string->input-port method)?  For example, I want to convert this string:

"(1 (0) 1 (0) 0)"

into this list:

'(1 (0) 1 (0) 0)

Is it possible to do this without opening a file?

[A]
From this similar question on
comp.lang.scheme
you can save the string to a file then read from it.
That might go something like this example code:
```
```
(let ((my-port (open-output-file "Foo")))
  (display "(1 (0) 1 (0) 0)" my-port)
  (close-output-port my-port))

(let* ((my-port (open-input-file "Foo"))
       (answer (read my-port)))
  (close-input-port my-port)
  answer)
```
```


q:
i have a basic ruby class:

class LogEntry

end

and what i would like to do is be able to define a hash with a few values like so:

EntryType = { :error => 0, :warning => 1, :info => 2 }

so that i can access the values like this (or something similar):

LogEntry.EntryType[:error]

is this even possible in Ruby? am i going about this the right way?

[A]
You can do this:
```
```
class LogEntry
    EntryType = { :error => 0, :warning => 1, :info => 2 }
end
```
```
But you want to reference it as
```
```
LogEntry::EntryType[:error]
```
```


q:
I have a calendar control derived from DataGridView. A custom item hover event is already in place. When handling the event, I have the item that was hovered and the mouse location. What is the best method to show a pop-up window with detailed information about the item? Should I use a stripped down form (no titlebar,controlbox, etc) and simply close it on the MouseLeave? Is there a better way?

Thanks!

[A]
Any type of Control, a Panel, a UserControl, etc. These will do as long as they doesn't have to pop outside the current form. If it needs to pop outside you might need to use a Form as you stated and removes it's border.
Pre create the Control or Form in the main form, then when the mouse hover the needed control, make the pop control visible, and when the mouse leaves, make it invisible.
Just watch out for the mouse events though, they could get caught by the newly poped control. This might require a little positioning gymnastic as you will have to offset the position so that the cursor never gets to hover the poped control.
Take example on Microsoft Windows tooltip.


q:
Let's say I have a table like this:

name | score_a | score_b
-----+---------+--------
 Joe |   100   |   24
 Sam |    96   |  438
 Bob |    76   |  101
 ... |   ...   |  ...

I'd like to select the minimum of score_a and score_b. In other words, something like:

SELECT name, MIN(score_a, score_b)
FROM table

The results, of course, would be:

name | min
-----+-----
 Joe |  24
 Sam |  96
 Bob |  76
 ... | ...

However, when I try this in Postgres, I get, "No function matches the given name and argument types. You may need to add explicit type casts." MAX() and MIN() appear to work across rows rather than columns.

Is it possible to do what I'm attempting?

[A]
LEAST
(a, b):
The
```
GREATEST
```
and
```
LEAST
```
functions select the largest or smallest value from a list of any number of expressions. The expressions must all be convertible to a common data type, which will be the type of the result (see
Section 10.5
for details). NULL values in the list are ignored. The result will be NULL only if all the expressions evaluate to NULL.
Note that
```
GREATEST
```
and
```
LEAST
```
are not in the SQL standard, but are a common extension. Some other databases make them return NULL if any argument is NULL, rather than only when all are NULL...


q:
Here's the problem:

1.) We have page here... www.blah.com/mypage.html

2.) That page requests a js file www.foo.com like this...

<script type="text/javascript" src="http://www.foo.com/jsfile.js" />

3.) "jsfile.js" uses Prototype to make an Ajax request back to www.foo.com.

4.) The ajax request calls www.foo.com/blah.html. The callback function gets the html response and throws it into a div.

This doesn't seem to work though, I guess it is XSS. Is that correct?

If so, how can I solve this problem? Is there any other way to get my html from www.foo.com to www.blah.com on the client without using an iframe?

[A]
It is XSS and it is forbidden. You should really not do things that way.
If you really need to, make your AJAX code call the local code (PHP, ASP, whatever) on blah.com and make it behave like client and fetch whatever you need from foo.com and return that back to the client. If you use PHP, you can do this with fopen('www.foo.com/blah.html', 'r') and then reading the contents as if it was a regular file.
Of course, allow_remote_url_fopen (or whatever it is called exactly) needs to be enabled in your php.ini.


q:
I would like to apply a transformation (rotation) to a UIImageView. I could just set the transform property of the view, but wouldn't setting the layer's transform make it faster? If so, how can I achieve this?

Assuming I have a UIImageView initialized with an image, can anyone help? Wouldn't it be better to have a UIVIew with a UIImageView in it?

[A]
If you're doing a simple rotation, the speed difference is probably insignificant, but you can get access to a view's layer by doing:
```
view.layer
```
So, you can just use
```
view.layer.affineTransform = newTranform;
```


q:
In my application I need to temporarily gray out the minimize button of the main form. Any ideas how this can be achieved? I don't mind doing p/invokes to Win32 dlls.

Edit: Graying out the minimize button would be the preferred solution, but is there any other way of preventing the form from becoming minimized?

[A]
```
```
form.MinimizeBox = false;
```
```
or if in the form scope
```
```
MinimizeBox = false;
```
```


q:
Is there an easy way write to a file asynchronously in Python?

I know the file io that comes with Python is blocking; which is fine in most cases.  For this particular case, I need writes not to block the application at all, or at least as minimally as possible.

[A]
Twisted has
non-blocking writes on file descriptors
.  If you're writing async code, I'd expect you to be using twisted, anyway.  :)


q:
I want boost::any_cast<T> to only throw an exception when the type of the any doesn't have an implicit conversion to T. The normal behaviour seems to be to throw an exception if the type of the any is not T, regardless of implicit conversions.

Example:

boost::any a = 1;
boost::any_cast<int>(a); // This succeeds, and rightfully so
boost::any_cast<long>(a); // I don't want this to throw
boost::any_cast<Widget>(a); // I want this to throw

Could anyone tell me if there's a simple way to get the functionality I want, or better yet give me a good reason for why the existing behaviour is the way it is?

[A]
Well you can't do it. The
```
any
```
mechanism works like this:
```
```
struct base {
    virtual ~base() { }
};

template<typename T>
struct concrete_base : base {
    T t;
    concrete_base(T t):t(t) { }
};

struct my_any {
    base * b;

    template<typename T>
    my_any(T t):b(new concrete_base<T>(t)) { }

    template<typename T>
    T any_cast() {
        concrete_base<T> * t = dynamic_cast< concrete_base<T>* >(b);
        if(!t) throw bad_any_cast();
        return t->t;
    }
};
```
```
I hope it's clear what the above does. There is no way you could do what you are looking for i think. The reason is that there is no information about the type kept that could prove useful here. RTTI doesn't provide it.


q:
I have an XML definition that contains an element with child elements. For example:

<a>
 <b>
  <c>C</c>
  <d>D</d>
 </b>
</a>

I have an XSLT with an output of text. For example:

<xsl...>
  <xsl:output method="text" indent="yes"/>
  <xsl:template match="/">
    <xsl:copy-of select="/a/b" />
  ...

I want to copy the entire b element and its children into a whitespace-removed string so that I can generate a SQL query. For example:

select * from some-table where xml = '<b><c>C</c><d>D</d></b>'

At the moment copy-of is finding the b element but dropping off all element and attribute information leaving only the text content within each. I think this might be to do with the output type.

Any ideas?

[A]
Your SQL statement scares me. XML is case-sensitive, and your comparison there is likely to fail if the input XML and XSLT (including all elements, attributes, and values) aren't cased exactly like that used in the original database insert.
I believe both Oracle (certain) and SQL Server (think so) have mechanisms to do a query against a column containing XML in a more XML-friendly way (for instance, using XPath).
What exactly are you trying to do? Your problem seems deeper than just getting this XSLT to transform correctly.


q:
I'm working on +1M LOC C/C++ project on Solaris (remote, via VNC or SSH). I have a daily updated copy of source code on my local machine too (Windows, just for browsing code).

I use VIM and ctags combo (on both Solaris and Windows) but I'm not happy with results / speed. What settings for ctags would you recommend? There are a lot of options what should be tagged and how. Should I use single tag file per project, per dir or perhaps just one for everything?


q:
I understand the first argument must be the result of GetFileVersionInfo().

The third and forth are target buffer and size

What is the second argument, lpSubBlock?

Thanks In Advance

[A]
It must be a string whose format you can find here:
http://www.hep.wisc.edu/~pinghc/books/apirefeng/v/verqueryvalue.html
There is another example of usage (in VB, easy to read):
http://support.microsoft.com/kb/160042
You can also check out this whole CodeProject article for a working example in C++:
http://www.codeproject.com/KB/cpp/GetLocalVersionInfos.aspx
Another article on the subject of retrieving version information:
http://www.microsoft.com/msj/0498/c0498.aspx


q:
Is there a way to change SQL Reporting "chart type" and "sub type" at runtime?

I'm working with a .rdlc report and can't seem to figure out the way to change this at runtime.  I don't have the "Expression" ability in either of these fields.

[A]
I am trying to do this exact same thing.  I have a set of measures that are shown and then a chart underneath that will show only one measure at a time, depending on user input (which of the measures they wish to see in chart form).  However, certain measures are better as columns instead of lines, so I'd like to change the chart type at render-time.
My initial idea is to overlap two charts and set their visibility opposite of each other and according to the user dropdown input.  Seems like there could be an easier way (if that idea would even work in the first place?)
Thanks.


q:
How would you take an arbitrary list of strings (of the form "%[text]%") and a database column, and turn them into a SQL query that does a LIKE comparison for each string in the list?

An example: I have three strings in my list, "%bc%", "%def%" and "%ab%". This builds the query:

([ColumnName] LIKE "%bc" AND [ColumnName] LIKE "%def%") AND [ColumnName] LIKE "%ab%"

A C# example would be excellent, but feel free to write it in the language of your choice.

[A]
It's just a string join on a map:
```
```
>>> los=['ab', 'cd', 'ef']
>>> ' and '.join(("somecolumn like '%%%s%%'" % s) for s in los)
"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'"
```
```
or
```
```
>>> ' and '.join(("somecolumn like '%" + s + "%'") for s in los)
"somecolumn like '%ab%' and somecolumn like '%cd%' and somecolumn like '%ef%'"
```
```


q: Would someone explain how to get LINQ working with Sqlite.

[A]
Check this provider:
SqlLite Linq Provider
Also you can consider using
SQL Compact
which has very good LINQ-to-SQL support.


q:
I'll have couple of python functions I must interface with from the assembly code. The solution doesn't need to be a complete solution because I'm not going to interface with python code for too long. Anyway, I chewed it a bit:

What does a python object look like in memory?

How can I call a python function?

How can I pass python objects as python objects for ctypes interface?

Could ctypes interface make my work easier in any alternative way?

[A]
You will want to read and understand
Extending and Embedding the Python Interpreter
and the
Python/C API Reference Manual
. This describes how to interface with Python from C. Everything you can do in C you can equivalently do in assembly code too, but you're on your own for this as it is not directly described from a Python perspective.


q:
Looks like my data warehouse project is moving to Teradata next year (from SQL Server 2005).

I'm looking for resources about best practices on Teradata - from limitations of its SQL dialect to idioms and conventions for getting queries to perform well - particularly if they highlight things which are significantly different from SQL Server 2005.  Specifically tips similar to those found in The Art of SQL (which is more Oracle-focused).

My business processes are currently in T-SQL stored procedures and rely fairly heavily on SQL Server 2005 features like PIVOT, UNPIVOT, and Common Table Expressions to produce about 27m rows of output a month from a 4TB data warehouse.

[A]
Top of the list on a Google search for "Teradata Best Practices" gave me
TERADATA ADVISORY GROUP SETS BEST PRACTICES FOR BUSINESS OBJECTS AND TERADATA CUSTOMERS
EDIT
: Seeing as that's just advertising, as you've pointed out, see how you go with these. Please bear in mind that I don't have a clue what Teradata is and can't see myself using it any time this side of the 22nd century AD.
Teradata Discussion Forums
Best Practices for Teradata Deployments
Best Study Guides For  NCR Teradata Certifications
The middle one looks promising with it's nice long link tree at the top
Oracle® Business Intelligence Applications Installation and Configuration Guide > Preinstallation and Predeployment Considerations for Oracle BI Applications > Teradata-Specific Database Guidelines for Oracle Business Analytics Warehouse >
and the first link, to the forums, should put you in touch with the right people.


q: I can not figure out what all the parameters to the arc() function are (by experimentation) and I have not found any tutorial that seems to explain them. Where would a good explanation of the arc() function be?

[A]
According to
MDC
:
```
```
arc(x, y, radius, startAngle, endAngle, anticlockwise)
```
```
x, y, and radius are obviously circle parameters.  startAngle and endAngle are in radians, starting east.  anticlockwise is a boolean.


q: What's the best way to validate that an IP entered by the user is valid?  It comes in as a string.

[A]
I think this would do it...
```
```
def validIP(address):
    parts = address.split(".")
    if len(parts) != 4:
        return False
    for item in parts:
        if not 0 <= int(item) <= 255:
            return False
    return True
```
```


q:
I have a vector with 1000 "nodes"

 if(count + 1 > m_listItems.capacity())
     m_listItems.reserve(count + 100);

The problem is I also clear it out when I'm about to refill it.

m_listItems.clear();

The capacity doesn't change.
I've used the resize(1); but that doesn't seem to alter the capacity.
So how does one change the reserve?

[A]
You could try this technique from
here
```
```
std::vector< int > v;
// ... fill v with stuff...
std::vector< int >().swap( v );
```
```


q:
I'm going to be developing a C++ application that uses a MySQL database.

I've written similar apps in Java using JDBC, as well as the Spring Framework.

Are there equivalent libraries for C++?  What have you had the most success with?

[A]
It looks like writing a data access layer using the
MySQL C API
is going to be the best bet.


q: So I added an EXE to my project's solution. The EXE does some stuff and outputs data via stdout. I want to capture the output, but more importantly how do I execute that EXE within my program?

[A]
```
Process.Start
```
. To capture stdout you need to redirect it via
```
ProcessStartInfo
```
- there is an example on
MSDN
. Make sure also that the exe is marked to be copied to the output directory (bin/release etc).
If you need to read from both stdout and stderr it gets tricky (with a naïve implementation there is a risk of deadlock due to buffering etc)...
here's
an example using worker threads.


q: I love stretching my terminal on unix. What is the history or reason behind windows lame command line?

[A] It isn't. You can right click the title bar, select properties, and in the "Layout" tab alter the screen buffer size (line width and scrollback) and the window size (viewport size). If you started cmd from a shortcut, you can save these settings for future sessions.


q: I have a SQL Server database and I want to know what columns and types it has. I'd prefer to do this through a query rather than using a GUI like Enterprise Manager. Is there a way to do this?

[A]
There are a few methods to get metadata about a table:
```
```
EXEC sp_help tablename
```
```
Will return several result sets, describing the table, it's columns and constraints.
The
```
INFORMATION_SCHEMA
```
views will give you the information you want, though unfortunately you have to query the views and join them manually.


q:
I have a problem with time

My server is in the USA and I'm in Denmark (Europa) and I would like to have my site show the time in my local time.  How can I do that?

I try this

Datetime localtime = DateTimeOffset.Now.ToOffset(new TimeSpan(1,0,0)).DateTime;

and it works, but it will only work when I'm in GMT+1 / UTC+1 and not when I'm in GMT+2 / UTC+2.
Is there another way of doing this - a simpler way of doing it?

[A]
You can get the time off the server and do this.
```
```
DateTime myTimeGMT = ServerTime.ToUniversalTime();
```
```
This do this:
```
```
DateTime myTimeLocal = myTimeGMT.ToLocalTime();
```
```
The only restriction here is the computer you are on must be set to the time zone you are converting to.
In my experience, .NET has trouble converting between timezones when neither the 'From' time or the 'To' time are the local time zone.
I hope this helps.


q:
I have a column in my database (a flag) with type varchar(1) that is populated either Y or NULL (this is how it is, not in my control).

In SQL Server, doing an ascending order by query, NULL is ordered at the top. Should this behaviour be consistent for Oracle and DB2?

If, instead I have a COALESCE on the column to ensure it is not null in the query, am I likely to hit any performance issues (due to table scans and the like)?

EDIT

The query needs to be consistent over all 3 databases, otherwise I will have to handle it in code, hence my thinking of using the COALESCE function

EDIT

I chose Pax as the answer, as it dealt with both parts of the question and gave a helpful workaround, however, thanks to me.yahoo.com/a/P4tXrx for the link to here

[A]
In oracle you can do this:
```
```
ORDER BY value NULLS FIRST
```
```
or
```
```
ORDER BY value NULLS LAST
```
```
Try it in SQL Server


q:
I am trying to create a control that implements the per-pixel alpha blend while painting a 32-bit bitmap.

I extended a CWnd and use static control in the resource editor. I managed to paint the alpha channel correctly but still the static control keep painting the gray background.

I overwrote the OnEraseBkgnd to prevent the control from painting the background but it didn't worked. I finally managed to do it by using WS_EX_TRANSPARENT.

My problem now is that my control is placed over other control. The first time the dialog is painted all works fine...but if I click over the "parent" control (ie the one beneath my control) my control doesn't received the WM_PAINT message. So it is not painted anymore.

If I minimize the aplication and maximized it again the controls are painted again.

Please, can anybody give a hint? I am getting crazy with this control!!!

Thanks.

[A]
I would have though that if you are processing both the
WM_ERASEBKGND
and the
WM_PAINT
messages then you should have cover all the painting options, without having to resort to using the
WS_EX_TRANSPARENT
style.
Are you sure your code
is not passing
these messages on to the
default processing
?
One other option might be to
subclass
the static control, just to make sure your code is the only one handling these two messages.


q:
I have two questions:

1) How can I make an array which points to objects of integers?

int* myName[5];  // is this correct?

2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method:

int **getStuff() {
// what goes here?
return *(myName); // im pretty sure this is not correct
}

Thanks for the help!

[A]
How can I make an array which points
  to objects?
```
```
int * myName[5]; /* correct */
```
```
If I want to return a pointer to an
  array, which points to objects (like
  (1)) how can I do this in a method?
Technically, you write this function:
```
```
int * (* getStuff() )[5] {
    return &myName;
}
```
```
That returns a pointer to that array. However, you don't want to do that. You wanted to return
a pointer to the first element of the array
:
```
```
int ** getStuff() {
    return myName; /* or return &myName[0]; */
}
```
```
That way, you can now access items as you want like
```
getStuff()[0] = &someInteger;
```


q:
I have a very large background image (about 940x940 pixels) and I'm wondering if anyone has tips for compressing a file this large further than Photoshop can handle?  The best compression without serious loss of quality from Photoshop is PNG 8 (250 KB); does anyone know of a way to compress an image down further than this (maybe compress a PNG after it's been saved)?

I don't normally deal with optimizing images this large, so I was hoping someone would have some pointers.

[A]
PNG images are already compressed internally, in a manner that doesn't benefit from more compression much (and may actually expand if you try to compress it).
You can:
Reduce the resolution from 940x940 to something smaller like 470x470.
Reduce the color depth
Compress using a lossy compression tool like JPEG
edit:
Of course 250KB is large for a web background. You might also want to rethink the graphic design that requires this.


q:
I have a search form in an app I'm currently developing, and I would like for it to be the equivalent of method="GET".

Thus, when clicking the search button, the user goes to search.aspx?q=the+query+he+entered

The reason I want this is simply bookmarkable URLs, plus it feels cleaner to do it this way.

I also don't want the viewstate hidden field value appended to the URL either.

The best I could come up with for this is:

Capture the server-side click event of the button and Response.Redirect.

Attach a Javascript onclick handler to the button that fires a window.location.replace.

Both feel quirky and sub-optimal...
Can you think of a better approach?

[A]
Use a plain old html form, not a server side form (runat=server), and you should indeed be able to make it work.
This could however be a problem if you have an out of the box visual studio master page which wraps the entire page in a server side form, because you can't nest forms.
Web forms don't have to suck, but the default implementations often do. You don't have to use web forms for everything. Sometimes plain old post/get and process request code will do just fine.


q:
I am new to mysqli, and trying to confirm that if I so something like the below, the errno will be set to the last error, if any, and not the error of the last query.

Is this a decent practice or should I be checking for the error in between every query?

Thanks!

$mysqli->autocommit(FALSE);

$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");

if ( 0==$mysqli->errno ) {
    $mysqli->commit();
} else {
    $mysqli->rollback();
    // Handle error
}

[A]
No -- it reports the error code of the last mysqli function call.  Zero means no error occurred on the last function call.  So if one in the middle fails, you won't know about it by checking only at the end.
In other words, yes, you need to check the error code after each function call.  Note that an error is indicated by the return value of
```
$mysqli->query()
```
as well.  Paraphrasing the example from the
mysqli_errno
doc:
```
```
if (!$mysqli->query("INSERT ...")) {
    printf("Errorcode: %d\n", $mysqli->errno);
}
```
```


q:
How can I compare strings in a case insensitive way in Python?

I would like to encapsulate comparison of a regular strings to a repository string, using simple and Pythonic code. I also would like to have ability to look up values in a dict hashed by strings using regular python strings.

[A]
Assuming ASCII strings:
```
```
string1 = 'Hello'
string2 = 'hello'

if string1.lower() == string2.lower():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")
```
```
As of Python 3.3,
casefold()
is a better alternative:
```
```
string1 = 'Hello'
string2 = 'hello'

if string1.casefold() == string2.casefold():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")
```
```
If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.


q:
I'm able to get cells to format as Dates, but I've been unable to get cells to format as currency... Anyone have an example of how to create a style to get this to work?  My code below show the styles I'm creating... the styleDateFormat works like a champ while styleCurrencyFormat has no affect on the cell.

private HSSFWorkbook wb;
private HSSFCellStyle styleDateFormat = null;
private HSSFCellStyle styleCurrencyFormat = null;

......

public CouponicsReportBean(){
    wb = new HSSFWorkbook();
    InitializeFonts();

}

public void InitializeFonts()
{
    styleDateFormat = wb.createCellStyle();
    styleDateFormat.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));

    styleCurrencyFormat = wb.createCellStyle();
    styleCurrencyFormat.setDataFormat(HSSFDataFormat.getBuiltinFormat("$#,##0.00"));

}

[A]
After digging through the documentation a bit more, I found the answer:
http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFDataFormat.html
Just need to find an appropriate pre-set format and supply the code.
```
```
styleCurrencyFormat.setDataFormat((short)8); //8 = "($#,##0.00_);[Red]($#,##0.00)"
```
```
Here are more examples:
http://www.roseindia.net/java/poi/setDataFormat.shtml


q:
I'm not at all familiar with VB.NET or ASP. I need to create a simple page which makes a call to a remote web service. I used the wsdl utility which comes with the DotNet SDK to generate a service proxy and write it to a VB file. Unfortunately I have no idea how to reference this code in either my ASPX file or the code behind VB file so I can create an instance of the proxy.

Edit: I should have qualified this by noting that I'm not using visual studio. I just coded up a .aspx with a .vb behind it and dropped it into an IIS location. Is there a way to do what you're suggesting outside of VS?

[A]
You need to add this code into your project so that it can be consumed.
Right click on your App_Code folder and select "Add Existing Item".  This will bring up explorer.  Use it to select the generated file and it will add it to your project.
Now you will be able to reference this code from within your page or code behind file
If there isn't an App_Code folder in your project, then right click on the project in solution explorer and select "Add New ASP.Net Folder"->App_Code


q: Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods?

[A]
If you're using Objective C, you'll need to use the NSURL, NSURLRequest, and NURLConnection classes.
Apple's NSURLRequest doc
. HttpRequest is for JavaScript.