Question: Pretty much as the question asks. Answers preferably in pseudo code and referenced. The correct answer should value speed over simplicity.

Answer:
See
Intersections of Rays, Segments, Planes and Triangles in 3D
. You can find ways to triangulate polygons.
If you really need ray/polygon intersection, it's on 16.9 of
Real-Time Rendering
(13.8 for 2nd ed).
We first compute the intersection
  between the ray and [the plane of the
  ploygon]
```
pie_p
```
, which is easily done
  by replacing
```
x
```
by the ray.
```
```
n_p DOT (o + td) + d_p = 0 <=> t = (-d_p - n_p DOT o) / (n_p DOT d)
```
```
If the denominator
```
|n_p DOT d| < epsilon
```
, where
```
epsilon
```
is very small
  number, then the ray is considered
  parallel to the polygon plane and no
  intersection occurs. Otherwise, the
  intersection point,
```
p
```
, of the ray and
  the polygon plane is computed:
```
p = o + td
```
. Thereafter, the problem of
  deciding whether
```
p
```
is inside the
  polygon is reduced from three to two
  dimentions...
See the book for more details.


Question:
I would like to know if you guys have any suggestions about debug levels when writing an application.

I thought about 4 levels:

0 : No Debug

1 : All inputs and outputs

2 : "I am here" notification from significant functions with main parameters

3 : All variables verbose

Answer:
Whatever you choose, there will be something you wanted to see which is just into the next level...
I don't think there is a general answer to this question, because it's so dependent on what the application is doing.  Much like the oily pages in the Haynes manual (UK readers will know what I mean), I tend to find that you end up with heavy logging in the areas which have traditionally been troublesome, and almost none in the area which is going to cause you trouble
next
.


Question:
I have a project where I've been using TDD and unit tests as "software vises". In essence I translate the requirements into tests that verify that the code conforms to the requirements. I rarely have to go back and edit the unit tests, which rather is the point: only the "real" code should be modified. At the moment, there are 900 unit tests.

Now some requirements have been changed by the gold-owners. Since the former requirements are so thorougly encoded in the existing unit tests, it seems that changing them to conform to the new requirements would be inviting disaster. How do you adapt your unit test suites to handle this kind of change?

Answer:
Per definition the
unit-tests
don't replicate the requirements for the application. They describe the requirements for a module. That's a difference, the module can be reused even in an application with different requirements or isn't used at all. So the changing requirements don't affect real unit-tests (except that you have to write new for new modules or abandon old tests for modules no longer needed for the changed requirements).
On the other hand:
acceptance-tests
deal with the requirements on application-level. So I think you talk about acceptance-tests.
I would add the new requirements as new acceptance-test. But for the old ones you have to look through them, how they are invalidated by the changed requirements.


Question:
I have the following (shortened query):

SELECT
    `Statistics`.`StatisticID`,
    COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
WHERE `FlagCount` = 0
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10

Now, neither FlagCount = 0 or COUNT(Flags.FlagType) work in the WHERE clause. I thought about using a SET but I'm not sure how I'd add that to the query. Any ideas?

Thanks,

Answer:
Use
```
HAVING COUNT(DISTINCT Flags.FlagType) = 0
```
.


Question:
I recently read a question on here about static and dynamic linking, which reminded me of some questions I've had about it. From that post, I can see what the technical difference is (including object file contents directly instead of merely pointing to it), but I'd like to know a bit more about the pros/cons of doing so.

A while ago, a friend of mine who's been programming several years was lamenting that C# isn't statically linked and saying that that was the feature he desired most for a future version. Unfortunately I'm a novice and don't really understand this statement.

Thanks for any enlightenment!

Answer:
A statically executable contains all the objects that it needs so no external DLL will be called when executed. The advantaje is that is is portable accross a lot of platforms no matter what version of DLLs have been installed on that system. The BIG disadvantage is that you are probable wasting disk space since you are including in your executable code that is already present in system/external DLLs. Moreover I think, but I'm not very sure, that DLLs are loaded in main memory only once, no matter how many executables are using them, but if you link statically the library objects inside your executable you load the same code twice (one for the DLL used by the rest of the programs and one for your executable). On the other hand this could be an advantage instead a disatvadvantage, since the executable contains only the objects of the external libraries that it needs, not the whole library. A DLL is loaded in memory as a whole when an application needs it.
Static linking is ideal to compile small apps that you want to carry from one system to another as a small tool. I.e. it was really useful for me to have a statically compiled version of tcpdump when it was not included in every Linux distro. It was bound to work on every Linux no matter what version of Kernel, glibc or other system libraries had. Perhaps it has not so much sense in Windows world since the platforms are much more homogeneus. If you compile for Windows XP / NET vX.X it will work across a lot of computers. If you compile something for Debian X.X it will surely not work on older/newer Debians or other distros such as Redhat.
This
thread
can also solve your questions.


Question:
After attending a talk on Oslo/M I am struggling a bit to see the advantages of using it over existing methods and in what situation it would be useful.

I know its quite new and not all details have been released etc but can some one give me some advantages and when you might use it?

Thanks,

Alex

Answer:
This questions seems to have the answer you're looking for:
What is model driven development good for?
Erik Wynne has a nice blog-post on this topic:
Oslo == 42
He also links to a post on MSDN, that contains some interesting thoughts:
Why do we need Oslo?


Question:
I'm not good at programming and my trying to open one of my spreadsheet documents.
Below in the basic login im using, I then request a list all my spreadsheet, which is returned in $feed.

And now I'm worried I'm not on the right track with opening a document so I can read and write cells.

<?php

require_once '../library/Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
$user="username";
$pass="user password";

// login
$service = Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $service);

$spreadsheetService = new Zend_Gdata_Spreadsheets($client);
$feed = $spreadsheetService->getSpreadsheetFeed();

print_r ($feed);
?>

Answer:
You're on the right track.  Are you using the information found
http://framework.zend.com/manual/en/zend.gdata.spreadsheets.html
?
Your code is getting a spreadsheet feed which lists all the available spreadsheets, which is an important step.  You'll want to follow the link above to get a list-based feed or a cell-based feed.
The documentation is pretty good I would recommend just reading through it all(yes it's long).


Question:
How do I split a list of arbitrary length into equal sized chunks?

See How to iterate over a list in chunks if the data result will be used directly for a loop, and does not need to be stored.

For the same question with a string input, see Split string every nth character?. The same techniques generally apply, though there are some variations.

Answer:
Here's a generator that yields evenly-sized chunks:
```
```
def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in range(0, len(lst), n):
        yield lst[i:i + n]
```
```
```
```
import pprint
pprint.pprint(list(chunks(range(10, 75), 10)))
[[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
 [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
 [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
 [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
 [50, 51, 52, 53, 54, 55, 56, 57, 58, 59],
 [60, 61, 62, 63, 64, 65, 66, 67, 68, 69],
 [70, 71, 72, 73, 74]]
```
```
For Python 2, using
```
xrange
```
instead of
```
range
```
:
```
```
def chunks(lst, n):
    """Yield successive n-sized chunks from lst."""
    for i in xrange(0, len(lst), n):
        yield lst[i:i + n]
```
```
Below is a list comprehension one-liner. The method above is preferable, though, since using named functions makes code easier to understand. For Python 3:
```
```
[lst[i:i + n] for i in range(0, len(lst), n)]
```
```
For Python 2:
```
```
[lst[i:i + n] for i in xrange(0, len(lst), n)]
```
```


Question:
I have made a small project in Oracle, by using the oracle forms builder - how do I create an installer (setup.exe) for my project (one that would setup the application on MS Windows?)

Please... help me, and thanks a lot

Answer:
What version of oracle forms are you using?
In my last job we used Forms v4.5 (Developer 2000) - and for that version (which is quite old now) the Forms Runtime software had to be installed on the client computers.
Then, when the user double clicked on an .FMX file the Forms runtime (F45run32.exe) would load and run the form.
Which is a long way of saying that for v4.5 you couldn't create a stand alone install.  (That may have changed with future versions)


Question:
I have a client with a LAMP website serving mostly video. He is currently on one server with all components. He is having some scaling problems. What are some of the techniques that can be used to help.

I used separating out the DB to another server with a GB Ethernet between it and the webserver. Maybe adding more web servers with some load balancing and additional MySQL servers with replication?

Would like some medium, large, super large examples on how to scale if possible.

The video is actually coming as jpg images. Similiar to this website:

http://www.webcams.travel/webcam/1170170095

And to add some details. I figure the max visitors per hour would be 1000, and I think would be lucky to have that. Maybe closer to 1000 a day.

Answer:
You need to work out exactly what the problem is - there is no general solution.
You need to build a performance test environment with real hardware and something which can simulate lots of clients. This may be quite expensive.
If the problem is the database (which it may be) then the solution is often to split it into several databases each holding part of the data.
But I wouldn't imagine that any sane person would store video on MySQL - if he is doing that, then a refactoring may be in order.


Question:
Need help narrowing the scope of this Regex to not return records if there is an alphanumeric character preceding the first "I"

"I([ ]{1,2})([a-zA-Z]|\d){2,13}"

Want to capture I APF From this string, but not the I ARPT.

I APF                     'NAPLES MUNI ARPT.            ' 42894 JEB 29785584

Thanks!

Answer:
```
\b
```
represents a word boundary in regular expressions, so the following should work (assuming you're happy with the rest of the regex):
```
```
("\bI([ ]{1,2})([a-zA-Z]|\d){2,13}")
```
```
A word boundary is defined as the zero-width space between a word character and a non-word character. Depending on your regex engine a word character is likely to be an alphanumeric character or an underscore, so using \b will match I ALF in
```
-I ALF
```
but not in
```
_I ALF
```


Question:
I'm adding an existing site to SVN.

The files already exist on the webserver, and now identical copies (- configuration files) exist in the repository.

I want to convert the webserver directory into an SVN working copy, but when I run:

svn checkout http://path.to/svn/repo/httpdocs .

I get the error:

svn: Failed to add file '': object of the same name already exists

How do I tell SVN to just overwrite those files whose contents are the same?

Answer:
Pull from the repository to a new directory, then rename the old one to
```
old_crufty
```
, and the new one to
```
my_real_webserver_directory
```
, and you're good to go.
If your intention is that every single file is in SVN, then this is a good way to test your theory. If your intention is that some files are not in SVN, then use Brian's copy/paste technique.


Question:
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this?

Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module>
    from django.core import management
ImportError: No module named django.core

Answer:
You must make sure that django is in your PYTHONPATH.
To test, just do a
```
import django
```
from a python shell. There should be no output:
```
```
ActivePython 2.5.1.1 (ActiveState Software Inc.) based on
Python 2.5.1 (r251:54863, May  1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>>
```
```
If you installed django via
```
setuptools
```
(
```
easy_install
```
, or with the
```
setup.py
```
included with django), then check in your
```
site-packages
```
if the
```
.pth
```
file (
```
easy-install.pth
```
,
```
django.pth
```
, ...) point to the correct folder.
HIH.


Question:
I have some XSD-s that define my objects hierarchy. for example math.xsd, base.xsd
while math.xsd is depends on base.xsd. I need to generate classes from those xsd-s.

I've already read about those two tools:
CodeXS tool  and  XSD.exe.
the problem with the xsd.exe is that I didn't succeed generating classes from two xsd-s that depends on each other. is there anyone who knows the right parameters for using the xsd.exe for such case?

moreover, I am looking for:
 - more tools
 - comparison between those tools
 - xsd to object using .net 3.5
Thanks.

Answer:
Microsoft: XSDObjectGen - Sample Code Generator 1.4.2.1
Stackoverflow: XSDObjectGen.exe vs XSD.exe


Question:
I am trying to get pylons to debug in Eclipse under Ubuntu.
Specifically. I am not sure what to use for the 'Main Module' on the Run configurations dialog.

(this is a similar question on stackoverflow, but I think it applies to windows as I can't find paster-script.py on my system)

Can anyone help?

Answer:
I've managed to fix this now.
In
```
Window>Preferences>Pydev>Interpreter-Python
```
remove the python interpreter and reload it (select
```
New
```
) after installing pylons.
In the Terminal cd into the projects directory. Then type
```
sudo python setup.py develop
```
Not sure what this does, but it does the trick (if any one wants to fill me in, please do)
In
```
Run>Open Debug Dialog
```
enter the location of paster in
```
Main Module
```
. For me this is
```
/usr/bin/paster
```
. Then in the
```
Arguments
```
tab in
```
Program arguments
```
enter
```
serve /locationOfYourProject/development.ini
```
All set to go.
It took a lot of search for me to find out that it does not work if the arguments includes
```
--reload
```


Question:
My Aim: Sending an email (e.g. support request, error report) out of a C# Windows forms application. I know how do do this technically but here is the catch:

In order to authenticate myself on the mail server (e.g. gmx, yahoo, own website) I need to store the login details inside the application (which runs on the client system). If someone extracts it or sniffs the network traffic he will have access to my email account. Maybe the second threat could be eliminated using a secure connection. However, it is still possible to get the password out of the application regardless if it is obfuscated or not.

So is there are 'secure' concept enabling me to send e-mail messages out of my program, which runs on the client pc without the need to store a password in accessible form and not requirering a special web service?

Answer:
I had such a requirement in the past which we solved by using a web service to post messages.
If for example a user wanted to submit a bug report it would be turned into a web service call to our web server and it would then be forwarded accordingly.
To answer your question:
There is no way you can hide you mail server. If your program can send emails, so can the user with another program. (the same goes for a web service.) What you can do is use an open smtp server (smtp relay) but that is just asking for trouble.


Question:
I am creating a Firefox Extension...what would be the javascript to open a URL in the current tab from a menuitem?

e.g. in my overlay.xul file i have the following line:

<menuitem label="Visit homepage" oncommand="window.location='http://www.somepage.com'"/>

but in firefox, when i click on the menu item, it opens the URL but it screws up the entire layout of the browser.

What's the correct way to do this?

Answer:
After browsing around, I found that I had to replace the above code with this:
```
```
<menuitem label="Visit homepage" oncommand="content.wrappedJSObject.location='http://www.somepage.com'"/>
```
```


Question: I am not a mathematician. I enjoy a good math puzzle, but I admit my weaknesses whole heartedly. That said, I've always had an interest in Neural Networks, and while I understand them enough to implement them from scratch, I hit a wall when I need to understand any concept that I can only find mathematic proofs for. Where is the programmer's guide to neural networks, using code instead of formula to explain the practical reasonings?

Answer:
Unfortunately, I don't know if there's a good single "programmers source" that will give you all of the concepts.  I liked
Neural and Adaptive Systems: Fundamentals through Simulations
.
The best way to have a "programmer's understanding" of neural networks is not so much by examining the code, but in the problem and the correct results.  So, if you don't want to look at math, I recommend you look at a given problem.  For example, consider the XOR problem as an example of why you need non-linear activation functions, look at the number of variables and their possible values for understanding why a neural network needs to be of a certain size and toplogy to be effective, and split your data into train/test regimes and do studies to see why overfitting is dangerous.  Examine the code with the data.
I also recommend not getting too hung up, but reading further.  Certain practices in feed-forward networks become more clear once you see their generalization in recurrent and constructive neural networks.  I also recommend going wider:  Bayesian networks, fuzzy cognitive maps, SOM, Boltzman machines, simulated annealing, and reinforcement learning all have intuitions.
Does this go towards answering your question?


Question:
I have to give a general note to some huge Java project for which I have but little visibility and I was wondering if there were any guidelines for determining:

what number of classes per package can be considered right, to low, or to high (this project has 3.89 classes per package, which seems a bit too small for me),

number of methods per class? (this project has 6.54 methods per class...

number of lines per method? (this project has about 7 lines per method (seems pretty good to me, maybe a bit low))

I should note that this question is only dealing with volumetry. I have a bunch of reports from quality tools (checkstyle, jdepend, cpd, pmd, ncss) that give me more vision about code redundancy, classes usage, bugs, etc.

Answer:
I think stats like that are pretty useless, how does knowing the lines per method show whether its any use to the project or not; i think you should be looking more along the lines of:
Do your packages encompass like
classes?
Do your classes work as an
entity on their own?
Do the methods
within the classes function
correctly and efficiently?
Surely other than memory usage, it doesn't matter whether the method is large or not? the other thing to look for in very protracted methods is whether the stack trace is going to be bigger than adding that functionality to a parent method.  I'd be wary of measuring a projects success based on the lines of code.


Question:
I thought that if a c pointer pointing to a char array was incremented then it would point to the next element in that array. But when I tried this I found that I had to increment it twice. Trying the increment using sizeof(char) I found that adding the size of a char was too much so it had to be divided by two.

#include <stdio.h>

int main(int argc, char * argv[]){
   char *pi;
   int i;
   pi = argv[1];
   printf("%d args.\n",argc-1);
   printf("input: ");
   for(i=0;i<argc-1;i++){
      printf("%c, ",*pi);
      /*The line below increments pi by 1 char worth of bytes */
      //pi+=sizeof(pi)/2;
      /* An alternative to the above line is putting pi++ twice - why? */
      pi++;
      pi++;
   }
   printf("\n");
   return 0;
}

Am I doing something wrong? or am I misunderstanding the method of incrementing pointers?

Answer:
If you have a pointer
```
ptr
```
of type
```
T*
```
and you add
```
N
```
, then the pointer will be advanced by
```
N * sizeof (*ptr)
```
or equivalent
```
N * sizeof (T)
```
bytes. You simply forgot to dereference
```
pi
```
. So what you got with
```
sizeof (pi)
```
was the sizeof of the
```
char*
```
, but not the sizeof of a
```
char
```
. Your line was equivalent to
```
pi+=sizeof(char*)/2;
```
Pointers on your platform are 4 bytes big. Thus in effect you did
```
pi+=2;
```
. Write
```
pi+=2
```
if you want to increment 2 times. Note that
```
char
```
has an sizeof of 1 by definition. You don't need to do
```
sizeof (char)
```
, it is always 1.


Question:
if __name__=='__main__':
    parser = OptionParser()
    parser.add_option("-i", "--input_file",
                    dest="input_filename",
                      help="Read input from FILE", metavar="FILE")

    (options, args) = parser.parse_args()
    print options

result is

$ python convert.py -i video_*
{'input_filename': 'video_1.wmv'}

there are video_[1-6].wmv in the current folder.
Question is why video_* become video_1.wmv. What i'm doing wrong?

Answer:
Python has nothing to do with this -- it's the shell.
Call
```
```
$ python convert.py -i 'video_*'
```
```
and it will pass in that wildcard.
The other six values were passed in as args, not attached to the
```
-i
```
, exactly as if you'd run
```
python convert.py -i video_1 video_2 video_3 video_4 video_5 video_6
```
, and the
```
-i
```
only attaches to the immediate next parameter.
That said, your best bet might to be just read your input filenames from
```
args
```
, rather than using
```
options.input
```
.


Question:
First off, how do I know if my html file is running on localhost in Xampp?
Is there a tutorial on how to manage files/directories and get that all working under htdocs?
Is there a good tutorial on how to setup includes?

I want to use "includes" in Xampp with my html.
Can I use both html includes AND php includes?
Do I have to put shtml?
Can I use shtml, html, htm, and php includes?
Do they have to be in an includes directory that is a subdirectory right under htdocs?
Can I reference includes in some other subdirectory?
My site will have over 100 pages, and I am trying to do "experiments" with different versions until I am happy. So, I have subdirectories for the various drop down menus. Unfortunately, I don't seem to be able to get this working in xampp.
Having trouble getting my javascript menus from Vista Buttons to show up, now that I moved my main directory for my site to the htdocs directory.

Answer:
To answer your first question, can you access
http://localhost/
? If so, then xampp is running correctly and there is nothing more that you need to do.
EDIT:
If you want to ensure that things are working correctly, place foo.html under /xampp/htdocs and then access it in a browser at
http://localhost/foo.html
. If you can't get this page then xampp still isn't running correctly.
In answer to your second question, all Includes whether in the HTML or within PHP are server side. If you have xampp installed correctly, then you can begin working in PHP immediately and can use the include functions within PHP (please note that even if a page only contains HTML, if you're using PHP it must still have a .php extension).
If you would rather use SSI in your .html pages, then
this link
might provide some help on how to set up and debug SSI in xampp.
Additionally, if you are not already doing so I would recommend that you work in Firefox with Firebug installed. Firebug will handle most of your JavaScript debugging needs.
As a final note, if you've moved directories and the like, the first thing I would check would be the src attributes on your script tags.


Question:
I'm trying to create an algorithm in C# which produces the following output strings:

AAAA
AAAB
AAAC
...and so on...
ZZZX
ZZZY
ZZZZ

What is the best way to accomplish this?

public static IEnumerable<string> GetWords()
{
    //Perform algorithm
    yield return word;
}

Answer:
well, if the length is a constant 4, then this would handle it:
```
```
public static IEnumerable<String> GetWords()
{
    for (Char c1 = 'A'; c1 <= 'Z'; c1++)
    {
        for (Char c2 = 'A'; c2 <= 'Z'; c2++)
        {
            for (Char c3 = 'A'; c3 <= 'Z'; c3++)
            {
                for (Char c4 = 'A'; c4 <= 'Z'; c4++)
                {
                    yield return "" + c1 + c2 + c3 + c4;
                }
            }
        }
    }
}
```
```
if the length is a parameter, this recursive solution would handle it:
```
```
public static IEnumerable<String> GetWords(Int32 length)
{
    if (length <= 0)
        yield break;

    for (Char c = 'A'; c <= 'Z'; c++)
    {
        if (length > 1)
        {
            foreach (String restWord in GetWords(length - 1))
                yield return c + restWord;
        }
        else
            yield return "" + c;
    }
}
```
```


Question:
I have a winforms application that is doing the following:

on each query:

Db connect

Db query

Db disconnect

as we are trying to avoid having to keep the db connection open.  This suffers from performance as we have to connect / disconnect everytime.

What is the idealized model here to have the fastest performance but without having open connection for too long.  Is there a best practice here?

Answer:
The most efficient means is connection pooling, and
ADO.NET does this automatically for you
as long as you make sure to close your connections. Just wrap your
```
SqlConnection
```
objects into
```
using
```
statements, and you won't have to worry about it.


Question: Does anyone have any experience with the triangulated GPS used by the non-3G iPhone?  How does it compare with 3G positioning?  Does the iPhone 3G use triangulation in the event that there is no GPS signal available? Is there anyway to determine the accuracy of the non 3G coordinates? Thanks.

Answer:
I have done a lot of mobile software with a bunch of different devices including 3G iphones and 3G blackberry's and here is what I have found.
The blackberry and iPhone GPS is really good when you have clear line of sight and at least 9 satellites present.  In some dense residential or urban areas you might only get 5-6 satellites which can take a while to converge.
If you do not have a signal, GSM phones like the iPhone will try and find your position using cell tower signal strength but it is NOT as accurate as GPS... not by a long shot.
I have heard, though this has not been confirmed that the iPhone also uses some server side machine learning when it can't find a GPS lock meaning that it takes the average all of the cell towers, plus the average of all the users who have used GPS in your area to try and find your best position.  This is sometimes called AGPS or assisted GPS where the GPS information and cell tower strength are used together.
Also, the only thing I can think of for finding the accuracy of the non 3G coordinates would be to programmaticly switch providers in your code, or simply go into preferences and turn off 3G and write an application that does some tests.
The Pragmatic Programmers have a great
iPhone SDK book
that just added a chapter on using the Location API, so that might be a great place to start.
Hope this helps.


Question: What is the best way to abstract the episerver infrastructure for easier testing?

Answer:
Perhaps this post will help:
EPiServer CMS 5 R2 and unit testing


Question: We recently had a code review . One of my classes was used so that I could return/pass more than one type of data from/to methods . The only methods that the class had were getters/setters . One of the team's members ( whose opinion I respect ) said that having a class like that is bad practice ( and not very OOP ) . Why is that ?

Answer:
In general, you'll want to isolate the knowledge needed to operate upon a class into the class itself.  If you have a class like this, either it is used in multiple places, and thus can take on some of the functionality in both of those places, or it is in a single place, and should be an inner class.  If it is used in multiple ways, but in completely different ways, such that there is no shared functionality, having it be a single class is misleading, indicating a shared functionality where there is none.
However, there are often specific reasons for where these general rules may or may not apply, so it depends on what your class was supposed to represent.


Question: I want to play around a bit with FLASH for app development. I'm looking for a good IDE for that.  Someone suggested Flash Develop.

Answer:
Major reason to use FlexBuilder: has a real debugger you can set breakpoints and single step and watch/edit variables.
Unless FlashDevelop has .. developed .. don't think it got any of that yet.
BTW - if you are a student/teacher FlexBuilder can be had for
free


Question:
What is the Python equivalent of the following code in Ruby?

def loop
  cont=nil
  for i in 1..4
    puts i
    callcc {|continuation| cont=continuation} if i==2
  end
  return cont
end

> c=loop
1
2
3
4
> c.call
3
4

Reference: Secrets of lightweight development success, Part 9: Continuations-based frameworks

Answer:
take a look at the
yield
statement to make generators.
I don't speak any ruby, but it seems like you're looking for this:
```
```
def loop():
    for i in xrange(1,5):
        print i
        if i == 2:
            yield

for i in loop():
    print "pass"
```
```
Edit: I realize this is basically a specialization of real continuations, but it should be sufficient for most purposes. Use
```
yield
```
to return the continuation and the
```
.next()
```
message on the generator (returned by just calling
```
loop()
```
) to reenter.


Question:
I am building an Entity Framework model for a subset of the Pubs database from microsoft. I am only interested and publishers and books, not publishers and employees, but there is a foreign key constraint between the publishers and emoloyees tables. When I remove the employees entity from my model, the model won't validate because of the foreign key constraint.

How do I create a model for a subset of a database when that subset links to other tabes with foreign key constraints?

Because this is for a demo, I deleted the offending tables and constraints from the database, but this won't work in production.

Answer:
Not sure what I'm missing here, but your
```
filesize
```
being -1 seems to be your problem.  The
API docs
clearly state that
```
expectedContentLength
```
may not be available and that
```
NSURLResponseUnknownLength
```
is returned in these cases.
```
NSURLResponseUnknownLength
```
is defined as:
```
```
#define NSURLResponseUnknownLength ((long long)-1)
```
```
In these cases, you cannot get an accurate progress.  You'll need to handle this and display an indeterminate progress meter of some sort.


Question:
I have a very simple model. I want to add a send email routine to on of the methods for the model:

$this->Email->delivery = 'smtp';
$this->Email->template = 'default';
$this->Email->sendAs = 'text';
$this->Email->from    = 'email';
$this->Email->to      = 'email';
$this->Email->subject = 'Error';

I've tried putting

App::import('Component', 'Email');

at the top, to no avail. The error I get is:

Fatal error: Call to undefined method stdClass::send() in E:\xampp\htdocs8080\app\models\debug.php on line 23

Any ideas?

I'm running CakePHP 1.2

Answer:
Components are supposed to be used in controllers, not models.
In your controller use
```
```
var $components = array('Email');
```
```
There is no need to use App::import();
Without knowing your app and reasons for wanting to use it in a model, I might suggest you re-think your system architecture and move this logic to your controller.
If you definitely need it in your mode, your code included something like...
```
```
$this->Email->delivery = ...
```
```
Have you put created a new instance of the component and set it to a property of your model called Email? (No idea if this will work mind.)
The error you are getting is because you are calling the send() method on a the stdClass object i.e. not an instance of the EmailComponent.


Question:
My scenario should be simple... the type I want to convert FROM is ALWAYS 'string'. What I want to convert to... could be many things - ints, DateTimes, ... strings, etc.

This would be easy:

string valueToConvertFrom = "123";

int blah = Convert.ToInt32(valueToConvertFrom);

However... I don't know (until runtime) that the value I need to convert to is an 'Int' (or whatever). I have tried this:

string valueToConvertFrom = "123";

Type convertToType = typeof(int);

object blah = Convert.ChangeType(valueToConvertFrom, convertToType);

But that gives me the following error: "Object must implement IConvertible."

I don't want to have to do a switch statement and call "Convert.ToBlah" based on the type name... any suggestions?

Answer:
String class implements IConvertible, this code simply SHOULD work. Which version of .NET are you aiming?
```
```
object o = Convert.ChangeType( str, convertToType );
```
```
Besides, most of the types you mentioned implement Parse method, so your best shot might be something like this.
```
```
Type convertToType = ...;
MethodInfo mi = convertToType.GetMethod("Parse", BindingFlags.Static);
object blah;
if(mi != null)
{
    blah = mi.Invoke(null, new object[]{valueToConvertFrom});
}
else
{
    // the type doesn't implement the Parse method, handle it another way :/
}
```
```


Question:
I put together a sample scenario of my issue and I hope its enough for someone to point me in the right direction.

I have two tables

Products

Product Meta

I need a result set of the following

Answer:
```
```
Select a.ProductId
  ,a.Name
  ,(Select c.MetaValue
    From [Product Meta] c
    Where c.ProductId = a.ProductId
    And c.MetaKey = 'A') As 'A'
   ,(Select d.MetaValue
    From [Product Meta] d
    Where d.ProductId = a.ProductId
    And d.MetaKey = 'B') As 'B'
   ,(Select e.MetaValue
      From [Product Meta] e
      Where e.ProductId = a.ProductId
      And e.MetaKey = 'C') As 'C'
From Products a
Order By a.ProductId Asc
```
```


Question:
Situation: you've got a .swf embedded in an html page, and when you click on something in the .swf, it needs to popup a chromeless window. Normally this would be fairly easy - but consider Safari, which completely disables all 'window.open' functionality while its popup-blocker is enabled (it makes an exception if the function is triggered onclick, but it doesn't count clicks in flash). How can you create something which gracefully degrades (provides an alternate and roughly equivalent experience) for browsers that won't execute window.open?

(note: this is AS3, and Safari 3 for PC or Mac we're talking about - but more broadly, any browser that doesn't support or refuses to allow the javascript window.open function.)

Answer:
If your SWF is loaded using
```
wmode='opaque'
```
or
```
wmode='transparent'
```
, then you could have the SWF output JavaScript code that would create an empty
```
<div>
```
that's positioned over the SWF area.  That
```
<div>
```
could then handle the
```
onclick
```
event and create the popup window rather than the Flash code.


Question:
On a more abstract level then a previous question, in my experience there are 3 ways to call a javascript function on an html page from an embedded .swf using AS3: ExternalInterface, fscommand, and navigateToURL.

Let's compare and contrast these methods (and maybe others I haven't listed) and talk about the pros and cons of each - right now, ExternalInterface seems like the way to go in terms of flexibility, but is it right for all situations? Are there concrete benefits in terms of execution speed or anything like that? I'm curious - what do we think?

Answer: ExternalInferface was created to make communication between JS and Flash easier, so it doens't really make sense to use anything else. Common practice is to check if its available first by evaluating the value of the ExternalInterface.available property before making a call to some JS. This property tells you if the SWF in which you want to call some JS from is inside a container that offers an external interface. In otherwords, if using ExternalInterface will work. If its not available then just use flash.net.sendToUrl. Never use fscommand() as it uses VBScript and can cause conflicts with other VBScript on a page. Additionally, you can only send one argument string with fscommand and have to split it on the JS side.


Question: Can someone explain in simple terms the "signals and slots" pattern?

Answer:
Signals and slots are a way of decoupling a sender (the signal) and zero or more receivers (the slots). Let's say you a system which has events that you want to make available to any other part of the system interested in those events. Rather than hard-wiring the code that generates event to the code that wants to know about those events, you would use a signals and slots pattern.
When the sender signals an event (usually by calling the function associated with that event/signal) all the receivers for that event are automatically called. This allows you to connect and disconnect receivers as necessary during the lifetime of the program.
Since this question was tagged C++, here is a link to the
Boost.Signals
library which has a much more thorough explanation.


Question: Unit tests are cheaper to write and maintain, but they don't cover all scenarios. What is the right balance between them?

Answer:
On the app I am working on at the moment, there are probably 10:1 unit to functional tests. The unit test work simply things like retrieving entities from DB, error handling tests for db/network connectivity etc. These things run quick - minutes or less and are run by devs daily.
functional tests while fewer tend to be kitchen sink approach - can user complete order etc. tend to cover the business domain end of things are run by business analsyts and operations - sadly for us, often by hand. These things take weeks to run and usually to finalize a release cycle.


Question:
Given a list of sets:

S_1 : [ 1, 2, 3, 4 ]

S_2 : [ 3, 4, 5, 6, 7 ]

S_3 : [ 8, 9, 10, 11 ]

S_4 : [ 1, 8, 12, 13 ]

S_5 : [ 6, 7, 14, 15, 16, 17 ]

What the most efficient way to merge all sets that share at least 2 elements?  I suppose this is similar to a connected components problem.  So the result would be:

[ 1, 2, 3, 4, 5, 6, 7, 14, 15, 16, 17] (S_1 UNION S_2 UNION S_5)

[ 8, 9, 10, 11 ]

[ 1, 8, 12, 13 ] (S_4 shares 1 with S_1, and 8 with S_3, but not merged because they only share one element in each)

The naive implementation is O(N^2), where N is the number of sets, which is unworkable for us.  This would need to be efficient for millions of sets.

Answer:
If you can order the elements in the set, you can look into using
Mergesort
on the sets. The only modification needed is to check for duplicates during the merge phase. If one is found, just discard the duplicate. Since mergesort is O(n*log(n)), this will offer imrpoved speed when compared to the naive O(n^2) algorithm.
However, to really be effective, you should maintain a sorted set and keep it sorted, so that  you can skip the sort phase and go straight to the merge phase.


Question: As the title says really. Does the virtual keyword cause a performance hit?

Answer:
First off, in Actionscript you don't need to explicitly mark a method to be overridden as virtual as you do in C#, the compiler will do this for you. This is why the keyword doesn't show up in any docs because it is irrelevant from the developers perspective.
To answer your question though, which is whether overriding a method makes it slower, the answer is no as long as your class is sealed, meaning you don't use the 'dynamic' keyword when defining the class.
The reason why is that when constructing a sealed class, you're going to have explicit markers to every method for that object, when overriding a method you get a marker directly to the new function, the class does not have to look it up at runtime like in a dynamic class.


Question: Is there a good Silverlight Design Architecture?

Answer:
There is
Prism
it was originally designed for WPF but there is now a Silverlight release.


Question:
Is there a way to use these operators to input and output binary data? The reason I want to do this is that it makes the code readable.
Ex: infile >> filedecrypter >> metadataparser >> audiodecoder >> effects >> soundplayer;

Answer:
Indeed that can be done, if the library or your code provides the overloads for
```
operator<<
```
and
```
operator>>
```
for it to work. Simple example on how one could do it:
```
```
class transformer {
    public:
    virtual std::iostream& transform(std::iostream&) = 0;
};

class noise : public transformer {
    public:
    virtual std::iostream& transform(std::iostream&) {
         /* extract, change and put into again */
    }
};

class echo : public transformer {
    public:
    virtual std::iostream& transform(std::iostream&) {
         /* extract, change and put into again */
    }
};

std::iostream& operator>>(std::iostream& io, transformer& ts) {
    return ts.transform(io);
}

int main() {
    std::stringstream data;
    std::ifstream file("sound.wav");

    noise n; echo e;

    data << file.rdbuf();
    data >> n >> e;
    /* pipelined data now ready to be played back */
}
```
```
The problem with using a pure
```
std::istream
```
is that you would read, but then you wouldn't have a way to put the transformed data back for the next step in the pipeline. Thus i'm using
```
std::iostream
```
here. This approach doesn't seem to be efficient, as every operator>> call would extract the whole data, and put into again.
To have a more performant way to stream this would be to create an
```
expression template
```
. This means, while
```
operator>>
```
is called, you don't do the transforming yet, but you return expression types that will record the chain of operations within its type:
```
```
typedef transform< echo< noise< istream > > > pipeline;
std::ifstream file("file.wav");
pipeline pipe(file);
int byte = pipe.get();
```
```
would be an example of such a type. The pipelines' structure is decoded into the type itself. Therefore, no virtual functions are needed anymore in the pipeline. It's not constructed on-demand, but using typedef here, to show the principle. Programming such a system is not easy. So you probably should look into existing systems, like Boost.Iostreams (see below). To give you an idea how it would look like, here is an example i just coded up for you :) :
```
```
#include <iostream>

template<typename T>
struct transformer {
    int get() {
        return static_cast<T*>(this)->read();
    }
};

struct echot {
    template<typename Chain>
    struct chain : transformer< chain<Chain> > {
        Chain c;

        int read() {
            return c.get() + 1;
        }

        chain(Chain const& c):c(c) { }
    };
} echo;

struct noiset {
    template<typename Chain>
    struct chain : transformer< chain<Chain> > {
        Chain c;

        int read() {
            return c.get() * 2;
        }

        chain(Chain c):c(c) { }
    };
} noise;

template<typename T>
typename T::template chain<std::istream&> operator>>(std::istream& is, T) {
    return typename T::template chain<std::istream&>(is);
}

template<typename T, typename U>
typename U::template chain<T> operator>>(T t, U u) {
    return typename U::template chain<T>(t);
}

int main() {
    std::cout << (std::cin >> echo >> noise).get() << std::endl;
}
```
```
Entering 0 yields the ASCII code 48 here, which is added 1, and multiplied by 2, yielding a value of 98, which is also finally output. I think you agree this is not some code a starter would want to write. So maybe look into boost.
Boost has an sophisticated iostreams library, which can do many things. I'm sure you would find something fitting to this.
Boost.Iostreams


Question:
I am trying to fade in a
 on mouseover and fade out on mouseout:

  $("p.follow").mouseover(function(){
        $(this).fadeTo("slow", 1.00);
})
$("p.follow").mouseout(function(){
        $(this).fadeTo("fast", 0.50);
})

If you go to ryancoughlin.com and on the right side, if you go over it you will see what I mean, it is almost as if it is stuck and keeps fading in.

Any ideas?

Answer:
Try this:
```
```
$("p.follow").hover(function()
   {
      $(this).stop().fadeTo("slow", 1.00);
   },
   function()
   {
      $(this).stop().fadeTo("fast", 0.50);
   });
```
```
Two key differences: I use the jQuery
```
hover
```
event to associate mouseover and mouseout event handlers such that child elements won't result in confusing behavior, and i use the
```
stop()
```
function to prevent animations from overlapping and canceling each other out.


Question:
I have configured a simple LAMP stack on Debian and I am experiencing some problems with the Apache web server.

Each 3-4 hours the web server is entering a deadlock and all the requests that hit the database block. The server is creating a new child for each request. The number of processes increases very quickly. After a few seconds Monit notices something is wrong and restarts the Apache server.

I suspect this problem is generated by the way PHP handles database connection pooling because the server is still able to answer static content requests. Have you experienced this kind of behavior? What should I try to do?

Update: Problem solved. It seems it's a bad idea to use APC for opcode caching and user data. I am now using Memcache for storing user data and APC only for code. I still get some segmentation faults from time to time but the server is most of the time stable.

Answer:
Why don't you have a look at the logs?
```
/var/log/apache2/*
```
is a good place to start. What is requested just before the server dies? From there on, you can probably deduce what's going wrong. As php scripts are terminated after 30 seconds by default, the mistake needs to be quite massive to cause something like that.


Question:
I would like to do something like the following but can't seem to get the syntax for the Do method quite right.

var sqr = new _mocks.CreateRenderer<ShapeRenderer>();
Expect.Call(sqr.CanRender(null)).IgnoreArguments().Do(x =>x.GetType() == typeof(Square)).Repeat.Any();

So basically, I would like to set up the sqr.CanRender() method to return true if the input is of type Square and false otherwise.

Answer:
Are you looking for this?
```
```
Expect.Call(sqr.CanRender(null)).IgnoreArguments()
    .Do((Func<Shape, bool>) delegate(Agent x){return x.GetType() == typeof(Square);})
    .Repeat.Any();
```
```
EDIT: The answer was correct in spirit bu the original syntax did not quite work.


Question:
I've been frustrated by this for the entire weekend, plus a day or two, so any help would be significantly appreciated.

I'm trying to write a program that can programmatically go into a SharePoint 2007 doc library, open a file, change the contents of the file, then put the file back. I've gotten all but the last part of this down. The reason Office Open XML is involved is that that's how I'm opening the document and modifying it - through the Office Open XML SDK. My question is: How do I get it from the document back into the library?

The problem as I see it is that there's no save function on the WordprocessingDocument object itself. This prevents me from saving it into the SPFile's SaveBinary function.

Answer:
Yesterday I saw a webcast with Andrew Connell where he opened a doc from a doc library, added a watermark and saved the file again. It sure sounds like you should have a look at that webcast:
https://msevents.microsoft.com/CUI/WebCastRegistrationConfirmation.aspx?culture=en-US&RegistrationID=1299758384&Validate=false
btw I found that all 10 of the web casts in that serie were very good.


Question:
This fails with 'X.m is not a function'...

var Y = function () {
    this.m = function () {
        alert('this is m');
    };
};

var X = new function () { };

X.prototype = new Y();
X.m();

It would certainly work if I skipped the new keyword in the X definition and then instantiated X before calling m() on it. Why can't I do it this way?

Answer:
No you cannot set the prototype and have that change effect previously existing instances.  You can however, modify the prototype object to have the desired effect.  But not the way you have attempted.  This is because your instance X is an object, not a class.  (This is because you used the "new" operator before the definition of your class.)
Simple test:
```
```
var X = new function () { };
alert(X.prototype);  // displays "undefined" because X is an
                     // object not a class
```
```
So when you set the "prototype" attribute on X you are not storing the template object in a class, you are merely creating a new attribute on object X with the name "prototype" so, if you did this:
```
```
var Y = function () {
    this.m = function () {
        alert('this is m');
    };
};

var X = new function () { };
X.prototype = new  Y();
X.prototype.m();  // displays "this is m"
```
```
Then you get the output you expected previously.
Even though you created X as an instance of an anonymous class, you can still access that class through the "constructor" property.  Once you have that reference, you can then modify the prototype object.  Like this:
```
```
X.constructor.prototype.m = new Y().m;
X.m();  // displays "this is m"
```
```
You should note however, that this will not work:
```
```
X.constructor.prototype = new Y();
X.m();  // fails
```
```
Because changing the entire prototype object only effects instances created in the future.


Question:
There are several people about (myself being one of them) who have been developing RIA for a while now using Flex and AJAX.  However Silverlight is now on the scene and worth picking up.

Question is, as someone who has never looked at .NET before, should I just dive in Silverlight and try and make up the bits I'm missing, or start somewhere else in .NET in order to get a foundation first?

Answer:
I firmly believe in learning foundations first. I would start off by writing console apps - get the hang of collections, IO, the language itself (whether that's VB or C#, or even something else).
It's probably worth learning a bit of "normal" WPF after that, on the grounds that it may well be easier to experiment that way than with Silverlight itself. (I can't say I've written any Silverlight myself yet.)
If you dive straight into Silverlight, when you run into problems you won't know whether it's because you're unfamiliar with the language, the core platform, or Silverlight itself. You'll take a while longer to get going with my suggestion above, but once you've got going it'll be a much smoother ride, in my view.


Question:
How do I expose the ActualWidth property of one of the components of my user control to users?

I have found plenty of examples of how to expose a normal property by creating a new dependency property and binding, but none on how to expose a read-only property like ActualWidth.

Answer:
```
ActualWidth
```
is a public readonly property (coming from
```
FrameworkElement
```
) and is exposed by default. What is the case that you are trying to achieve?


Question:
From the .net 4.0 previews I have read until now there has been lots of talk on how the next .net version will handle and use cpus with multiple cores. We will have additions like plinq that will help us make use of multiple cores. My question is why should I have to bother my mind with handling multiple cores when all I want is to make my application run faster. Why can't there be a kind of virtual cpu layer that exposes all cores as 1 core to my application?

Edit:
I would like to rephrase my question to avoid misunderstanding,
Could there be made a software that would expose a virtual thread to my application that would be 10 times faster because underlaying it was using 10 cores. I do not want to have different threads doing things in paralell, I just want my one thread running faster. I guess this is not a big problem today but soon we'll have 80 core processors to play with and then I would feel a bit shorthanded only using 1 of them.

Answer:
You are misunderstanding the point of multiple cores in the first place.
With more than one core, you can perform two or more different operations in parallel (at the same time).  This is called threading.
This can't be done automatically because the "normal" programs you write are linear.  You can't easily convert one series of instructions into several series of instructions without taking into consideration side effects.
GPU's (specialized CPU's on graphics cards), for example, may contain hundreds of "cores" (stream processors) which operate in parallel to render the pixels on your screen.  With only one processor, you'd have to render pixel-by-pixel on a super-fast processor to achieve the same effect.
The reason CPU manufacturers moved to more than one core was because manufacturing a single core at higher speeds was getting more difficult and expensive, and that a single core would suck up more power and produce more heat than two cores at half the speed (basically; this isn't true in all cases).


Question:
In my specific case, I have two kinds of "messages" that I need to retrive and paginate.

Let's omit the details, and just say that the first kind is in a model called Msg1 and the other is called Msg2

The fields of these two models are completely different, the only fields that are common to the two models are "date" and "title" (and of course, id).

I can get Msg1.objects.all() and Msg2.objects.all() but can I combine these two queries into one query, sort it by date, and paginate it?

I need to preserve the lazy nature of the query.

The trivial solution is to list(query) both queries and combine them in a python list. but this is inefficient for obvious reasons.

I looked through the django references on models and dp-api, but it doesn't seem that there is a way to combine queries of different models/tables into one.

Answer:
"combine these two queries into one query, sort it by date, and paginate it?"
That's the SQL union.   Leave the Django ORM and use a SQL union.  It's not brilliantly fast because SQL has to create a temporary result, which it sorts.
Create the temporary result, which can be sorted.  Since a list has a sort method, you'll have to merge the two results into one list.
Write a merge algorithm that accepts two query sets, paginating the results.
Edit.  Here's a merge algorithm.
```
```
def merge( qs1, qs2 ):
    iqs1= iter(qs1)
    iqs2= iter(qs2)
    k1= iqs1.next()
    k2= iqs2.next()
    k1_data, k2_data = True, True
    while k1_data or k2_data:
        if not k2_data:
            yield k1
            try:
                k1= iqs1.next()
            except StopIteration:
                k1_data= False
        elif not k1_data:
            yield k2
            try:
                k2= iqs2.next()
            except StopIteration:
                k2_data= False
        elif k1.key <= k2.key:
            yield k1
            try:
                k1= iqs1.next()
            except StopIteration:
                k1_data= False
        elif k2.key < k1.key: # or define __cmp__.
            yield k2
            try:
                k2= iqs2.next()
            except StopIteration:
                k2_data= False
        else:
            raise Exception( "Wow..." )
```
```
You can fold in pagination:
```
```
def paginate( qs1, qs2, start=0, size=20 ):
    count= 0
    for row in merge( qs1, qs2 ):
        if start <= count < start+size:
            yield row
        count += 1
        if count == start+size:
            break
```
```


Question:
Why whenever I compile and run the following code in Visual Studio 2008:

double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2;
Console::WriteLine(whole_number);

I get an incorrect value of 26 while the answer is 25.

However when I use static casts on the doubles, I get the right answer which is 25.

How can the wrong output be explained?

Answer:
It's absolutely right.
```
```
double value1 = 10.5;
double value2 = 15.5;
int whole_number = value1 + value2; // int whole_number = 26.0;
Console::WriteLine(whole_number);
```
```
What would you expect instead? The compiler first evaluates the right side, and then implicitly converts to the int. Thus,
```
26.0
```
becomes
```
26
```
When you cast before you add, then you are going to add
```
10
```
and
```
15
```
, which results in
```
25
```
:)


Question:
I've worked on a number of CMS systems using the .NET platform (the CMS management system is in ASP.NET, and the site which renders the content is both ASP.NET and PHP).

I've traditionally stored the generated content in classes that serialize to XML, which is stored in MSSQL 2005/2008 in a varchar(max) field.  This has made it convenient structuarally for different consumers of the content to work with, and it can be bound to classes (for re-opening the CMS record and editing it, or for the consuming website).

However, I've been wondering what type of storage mechanism is popular with other CMS shops, and if anyone likes or has serious issue with the approach I'm most familiar with.

Good, bad, ugly?  What would you do?

Answer:
I personally treat the data as any other data that would be stored in the system, for example I have a module built for DNN that stores collection of text data, I have the following collection of columns in a table for it.
EntryId
UpdatedBy
UpdatedDate
CreatedBy
CreatedDate
SortOrder
Content (NTEXT)
Hidden (Bit)
I find that this keeps the data easy to find, and it is easy to manipulate regardless of the caller.


Question: I am working on a project using rails 2.1.1.  With the new release of 2.2.2 I want to migrate to the new version.  Is there anything I need to change to migrate my 2.1.1 controllers, views, and models?

Answer:
There aren't any major changes in the way things are done.  Here is the list of
deprecations
Of course the best way to quickly discover changes is to have a good test suite in place.  If you don't have that, I suggest dropping 2.2 into vendor/rails and clicking around the site by hand.


Question:
We have a large MS Access project that requires GUI functionality that is difficult / impossible to do in the VBA / access forms environment.

Over time, we wish to re-write / migrate to a managed C# environment with WPF as the presentation layer.

The only practical way for us to do this is over a longer period of time - converting some of the VBA forms first (that would give the best productivity benefit), and then over the course of 12-24 months convert the entire system.

What do you believe is the best approach. Can MS Access host the WPF forms as we convert them?

Answer:
What if you look into Visual Studio Tools for Office (VSTO) ?
You can write managed .NET addins for Office in C#, that will integrate as ribbons with office.
Now, the problem is that Access add-ins are not supported in VSTO AFAIK.
But, take a look
here
, it seems to be not that impossible.
So, if you happen to be lucky, you could
Write a C# ribbon for Access which would have all the advanced GUI you need
Write services in C# that could be accessed from Access to encapsulate important business logic for instance, so that you could gradually move not only GUI, but build proper domain object model in C#.
If you decide to try it out, let me know how it turned out :)
Good luck anyway.
PS something else which maybe is helpful?
Access 2007 Developer Extensions (ADE)


Question: I know FireBug with YSlow has to be by far my personal favourite. I also use IE developer toolbar when forced to test pages in IE. Is there any other jewels out there hiding??

Answer:
I use the
Web Developer Extension
for Firefox, has tons of useful options.
(source:
mozilla.org
)
Also like the
Live HTTP Headers
Extension.


Question: What's the coolest mashup you've built?  What APIs did you use?  How was the mashup better than the sum of its parts?

Answer: Although probably not a true mashup, I created a script hat would read the Apple Movie Trailer RSS feed, and then visit the links in the feed to download the HTML of the pages linked to in the RSS feed. From there, it would download the container .mov files, and parse out the actual URL to the movie you can actually download.  SO while all the information was coming from Apple, the script would download multiple things, from different parts of their site, to piece together a final RSS feed that would contain links to .mov files that actually contained the movie trailer.


Question:
I have code like this to move the player in my game left, right, up, and down:

keysSetRepeat(20, 5);

while (lives) {
    scanKeys();

    if (keysDownRepeat() & (KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN)) {
        u8 new_x = x;
        u8 new_y = y;

        if (keysDownRepeat() & KEY_LEFT) {
            new_x--;
        } else if (keysDownRepeat() & KEY_RIGHT) {
            new_x++;
        } else if (keysDownRepeat() & KEY_DOWN) {
            new_y++;
        } else if (keysDownRepeat() & KEY_UP) {
            new_y--;
        }

        // ...
    }

    // ...

    swiWaitForVBlank();
}

Why are the keys not being detected? If I replace keysDownRepeat() with keysDown() it works (without the repeat rate, of course). The documentation is no help here.

Answer:
I had to find the libnds source code to figure this out. Look at the implementation of keysDownRepeat():
```
```
uint32 keysDownRepeat(void) {
    uint32 tmp = keysrepeat;

    keysrepeat = 0;

    return tmp;
}
```
```
It actually returns the keys then resets them back to 0. This wasn't documented. I solved this by storing the result of
```
keysDownRepeat()
```
into a variable and using the variable to check the keys:
```
```
keysSetRepeat(20, 5);

while (lives) {
    scanKeys();
    u32 keys_down_repeat = keysDownRepeat();

    if (keys_down_repeat & (KEY_LEFT | KEY_RIGHT | KEY_UP | KEY_DOWN)) {
        u8 new_x = x;
        u8 new_y = y;

        if (keys_down_repeat & KEY_LEFT) {
            new_x--;
        } else if (keys_down_repeat & KEY_RIGHT) {
            new_x++;
        } else if (keys_down_repeat & KEY_DOWN) {
            new_y++;
        } else if (keys_down_repeat & KEY_UP) {
            new_y--;
        }

        // ...
    }

    // ...

    swiWaitForVBlank();
}
```
```


Question:
Is it possible to migrate a VB.NET Winform solution to a 3.5 WPF solution.  If so, any suggestions how to do it?

Thanks in advance!
JFV

Answer:
Microsoft is doing everything for us so that we have to throw away everything we've written 2 years ago.
According to Josh Smith,
Is there a way to convert Winforms application to a WPF application?
No.  Those two UI platforms are very different and there is no app which converts a WinForms app to a WPF app.  Of course, this will not prevent you from reusing any business/DAL/logging/Ioc/etc libraries you use in WinForms.
However, you might want to check out
this
, quite basic but functional WinForms->XAML converter, written by Rob Relyea from WPF & Xaml Language Team.
According to him, "We (Microsoft) haven't built a real converter because we think most people will not just move over controls, but often will rethink their application as they move it.  We'd love feedback..."
Also, you might want to check out
Guidance for migrating an app from Windows Forms to WPF
, also by Rob Relyea.


Question:
I know I can configure command line arguments in the Run configuration but I want to run a java file multiple times with different command line arguments. It's a pain to change the Run Configuration every time.

Is there a way I can make Eclipse prompt me for command line arguments every time I run the program?

Answer:
Add
```
string_prompt
```
as a
```
Program Argument
```
in the
```
Run
```
configuration.
```
```
${string_prompt}
```
```
There are also a
```
file_prompt
```
and a
```
folder_prompt
```
if you want specifically files\folders.
These are available through the
```
Variables
```
button on the
```
(x)= Arguments
```
tab of the Run Configuration dialog.


Question:
I am using the FlexiGrid jQuery plug in and I need to get a JSON object back form my MVC App, simple enough if the FlexiGrid took just the object but I need to add a few items to the response string for it to work properly with FlexiGrid.

So here is a portion of my controller code:

If Request.QueryString("json") IsNot Nothing Then
    Dim data As New StringBuilder()
    data.Append("page: " & pageIndex & "," & vbCrLf)
    data.Append("total: " & ViewData.TotalCount & "," & vbCrLf)
    data.Append("rows: ")
    data.Append(Json(objCustomerList))

    Return Content(data.ToString())
End If

Unfortunately in the above code Json(objCustomerList) returns 'System.Web.MVV.JsonResult' instead of the desired JSON string data.  I also tried Json(objCustomerList).ToString() just to see what would happen and the same thing again.

Any ideas?

Answer:
```
Json()
```
method in ASP.NET MVC is just using the
```
JavaScriptSerializer
```
class via the
```
JsonResult
```
class.  You could use that yourself if you wanted to serialize the objCustomerList object using JSON to a string.
My recommendation would be to take a slightly different approach.
Create a Model that represented the .NET equivalent of the JavaScript object you were trying to create.  Maybe a FlexiGridModel object with Page, Total, Rows, and CustomerList properties.
Then when you pass that FlexiGridModel to
```
Json()
```
it would just work, no need to build a JSON string using
```
StringBuilder
```
.
If you just want your code to work there is an
override on
```
JavaScriptSerializer.Serialize()
```
that takes the object to serialize and the
```
StringBuilder
```
to append the results to.  Which should be exactly what you are looking for.
Some relevant links:
JavaScriptSerializer example
ASP.NET MVC JsonResult source
Codeproject: ASP.NET MVC Flexigrid sample


Question:
In T-SQL, SPACE() function is used to add spaces to a string. For e.g.

@s = 'He' + space(5) + 'llo'

Output

He     llo

So is there any function in PL/SQL that is equivalent to SPACE()?

Thank you.

Answer:
You can use RPAD or LPAD functions
```
```
select 'He'  || rpad(' ',5,' ') || 'llo'
from dual;
/
```
```
or in PL/SQL it would be:
```
```
declare
  x varchar2(20);
begin
  x:= 'He'  || rpad(' ',5,' ') || 'llo';
end;
/
```
```


Question:
How to declare a static dictionary object inside a static class? I tried

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic = new Dictionary<string, string>()
    {
        { "1", "User name or password problem" }
    };
}

But the compiler complains that "A const field of a reference type other than string can only be initialized with null".

Answer:
```
```
public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };
    }
}
```
```
Probably initialise in the constructor.


Question:
Reporting Services 2000 SP2

I've got a matrix displaying the number of employees

                 Business1      Business2      Business3
StartBefore99    9              14             4
StartAfter99     30             20             34

I'd like to display percentages eg

                 Business1      Business2      Business3
StartBefore99    9 (23%)        14 (41%)       4 (10%)
StartAfter99     30 (77%)       20  (59%)      34 (90%)

Any suggestions?  I could do it in SQL, but would prefer to do an expression in RS.

Cheers

Answer:
```
```
public static class ErrorCode
{
    public const IDictionary<string , string > m_ErrorCodeDic;

    public static ErrorCode()
    {
      m_ErrorCodeDic = new Dictionary<string, string>()
             { {"1","User name or password problem"} };
    }
}
```
```
Probably initialise in the constructor.


Question:
When editing PHP code (I'm not sure if it's specific to that language) and I create a new line in the middle of comma-separated lists that span multiple lines, the indent rules always unindent the line I'm leaving. Here's a video of it. This happens in arrays, function argument lists, etc.

Is there anything I can do to stop this from happening, or any quicker methods of fixing the error than moving up, re-indenting it, moving down, re-indenting (since it gets cleared when you leave the line), and continuing?

.vimrc

Answer:
Try
```
:set indentexpr=""
```
and see if that helps. See
```
:help filetype-indent-off
```
for the section that deals with filetype plugins (which is probably where this indentexpr is coming from).


Question:
I'm a complete beginner when it comes to programming. I'm taking a stab at PHP, and have seen how powerful the frameworks can be. But should I even consider trying to work with a framework until I have a strong grasp of PHP itself?

Note: I'd most likely be using CodeIgnitor, but the question applies to any of the frameworks.

Answer:
Preferably, you should have a strong grasp of the language (and programming in general) before you start using frameworks. Frameworks can and will save you a lot of work, but you they also introduce advanced concepts and implementations.
After you gain some experience and start to wonder what's the best way to solve some common problems you have faced before - that will be a good time to give frameworks a try.
I would suggest you try to read some of the source code of the different frameworks and see if it makes sense to you. If it doesn't - you are probably not ready yet.


Question: What is SSL and how does it relate to HTTPS?

Answer:
HTTPS is just HTTP over SSL.  Or Hypertext Transfer Protocol over Secure Socket Layer.
SSL is an encrypted channel for communication.  HTTP is the way to transfer web pages and other web content across the network.


Question:
I'm a C/Python programmer in C++ land working with the STL for the first time.

In Python, extending a list with another list uses the .extend method:

>>> v = [1, 2, 3]
>>> v_prime = [4, 5, 6]
>>> v.extend(v_prime)
>>> print(v)
[1, 2, 3, 4, 5, 6]

I currently use this algorithmic approach to extend vectors in C++:

v.resize(v.size() + v_prime.size());
copy(v_prime.begin(), v_prime.end(), v.rbegin());

Is this the canonical way of extending vectors, or if there is a simpler way that I'm missing?

Answer:
From
here
```
```
// reserve() is optional - just to improve performance
v.reserve(v.size() + distance(v_prime.begin(),v_prime.end()));
v.insert(v.end(),v_prime.begin(),v_prime.end());
```
```


Question:
I am having trouble setting the path to jquery in an mvc app. In my master page I have the script declared and jquery works at the root of my app. When I navigate to a content view page in my app jquery does not get loaded properly. Do I need to set the path in the content page as well or declare the path differently?

<script src="Views/Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>

Answer: The src on the masterpage is relative, which won't work on child pages. It should work if you declare the path as an absolute path (e.g. "/Views/Scripts/jquery-1.2.6.min.js");


Question:
Is there any way to save the state of vim settings with a document?

To clarify: I'm editing a document and I change a bunch of settings. I don't necessarily recall which; and I don't want to use these settings again, except for the current document. I don't want to manually try to remember what I've changed; or what the magic abbreviations are for the settings I've changed. I just want to have, say, for "mydoc.txt", a "mydoc.vim" file that puts me back where I left off, and the settings file would be saved automatically based on a vim setting, say, or maybe a ctrl-key does it before I exit. It would be handy if vim could automatically look for such a file.

And it would be preferable not to have to edit the settings into and out of the document itself.

Answer:
Yes, vim settings can be included within the document.
They are mostly found within comments, so they don't mess up the original file. An example for tab-specific settings is:
```
```
/* ex: set tabstop=8 expandtab: */
```
```
Note that this command works in most cases, however, servers are often setup without
```
modeline
```
turned on for security reasons. To turn on that feature add the following in your $HOME/.vimrc or the system $VIM/vimrc:
```
```
set modeline
```
```


Question:
I am using the rounded corners plugin for jquery and have it working rounding elements in my page. The only issue I have is that the elements appear on the page un-rounded and then round. What do I need to do so that the elements only appear rounded?

I originally put my script tags in the head element but should they go somewhere else in a master page to improve perf?

Answer:
Yes, vim settings can be included within the document.
They are mostly found within comments, so they don't mess up the original file. An example for tab-specific settings is:
```
```
/* ex: set tabstop=8 expandtab: */
```
```
Note that this command works in most cases, however, servers are often setup without
```
modeline
```
turned on for security reasons. To turn on that feature add the following in your $HOME/.vimrc or the system $VIM/vimrc:
```
```
set modeline
```
```


Question:
I am a Winforms and business engine developer who is using asp.net for the first time in over 2 years, and in that time I have noticed a few convention changes.

What is the logic behind the anti-'tables for layout' movement?

Is it to allow css classes to be used to handle layout, and if so, should this really be an issue on pages you are fairly sure will remain static, or is it just considered 'ugly'?

Answer:
There are a number of reasons. One reason is accessibility...layout tables do not add semantics to the content so screen readers have trouble with them. So only use tables for tabular data.
Here
are a few points that answer the question in more details
Tables are slow
Tables can be inflexible
Accessibility issues are easier with CSS
Tables don’t degrade
Tables don’t print as well


Question: I would like to start a small part time business other than my full time programming job. Have you guys done that before? I know programmers who teach in evening schools after work. But then again, that is not business. What would you recommend to get another income stream going?

Answer:
I would recommend having some sort of business plan. Don't just start writing some application or creating some web site and think it will sell. Do some research on the actual market for your product.
Also, having done it before, I would suggest having at least 1 other partner in the business. Doing it all yourself quickly becomes a waste of effort. You can do it, but it sure is a heck of a lot easier if you have someone to help with ideas, programming, accounting, web design, etc.
Also, think hard about whether you really want another job outside of your current job. I don't know what your life is like outside of your day job, but having another job (particularly one that requires daily attention like a website that has to be constantly updated) can be a real drain on your life.
If you do come up with a business plan and start a business, make it something you thoroughly enjoy! It can be very rewarding if you do.


Question:
I got my Xampp server running and can run my html in subdirectories now, as well (can't have spaces in the subdirectory names).

SSI Includes or PHP Includes:

Xampp says SSI is deactivated. Tried uncommenting the lines for includes, but it doesn't change the deactivation.

How do I activate SSI?

Then, how do I implement either SSI include statements or PHP include statements into my html to call up html files that include html, images, javascript and commands that call other javascript menu files?

Answer:
I don't know if Xampp has a special way of activating SSI or not, but the
normal Apache way
should work.
The normal way to include files in SSI is
```
```
<!--#include virtual="/something/file.html" -->
```
```
where the url to the file is actually
http://www.example.com/something/file.html
.


Question:
I'm writing an application in PHP 5. I want to delete some rows in a SQLite v2 database file. I'm doing something like this:

$sqliteConnection = new SQLiteDatabase('path/to/db');
$queryString = "DELETE FROM myTable WHERE status='not good'";
$result = $sqliteConnection->query($queryString);

how can I know how many rows were affected by this query? how many rows have I deleted?

Answer:
The PHP function
```
sqlite_changes()
```
does this for you.
Returns the numbers of rows that were changed by the most recent SQL statement executed against the
```
dbhandle
```
database handle.
Call it either in procedural-style:
```
```
echo 'Number of rows modified: ', sqlite_changes($sqliteConnection);
```
```
or in object-style:
```
```
echo 'Number of rows modified: ', $sqliteConnection->changes();
```
```


Question:
Is there any Java library that supports hierarchical column?

For example (the first three row are columns) :

------------------------------------------------
2008                                           |
------------------------------------------------
January               | February               |
------------------------------------------------
Week1 | Week2 | Week3 | Week 1 | Week2 | Week3 |
------------------------------------------------
10    | 20    | 14    | 12     | 15    | 3     |
------------------------------------------------

Answer:
May be a
JXTree
from
SwingLab
could approach what you are looking for.
Illustration
here
, from the
Swingx
project
http://avatar21.superihost.com/images/JXTableJXTreeTable.png


Question:
We are using OpenLDAP client library to conect to an LDAP server. The problem is that if there is no activity for some time, server (or firewall in the middle) drops TCP connection.

Our current implementation of "keep-alive" just does search for baseDN from time to time - any better ideas ?

Answer:
The only alternative seems to be reconnect:
```
```
ldap_set_option( ld, LDAP_OPT_RECONNECT, LDAP_OPT_ON );
```
```


Question:
I have a N-Ary non sorted in any way tree and each node can have 0-N children. Given the data structure below, how can I fill the tree view assuming you have an array of TermNodes and that array is the first level of the TreeView? I have not been able to come up with a recursive way to do this.

class TermNode
{
   public string Name;
   public string Definition;
   public List<TermNode> Children
}

Answer:
Here is a bit of code to get you started with the recursion. It's not tested (I can't right now), but you should get the idea:
```
```
public static void BuildTreeView(TreeNodeCollection Parent, List<TermNode> TermNodeList)
{
  foreach (TermNode n in TermNodeList)
  {
    TreeNode CurrentNode = Parent.Add(n.Name);
    // no need to recurse on empty list
    if (n.List.Count > 0) BuildTreeView(CurrentNode.Nodes, n.List);
  }
}

// initial call
List<TermNode> AllTermNodes = /* all your nodes at root level */;

BuildTreeView(treeView1.Nodes, AllTermNodes);
```
```


Question: What is the concept of erasure in generics in Java?

Answer:
It's basically the way that generics are implemented in Java via compiler trickery. The compiled generic code
actually
just uses
```
java.lang.Object
```
wherever you talk about
```
T
```
(or some other type parameter) - and there's some metadata to tell the compiler that it really is a generic type.
When you compile some code against a generic type or method, the compiler works out what you really mean (i.e. what the type argument for
```
T
```
is) and verifies at
compile
time that you're doing the right thing, but the emitted code again just talks in terms of
```
java.lang.Object
```
- the compiler generates extra casts where necessary. At execution time, a
```
List<String>
```
and a
```
List<Date>
```
are exactly the same; the extra type information has been
erased
by the compiler.
Compare this with, say, C#, where the information is retained at execution time, allowing code to contain expressions such as
```
typeof(T)
```
which is the equivalent to
```
T.class
```
- except that the latter is invalid. (There are further differences between .NET generics and Java generics, mind you.) Type erasure is the source of many of the "odd" warning/error messages when dealing with Java generics.
Other resources:
Oracle documentation
Wikipedia
Gilad Bracha's Java generics guide
(PDF - highly recommended; link may need to change periodically)
Angelika Langer's Java Generics FAQ


Question:
I have a controller that returns either JSON or partial html depending on if the user is logged in.

Is there anyway to tell the difference once the result has been returned??
What is the best way.

Obviously i have different actions to complete if the response is json or if it is the partial html. With the json one i do a redirect to the login page, and with the html one i just display it. If only i could render the html server side and send it back in json format?? From what i have heard this cannot be done as yet. Thoughts?

Cheers.

DUPLICATE: Can I evaluate the response type of an $.ajax() call in success callback?

Answer:
I'd say, assuming you have control of the thing returning JSON or partial HTML, that you should change the Content-Type header of the JSON result to something like
```
application/x-format-json
```
or an equally obvious type.


Question:
I have two UIActionSheets and I am thinking that I will control them with one delegate (the UIViewController that instantiates them).  The delegate will capture an actionSheet call and try to figure out which of the two threw the event.

I tried to get the modalView's title to differentiate, but it seems to be invalid...

Should this work?

If not, is there some other way to distinguish which UIActionSheet did the event?

Or do I need to create two different classes that will be separate delegates for each UIActionSheet?

Thanks in advance.

Answer:
I think you need the
tag
property of the
UIActionSheet
.
Something like:
```
```
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle ... ];
actionSheet.tag = 10;
[actionSheet showInView:self.view];
```
```
Then in your delegate:
```
```
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  switch (actionSheet.tag) {
    case 10:
      ...
  }
}
```
```
tag
is a property of
UIView
and can be set in Interface Builder for components that appear there too. Quite handy, though I've never actually used it in this context myself.


Question: How can I differentiate a Workflow system from a normal application that automates some work? Are there any specific feature a system must have to be categorized as a workflow system?

Answer:
Workflow systems manage objects (often logically or actual electronic replacements for documents) that have an associated state. The state of an object in the system is node in a
state machine
(or a
Petri net
).
State transitions move an object from one state to another. The transitions can be triggered by people, automated events, timers, calendars, etc. Usually the transitions represent steps in a process in the real world.
That's pretty abstract, so consider an example: bug tracking software. A bug report probably starts out unvalidated, and as such is in a QA tester's queue. The QA tester will validate the report and make sure the steps are clear, grade the report for severity etc., and assign it to a developer or developer group. It is then in the developer's queue, who will ultimately fix or decide not to fix the bug, which will send it back to QA for validation. If there's a dispute over the bug, it might go into a state in which it bubbles up the management stack.
A trivial implementation of the above is to use an enumeration for the state associated with every object, and make everybody's inbox be a query for objects with a state of a particular enumeration value.
That's the gist of it, but things can get more complex, such as splitting off new objects, reacting to non-human events such as timing, internal or external (i.e. third-party) services, etc.


Question: When I publish my ASP.NET site in RELEASE mode, and set compilation debug="false", will my ASP.NET and System.Diagnostics Tracing still work?

Answer:
I believe that tracing is set separately from debugging in the configuration, so yes, if properly configured.
```
```
<configuration>
 <system.web>
  <trace enabled="true" requestLimit="40" localOnly="false"/>
 </system.web>
</configuration>
```
```


Question: Does anyone have any experience with doing this?  I'm working on a Java decompiler right now in C++, but would like a higher level language to do the actual transformations of the internal trees.  I'm curious if the overhead of marshaling data between languages is worth the benefit of a more expressive and language for better articulating what I'm trying to accomplish (like Haskell).  Is this actually done in the "real world", or is it usually pick a language at the beginning of a project and stick with it?  Any tips from those who have attempted it?

Answer:
I'm a big advocate of always choosing the right programming language for each challenge. If there is another language which handles some otherwise tricky task easily, I'd say go for it.
Does it happen in the real world? Yes. I am currently working on a project which is made up of both PHP and objective-c code.
The trick is, as you pointed out, the communication between the two languages. If at all possible, let each language stick to its own domain, and have the two sections communicate in the simplest way possible. In my case, it was XML documents sent via http. In your case, some kind of formatted text file might be the answer.


Question:
What does STRAIGHT_JOIN do in this code ?

SELECT  STRAIGHT_JOIN ClosingBalance
FROM   Accounts
WHERE idAccounts = FidDebit;

Answer:
From
here
:
STRAIGHT_JOIN is similar to JOIN, except that the left table is always read before the right table. This can be used for those (few) cases for which the join optimizer puts the tables in the wrong order.


Question: What is best way to allow user to pick date from a mobile device from usability prospective?

Answer: Are you building WAP page in asp.net? You have a DatePicker control in the mobile toolset. On devices that supports it this will render as a regular date picker (as in regular asp.net) while on more limited devices it will render as a series of selectors where you first select the year, then the month and finally the date. Unless you have a good reason to do otherwise you should use this I think.


Question:
Hej,

assuming I have a code that looks like this:

List<User> userList = GetUserByName (u => u.Name == name);
DoSomethingWithTheUsers (userList.ToArray ());

Now I want to know the type of the objects in the Array in the method DoSomethingWithTheUsers (object[] myObjects)

Simply done by myObjects.First ().GetType () but what is to be done if the array is empty?
Is there a possibility to still get the Type?

Answer:
The array type will be an array of User, i.e. User[]. Why not just use Type.GetElementType() on the GetType() of the array? I.e. using your example:
```
```
myObjects.GetType().GetElementType()
```
```


Question:
I'm using a Delphi 2009 VCL TProgressBar as a kind of "empty/full" gauge.

On Vista, with Aero theme enabled, this has an animation associated with it, which is annoying and inappropriate for an gauge.

Is there any way of disabling this (NOT by adjusting user's theme settings!) to prevent the animation on this control?

To clarify, I want something basically identical to the 'disk space used' meters in Windows Explorer. No animation, but still with a nice border and shading effects.

Update:

I understand that I need a "meter", rather than a true progress bar. How can a themed meter be implemented using the standard windows progress bar control?

Answer:
As per the
Vista UI guidelines for progress bars
you should not be using a TProgressBar for such purposes at all, it states:
Use progress bars only for progress. Use meters to indicate percentages that aren't related to progress.
There are a lot of Third-Party components (for example
Abakus VCL
) that are aimed at Process Automation applications and the like, maybe you could use one of these controls instead?


Question:
I would like to automate the deployment of my SSIS and SSAS artifacts to remote development SQL Server 2005 & 2008 instances on a scheduled basis.

What would be the best solution for this?  I am using TFS 2008 as the source control system, so I'd like to integrate the solution with MSBuild and a scheduled Team Build.

Answer:
SSIS is the easiest, when I was using SSIS, we stored our packages in a file and all we to do was copy the file to the correct directory in C:\Program Files\Microsoft SQL Server\90\DTS\Packages. Which you can do by adding a Copy task to the end of your MSBuild. I am not sure if the xml will be available by default in the output directory, so watch for that.
As for SSAS, I never got around to automating it but, you will want to look into Analysis Management Objects (AMO), pulling from Books online it says:
Analysis Management Objects (AMO) provides a programmatic interface to
  the complete command set for Analysis Services as available to the
  developer. Therefore, AMO can be used for deployment and also to the
  many administrative commands it otherwise supports. For more
  information about the user of AMO to automate any kind of
  administrative task, see Analysis Management Objects (AMO).


Question:
I don't want to have the user install Google Gears so I can show him his guessed location. Is there a way to get the location without having to use Google Gears?

I have found http://www.wipmania.com/de/blog/google-geolocation-api/ but it does not offer an example.

Answer:
This is typically called IP Geolocation.
An example is
here
.
The thing is, most sites (if you plan on calling this as a web service) will charge you for it.  Otherwise, throw together a web service that grabs a geolocation page, parses it for the address, and returns that piece of information.
In PHP, this seems to work pretty well:
```
```
<?php
 if(isset($_GET["ip"])){
   echo geolocate($_GET["ip"]);
 }

 function geolocate($ip){
   $raw_html = file_get_contents("http://www.geody.com/geoip.php?ip=$ip");
   if(preg_match('/Location:(.*)/',$raw_html,$matches)){
     $location_raw = $matches[1];

     //Get rid of pesky HTML tags
     $location = preg_replace("/<[^>]*>/","",$location_raw);
     return $location;
   }else{
     return "ERROR";
   }
 }
```
```


Question:
all! Typing from Italy
This little piece of code works if the matrix size is less then 800 and fails with a segmentation fault for higher sizes....
I have tried it with gcc 4.3.2 compiler in linux and macosx and VisualStudio compiler in windows.
Seemsthe problem is in the stack size..... how can I increase it ?
How can I solve the problem for bigger matrix sizes ?
The code works fine in serial put fails in parallel execution.
 Thanks.

#include <omp.h>
#include <stdio.h>
#define Nu 4000
int main() {
float A[Nu][Nu],B[Nu][Nu],C[Nu][Nu];
int i,j;
#pragma omp parallel
printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
#pragma omp parallel for private(j,i) shared(A,B,C) schedule(static)
for(j=0;j<Nu;j++){
for(i=0;i<Nu;i++){
//printf("Hello from thread %d, i,j %d %d\n", omp_get_thread_num(),i,j );
A[i][j]=0;
B[i][j]=0;
C[i][j]=0;

}}

}

Answer:
Default stack size in OpenMP is 4-8 MB. There's an environment variable called STACKSIZE you can change (for example to 16384, which is 16 MB). See chapter 5-5 of
this PDF
.


Question:
How to find and remove unused Delphi runtime packages from a project that uses packages?

I have a Delphi project that is made up of several packages, in the requires part of the packages there are several Borland/3rd party packages listed (rtl.dcp, vcl.dcp ect) I know I need most of them, but there are ones I know I don't need that have crept in there over time, maybe a component used them once but then that component was removed, or maybe it was from me testing code.

How do I find out which are needed and which are not? and if they are not needed will they still need to be distributed with the final application or have any impact on the size/ memory requirement of the app?

I am trying to make it all as streamline as possible.

Answer: If you specify a package to be used as runime package, all the packages that package requires need to be deployed as runtime package as well. Delphi's compiler automatically checks if this is the case. So you don't need to explicitly require rtl.dcp, as long as you require one of your other packages that does. This means you could only specify the runtime packages you are sure of you need and the rest will be added by the compiler. Then you only need to check what packages you need to deploy in the end.


Question:
I have a space delimited list of files names, where spaces in the file names are prefixed by '\'

e.g. "first\ file second\ file"

How can I get my regex to match each file name?

Answer:
```
```
(\\ |[^ ])+
```
```
Everything except spaces, except when they're escaped.  Should work, sorry for misunderstanding your question initially.


Question: I understand SSO as the one time login for all the applications connected. I would like to know more about SSO and how exactly it is achieved.

Answer:
This is Donnie. He's a friend of mine.
The basic mechanism is to trust your friend's friend.
Another metaphor that's used is the sticker they give you when you enter a secured building.  In the morning, you show your valid ID (credential) to the security person, and for the rest of the day, the sticker acts as the pass (token). When you come back next day, you have to show your ID again.
Key technology is how you trust your friend or security guy or anyone in hostile network. See how Kerberos or asymmetric encryption work.


Question:
Are there Windows API functions that allows reading what the current password policy is?  For instance, minimum length, complexity etc.

If not reading, is there a way to verify a password against the policy programmatically?

Answer:
See
Security Watch Windows Domain Password Policies
. You can hit AD using
ADSI
or its wrappers. I found a
VBScript sample
. You can translate it to any language you want:
```
```
Sub ListPasswordPolicyInfo( strDomain )
    Dim objComputer
    Set objComputer = GetObject("WinNT://" & strDomain )
    WScript.Echo "MinPasswordAge: " &  ((objComputer.MinPasswordAge) / 86400)
    WScript.Echo "MinPasswordLength: " &  objComputer.MinPasswordLength
    WScript.Echo "PasswordHistoryLength: " &  objComputer.PasswordHistoryLength
    WScript.Echo "AutoUnlockInterval: " &  objComputer.AutoUnlockInterval
    WScript.Echo "LockOutObservationInterval: " &  objComputer.LockOutObservationInterval
End Sub

Dim strDomain
Do
    strDomain = inputbox( "Please enter a domainname", "Input" )
Loop until strDomain <> ""

ListPasswordPolicyInfo( strDomain )
```
```
As a bonus, check out
LDAP Admin
. It's an open source LDAP directory editor, which you can use to test things, and also checkout the code written in Delphi.


Question:
I need to deploy a web application on several laptops (although it is a web application, it is intended to run via localhost only - thus the need to deploy on several different machines).

Normally I would go to IIS and right click a directory to create a web application, but I would very much like to automate this leg of the installation. Can it be done?

I want to use IIS, but I want to create the web application automatically without opening the IIS Microsoft Management Console (MMC).

Answer:
To implement a minimal web server you can use HTTP.SYS (the core component of IIS deployed with Windows XP SP2 or higher). In .NET this can be done e.g. by using the HttpListener class in the
System.Net
namespace.


Question:
After creating a instance of a class, can we invoke the constructor explicitly?
For example

class A{
    A(int a)
    {
    }
}

A instance;

instance.A(2);

Can we do this?

Answer:
You can use
placement new
, which permits
```
```
new (&instance) A(2);
```
```
However, from your example you'd be calling a constructor on an object twice which is very bad practice. Instead I'd recommend you just do
```
```
A instance(2);
```
```
Placement new is usually only used when you need to pre-allocate the memory (e.g. in a custom memory manager) and construct the object later.


Question:
Using ICU 4.0 regex library, I find that the following regex is exhibiting exponential time:

actual: "[^<]*<\?"
C code: "[^<]*<\\?"

Aim: find "<?" where there is no other "<" before it

When running this regex on plain text with no "<" characters at all it appears to take exponential time. If the text has at least a single "<" then it is quick. I don't understand why.

Shouldn't the required match on "<?" prevent this from needing to backtrack? I would have thought that it would try to find the first "<" and then test the rest of the expression. If it can't find a "<" then it would give up because the pattern obviously can't match.

Is this a bug in the ICU regex or is it expected?

Answer:
The regex engine isn't that smart. It will try to match from
every
position, and
each
time seach for
```
<?
```
from the end, and backtrack until the start of the match-attempt. This gives a quadratic time complexity, O(
n
2
).