Question:
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

Answer:
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.


Question: 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?

Answer:
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/


Question:
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

Answer:
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?


Question: 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?

Answer:
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


Question:
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.

Answer:
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.


Question:
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

Answer:
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?


Question:
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)

Answer:
May
```
```
select max(debit-credit) from yourtable
```
```
work?
Try to test it.


Question: 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!

Answer:
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.


Question:
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.

Answer:
Jing
. Free, very easy to use, Windows version requires .NET 3.0 framework. Also, there is Mac version available.


Question:
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)

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


Question:
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

Answer:
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...


Question:
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

Answer:
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.


Question:
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.

Answer:
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.


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

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

Answer:
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/
```
```


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

Answer:
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.


Question:
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...

Answer:
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".


Question:
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.

Answer:
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);
```
```


Question:
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?

Answer:
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.


Question:
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?

Answer:
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.


Question:
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?

Answer:
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
```
```


Question:
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?

Answer:
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.


Question: 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.

Answer:
```
select *
from sysobjects
where type = 'TR'
```
Taken from
here
.


Question:
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)

Answer:
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)


Question:
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?

Answer:
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!


Question:
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?

Answer:
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.


Question:
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.

Answer:
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);
        }
```
```


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

Answer:
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!
```
```


Question:
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?

Answer:
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.


Question:
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.

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


Question:
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.

Answer:
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() );
});
```
```


Question:
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?

Answer:
```
```
new BindingList<MyObject>(orderedList.ToList())
```
```


Question:
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?

Answer:
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.


Question:
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 ?

Answer:
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.


Question:
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.

Answer:
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 :)


Question:
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?

Answer:
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.


Question: 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?

Answer:
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.


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

Answer:
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.


Question:
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>.

Answer:
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.


Question:
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?

Answer:
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);
```
```


Question:
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?

Answer:
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).


Question:
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?

Answer:
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!


Question: 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?

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


Question: 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.

Answer:
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.


Question: 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)?

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


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

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

Answer:
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.


Question:
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

Answer:
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


Question:
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).

Answer:
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.


Question:
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.

Answer:
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);
```
```


Question:
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?

Answer:
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
```
.


Question:
Testing:

return request.getCookies() == null;

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

Answer:
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>
```
```


Question:
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.

Answer:
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?


Question:
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?

Answer:
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)
```
```


Question:
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?

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


Question:
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!

Answer:
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.


Question:
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?

Answer:
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...


Question:
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?

Answer:
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.


Question:
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?

Answer:
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;
```


Question:
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?

Answer:
```
```
form.MinimizeBox = false;
```
```
or if in the form scope
```
```
MinimizeBox = false;
```
```


Question:
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.

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


Question:
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?

Answer:
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.


Question:
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?

Answer:
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.


Question:
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?

Answer:
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.


Question:
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

Answer:
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


Question:
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.

Answer:
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.


Question:
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.

Answer:
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%'"
```
```


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

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


Question:
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?

Answer:
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.


Question:
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.

Answer:
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.


Question: 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?

Answer:
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.


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

Answer:
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
```
```


Question:
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?

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


Question:
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?

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


Question: 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?

Answer:
```
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.


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

Answer: 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.


Question: 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?

Answer:
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.


Question:
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?

Answer:
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.


Question:
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

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


Question:
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.

Answer:
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.


Question:
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!

Answer:
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;
```


Question:
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.

Answer:
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.


Question:
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?

Answer:
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.


Question:
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
}

Answer:
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);
}
```
```


Question:
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.

Answer:
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.


Question:
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"));

}

Answer:
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


Question:
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?

Answer:
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


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

Answer:
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.


Question:
I've be working with a Java application run through the command-line. It deals with XML files, specially the dblp.xml database which has more than 400MB.

I was using JVM 5 and my app needed sort of 600-700MB of memory to processe the dblp.xml. After updating to JVM 6, it starting needing more than 1gb of memory (something I don't have), although it runs a bit faster.

I'm pretty sure of the memory consumption difference, because I've already tested both again and again in this same computer. Resulting in the same difference of memory consumption.

I didn't set any special parameters, just -Xmx800M or -Xmx1000M.
Running with Ubuntu Hardy Heron on a dual core 1.7ghz, with 1,5gb of memory
Using only the top/ps commands to measure

Any one have an idea why this occurs? I really wanted to use JVM 6, because in my production server it is the JVM in use, and I'm not quite able to change easily.

Thanks

Answer:
My advice would be to use a tool like
JProfiler
to try to get a handle on exactly where your memory consumption increased.  If you can't spend on JProfiler, check out this list of
open source java profiling tools
.
Guessing at the cause of performance problems is a bad idea, because you are almost always wrong in your guess, and you waste time optimizing the wrong piece of the system.  Once you have some objective data, you may be able to come up with an optimization reducing your memory consumption.
If it is true that the newer JVM is trading memory for speed (by caching) then there is likely a jvm arg you can use to stop this behavior.  Best bet is to check out the release notes for Java 6 and see if any such feature is mentioned.


Question: What does RESTful Authentication mean and how does it work?  I can't find a good overview on Google.  My only understanding is that you pass the session key (remeberal) in the URL, but this could be horribly wrong.

Answer:
It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST.  Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.
The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in
RFC 2617
.


Question:
I am working on setting up a Drupal based website and wanted to replace the site title in the header with an image file.  I came across this article: "Revised Image Replacement" summarizing several techniques for doing just that.

I was wondering what the current best practice is, in terms of SEO and browser compatibility?

Answer:
```
```
function myget($string)
{
  return mysql_real_escape_string(stripslashes($_GET[$string]));
}
```
```
This is the solution in PHP.


Question:
Does anyone know of a freeware shipping calculator for PHP?  I do not want anything too fancy, and it can be compatible with any of the major US domestic shipping services.

If anyone knows of one that is a plugin for CodeIgniter that would be nice.

Travis

Answer:
Usually services like this are based on web services offered from the various couriers.  You would send the weight and dimensions of the box you want to ship to their web service, and they would return a corresponding shipping price. Each couriers API would be different.  I'm not sure if there are any libraries that aggregate all these services together, but I've never seen one.  Since prices can change at any time, you pretty much have to use some kind of web service to access this information.   That is, unless you are Amazon sized and have preexisting arrangements for pricing rates on shipping with the various couriers.  Just from a quick lookup, here is some of the services that
FedEx
offers.


Question:
I'm trying to make a TCP Client program in C where the client will start up, connect to a server. Then it will send a little information and then just listen to what it receives and react accordingly.

The part that I'm having trouble with is the continuous listening. Here is what I have

...

while (1) {
   numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);
   buf[numbytes] = '\0';
   printf("Received: %s\n", buf);
   // more code to react goes here
}

...

Upon connecting to the server, after sending two lines of data, the server should receive a good bit of information, but when I run this, it prints:

Received:

And then continues to just sit there until i force it to close.

** EDIT ** when i do what Jonathan told me to do, I get the following:

Count: -1, Error: 111, Received:

So that means its erroring, but what do i do about it?

Answer:
Print out the number of bytes received - it is likely to be zero, but confirm that.
It would be worth checking that you aren't getting an error - and therefore underflowing your buffer.
[
Note: from here onwards is the work of Pax -
thank you
, and I've converted it to Community Wiki so I don't get rep points undeservedly.
]
The following code will do this.  Try it and report back on the results, please.
```
```
while (1) {
    numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0);
    buf[numbytes] = '\0';
    printf("Count: %d, Error: %d, Received: %s\n", numbytes, errno, buf);
    // more code to react goes here
}
```
```
After question edit:
Error number 111 is ECONNREFUSED - this is not a usual error code for recv(), but is more suited to the open-type call (open(), connect(), etc).
In any case, ECONNREFUSED is a problem at the server end, not the client - the server has purposefully refused to accept your incoming connection, so you will need to investigate that end of the link.
In order to test this, change your code so that it's connecting to www.microsoft.com on port 80, then send a couple of lines of any old rubbish.  You should get back an error from their web server indicating a malformed HTTP request. This will prove there's no problem on your client end.
This is what I get back when I
```
telnet www.microsoft.com 80
```
and type in
```
hello
```
followed by
```
ENTER
```
twice:
```
```
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 27 Nov 2008 01:45:09 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Verb

HTTP Error 400. The request verb is invalid.

```
```
You should see something similar.


Question:
I have an app that I'm writing a little wizard for.  It automated a small part of the app by moving the mouse to appropriate buttons, menus and clicking them so the user can watch.

So far it moves the mouse to a tree item and sends a right-click.  That pops up a menu via TrackPopupMenu.  Next I move the mouse to the appropriate item on the popup menu.  What I can't figure out is how to select the menu item.

I've tried sending left-clicks to the menu's owner window, tried sending WM_COMMAND to the menu's owner, etc.  Nothing works.

I suppose the menu is a window in and of itself, but I don't know how to get the HWND for it from the HMENU that I have.

Any thoughts on how to PostMessage a click to the popup menu?

PS I'm using a separate thread to drive the mouse and post messages, so no problems with TrackPopupMenu being synchronous.

Answer:
I expect you could generate the necessary click messages by calling
```
SendInput
```
. Move the mouse over where the menu is, and then click.
You might want to take a look at the
WH_JOURNALPLAYBACK
hook. I think it's designed to do exactly what you seem to be trying to do manually.


Question:
Given two colors and n steps, how can one calculate n colors including the two given colors that create a fade effect?

If possible pseudo-code is preferred but this will probably be implemented in Java.

Thanks!

Answer:
Divide each colour into its RGB components and then calculate the individual steps required.
```
```
oldRed = 120;
newRed = 200;
steps = 10;
redStepAmount = (newRed - oldRed) / steps;

currentRed = oldRed;
for (i = 0; i < steps; i++) {
   currentRed += redStepAmount;
}
```
```
Obviously extend that for green and blue.


Question:
Hi if I am creating something on the stack using new I declare it like:

object *myObject = new object(contr, params);

Is there a way to declare this such as:

object *myObject;
myObject = new object(constr, params);

Is this correct?

Answer:
Yes, that is correct.  But new does not create things on the stack, it creates them on the heap.
To create object on the stack you would do:
```
```
object myObject(constr, params);
```
```
There is no other way to create an object on the stack and once it is created on the stack you can't "recreate" it with the same name later in the same function.


Question: i have a windows client and i want to upgrade subversion from 1.5.3 to 1.5.4.  are there installation steps. . do i just copy the zip and extract and override the existing directoies ..  i can't find any clear upgrade instructions . .

Answer:
Which windows client are you using?
TortoiseSVN's upgrade path for me so far has been pretty flawless. You just download the latest installer, run it, and get back to work.
The only time I had an issue was upgrading from 1.4x to 1.5x, you
do
have to restart the computer after this installation, otherwise you'll start getting all sorts of funky errors because the Tortoise SVN in memory cache will be out of date and incompatible.
After a restart everything was fine. The repositories always get auto-upgraded, and unless there's something in the changelog saying otherwise, you can upgrade worry free.
Upgrading the client side of things should be a low concern anyways, just make a backup of your working copy, perform the upgrade, and if you do have problems, checkout the project into a new folder, move any changed files in, and your all set.
Upgrading the repository could have more ramifications, but again, I've yet to have a problem on that side of the system.
Having backups is a good fail safe.


Question:
void (int a[]) {
    a[5] = 3; // this is wrong?
    }

Can I do this so that the array that is passed in is modified?

Sorry for deleting, a bit new here...

I have another question which might answer my question:

If I have

void Test(int a) {
}

void Best(int &a) {
}

are these two statements equivalent?

Test(a);
Best(&a);

Answer:
If you get the variable not by reference and not by pointer, it means that the function is essentially isolated, getting an ad-hoc copy of a. No matter what you do (without trying to hack the stack or things like that) you wouldn't have access to that value in the calling context.
If you know something about the calling context, you may be able to do things based on some anticipation of stack contents, but it's generally a bad idea.
If your method takes a[] which is essentially a*, then yes, you can alter the contents of the cell that a points to, but you won't be able to alter a (the pointer) itself to point at something else.


Question:
Duplicate:

What is aspect-oriented programming?

Every time I here a podcast or read a blog entry about it, even here, they make it sound like string theory or something.  Is the best way to describe it OOP with Dependency Injection on steroids?

Every time someone tries to explain it, it’s like, Aspects, [Adults from Peanuts Cartoon sound],  Orthogonal, [more noise], cross cutting concerns, etc.  Seriously, can anyone describe it in layman’s terms.

Answer:
Laymans terms so let me give you an example. Let's say you have a web application, and you need to add error logging / auditing. One implementation would be to go into every public method and add your try catch blocks etc...
Well Aspect oriented says hogwash with that, let me inject my method around your method so for example instead of calling YourClass.UpdateModel(), the system might call,
LoggingHandler.CallMethod() this method might then redirect the call to UpdateModel but wraps it in a try catch block to handle logging errors.
Now the trick is that this redirection happens automagically, through configuration or by applying attributes to methods.
This works for as you said cross cutting things which are very common programing elements that exist in every domain, such as: Logging, Auditing, Transaction Mgmt, Authorization.
The idea behind it is to remove all this common plumbing code out of your business / app tier so you can focus on solving the problem not worrying about logging this method call or that method call.


Question:
I was using GetWindowLong like this:

[DllImport("user32.dll")]
private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);

But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible.
http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx

The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):

LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex);

I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:

[DllImport("user32.dll")]
private static extern long GetWindowLong(IntPtr hWnd, int nIndex);

What is right, and how can I ensure proper 64bit compatibility?

Answer:
You should define GetWindowLongPtr using an IntPtr.  In C/C++ a LONG_PTR is 32-bits on a 32-bit system and 64-bits on a 64-bit system (see
here
).  IntPtr in C# is designed to work the same way (see
here
).
So what you want is:
```
```
[DllImport("user32.dll")]
private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);
```
```


Question:
This is probably pretty basic... but I don't seem to get it:

How does

(2 & 1) = 0
(3 & 1) = 1
(4 & 1) = 0

etc..

This pattern above seems to help find even numbers

or

(0 | 1) = 1
(1 | 1) = 1
(2 | 1) = 3
(3 | 1) = 4
(4 | 1) = 5
(5 | 1) = 5

I know how boolean algebra works between bits. But I don't understand how Boolean algebra works with integers (in C# at the least).

thanks in advance.

Answer:
It works the same way in C# as it does in binary.
```
2 | 1 = 3
```
and
```
4 | 1 = 5
```
.
To understand this, you need to think about the binary representation of 1,2,3,4,and 5:
```
010 | 001 = 011
```
and
```
100 | 001 = 101
```
.
Similarly:
```
010 & 001 = 000
```
and
```
011 & 001 = 001
```


Question:
I'm working on a .Net application which uses Asp.net 3.5 and Lucene.Net I am showing search results given by Lucene.Net in an asp.net datagrid. I need to implement Paging (10 records on each page) for this aspx page.

How do I get this done using Lucene.Net?

Answer:
Here is a way to build a simple list matching a specific page with Lucene.Net. This is not ASP.Net specific.
```
```
int first = 0, last = 9; // TODO: Set first and last to correct values according to page number and size
Searcher searcher = new IndexSearcher(YourIndexFolder);
Query query = BuildQuery(); // TODO: Implement BuildQuery
Hits hits = searcher.Search(query);
List<Document> results = new List<Document>();
for (int i = first; i <= last && i < hits.Length(); i++)
    results.Add(hits.Doc(i));

// results now contains a page of documents matching the query
```
```
Basically the Hits collection is very lightweight. The cost of getting this list is minimal. You just instantiate the needed Documents by calling hits.Doc(i) to build your page.


Question: Has anyone ever used the Bridge pattern in a real world application? If so, how did you use it? Is it me, or is it just the Adapter pattern with a little dependency injection thrown into the mix? Does it really deserve its own pattern?

Answer:
A classic example of the Bridge pattern is used in the definition of shapes in an UI environment (see the
Bridge pattern Wikipedia entry
).  The Bridge pattern is a
composite
of the
Template
and
Strategy
patterns.
It is a common view some aspects of the Adapter pattern in the Bridge pattern.  However, to quote from
this article
:
At first sight, the Bridge pattern looks a lot like the Adapter pattern in that a class is used to convert one kind of interface to another. However, the intent of the Adapter pattern is to make one or more classes' interfaces look the same as that of a particular class. The Bridge pattern is designed to separate a class's interface from its implementation so you can vary or replace the implementation without changing the client code.