Question:
I've used a Continuous Integration server in the past with great success, and hadn't had the need to ever perform a code freeze on the source control system.

However, lately it seems that everywhere I look, most shops are using the concept of code freezes when preparing for a release, or even a new test version of their product. This idea runs even in my current project.

When you check-in early and often, and use unit tests, integration tests, acceptance tests, etc., are code freezes still needed?

Answer:
I think that code freezes are important because each new feature is a potential new source of bugs. Sure regression tests are great and help address this issue. But code freezes allow the developers to focus on fixing
currently outstanding bugs
and get the current feature set into a release worthy state.
At best, if I really wanted to develop new code during a code freeze, I would fork the frozen tree, do my work there, then after the freeze, merge the forked tree back in.


Question: I know about using a -vsdoc.js file for IntelliSense, and the one for jQuery is easy to find. What other JavaScript, Ajax, and DHTML libraries have them and where can  I find those files? Also, is there a document which outlines the specifications for -vsdoc.js files?

Answer:
An excellent blog posting from Betrand LeRoy on IntelliSense format for JavaScript:
The format for JavaScript doc comments
.
In a nutshell:
Summary - used to describe a function/method or event. Syntax:
```
```
<summary locid="descriptionID">Description</summary>
```
```
Parameter - describe a parameter to a function/method. Syntax:
```
```
<param name="parameterName"
    mayBeNull="true|false" optional="true|false"
    type="ParameterType" parameterArray="true|false"
    integer="true|false" domElement="true|false"
    elementType="ArrayElementType" elementInteger="true|false"
    elementDomElement="true|false"
    elementMayBeNull="true|false">Description</param>
```
```
The param tag is used to describe the parameters of a method or constructor. The param tags should be in the same order as the method or constructor's parameters and have the same names.
Function return type - syntax:
```
```
<returns
    type="ValueType" integer="true|false" domElement="true|false"
    mayBeNull="true|false" elementType="ArrayElementType"
    elementInteger="true|false" elementDomElement="true|false"
    elementMayBeNull="true|false">Description</returns>
```
```
Value type - describes a property (shouldnt use 'summary' for a prop) - syntax:
```
```
<value
    type="ValueType" integer="true|false" domElement="true|false"
    mayBeNull="true|false" elementType="ArrayElementType"
    elementInteger="true|false" elementDomElement="true|false"
    elementMayBeNull="true|false"
    locid="descriptionID">Description</value>
```
```
Field - used to describe a field in a JavaScript class - syntax:
```
```
<field name="fieldName" type="FieldType"
    integer="true|false" domElement="true|false" mayBeNull="true|false"
    elementType="ArrayElementType" elementInteger="true|false"
    elementDomElement="true|false" elementMayBeNull="true|false"
    locid="descriptionID">Description</field>
```
```
How to include IntelliSense for an external JavaScript file, the following syntax as the first line(s) in a JavaScript file:
```
```
<reference path="path/to/the/script/reference.js"
    assembly="Assembly.Name" name="ScriptResourceName.js"/>
```
```


Question: Assuming one has an abstract base class foo with __get() defined, and a child class bar which inherits from foo with a private variable $var, will the parent __get() be called when trying to access the private $var from outside the class?

Answer:
Yes.
```
```
<?php
    abstract class foo
    {
        public function __get($var)
        {
            echo "Parent (Foo) __get() called for $var\n";
        }
    }

   class bar extends foo
   {
        private $var;
        public function __construct()
        {
            $this->var = "25\n";
        }

        public function getVar()
        {
            return $this->var;
        }
    }

    $obj = new bar();
    echo $obj->var;
    echo $obj->getVar();
?>
```
```
output:
$ php test.php
Parent (Foo) __get() called for var
25


Question:
I just found out that by converting PNG32 to PNG8 via Photoshop will fix the PNG transparency bug in IE<=6.

So I had this thought that instead of serving PNG32 to all browser, why not serve PNG8 if the client is using IE<=6.

I'm not really an expert when it comes to htaccess/httpd directives so I'm here for help.

The title is the psuedocode itself.

Answer:
Put this in your .htaccess
```
```
RewriteEngine on
RewriteRule ^/(.*)\.png$ /$18.png [L,QSA]
```
```
Should work.


Question:
How do I write the CC logo in HTML, is there something like &copy; (which gives ©)?

(CC stands for Creative Commons).

Answer:
As far as I know, there is no character for this, so you'll have to use a graphic.
There are some nice ones
here
. By the way, on this page, there's also a logo font you could use in HTML, but this won't show correctly for other users that don't have the font installed.


Question:
in my flex application, I created a Tilelist. In this Tilelist, I am using an ItemRenderer to create a box consisting of an image and an VSlider in each tile.

The tile need to be dragable when you click on the image, but not dragable when you slide the slider. How can I achieve this ? I have been scratching my head searching on Google for one day and I have really no idea.

I look forward to your help.
Thank you.

Answer:
I found a solution to my problem, however it may not be the best one.
Using this :
```
```
public var overImage:Boolean = false;

        public function checkAllow(evt:DragEvent):void {

            if(overImage == false)
            {
                evt.preventDefault()
            }
        }

        public function isOverImage():void {
            overImage = true;
        }

        public function isOutImage():void {
            overImage = false;
        }
```
```
I call those functions like this :
On my image component
```
```
mouseOver="outerDocument.isOverImage()" mouseOut="outerDocument.isOutImage()"
```
```
And for my tilelist I did this
```
```
Tiles.addEventListener(DragEvent.DRAG_START, checkAllow);
```
```
Hope it helps some people.


Question: I am trying to find out how much memory my application is consuming from within the program itself. The memory usage I am looking for is the number reported in the "Mem Usage" column on the Processes tab of Windows Task Manager.

Answer:
A good starting point would be
GetProcessMemoryInfo
, which reports various memory info about the specified process. You can pass
```
GetCurrentProcess()
```
as the process handle in order to get information about the calling process.
Probably the
```
WorkingSetSize
```
member of
```
PROCESS_MEMORY_COUNTERS
```
is the closest match to the Mem Usage coulmn in task manager, but it's not going to be exactly the same. I would experiment with the different values to find the one that's closest to your needs.


Question: I want to select a bunch of spans in a div whose CSS contains a particular background color. How do I achieve this?

Answer:
Use the attribute selector [attribute=value] to look for a certain attribute value.
```
```
#id_of_the_div span[background-color=rgb(255,255,255)]
```
```


Question: I'm trying to pull data from an ODBC app to SQL2005(dev ed) DB on an hourly basis.  When I run SSIS the option to import all tables and views is grayed out and forces your to write a query. How would I go about setting up a SSIS integration service to update ALL 250 some tables on an hourly basis.

Answer:
perhaps you could rephrase your question a little, I am not 100% sure what you are asking here. Are you trying to get data into SQL Server from an application via SSIS with the Data Transform task using an ODBC connection to the Application?
Anyhoo, the simple answer to the MS Access part of your question is "hell no" MS Access is never, ever the answer to anything ;-)
I would be inclined to find out why the tables and views are greyed out and fix that issue. (not enough info in this question to determine why they are greyed out)


Question:
I just want ask the steps when trying to create a simple SQL select statement in UNIX inside/within IF..THEN..FI statement.

I know how to use the 'select' and 'if..then' statements in SQL*Plus, but I'm having a difficulties having a UNIX script to point to variables: If 'ABC' to 'Select...'

Example:

if [ "$?" = 'ABC' ]
then
    SELECT employid, name, age FROM tablename;
else
    exit 1
fi

if [ "$?" = 'XYZ' ]
then
    SELECT employid, name, age FROM tablename;
else
    exit 1
fi

How do I put it in a UNIX script more correctly syntax wise and right to the point?

Thanks.

Answer:
This sounds like you're trying to embed SQLPlus in a shell script.  From memory the incantation should look something like:
```
```
if [ $? -eq ABC ]; then
SQLPLUS /S USER/PASS@Instance <<EOF
SET echo off;
SET pagesize 0;
SET heading off;
SPOOL foo.out
select foo from bar
EOF
fi
```
```
Everything between the SQLPLUS and EOF is passed to SQLPlus, so we have some statements to control the formatting (you may want different ones) and the actual query.  The SPOOL command in the SQLPlus script sends the output to a file.  For more detailed docs on using SQLPlus, You can download them from
Oracle's web site.


Question: I know they're using a jQuery plugin, but I can't seem to find which one they used. In particular, what I'm looking for is autocomplete with exactly the same functionality as SO's autocomplete, where it will perform an AJAX command with each new word typed in and allow you to select one from a dropdown.

Answer:
Note that the tag editor
has been completely re-written now
, and no longer resembles the original, simple text box w/ suggestion drop-down that adorned the site for nearly three years.
If you're interested in the new form, see this Meta question:
https://meta.stackexchange.com/questions/102510/can-i-use-the-tag-textbox-script
Autocomplete
is the plugin used originally, albeit with various tweaks and customizations made to it over the years.


Question:
I run a series of time consuming operations on a background worker thread.  At various stages I update a (windows form) progress bar by invoking a delegate.  However, one of the more time operations occurs on a single line of code.

Is it possible to :

a) Update the UI while that single line of code is being executed, or at least display an animated icon that shows the user that work is being done.

b) Let the user cancel the background worker thread while that single line of code is being executed

Answer:
Unfortunately, probably not.  The background worker thread needs to call ReportProgress to update the UI thread, and it needs to watch the CancellationPending to know whether it should stop or not.  So, if your worker thread is running along-running operation in a single line, there's no way to make this work.
Perhaps, I've misunderstood, so here's code that simulates what I'm getting at:
```
```
public void DoWork() {
    System.Threading.Thread.Sleep(10000);

    // won't execute until the sleep is over
    bgWorker.ReportProgress(100);
}
```
```


Question:
Recently I had to move one of my web applications to a new hosting provider. The mail and web service is still held on the old hosting site however, when I try to send an email from the new server,I get an error;

"The server rejected one or more recipient addresses. The server response was:

450 <email_address>: Recipient address rejected: Greylisted for 5 minutes

I asked my old hosting provider what I need to do to fix this and they replied with

The mail server operates on POP before
  SMTP. If a valid POP login is not
  received before sending mail through
  the server, then the mail is
  greylisted and held for 5 minutes
  before a retry.

To prevent this, simply do a Receive
  before sending mail

Does anyone have any idea how I do a POP before SMTP in C#?

Answer:
i'm not sure how C# would handle the specifics (sockets?), but basically you just want to make a connection to your new POP server. here's a sample POP transaction:
```
```
$ telnet new-pop-server.com 110
Connected to new-pop-server.com.
Escape character is '^]'.
+OK
USER <username>
+OK
PASS <password>
+OK               // you're authenticated at this point
LIST
+OK
.                 // no new messages!
QUIT
+OK
```
```
once you're authorized you should be able to send your mail programatically. (USER, PASS, LIST, QUIT) are all commands you would send (
pop3 RFC
).


Question:
want to pass boost::bind to a method expecting a plain function pointer (same signature).

typedef void TriggerProc_type(Variable*,void*);
void InitVariable(TriggerProc_type *proc);
boost::function<void (Variable*, void*)> triggerProc ...
InitVariable(triggerProc);

error C2664: 'InitVariable' : cannot convert parameter 1 from
'boost::function<Signature>' to 'void (__cdecl *)(type *,void *)'

I can avoid storing a boost::function and just pass the bound functor directly, but then I get similar error:

error C2664: 'blah(void (__cdecl *)(type *,void *))' : cannot convert parameter
1 from 'boost::_bi::bind_t<R,F,L>' to 'void (__cdecl *)(type *,void *)'

Answer:
I think you want to use the target() member function of boost::function (isn't that a mouthful...)
```
```
#include <boost/function.hpp>
#include <iostream>

int f(int x)
{
  return x + x;
}

typedef int (*pointer_to_func)(int);

int
main()
{
  boost::function<int(int x)> g(f);

  if(*g.target<pointer_to_func>() == f) {
    std::cout << "g contains f" << std::endl;
  } else {
    std::cout << "g does not contain f" << std::endl;
  }

  return 0;
}
```
```


Question:
In Visual Studio, How do I show all classes inherited from a base class?

For example, in ASP.NET MVC there are several 'ActionResult' types -- and they all inherit from / implement the base class ActionResult.

It looks like unless you just 'know' that View and Json are valid ActionResult types, there is no way you can easily find this information out.

Please prove me wrong.

Is there something in the object browser that makes this easy to find out?

I'm even up for suggestions of tools outside of Visual Studio to discover this information about various classes.  For example: is there something in Resharper that will help me out?

Answer:
Sure,
Resharper
can do this. And much more.
Just right click on type name in any place and choose "Go To Inheritor" in context menu.
"Go To Inheritor" can be also applied to method for navigating to overrides and an interface method's implementations. For an interface you could call "Find Usages Advanced" again, just right click) where to find all extendings and implementations. For a type - derived types.
And my favorite feature - click with holding Control on any type/method for navigating to its declaration.
I think it's a must-have tool for .net developers.
In Resharper 9.2, on any type in source code, rt-click "Find Usage Advanced", select Find="Derived" and Scope="Solutions and Libraries".
For example, to find all inheritors (both in the library and your code) of some base class in an included DLL from any vendor, declare a variable in your code with that base class. Then right-click on that base class name you just typed.


Question: I have a rather complex decorator written by someone else. What I want to do is call a decorated version of the function one time based on a descision or call the original function (not decorated) another time. Is this possible?

Answer:
With:
```
```
decorator(original_function)()
```
```
Without:
```
```
original_function()
```
```
A decorator is just a function which takes a function as an argument and returns another one. The @ syntax is totally optional. Perhaps a sift through some
documentation
might help clarify things.


Question:
I have a Flash application that is hosted from within a Drupal page.  Some parts of the Flash application should be available to all users, but some should only be available to a logged-in user.  (The specific role doesn't matter, just that they are any authorized user of the site).

From within Flash, I can detect whether the user is logged on by screen-scraping the "?q=user" page, but this is very brittle.  What is the "right" way to do this?  I can install additional Modules if necessary, but they need to be compatible with Drupal 6, not 5.

Similarly, if there is no user currently logged in, how can I take a username and password that they provide to me and log them in (or determine that the password is bad)?

Answer:
The "right" solution
you probably want to look at something like the
services module
. basically, you want to expose user services to your flash app, so you can send requests (via XML-RPC or whatever implementation you choose) to get information like "what access does the current logged in user have", or "login this user with username x and password y" etc...
The do it yourself quickly solution
if you're familiar with module development, you can create your own module quickly to just get the functionality you need, without having to go through a "real" web services layer. here's a quick example, creating a module called "myservices":
```
```
<?php
// myservices.info
   name = My Services
   description = Expose basic services
   core = 6.x

<?php
// myservices.module

   function myservices_menu() {
       $items['myservices/user'] = array(
         'title' => 'Get auth',
         'page callback' => 'myservices_get_user',
         'access arguments' => array('access content'),
       );
       return $items;
   }

   function myservices_get_user() {
       global $user;
       if (in_array('authenticated user', $user->roles) ) {
           print 'yes';
       } else {
           print 'no';
       }
   }
```
```
put those two files in a directory "myservices" in your modules directory, activate it, and then go to
```
http://yourdomain.com/myservices/user
```
if you're authenticated, it'll just return
```
yes
```
, and if not
```
no
```
, etc... which you can pick up in your flash app.


Question: What happens if the browser receives a redirect response to an ajax request?

Answer:
The
```
ajax-request
```
will follow that redirect afaik. The actual content (
```
.responseText
```
,
```
.responseXML
```
) will be the content from the page you are redirected to.
You might be able to intercept the redirect (
```
status-code
```
,
```
location-header
```
) on
```
readyState
```
2 or 3, but not sure about it.


Question: Is there any software to help in learning / understanding / experimenting with the rules of harmony and counterpoint?

Answer:
While very carefully coded applications could give you some hints, I find that the most important lesson is when to break the rules. And a computer program could never help with that.
I suggest you buy a book instead. Good ones include
The style of Palestrina and the dissonance
Twentieth century harmony
I haven't read any English books on baroque, wiener or romantic style.


Question:
Is it possible to detect, on the client side, whether the user is using an encrypted page or not?

Put another way -- I want to know if the URL of the current page starts with http or https.

Answer:
Use
```
window.location.protocol
```
to check if it is
```
https:
```
```
```
function isSecure()
{
   return window.location.protocol == 'https:';
}
```
```
Alternatively you can omit specifying "window" if you don't have a locally scoped location.
```
```
function isSecure()
{
   return location.protocol == 'https:';
}
```
```


Question:
I am working on a small project to take a CSV file and then insert its data into a HTML table (I would use datagrid and dataset or datatable, but the system I will be talking to does not support ASP.NET uploads for sending newsletters).

Anyway, I will use the file.readalllines method to return the contents of the csv file into a string array.

But for each string member of the array, I will be using the string.split function to split up the string into the char array. Problem is (and the csv file is generated by the system I talk to btw - I get data from this system and feed data into it), the csv contents are makes of cars. This means that I could have:

Nissan Almera

Nissan Almera 1.4 TDi

VW Golf 1.9 SE

And so forth...

Is there a robust way I could ensure that where I have Almera 1.4 TDi, for example, it is one member in the char array I split each string into, rather than seperate members.

Answer:
The Split() method takes a char parameter which can be used to specify the delimiter. So you can do something like:
```
```
String.Split(Convert.ToChar(","));
```
```
Judging by your question all the car makes should be delimited by commas so this should work.


Question: I know of is and as for instanceof, but what about the reflective isInstance() method?

Answer:
The equivalent of Java’s
```
obj.getClass().isInstance(otherObj)
```
in C# is as follows:
```
```
bool result = obj.GetType().IsAssignableFrom(otherObj.GetType());
```
```
Note that while both Java and C# work on the runtime type object (Java
```
java.lang.Class
```
≣ C#
```
System.Type
```
) of an
```
obj
```
(via
```
.getClass()
```
vs
```
.getType()
```
), Java’s
```
isInstance
```
takes an object as its argument, whereas C#’s
```
IsAssignableFrom
```
expects another
```
System.Type
```
object.


Question:
How can I determine current version of my repository to see if I need to upgrade it (svnadmin upgrade)?

In reality I'm hosting SVN with 3rd party and I want to find out if I need to ask them to upgrade my repos or not.

I'm asking since 1.5 server will keep repo version at 1.4, unless I miss something?

Answer:
Have a look at
```
<REPO>/db/format
```
. After upgrading to 1.5 format, my
```
format
```
file shows:
```
```
3
layout sharded 1000
```
```
Before it used to be:
```
```
2
```
```


Question:
Does this pattern:

setTimeout(function(){
             // do stuff
}, 0);

Actually return control to the UI from within a loop? When are you supposed to use it? Does it work equally well in all browsers?

Answer:
http://blog.thinkature.com/index.php/2006/11/26/escaping-the-javascript-call-stack-with-settimeout/
Some good info in there. Basically, you are correct and it works on pretty much all browsers. Cool trick.
You would want to use this in the example that the author of the post gave, as well as instances where you need to return execution back to the calling function before your code is executed. Javascript is, apparently, not multi-threaded, but this comes close.
Hope this helps :)


Question: I've heard a lot about profiling. What is this all about? As far as I understand this is some kind of performance measurement but can someone elaborate this on more clearly so that a newbie can grasp the idea. Also, I use Eclipse IDE for my Java program. Can I profile my program using Eclipse IDE? What are the factors to be considered while profiling (I mean the best practices)?

Answer:
Profiling basically shows you how often a given line of code is executed and how much time was spent in it (compared to other lines). This makes it easy to pinpoint the location where your code spends most of the time.
It also makes it possible to find places where your code spends much time without doing anything: this is the typical sign of a
cache miss
and this is where you should get active.
Usually, programs spend very much time (say, 90%) in one place. Unfortunately, finding this place without profiling isn't possible. Guesswork often goes awry. So if you optimize in the wrong place, this won't help at all: if the overall time spent in that line is only 10%, your code will only get 10% faster (at best!). If, however, you succeed in removing the call that takes 90% of the time, your programm will get
ten times faster
.
This, in a nutshell, is profiling.
Eclipse offers builtin profiling capabilies and I've been told that they're pretty good but since I don't know them, let someone else answer that.


Question:
How does one choose the size of a buffer (bytes I read from or write to socket) for the maximum throughput when implementing a low-level HTTP and FTP transfer? My application should transfer data with HTTP or FTP on connections varying from 130 Kbps to 3 Mbps (I know the expected speed beforehand). Sometimes it's a one way transfer, sometimes it goes in both directions. Should I stick with some average buffer size or I must vary it depending on the connection speed?

Thanks.

Answer:
Choose a buffer size over 8KB.  9000 is typically the largest MTU (maximum transmission unit) size used in even the fastest networks.
When you use a buffer larger than the MTU of the connection, the operating system will break it down in to MTU sized pieces as needed, and thus anything you use over the MTU will have little effect on network performance.
However, using a large buffer will likely have other effect on performance, if you're transferring files, then using large buffers may increase the read performance, thus improving the speed of your application.
So, Usually picking a nice round number like 16KB is a good idea.  Definitely don't go under 1500, as this can negatively effect network performance (causing the operating system to sometimes send small packets, which decrease performance on the network).


Question:
In Ant is there any way to do something like this:

<arguments id="arg-list">
    <arg value="arg1" />
    <arg value="arg2" />
</arguments>

<property name="prop1" refid="arg-list" />

I'm trying to write a macro for psexec and I'm looking for a nice way to pass in the argument list.

I know that you can do something similar with classpaths...

Thanks!

Answer:
I don't know of an answer to your specific question. The documentation is clear that refid 'Only yields reasonable results for references to PATH like structures or properties.'
Without a bit more information on what you're trying to do, it's hard to comment. At the risk of changing your design, rather than answering your question, I suggest:
1) You can pass the argument list to exec as a line:
```
```
<macrodef name="example">
  <attribute name="args"/>
  <sequential>
    <exec executable="example.exe">
      <arg value="somearg" />
      <arg line="@{args}"/>
    </exec>
  </sequential>
</macrodef>

<example args="somearg arg1 arg2"/>
```
```
Which will run example.exe:
```
```
example.exe arg1 arg2
```
```
2) I pass in arguments to macros that call external apps like this:
```
```
<macrodef name="example">
  <element name="params" optional="yes" implicit="yes"/>
  <sequential>
    <exec taskname="eg" executable="example.exe">
      <arg value="somearg" />
      <params />
    </exec>
  </sequential>
</macrodef>

<example>
  <arg value="arg1"/>
  <arg value="arg2"/>
</example>
```
```
This will run example.exe:
```
```
example.exe somearg arg1 arg2
```
```
I hope I haven't been teaching my grandmother to suck eggs here.


Question:
I've noticed, using visual studio 2003, that I can "comment out" my comments to make them no longer be comments. This one needs an example:

If I have:

/*
int commented_out = 0;
*/

I can comment out the /* and */ with // and code within the /* and */ is no longer "commented out" (the text changes to non-comment color and the compiler treats it as code once again). Like so:

///*
int commented_out = 0;
//*/

I've found this is true for msvc 2003, is this normal C++ behavior or is it just a fluke that works with this compiler?

Answer:
It should work in any compiler as the
```
//
```
is encountered first in the input stream.
I tend to use
```
#if 0
```
for this sort of stuff and change it to
```
#if 1
```
to uncomment, shown here:
```
```
#if 0
    int commented_out = 0;
#endif
```
```
Then I don't have to worry about comment markers at all.


Question:
I was wondering if there is a way to implement an action listener for a Jbutton without a name. For example, I have the following for loop that creates a button for each letter of the alphabet.

for (int i = 65; i < 91; i++){
     alphabetPanel.add(new JButton("<html><center>" + (char)i));
}

Is there a way that I can add an action listener for each of those buttons without getting rid of my for loop and hard coding each JButton and then creating an action listener for each?

Thanks in advance,

Tomek

Answer:
Your question is a little vague.  it would be trivial to modify the loop to add a listener inside the loop:
```
```
ActionListener listener = something;

for (int i = 65; i < 91; i++){
     JButton button = new JButton("<html><center>" + (char)i);
     button.addActionListener( listener );
     alphabetPanel.add(button);
}
```
```
if you can't modify the loop you could iterate over all of the panel's children, and add listeners to any of the children that are jbuttons.
also why are you using html to center the text?  isn't that overkill? doesn't jbutton already center text?
you could use setHorizontalAlignement(SwingConstants.CENTER) to do it too.


Question:
I'm trying to design a homepage for an MVC site that has two different views, based on if the user is logged in or not.

So image the default (not logged in) view is showing general, nonspecific info. If i'm logged in, the view is showing mostly personal stuff instead.

What's the best practice to handling this? Don't forget, we also need to unit test this.

Thanks heaps!

Answer:
This should be a simple case of returning the appropriate view from your controller.
```
```
public ActionResult Index()

    If (User.IsLoggedOn)
    {
        // Do user-specific controller stuff here...

        return View("LoggedOnIndex");
    }
    else
    {
        // Do anon controller stuff here...

        return View("AnonymousIndex");
    }
```
```


Question: How does one do namespaced controllers in Merb, for instance to create an admin section to the site? In Rails one would use Admin::CategoriesController, is this similar in Merb or is this another recommended way of doing it?

Answer:
The namespace method seems to do it.
This is placed in the routes file (router.rb):
```
```
namespace :admin do
  resources :categories
end
```
```
This generates routes like:
```
edit_admin_category - /admin/categories/:id/edit(.:format)
delete_admin_category - /admin/categories/:id/delete(.:format)
admin_categories - /admin/categories(/index)(.:format)
new_admin_category - /admin/categories/new(.:format)
admin_category - /admin/categories/:id(.:format)
```
I then put my controller in a module like this:
```
```
module Admin
  class Categories < Application
    def index
      ...
    end

    .
    .
    .
  end
end
```
```
I am not sure if this is the recommended way, any suggestions to this would be great.


Question:
I'm using a logging module that can have reporting enabled/disabled at runtime. Calls generally go something like:

WARN(
     "Danger Will Robinson! There are "
     + boost::lexical_cast<string>(minutes)
     + " minutes of oxygen left!"
);

I'm using an inline function for WARN, but I'm curious as to how much optimization is going on behind the scenes -- evaluation of the arguments throughout the entire program would be costly. The WARN function goes something like this:

bool WARNINGS_ENABLED = false;
inline void WARN(const string &message) {
    if (!WARNINGS_ENABLED) {
       return;
    }
    // ...
}

Given that constructing the string argument has no side-effects, will the compiler optimize it out? Is a certain level of optimization required (-Ox in g++ for some x)?

Answer:
I'd guess that it only has a chance to optimize it out if it can prove that there are no side effects (which might be difficult for the compiler to do for an expensive function call).
I'm not a boost expert, but I'm guessing there's a way to construct a lambda that will only be evaluated to generate the string if WARNINGS_ENABLED is true.  Something like...
```
```
inline void warnFunc(some_boost_lambda &message_generator) {
  if (WARNINGS_ENABLED) {
    cerr << message_generator() << endl;
  }
}

#define WARN(msg) warnFunc(...insert boost magic here to turn msg into a lambda...)
```
```


Question:
I'm attempting to utilize VBScript to connect pull the physicalDeliveryOfficeName attribute in Active Directory by providing the email address.

I know how to do it with a common name like the following:

Set MyUser = GetObject ("LDAP://cn=" & uname & ",ou=" & strname & ",DC=bobdom,DC=net")

However only the email address is available.  How to do this? I've even tried

Set MyUser = GetObject ("LDAP://mail=" & uname & ",ou=" & strname & ",DC=bobdom,DC=net")

and that doesn't work.

Answer:
If using an
LDAP
query (not sure if you need the server name in there in your case):
```
```
<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(objectClass=user)(mail=mike.spencer@kenblanchard.com));
```
```
Trying it out in my own environment, it looks like this (with a couple things genericized):
```
```
<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(mail=email@company.com));name,mail,member,description,memberOf,userParameters,userAccountControl,whenCreated,CN;subTreeCount=1
```
```
And the whole batch looks like this (in ASP; if done in a .vbs file you'll need to change the
```
Server.CreateObject
```
to just
```
CreateObject
```
... I think).
```
```
Set oCon        = Server.CreateObject("ADODB.Connection")
oCon.Provider   = "ADsDSOObject"
oCon.Open "ADProvider", "ADUsername", "ADPassword"

Set oCmd        = Server.CreateObject("ADODB.Command")
Set oCmd.ActiveConnection = oCon

sQuery = "<LDAP://SERVERNAME/DC=bobdom,DC=net>;(&(mail=email@company.com));name,distinguishedName,physicalDeliveryOfficeName;subTreeCount=1>"

oCmd.CommandText = sQuery
Set ADRecordSet = oCmd.Execute
```
```
You may need to fiddle with
```
subTreeCount
```
.


Question:
What is the correct way to convert ASP.NET SOAP-based web services to JSON-based responses?
...And then call these from jQuery?

What are "best practices" when integrating jQuery based AJAX and ASP.NET?
Articles? Books?

Answer:
JSON conversion to .NET classes can be done with
System.Runtime.Serialization
and
System.Runtime.Serialization.JSON
. I suspect you're more interested in setting up function calls from client to server. I think it is worth trying
this tutorial
.
In this tutorial, you'll need to add a webservice '.asmx' file.  In the asmx file you will be able to create functions callable from client script.  Your ASP.NET pages can also reference client script generated to make calling the .asmx functions.
If you actually want to do JSON serialization though, you could also use the following:
```
```
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

public class JsonSerializer
{
    // To make a type serializeable, mark it with DataContractAttribute
    // To make a member of such types serializeable, mark them with DataMemberAttribute
    // All types marked for serialization then need to be passed to JsonSerialize as
    // parameter 'types'

    static public string JsonSerialize(object objectToSerialize, params Type[] types)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(
            types[0], types.Skip(1));

        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, objectToSerialize);
        ms.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(ms);
        return sr.ReadToEnd();
    }
}
```
```


Question:
In PHP, I can write:

$vname = 'phone';
$$vname = '555-1234';
print $phone;

... And the script will output "555-1234".

Is there any equivalent in Perl?

Is there any way to constrain $phone to the scope of the local block, as if I'd written my $phone? Using my $$vname gives me "Can't declare scalar dereference in my at ..." errors.

Answer:
You can do it in a very similar way:
```
```
$vname = "phone";
$$vname = "555-1234";
print $phone;
```
```
But that you can doesn't mean that you should. The best way to manage this is,
as Michael Carman says
,
USE A HASH!


Question:
Something that confuses me, but has never caused any problems... the recommended way to dispatch an event is as follows:

public event EventHandler SomeEvent;
...
{
    ....
    if(SomeEvent!=null)SomeEvent();
}

In a multi-threaded environment, how does this code guarantee that another thread will not alter the invocation list of SomeEvent between the check for null and the invocation of the event?

Answer:
The recommended way is a little different and uses a temporary as follows:
```
```
EventHandler tmpEvent = SomeEvent;
if (tmpEvent != null)
{
    tmpEvent();
}
```
```


Question:
I am confused by J2ee webservers !! I downloaded a free Glassfish server from sun, then as I am an Oracle developer downloaded the latest JDeveloper, which comes with a Weblogic server from BEa/Oracle.  One is free the other costs $1000s.  What is the real difference.

I want to write a SOAP interface to my Oracle database 10g, can I get away with the Glassfish server, why should I used a Weblogic server, and how does this differ from the Oracle Application server for J2EE apps.

As you can see I am confused to say the least, and would appreciate any enlightenment.  I am an experience SQL PL/SQL developer, but new to Java so have a certain lack of knowledge in this area.

Answer:
Personally, if you are looking for an open source J2EE app server, I'd tend to go with JBoss if only because it has a much larger market share, making it a lot more likely that you are going to be able to find people that can answer questions or that have done some particular task and have posted instructions.
For the most part, if you are writing a pure J2EE application, it is relatively transparent to the developer what application server you deploy to.  If you decide to take advantage of application-server specific extensions, then the choice of app server may matter to developers, but most Java shops are using a rather vanilla setup that can move reasonably easily between application servers.  If you want to embrace one particular application server's extensions, there may be some performance/ productivity gains available in exchange for a loss of productivity.
The people that are more likely to care about what application server you are using are the admins.  Different application servers have very different administrative interfaces (and different levels of administrative complexity and configurability).  The bigger the site and the more critical the application, the more this sort of thing comes in to play.  Different application servers also have different JVM implementations which has different performance characteristics.  You also have the cost of support.  Even if you use a free application server like JBoss, you probably want to purchase a support contract if you are deploying a mission critical application there.  If you're deploying something smaller scale where you're comfortable relying on free sources of assistance (i.e. Google, Stackoverflow, etc.) one of the open source app servers is probably a no-brainer.


Question:
If I have a list like this:

<ul id="mylist">
    <li id="list-item1">text 1</li>
    <li id="list-item2">text 2</li>
    <li id="list-item3">text 3</li>
    <li id="list-item4">text 4</li>
</ul>

What's the easiest way to re-arrange the DOM nodes to my preference? (This needs to happen automatically when the page loads, the list-order preference is gained from a cookie)

E.g.

<ul id="mylist">
    <li id="list-item3">text 3</li>
    <li id="list-item4">text 4</li>
    <li id="list-item2">text 2</li>
    <li id="list-item1">text 1</li>
</ul>

Answer:
Though there's probably an easier way to do this using a JS Library, here's a working solution using vanilla js.
```
```
var list = document.getElementById('mylist');

var items = list.childNodes;
var itemsArr = [];
for (var i in items) {
    if (items[i].nodeType == 1) { // get rid of the whitespace text nodes
        itemsArr.push(items[i]);
    }
}

itemsArr.sort(function(a, b) {
  return a.innerHTML == b.innerHTML
          ? 0
          : (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (i = 0; i < itemsArr.length; ++i) {
  list.appendChild(itemsArr[i]);
}
```
```


Question:
I have some shapefile (demographic/heat map data in the USA, such as crime in New York) data imported into a sql server 2008 database, field data type: Geography.

How can i get this data, from a select query, in a format which i can then display on google maps or microsoft virtual earth?

thanks!

Edit 1: So far, the best solution has been to use a (free) 3rd Party dll (SharpMap). I'm hoping someone might suggest some sql tricks in sql2008 to return it in a compatible format ...

Answer:
The easiest way to do this is to select to XML and then transform the data into GeoRSS or KML.  Virtual Earth and Google Maps both have support for KML so that would probably be the easiest way to do it.
There are considerations though.  If you have many many vertices in your data you probably want to implement some sort of AJAX method to retrieve only the data in the map view.  You can generalize data in SQL 2008 to make a fewer amount of vertices depending on your zoom level.  If you are zoomed out to a country level you don't need nearly as much detail as zoomed into a town.
MapDotNet
has a lot of features for getting your data in a Virtual Earth map more easily.  It is relatively easy to perfrom a select query and display the data as you desire.  I'm sure there are other similar products for Google maps but I haven't personally used them.  It has support for polygons as well as heat maps and gives you a lot more functionality than just using Virtual Earth.  Virtual Earth is powerful but there are a lot of GIS tools someone from a mapping background would expect that you have to program in yoursef.


Question:
How can you express X of Y are true, in boolean logic?  a rule like 2 of the following must be true (A, B, C, D, E, F)
is it a form of multiplcation or set operations?

the end result is all the permutations like AB OR AC OR AD, if you said 3 of following it is like ABC, ABD, ABE, etc.. so it is like (A,B,C)^2?

thanks!

Answer:
You've got the idea there.  To express "k of n holds" you're going to need to enumerate all cases for which k holds.  So, if we have variables A B C D E, and you want 3 of 5, you'll need
```
```
(A  &  B &  C & ~D & ~E) |
(A  &  B & ~C &  D & ~E) |
(A  &  B & ~C & ~D &  E) | ...
(~A & ~B &  C &  D &  E)
```
```
where & is "and", | is "or" and ~ is "not".


Question:
I have a website cgi-bin program that is written in c++.

Unfortunately the website provider for my friend's site only allows Perl or PHP cgi-bin scripts.

Is there an easy way to simply have a very small Perl or PHP wrapper that just calls the c++ compiled binary?

Would the c++ program still be able to read from stdin for POST commands or would it have to be read by the Perl or PHP and then forwarded.

Answer:
You can use PHP's system() function to execute a shell command, which you could use to launch another program.  The STDOUT of that program would then go to the same place as php's stdout (to the HTTP connection).  You might have to do some messing around to get stdin to read from get/post/etc.
But most likely the website provider has disabled the ability of you to execute programs in this way.  It can be a security risk, and if they specifically only allow php and perl, then they would probably specifically disable as many methods of running non-php/perl as they could. So, short answer is you're probably out of luck.


Question:
I'm quite confused about the basic concepts of a Hash table. If I were to code a hash how would I even begin? What is the difference between a Hash table and just a normal array?

Basically if someone answered this question I think all my questions would be answered:
If I had 100 randomly generated numbers (as keys), how would I implement a hash table and why would that be advantageous over an array?

Psuedo-code or Java would be appreciated as a learning tool...

Answer:
Hashtables are
associative
.  This is a huge difference from arrays, which are just linear data structures.  With an array, you might do something like this:
```
```
int[] arr = ...
for (int i = 0; i < arr.length; i++) {
    System.out.println(arr[i] + 1);
}
```
```
Notice how you are getting an element out of the array by specifying an exact memory offset (
```
i
```
).  This contrasts with hashtables, which allow you to store key/value pairs, later retrieving the value based on the key:
```
```
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
table.put("Daniel", 20);
table.put("Chris", 18);
table.put("Joseph", 16);
```
```
With the above table, we can make the following call:
```
```
int n = table.get("Chris");
```
```
...and be assured that
```
n
```
will be valued at
```
18
```
.
I think this will probably answer most of your questions.  The implementation of a hashtable is a fairly interesting topic, one
which Wikipedia addresses passably well
.


Question:
I was wondering if someone would be able to help me write a CQL query for NDepend that will show me all the methods in my form class that handle the form events.  So I would like to be able to find all the methods that look like this:

Private Sub AddFolderButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddFolderButton.Click

I have had a look through some of the options but I can't really find anything that does what I need.

I have only just started using NDepend, so I haven't really got used to it yet, but I do know one thing how the hell did I live without it all this time.

Answer:
I have sort of got something that works but its not really 100% correct, because all the form generated event handlers have an underscores in there name, I used the underscore as a filter,  I also filter where the name has "EventArgs" in it.  The query looks like this:
```
```
SELECT METHODS WHERE NameLike "_" OR NameLike "EventArgs" AND !IsSpecialName AND IsPrivate
```
```
That query pretty much returns all the methods that handle events but I would still like to find a more correct way.


Question:
Currently we have a DLL that checks whether a username/password is a valid Windows user using the Windows API LogonUser method. We need to enhance it so it checks whether the user belongs to a specified group as well. Is there a Windows method that does that?

Given a Windows username and password, find out whether the user belongs to a specified group.

Answer:
The closest single API is
CheckTokenMembership
, which just leaves the problem of obtaining the user's SID and handle for the group.
If you can use ATL check out the methods on the
CAccessToken
class ... and even if you can't use it check out the implementation in atlsecurity.h for examples.


Question:
I'm working on deploying a small community site. User registration requires nothing more than a username, email address, and password. I'm not even asking for a name, and certainly not storing any sensitive data.

Should I still invest in an SSL certificate? Would it be considered terrible practice to transmit a user's password without one?

This is just a personal project, so I'd like to avoid the extra cost if I could, but I can't help but feel I'd be irresponsible if I didn't secure everything properly.

Answer:
I wouldn't bother with SSL for something like that.
Think about it... there are a million messageboards on the Internet
and none of them use SSL.
Unless you are storing Credit Card numbers or other sensitive
financial/personal information, I just don't think it's worth the
cost.
EDIT: This response is totally outdated. Yes, EVERYONE needs SSL.  Most hosting companies include support for Let's Encrypt (free SSL) so you don't have any reason not to use it anymore.


Question:
I was wondering if there was some kind of J tool in the java swing library that opens up a file browser window and allows a user to choose a file. Then the ouput of the file would be the absolute path of the chosen file.

Thanks in advance,

Answer:
You can use the
JFileChooser
class, check
this example
.


Question:
How do I utilize a ?: operator in the SELECT clause of a LINQ query?  If this can't be done, how can I emulate one?  The goal is to get a CASE block in my select clause. As you might suspect, I'm getting an error: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

Is this the proper way, or a sufficient way, to say "from a inner join i on a.ipid=i.id inner join u on i.uid=u.id"?  If not, please provide one.  Thanks.

var query =
    from a in db.tblActivities
    from i in db.tblIPs
    from u in db.tblUsers
    select new {
        u.UserName == null
            ? i.Address
            : u.UserName,
        a.Request,
        a.DateTime };

Answer:
I'm fairly new to Linq to SQL but I'm pretty sure it would go like this:
```
```
var query =
    from a in db.tblActivities
    from i in a.tblIPs
    from u in i.tblUsers
    select new
    {
        userName = (u.UserName == null)
            ? i.Address
            : u.UserName,
        a.Request,
        a.DateTime
    };
```
```
The if statement needs to be in parentheses and the results outside of them.  As for the joins, you follow the chain down from one->many.


Question: In visual studio 2008, when we press Ctrl+F5, the ASP.NET Development Server is launched to simulate a Web Server. I'm wondering what server does it simulate? IIS6 or IIS7? Is it possible to customize what server it simulate?

Answer:
Sorry, a question, not an answer:
What are the server differences between IIS6 and II7 that matter to your code?
For ASP.NET development, the web server itself is somewhat ASP.NET neutral.   It forwards the request to the .NET framework, so THAT's the part that matters.
More info here:
http://msdn.microsoft.com/en-us/library/58wxa9w5.aspx
Adding Morgan Cheng's comment into the answer:
There is some difference between IIS6 and IIS7 on how to explain web.config. For example, to customize UrlRouteHandler, according to MSDN. IIS6 and IIS7 are different. Details in
http://msdn.microsoft.com/en-us/library/system.web.routing.urlroutinghandler.aspx


Question: I am trying to see what are the gotchas in using XmlHttpWebRequest such that it works for Safari, Firefox and IE?

Answer:
Here's somebody who got his hands dirty with that question:
http://www.webmasterworld.com/javascript/3195000.htm
One general way to research these questions is to peek at the source code of a javascript library, like jQuery, since one of the functions of the library is to handle the differences.   Here's a snippet of jQuery that deals with XMLHttpRequest.  Note the comments about browser differences.
```
```
// Create the request object; Microsoft failed to properly
    // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
    var xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();

    // Open the socket
    // Passing null username, generates a login popup on Opera (#2865)
    if( s.username )
        xhr.open(type, s.url, s.async, s.username, s.password);
    else
        xhr.open(type, s.url, s.async);

    // Need an extra try/catch for cross domain requests in Firefox 3
    try {
```
```


Question:
I am trying to do something like this

public void GetData(ref Dictionary<T,V> dataDictionary)
{

}

Where T can be GUID, string, or int and V is custom user or item object.

Answer:
Does this help?  Any additional info would be helpful.
```
```
public void GetData<T, V>(ref Dictionary<T, V> dataDictionary) {
    if (typeof(T) == typeof(string) || typeof(T) == typeof(int) || typeof(T) == typeof(Guid)) {
       ...
    } else {
        throw new ArgumentException();
    }
}
```
```


Question: I remember from way back at university using a switch with 'binary search' or 'binary switch'. Something like that, My google foo is broken today. Anyway it goes down like this: You define an array of possible options (Strings usually), some magic happens, and those options in the array become the cases in the switch happens. I do remember that they had to be in alphabetical order for this to work. Can you help me remember the magic? Even a name of what I should be looking at would be fantastic.

Answer:
I think what you are looking for is an
Enum
.
From the link above...
```
```
public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY
}

public class EnumTest {

    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
         switch (day) {
            case MONDAY:
                 System.out.println("Mondays are bad.");
                 break;

            case FRIDAY:
                 System.out.println("Fridays are better.");
                 break;

            case SATURDAY:
            case SUNDAY:
                 System.out.println("Weekends are best.");
                 break;

            default:
                 System.out.println("Midweek days are so-so.");
                 break;
        }
    }

    ....
}
```
```


Question:
Is there a way to have a function return a editable reference to some internal data. Here's an example I hope helps show what I mean.

class foo
{
    public int value;
}

class bar
{
    bar()
    {
       m_foo = new foo();
       m_foo.value = 42;
    }
    private m_foo;
    foo getFoo(){return m_foo;}
}

class main
{
    int main()
    {
        bar b = new bar();
        b.getFoo().value = 37;
    }
}

The return of getFoo() according to "==" is the same as the internal m_foo until I try to edit it. In c/c++ I'd return a reference or pointer.

Answer:
You're already returning the reference of
```
foo
```
in
```
getFoo
```
(this happens by default). So any changes that you make to the return value of
```
getFoo
```
will be reflected in the internal
```
foo
```
data structure in
```
bar
```
.


Question:
I have a client-server architecture where client communicates with the server using .NET Remoting. Server handles all business logic and database interaction. I need to add an operation which may take a while to execute and the dataset it returns might be quite large. I'm thinking of employing asynchronous call for that. Now the problem arises: assume, the client made this async call, operation started SQL query, and user either closes the client or clicks Cancel -- what will happen to the operation? Is there any way to cancel the pending async call, which is busy talking to SQL server?

Thanks.

Answer:
You could design your client/server interaction so that the server let a worker thread do the SQL stuff so that it was ready to receive another call from the client.   So, the client makes call 1 and says do SQL work.   The server gives that work to the worker thread and is ready for new incoming.   Then the client makes call 2 and says, "never mind".  The server would do some bookkeeping to make sure it doesn't call back to the client when the worker thread is done.
Can the server safely interrupt the worker thread.  I'm not sure.   Would that have any affect on what SQL Server is doing.   Not sure.


Question:
If you have a particular line of C code in mind to examine in the machine output, how would you locate it in objdump output.  Here is an example

if (cond)
   foo;
   bar();

and I want to see if bar was inlined as I'd like.
Or would you use some alternative tool instead of objdump?

Answer:
You can start objdump using the
```
-S
```
option (like
```
"objdump -Sd a.out"
```
). It will display the sourcecode intermixxed with the assembler code, if the source-files the code was compiled from are available.
Alternatively, you can use the following way:
```
```
int main(void) {
    int a = 0;
    asm("#");
    return a;
}
```
```
becomes
```
```
.file   "a.c"
        .text
.globl main
        .type   main, @function
main:
        leal    4(%esp), %ecx
        andl    $-16, %esp
        pushl   -4(%ecx)
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %ecx
        subl    $16, %esp
        movl    $0, -8(%ebp)
#APP
# 3 "a.c" 1
        #
# 0 "" 2
#NO_APP
        movl    -8(%ebp), %eax
        addl    $16, %esp
        popl    %ecx
        popl    %ebp
        leal    -4(%ecx), %esp
        ret
        .size   main, .-main
        .ident  "GCC: (GNU) 4.3.2"
        .section        .note.GNU-stack,"",@progbits
```
```


Question: I am extremely new at php and I was wondering if someone could help me use either a for() or while() loop to create an array of 10 elements.

Answer:
```
```
$array = array();
$array2 = array();

// for example
for ($i = 0; $i < 10; ++$i) {
    $array[] = 'new element';
}

// while example
while (count($array2) < 10 ) {
    $array2[] = 'new element';
}

print "For: ".count($array)."
";
print "While: ".count($array2)."
";
```
```


Question:
What is the time complexity of dynamic memory allocation using new, malloc, etc.?  I know very little about how memory allocators are implemented, but I assume the answer is that it depends on the implementation.   Therefore, please answer for some of the more common cases/implementations.

Edit:
I vaguely remember hearing that heap allocation is unbounded in the worst case, but I'm really interested in the average/typical case.

Answer:
I would think it would generally be O(n) where n is the number of available memory blocks (since you have to scan the available memory blocks to find a suitable one).
Having said that, I've seen optimizations that can make it faster, specifically maintaining multiple lists of available blocks depending on their size ranges (so blocks less than 1k are in one list, blocks from 1k to 10k are in another list and so on).
This is still O(n) however, just with a smaller n.
I'd be interested in seeing your source that there's a heap allocation that's unbounded (if, by that, you mean it could take forever).


Question:
What is the best way to give the user feedback for a color selection?

I have a dialog with a "Select Color" push button which pops a QColorDialog. After the selection is made I want to show the user the color selected.

Usually I do this using a QLabel and changing it's background color in the palette. This method is cumbersome and I think not very portable.

Is there a standard way of doing this?

Answer:
The way I'm doing it is the following :
I actually change the color of the button, to reflect the user choice. To do this, I'm using the Qt style sheet, which ensure it is portable :
```
```
const QString COLOR_STYLE("QPushButton { background-color : %1; color : %2; }");

QColor ChosenColor; // Color chosen by the user with QColorDialog
QColor IdealTextColor = getIdealTextColor(ChosenColor);
btnChooseColor->setStyleSheet(COLOR_STYLE.arg(ChosenColor.name()).arg(IdealTextColor.name()));
```
```
To make sure the label of the button is always readable, I'm calling the method getIdealTextColor(), which is a method I've found from a codeproject article :
```
```
//==============================================================================
//  Nom : getIdealTextColor
//! @return an ideal label color, based on the given background color.
//! Based on http://www.codeproject.com/cs/media/IdealTextColor.asp
//==============================================================================
QColor JSPreferencesDlg::getIdealTextColor(const QColor& rBackgroundColor) const
{
    const int THRESHOLD = 105;
    int BackgroundDelta = (rBackgroundColor.red() * 0.299) + (rBackgroundColor.green() * 0.587) + (rBackgroundColor.blue() * 0.114);
    return QColor((255- BackgroundDelta < THRESHOLD) ? Qt::black : Qt::white);
}
```
```


Question:
Suppose that I have a Java class with a static method, like so:

class A
{
    static void foo()
    {
        // Which class invoked me?
    }
}

And suppose further that class A has an arbitrary number of subclasses:

class B extends A { }
class C extends A { }
class D extends A { }
...

Now consider the following method invocations:

A.foo();
B.foo();
C.foo();
D.foo();
...

My question is, how can method foo() tell which class is invoking it?

Answer:
It can't, and that's part of the problem with static methods.  As far as the compiler is concerned
```
A.foo()
```
and
```
B.foo()
```
are exactly the same thing.  In fact, they compile down to the same bytecode.  You can't get more similar than that.
If you really need this sort of information, use a singleton and turn
```
foo()
```
into an instance method.  If you still like the static syntax, you can build a facade
```
A.foo()
```
.


Question:
Of course, the immediate answer for most situations is "yes", and I am a firm believer that a process should correctly cleanup any resources it has allocated, but what I have in my situation is a long-running system daemon that opens a fixed number of file descriptors at the startup, and closes them all before exiting.

This is an embedded platform, and I'm trying to make the code as compact as possible, while not introducing any bad style. But since file descriptors are closed before exit anyway, does this file descriptor cleanup code serve any purpose?  Do you always close all your file descriptors?

Answer:
man 3 exit:
```
```
....
All open stdio(3) streams are flushed and closed.  Files created by tmpfile(3) are removed.
```
```
So i believe leaving main effectively calls the exit function with main's return value. Though I would argue that it is bad style. Personally, I
always
explicitly free/close any acquired resources.


Question:
I'd like to give customers a choice of the database engine, but also want to minimize my troubles of such a decision.

The engines in question are MySQL (5 or later) and SQL Server (2005 or later).

Answer:
Google for the differences in datatypes.
But the schema is just a part of the picture.
The SQL dialects are different too.  Google for those differences.   Then, either stick to a subset of SQL that's common to both, or build in a scheme to use somewhat different SQL in each.
Don't wait until the end to test on the "other" db.  Test on both from the start so that you don't invest too much in a dead end design direction.
Here's a starting place:
http://www.microsoft.com/technet/prodtechnol/sql/2000/deploy/mysql.mspx#EZD
and:
http://troels.arvin.dk/db/rdbms/#insert


Question:
I'm trying to process a credit card transaction in .net and it works perfectly in Safari, Opera, and IE. When I try the same transaction in Firefox it sends two requests and I end up with a double charged card. From a quick search on Google it seems that this is an issue with Firebug but I am unable to find a way to stop this double post.

Does anyone have any idea on how to prevent Firefox (and Firebug) from doing this?

Answer:
Use a
nonce
, a unique key which is only used once.
Send a unique number along with the form fields to the browser (this is often done with a hidden input field), and store a copy on the server with the transaction. Within the form, change the number on submit.  Validate that the keys match when processing your requests.
There may also be a clear explanation of what's happening on the front end, and that issue could be eliminated client-side.  It's best to solve the double-submit problem on the server, simply because there are so many ways in which a double submit could occur.


Question: Is it possible to free memory allocated by C's alloca() explicitly, before the current function exits?  If so,how?

Answer:
No, because it's allocated on the stack along with the local variables.  If you want memory that you can explicitly free, use one of the dynamic memory allocation functions.
There's no hybrid that allows you to explicitly free
AND
have it automatically free on function exit as well, at least not in the standard.


Question:
I am using UIActivityIndicatorView to showing user that there is something going on, let them wait. But UIActivityIndicatorView looks small, do not have background color, and not very obvious to the user. While in iPhone SDK's UIImagePickerController, it uses the similar mechanism, but with the black background as well as some text besides the indicator.

I am wondering whether there is any existing component to do that task, or I have to implement my own class to perform that task.

Any suggestion are highly welcome, thanks in advance.

Answer:
If you just want a different background color of your UIActivityIndictatorView, you could just send the setBackgroundColor message to the object, i.e.:
```
```
[activityIndicator setBackgroundColor:[UIColor blackColor]];
```
```
By the way, you can change the size of the indicator as well. just do setFrame or initWithFrame with a bigger rect. Remember UIActivityIndicatorView inherits from UIView so you get all the customization of UIView.


Question:
My installation of APEX has come pear shaped on a Oracle 9.2.0.5.0 instance, all the packages are invalid.

I've tried recompiling everything with DBMS_UTILITY.compile_schema, but still all the packages are invalid. So, tried recompiling individual packages,

SQL> ALTER PACKAGE FLOWS_020000.WWV_FLOW_QUERY COMPILE BODY;

Warning: Package Body altered with compilation errors.

SQL> show err
No errors.
SQL>
SQL> ALTER PACKAGE FLOWS_020000.WWV_FLOW_QUERY COMPILE;

Warning: Package altered with compilation errors.

SQL> show err
No errors.
SQL>

nothing in the alter log for it..

How can I find what the error is? shouldn't "show err" give it to me?

Answer:
try
```
```
SHOW ERRORS PACKAGE BODY FLOWS_020000.WWV_FLOW_QUERY
```
```


Question:
Given the following simple example:

    List<string> list = new List<string>() { "One", "Two", "Three", "three", "Four", "Five" };

    CaseInsensitiveComparer ignoreCaseComparer = new CaseInsensitiveComparer();

    var distinctList = list.Distinct(ignoreCaseComparer as IEqualityComparer<string>).ToList();

It appears the CaseInsensitiveComparer is not actually being used to do a case-insensitive comparison.

In other words distinctList  contains the same number of items as list.   Instead I would expect, for example, "Three" and "three" be considered equal.

Am I missing something or is this an issue with the Distinct operator?

Answer:
```
StringComparer
```
does what you need:
```
```
List<string> list = new List<string>() {
    "One", "Two", "Three", "three", "Four", "Five" };

var distinctList = list.Distinct(
    StringComparer.CurrentCultureIgnoreCase).ToList();
```
```
(or invariant / ordinal / etc depending on the data you are comparing)


Question:
I'd like to popup a simple dialog with an editor box, to let user enter some value then just return. I am wondering whether iPhone SDK has that kind of support.

Thanks.

Answer: You need to create your popup (UIAlertView) and add a UITextField (or whatever component you'd like to use) to it as a sub-view.  The UIAlertView won't auto-resize for the component you add so you have to hack that part of it together by adding text to it.  The text will increase the height of your popup and provided you don't add too much be hidden by your component.


Question:
I want to assign default values to a column in my select sql query so that if the value of that column is null I get that default value in my recordset.  Is there anyway to do this?

Example:

select col1 (some default value) from tblname;

Answer:
```
```
select
  isnull(col1, defaultvalue)
from
  tblname;
```
```


Question: Can anyone help me to put a vertical scroll bar for an <asp:CheckBoxList>?

Answer:
Try actually sending the Key Combination Ctrl+C, instead of directly terminating the process:
```
```
[DllImport("user32.dll")]
        public static extern int SendMessage(
              int hWnd,      // handle to destination window
              uint Msg,       // message
              long wParam,  // first message parameter
              long lParam   // second message parameter
              );
```
```
Look it up on the MSDN, you should find what you need there in order to send the Ctrl+Key combination...
I know that the message you need for sending Alt+Key is WM_SYSTEMKEYDOWN and WM_SYSTEMKEYUP, can't tell you about Ctrl...


Question:
I have a solution in Visual Studio 2008 which has multiple projects. One of the projects is a WCF project. Sometimes I just want to debug other projects, but when I press F5, Visual Studio has wcfsvchost.exe launched to host the WCF project even it is not "StartUp Project".

Currently, every time I debugging other projects, I Have to Unload the WCF project to prevent the annoying WcfSvcHost.exe host pop up. However, it is not convenient. Anybody know better idea to prevent WCF project to be hosted in debugging mode?

Answer:
You could try to unload the WCF project in the solution, then debug.
Sorry it was late I misread the last part to fast, then the only other way, that I know of, is to comment out the web parts in the Property Group of the project.  This prevented the pop-up for me
Unload the project, Comment out the mentioned part, reload.
```
```
<!--<PublishUrl>http://localhost/WindowsFormsApplication1/</PublishUrl>
<Install>true</Install>
<InstallFrom>Web</InstallFrom>
<UpdateEnabled>true</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>true</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>-->
```
```


Question:
So my program needs to go through a plain text file line by line essentially:

Read line 1:
Do commands
loop
Read line2:
Do Commands
loop

etc until its done with the entire file does anyone know any good coding examples for this, all the tutorials seem to show open and writing/reading textfiles but nothing on how to do it line by line.

Answer:
You could do it like this:
```
```
Using f As System.IO.FileStream = System.IO.File.OpenRead("somefile.txt")
    Using s As System.IO.StreamReader = New System.IO.StreamReader(f)
        While Not s.EndOfStream
            Dim line As String = s.ReadLine

            'put you line processing code here

        End While
    End Using
End Using
```
```


Question:
Suppose I have some code:

let listB = [ 1; 2; 3 ]

Using Lisp notation, how do I do a car and cadr against this list? I know cons is ::.

Or in Scheme, first and rest?

Answer:
List.head
: Returns the first element of a nonempty list
(The head of the list)
.
List.tail
: Returns all the elements of a
nonempty list except the first
(The tail or rest of the list)
.
Example (
using F# Interactive Console
):
```
```
> let sample = [1;2;3;4];;

val sample : int list

> List.head sample;;

val it : int = 1

> List.tail sample;;

val it : int list = [2; 3; 4]
```
```


Question:
I've got a lot of pages in my site, I'm trying to think of a nice way to separate these into areas that are a little more isolated than just simple directories under my base web project.  Is there a way to put my web forms into a separate class library?  If so, how is it done?

Thanks in advance.

Answer:
At first thought, I don't think this is possible, due to the way ASPX is non-precompiled..
However, you can create classes that inherit from
```
Page
```
and place them into a DLL to re-use code-behind functionality. This can of course include control instantiate logic if required, but there is no designer to work with (if you need it).


Question: Is it possible to retrieve the CPUID and MAC address of a client machine from a Ruby on Rails application?. Are there any plugins available for this?

Answer:
I'm pretty sure it is not possible to parse the /proc filesystem of a client computer through a Rails applications (and thank God for that).
What you could do is make use of Javascript to some extent. There are quite some sites on the internet (mainly privacy scanners) which make use of Javascript to show extensive information about a client system. This might even work for the type of CPU of the client uses (assuming that is what you mean by 'CPUID').
What neither Javascript nor Rails can do for you though, is show you the MAC address of a client (assuming with 'macid' you mean a MAC address). If you take a deeper look into the way TCP/IP networking is done, you'll notice that this is by design. A computer in another network segment (say, the internet) is never intended to know your MAC address, nor does it need to.
If you really want to know someone's MAC, you'll need to use something like a Java applet or an ActiveX control (though that limits you to a certain platform). Those things should prompt your user for confirmation / permission before sending out privacy sensitive information like MAC addresses, which is a Good Thing.


Question:
I have a list of email address which I want to distribute evenly by domain.

For example:

let the list be,

a@a.com
b@a.com
c@a.com
a@b.com
b@b.com
c@c.com

The output should be

a@a.com
a@b.com
c@c.com
b@a.com
b@b.com
c@a.com

The source list is not sorted by domain as in example, but can be sorted by domain, if that can help. What would be an efficient (single/two pass?) algorithm of doing this?

raj

Answer:
My starting attempt would be a hash map of linked lists, so that once all the domain collisions were grouped, you could iterate though the linked lists one at a time.
If that makes any sense.
The following code is completely
UNTESTED
, and I know there is a bunch of stuff not right in the second loop, but it was faster than trying to explain further.
```
```
$sortedList = array();
$tempList
$emailList = array('a@a.com', 'b@a.com', 'c@b.com', 'd@b.com', 'e@c.com', 'f@a.com');

$emailCount = 0;
foreach ( $emailList as $email ) {
    list($username, $domain) = explode('@', $email);
    $tempList[$domain][] = $user;
    $emailCount++;
}

for ( $i = 0; $i < $emailCount; $i++ ) {
    $listIndex = $i % count($tempList);
    if ( !empty($tempList[$listIndex]) ) {
        $sortedList[] = $tempList[$listIndex][0];
        unset($tempList[$listIndex][0]);
    } else {
        unset$tempList[$listIndex]);
    }
}
```
```


Question: we are writing tests for a COM library written in VB 6.0.The problem we are facing is that, we are unable to access events declared in VB( withevents). We get exception, "object does not support set of events". How can we overcome this problem?

Answer:
For example, we have a class in VB 6.0 called DatabaseCommand.
```
```
Option Explicit

Public Event SavedSuccessfully()

Public Sub Execute(ByVal vAge As Integer, ByVal vName As String, ByVal vAddress As String)

    RaiseEvent SavedSuccessfully

End Sub
```
```
Now, personclass
```
```
Private WithEvents dbCommand As DatabaseCommand

Public Sub Init(ByVal vDBCommand As DatabaseCommand)

    Set dbCommand = vDBCommand

End Sub

Private Sub dbCommand_SavedSuccessfully()
    'not implemented
End Sub
```
```
Now, when try to test this ( after compiling the vb project)
```
```
MockRepository repository = new MockRepository();

PersonLib.DatabaseCommand db = repository.DynamicMock<PersonLib.DatabaseCommand>();

PersonLib.PersonClass person = new PersonLib.PersonClass();

person.Init(db);  --- this line throws error - Object or class does not support the set of events
```
```


Question: I am an intermediate C programmer. If you have made any coding mistake that you came to know later that it was the most hazardous / harmful to the total application please share that code or description. I want to know this because in future I may come across such situations and I want to have your advice to avoid such mistakes.

Answer:
```
```
if (c = 1) // insert code here
```
```


Question: My application communicates with another system via IBM Websphere MQ. Sometimes no message comes into my queue but the other system said They already sent to me. So I want to know how to keep a history for all messages that arriving on my queue.

Answer:
Keep in mind that it may still be coming across the network as the MQ architecture may have many middle-ware queues.  Similarly, there's no requirement for a message to immediately get transmitted across a channel - the sender may batch up the messages and send them with a trigger.
The best way to ensure you log everything that arrives is to do this is with an interceptor queue.
This is the queue (let's call it A) that the channel writes to and, until this change, your application read from.  You then have a transfer process the reads from A, logs the message then writes it to the second queue (B).  This second queue is what your application now reads from.


Question:
Is there an application , which can parse a given set of stored procedures (SQL Server 2000) and  gets all tables and associated columns that are being used in it.
The stored procedure can have tables from different databases.

Output should be like
TableA
   columnA
   columnC
   columnD

TableB
   columnE
   columnF
   columnG

I have written an small application using Database Edition GDR Any one interested can refer to http://tsqlparsergdr.codeplex.com

Answer:
UPDATE - 20 Jan 2009
*
Visual Studio DB Professional Edition shipped with a full T-SQL script DOM parser
http://blogs.msdn.com/gertd/archive/2008/08/21/getting-to-the-crown-jewels.aspx
Not a concrete solution - but a line of thought.
Considered sysdepends as a potential solution - but it is notoriously unreliable at containing
all
the dependent object information.
but how about something Lex/Yacc derived?  There are a few commercial parsers e.g.
http://www.sqlparser.com/download.php
Not looked for open-source implementation but I think I would look for that route.  Here's how I started my search:
http://www.google.com/search?hl=en&q=sql+lex+yacc+parse
BNF syntax for ANSI SQL can be found here:
http://savage.net.au/SQL/
With a lex implementation of choice, this seems a relatively straight forward engineering problem from here.  (albeit with some heavylifting if you want to support MS SQL extensions)


Question:
A lot of programmers who are used Visual Studio have a hard time adjusting to the fact that in other source control systems, files do not need to be locked/checked out to one developer at any given time.

Proponents of merging say that allowing two people to work on the same file speeds up productivity since it eliminates queuing up for the same source file. It also avoids cases where code needs to be written but the source is checked out to a guy who just left on a two-week vacation.

Locking advocates say that a lot of risk is introduced when more than one person works on the same file simultaneously. Communication and coordination between team members becomes much more necessary when using the merge model, according to them. Plus, a lot of people seem to mistrust automated merges.

What is the most compelling reason for you to use one method over the other?

Answer:
Locking files may not scale very well to larger team. With version control systems that utilizes a lot of branching and merging, it simply may not be practical to let any one person give such control over the repository (thus, not scale to larger team).
With Subversion, for example, branching is a pointer copy, so you can easily create a TRY branch to avoid corrupting the trunk if you are experimenting with something, but want to commit.
With distributed version control systems like Git, every check out essentially is a branch.


Question:
What's the best way to take some plain text (not PHP code) which contains PHP-style variables, and then substitute in the value of the variable. This is kinda hard to describe, so here's an example.

// -- myFile.txt --
Mary had a little $pet.

// -- parser.php --
$pet = "lamb";
// open myFile.txt and transform it such that...
$newContents = "Mary had a little lamb.";

I've been considering using a regex or perhaps eval(), though I'm not sure which would be easiest. This script is only going to be running locally, so any worries regarding security issues and eval() do not apply (i think?).

I'll also just add that I can get all the necessary variables into an array by using get_defined_vars():

$allVars = get_defined_vars();
echo $pet;             // "lamb"
echo $allVars['pet'];  // "lamb"

Answer:
Here's what I've just come up with, but I'd still be interested to know if there's a better way. Cheers.
```
```
$allVars = get_defined_vars();
$file = file_get_contents('myFile.txt');

foreach ($allVars as $var => $val) {
    $file = preg_replace("@\\$" . $var . "([^a-zA-Z_0-9\x7f-\xff]|$)@", $val . "\\1", $file);
}
```
```


Question:
In my models, there are lots of attributes and methods that perform some calculation based on the model instance's attributes.  I've been having the methods return nil if the attributes that the calculations depend on are nil.  As a consequence of this design decision, I'm doing a lot of nil checks before displaying these values in my views.

I thought about having these methods return zero instead of nil when they don't have enough information, but I chose nil because zero is a valid computation result and nil implies that there was not enough information.

Should I return 0 instead of nil?  Is there any other pattern that I could use to avoid doing a bunch of nil checks in my views?

Answer:
I tend to think you are doing things right if your problem is choosing whether to display, or not display, the results of a calculation.  If it would make no sense to display any value, then nil is perfectly reasonable.
If, however, your business logic is resulting in you getting into a state where much of the view will be habitually blank, then you probably should refactor such that your program loses its leaky abstractions.
Consider, for example, an application which starts by tracking recipes for
```
Food
```
.  Then, as requirements morph, we get the notion of pies needing to display different information than burgers.  Rather than having a
```
calculate_deliciousness_of_pie_or_nil_for_burger
```
method, and then checking for nil in the view, I'd break that into a pie view for pies and a burger view for burgers.  This might (probably would) require rethinking my object abstractions.


Question: I need to read account number from Maestro/Mastercard with smart card reader. I am using Java 1.6 and its javax.smartcardio package. I need to send APDU command which will ask EMV application stored on card's chip for PAN number. Problem is, I cannot find regular byte array to construct APDU command which will return needed data anywhere...

Answer:
You need to do construct a CommandAPDU object and pass it to the transmit()-command.
You should be able to find the precise command in the documentation for your smartcard, but here is one example:
```
```
byte[] readFile(CardChannel channel) throws CardException {
  CommandAPDU command = new CommandAPDU(0xB0, 0x60, 0x10, 0x00);
  ResponseAPDU response = channel.transmit(command);
  return response.getData();
}
```
```


Question:
I'm putting a crontab job for updating with apt-get once a day (running Debian Lenny, there are updates almost daily). But almost all examples i've seen of this cron job invoke the -d flag.

This elicits 4 questions:

Why should I only download the
packages and not install them?

Doesn't this defeat the purpose of
running it automatically?

Don't I have to go in and actually
install the updates later?

Is it safe for me to run the cron
job without the -d flag?

Answer:
You're operating on a faulty assumption--neither apt-get (nor aptitude) are meant to be run automatically, nor is the Debian packaging system really designed for it. That's why the tools make it difficult.
What happens when a software upgrade breaks because you forgot to update a configuration file? This has happened to me in the past (apache2), and some with severe consequences that prevented the machine from booting (mdadm). What happens when the software brings in dependencies you don't want (i.e. bringing in the entire X11 windowing system, on a server)? Etc, etc...
If you're worried about installing security upgrades automatically, you want to look at the
unattended-upgrades
package. It will download and install packages from the security archive for you.


Question:
I have a dll that must be useable from C etc, so I cant use string objects etc as a normal would, but I'm not sure on how to do this safely..

const char *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    return ss.str().c_str();
}

could the c string be destroyed when ss falls off the stack? I'm  assuming so...

Another option may be to create a new string on the heap, but what is going to deallocate that?

const char *GetString()
{
    std::stringstream ss;
    ss << "The random number is: " << rand();
    char *out = new char[ss.str().size()];
    strcpy(ss.str().c_str(), out);
    return out;//is out ever deleted?
}

The same goes for pointers to other things as well as strings.

Answer:
The first would actually not work because the stringstream deallocates it's space on destruction. So if you try to de-reference that pointer there is a good chance that your program would crash.
The second option you mention is how it's usually done and the user of the function is required to deallocate the space. IIf this is a C program which uses the function make sure you allocate with malloc() and free with free()
Another option is to return an address of a static char array. This is relevant if you know in advance a good upper bound to the length. More importantly this should be used ONLY if there is no chance that the function is going to be called from two different threads at the same time because using a static array essentially makes your function non-
reentrant
.


Question: I am designing an Automatic text summarizer. One of the major modules in this project requires TRAINING CORPUS. Can someone please help me out by providing TRAINING CORPUS or referring some link to download it. Thanks in anticipation

Answer:
See
How to Write a Spelling Corrector
by Norvig. He mentions
Project Gutenberg
,
Wiktionary
,
British National Corpus
,
Birkbeck spelling error corpus
. There's also
Brown Corpus
.


Question: I'm having a problem where a jQuery setting against an .html() property on a selected element is returning the error 'nodeName' is null or not an object. This only occurs on IE6 and IE7, but not FF2, FF3, Opera (latest Nov 12,2008) or Safari (again, latest).

Answer:
I resolved the problem. The example looks like this:
$('#section #detail .data').html(data);
...where data is HTML returned from an AJAX call, and this bug only occurs on IE6 and IE7 on the second attempt AJAX call, not the first. It's inexplicable. The error returned is:
```
```
'nodeName' is null or not an object
```
```
The fix is to simply clear the variable first before setting:
$('#section #detail .data').html('');
$('#section #detail .data').html(data);
And then IE6 and IE7 started working again with it.
BTW, I had to install Visual Web Developer 2008 Express Edition to get a debugger working in IE7. That info is
here
.


Question:
In Erlang, every process has a group leader, and when a process wants to print something (i.e. it calls the io library or does something similar), it will send a message to its group leader.

My question is, where can I find the specification of these messages? Or in general, the specification of what a group leader should do?

I managed to find out with some experimenting that sometimes the process sends an {io_request, Sender, GroupLeader, Request} term, and the answer is an {io_reply, GroupLeader, ok} term, but there may be other cases.

Answer:
The Erlang Rationale (video)
or
(slides)
;  is a good source of information, as is the source code for
user.erl
.
In short:
```
```
{io_request, From, ReplyAs, Request}
  %From is the process to send the reply to,
  %ReplyAs is any term the caller desires to
  %match up the request and the response. (returned verbatim in the reply)
  {io_reply, ReplyAs, Reply}
```
```
Some requests in user.erl:
```
```
{put_chars, IoList} % puts the iolist
 {put_chars, M,F,A} % puts the result of apply(M,F,A)
 {get_geometry, 'rows' | 'columns'} % returns the number of rows or columns of the console
 {get_line, Prompt} % calls io_lib:collect_line(Prompt)
 {get_chars, Prompt, Mod, Func, ExtraArgs}
 {get_until, Prompt, Mod, Func, Args}
 {setopts, Options} % only option supported by user is 'binary'
                    % (binary mode if present in Options, list mode otherwise)
```
```


Question:
Let's say I'm running a simple server and have accept()ed a connection from a client.

What is the best way to tell when the client has disconnected? Normally, a client is supposed to send a close command, but what if it disconnects manually or loses network connection altogether? How can the server detect or handle this?

Answer:
select (with the read mask set) will return with the handle signalled, but when you use ioctl* to check the number of bytes pending to be read, it will be zero. This is a sign that the socket has been disconnected.
This is a great discussion on the various methods of checking that the client has disconnected:
Stephen Cleary, Detection of Half-Open (Dropped) Connections
.
* for Windows use ioctlsocket.


Question:
Consider the following signature in C#:

double Divide(int numerator, int denominator);

Is there a performance difference between the following implementations?

return (double)numerator / denominator;

return numerator / (double)denominator;

return (double)numerator / (double)denominator;

I'm assuming that both of the above return the same answer.

Have I missed any other equivalent solution?

Answer:
Have you tried comparing the IL (for example, with
Reflector
)?
```
```
static double A(int numerator, int denominator)
{ return (double)numerator / denominator; }

static double B(int numerator, int denominator)
{ return numerator / (double)denominator; }

static double C(int numerator, int denominator)
{ return (double)numerator / (double)denominator; }
```
```
All three become (give or take the name):
```
```
.method private hidebysig static float64 A(int32 numerator, int32 denominator) cil managed
{
    .maxstack 8
    L_0000: ldarg.0 // pushes numerator onto the stack
    L_0001: conv.r8 // converts the value at the top of the stack to double
    L_0002: ldarg.1 // pushes denominator onto the stack
    L_0003: conv.r8 // converts the value at the top of the stack to double
    L_0004: div     // pops two values, divides, and pushes the result
    L_0005: ret     // pops the value from the top of the stack as the return value
}
```
```
So no: there is exactly zero difference.


Question:
At the moment I have a set of divs, generated dynamically by php and all having their ids starting with 'itembox', with a count number appended. I have a droppable garbage bin area on the page so that the user can delete an individual itembox by fdragging and dropping on to the bin.

My problem is that the droppable won't seem to activate when I drag the original, while it will function (perfectly) when I have helper: 'clone' set. Unfortunately, though, when dragging, the cloning function takes its clone from the first iteration of the itembox, no matter which itembox is actually dragged.

So I'm looking for a solution to either make the droppable accept an original or force the cloning function to take its clone from the itembox actually dragged.

Answer:
I guess the problem must lie in the accept option of your droppable initializer. Just try the following:
```
```
$('#mydroppable').droppable(
{
    accept: function() { return true; },
    drop: function () { alert("Dropped!"); }
});
```
```
Now this will accept everything, so you should probably implement some filtering in the accept function but none the less this should work.


Question:
I understand the following elements :

there is some sort of crawling (configured in central administration)

when the crawling is done, there is a slight delay, after which you can have your search results displayed.

But, in a document library with publishing enabled, documents that are not published don't appear in search results. Is that normal ?

Answer:
All contents are crawled using the default content access account. Most of the time, this is a dedicated account, and SharePoint give it "Full Read" permissions.
Unfortunately, non approved items are not visible for "read users". So it will index the latest published version.
However, you can't really give more permissions to this user. If you do so, it will always index unpublished item, without indexing the latest publish version. So user without approvers permissions won't be able to search those items.


Question: What is the difference between atan and atan2 in C++?

Answer:
```
std::atan2
```
allows calculating the arctangent of all four quadrants.
```
std::atan
```
only allows calculating from quadrants 1 and 4.


Question:
My record sheet app has a menu option for creating a new, blank record sheet. When I open a sheet window, I can open new windows without a problem, using subprocess.Popen() to do it.

However, under Windows (I haven't tested it on other OSes yet), if I open a new window then use the "open file" dialog to populate the fields with data from a file, I'm no longer able to create new windows. Once it's populated, Windows gives me the

'foo.py' is not recognized as an internal or external command, operable
  program or batch file.

I don't understand what would cause Windows to suddenly not recognize the Popen() call. I don't have any code that would affect it in any way that I'm aware of.

Answer:
From the error message, it looks like you need to pass the full path of "foo.py" to your Popen call. Normally just having "foo.py" will search in your current working directory, but this can be a bit unpredictable on Windows, I have found. Yours seems to be jumping around with the open file dialog.
Secondly, just for good measure, it would seem like you would need to pass foo.py as an argument to python.exe executable, rather than executing foo.py itself. Again, I would specify this by path.
So to be safe, something like:
```
```
subprocess.Popen([r'C:\Python2.5\python.exe', r'C:\path\to\foo.py'])
```
```


Question:
When my IronPython program gets to the line

import wx

I get this message:

A first chance exception of type
'IronPython.Runtime.Exceptions.PythonImportErrorException' occurred in IronPython.dll

Additional information: No module named _core_

although I do have the file wx\_core_.pyd. Also, before attempting the import, I have the lines:

sys.path.append('c:\\Python24\\Lib\\site-packages')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wx\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wx-2.6-msw-unicode\\wxpython\\lib')
sys.path.append('c:\\Python24\\Lib\\site-packages\\wxaddons')

which I hoped would let IronPython find everything it needed.

Answer:
No, this won't work. Wx bindings (like most other "python bindings") are actually compiled against CPython.
In this regards they are not just packages on sys.path to be found, as you have tried. They actually depend on CPython itself.
This rather dry document explains the process.
Note: There was a mission by some of the crew at Resolver Systems to allow you to use CPython bindings with IronPython (called
IronClad
) but this is in its early stages, and I think they will concentrate on getting things like Numpy working first, GUI toolkits will always be the last, and hardest.


Question:
Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.

For example

byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};

byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}

Answer:
You can put the byte array into
String
and run match by IndexOf. Or you can at least reuse
existing algorithms
on string matching.
```
```
[STAThread]
    static void Main(string[] args)
    {
        byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
        byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125};
        string needle, haystack;

        unsafe
        {
            fixed(byte * p = pattern) {
                needle = new string((SByte *) p, 0, pattern.Length);
            } // fixed

            fixed (byte * p2 = toBeSearched)
            {
                haystack = new string((SByte *) p2, 0, toBeSearched.Length);
            } // fixed

            int i = haystack.IndexOf(needle, 0);
            System.Console.Out.WriteLine(i);
        }
    }
```
```


Question:
While connecting .NET to sybase server I got this error message:

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

This has worked properly before. System DSN with same details worked and data connection through vs.net also worked.

I am using VS.NET 2005.

Any suggestions?

Answer:
Perform the following steps:
Start the Registry Editor by typing
```
regedit
```
in the Run window.
Select the following key in the registry:
```
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
```
.
In the Security menu, click Permissions.
Grant Full Permission to the account which is being used for making connections.
Quit the Registry Editor.


Question:
Is there any such thing as a virtual Lineprinter.I mean a software emulation of a printer, that outputs to screen.

I have a project to change the output of print job. My past experience with a lineprinter was tedious rounds of

loop:
   print
   walk down two flights
   check the output
   walk back up two flights
   edit code
got loop:

Anyone who thinks a lineprinter can be installed in a programmers office has not used a LinePrinter!

Googles just turning up printer emulation, as in printers that emulate other printers or virtual printer ports!

Answer:
Perform the following steps:
Start the Registry Editor by typing
```
regedit
```
in the Run window.
Select the following key in the registry:
```
HKEY_LOCAL_MACHINE\SOFTWARE\ODBC
```
.
In the Security menu, click Permissions.
Grant Full Permission to the account which is being used for making connections.
Quit the Registry Editor.