q:
I need to have a set of overloaded functions in my code but I get convertion wanrings.
Here is a test code:

#include windows.h

void f(DWORD arg){...}

//void f(SIZE_T arg){}

void main(void)
{
DWORD dword=0;
SIZE_T size_t=dword;
f(size_t);

}

The compiler gives warning:

test.cpp(11) : warning C4244: 'argument' : conversion from 'SIZE_T' to 'DWORD', possible loss of data

If I uncomment void f(SIZE_T arg) I get

test.cpp(5) : error C2084: function 'void f(DWORD)' already has a body

How can I avoid having this warning or error?

[A]
```
size_t
```
is guaranteed to be an unsigned integral type, but the number of bits it has isn't specified.  It could be equal to a
```
DWORD
```
(32 bits), or it could be 64 bits on a 64-bit platform.  For maximal portability, you shouldn't assume it has a certain number of bits, which is what the compiler is warning you about.  If you know your value will never exceed 2^32 (which is a reasonable assumption in 99.99% of cases), then you can just cast to a
```
DWORD
```
to get rid of the warning:
```
```
SIZE_T sz = dword;
f((DWORD)sz);  // no warning here
```
```
The error you're getting is because in your case,
```
size_t
```
is actually 32 bits, and so the function signatures of your two
```
f
```
functions are identical - they both take a single unsigned 32-bit parameter.  You'll have to use separate names for them in order to guarantee that your program is portable between 32- and 64-bit platforms:
```
```
void f_DWORD(DWORD arg) { ... }
void f_size_t(size_t arg) { ... }
```
```
One final note:
```
size_t
```
is a built-in type.
```
SIZE_T
```
is non-standard and is almost definitely a typedef or a #define for
```
size_t
```
.  You should use
```
size_t
```
instead of
```
SIZE_T
```
, and you should also avoid naming your variables
```
size_t
```
, since that introduces confusion by shadowing a type name with a variable name.


q:
I have a repository which contains some unversioned directories and files. The server running svn was recently changed and since the checkout was done using the url svn://OLD-IP, I relocated my svn working copy, this time to the url svn://NEW-DOMAIN-NAME.

Now since there are some unversioned resources, the switch did not happen properly and the working copy got locked. A cleanup operation did not work either because of these unversioned resources.

I looked up in the net and found about svn ignore and tried that but to no use. I am unable to release all locks. Any ideas on solving the problem? Once I release the locks, I believe I can use svn ignore and carry on the relocate operation.

[A]
Check your
```
svn status
```
output and the legend for the letters at
```
svn help status
```
.
Quite often, the problem is that there is a file where svn expects a directory, or other kinds of similar confusion (the letters should tell you which it is). If there are any conflicts (
```
C
```
), solve them first. You can recover lost directories with
```
svn update
```
, and
```
svn revert
```
can often help too (if there is anything important on your working copy which is not in the repository, make a backup of the working copy first!).
After most of the confusion has been cleared,
```
svn cleanup
```
and
```
svn update
```
/
```
svn switch
```
(
```
update
```
is nothing more than a special case of
```
switch
```
) should start working again.
In the worst case, you can do another checkout and manually copy over any locally modified files.

s: huggingface

c: devops

d: intermediate


q:
I have a form that sits behind ASP.NET forms authentication.  So far, the implementation follows a typical "out of the box" type configuration.

One page allows users to post messages.  If the user sits on that page for a long time to compose the message, it may run past the auth session expiration.  In that case, the post does not get recorded... they are just redirected to the login page.

What approach should I take to prevent the frustrating event of a long message being lost?

Obviously I could just make the auth session really long, but there are other factors in the system which discourage that approach.  Is there a way I could make an exception for this particular page so that it will never redirect to the Login so long as its a postback?

[A]
My coworker came up with a general solution to this kind of problem using an HttpModule.
Keep in mind he decided to to handle his own authentication in this particular application.
Here goes:
He created an HttpModule that detected when a user was no longer logged in. If the user was no longer logged in he took the ViewState of that page along with all the form variables and stored it into a collection. After that the user gets redirected to the login page with the form variables of the previous page and the ViewState information encoded in a hidden field.
After the user successfully reauthenticates, there is a check for the hidden field. If that hidden field is available, a HTML form is populated with the old post's form variables and viewstate. Javascript was then used auto submit this form to the server.


q: I am invoking a C library via JNI that prints to stdout.  How can I redirect this output to System.out?

[A]
```
System.out
```
is
```
stdout
```
.  Is there some more fundamental problem you're having (mixed up output, perhaps?).
Since another member has also mentioned that last point - I should explain further:
```
System.out
```
and
```
stdout
```
both correspond to file descriptor #1.
However both Java's
```
OutputStream
```
(and derived classes) and C's
```
stdio
```
library have their own (independent) buffering mechanisms so as to reduce the number of calls to the underlying
```
write
```
system call.  Just because you've called
```
printf
```
or similar, it's not guaranteed that your output will appear straightaway.
Because these buffering methods are independent, output from within Java code could (in theory) get mixed up or otherwise appear out-of-order relative to output from the C code.
If that's a concern, you should arrange to call
```
System.out.flush()
```
before calling your JNI function, and in your C function (if it's using
```
stdio
```
rather than the low-level
```
write
```
call) you should call
```
fflush(stdout)
```
before returning.


q:
I can't seem to find a true restful Blog API - are there any?
I'm writing some blog software and wondered if there was a standard restful API, if not I'll go buy the RESTful Web Services book and design my own.

[A]
How about
AtomPub
?
Atom is the name of an XML-based Web
  content and metadata syndication
  format, and an application-level
  protocol for publishing and editing
  Web resources.
It isn't limited to blogs, but blogs certainly fall under the realm of applications are used for "publishing and editing Web resources".


q:
I'm having a problem with a administrative app I'm working on.  I'm build an interface for stopping, starting and querying various services across 40 or so servers.

I'm looking at service.controller and have been successful in stopping and starting various services with button events but now I'm trying to figure out a way to return the service status to a text box and query for service status every 10 seconds or so and I feel like I'm hitting a brick wall.

Does anyone have any tips or insight?

Thanks!!

[A]
You can trigger the periodic service check by using a Timer object. You can run your service queries on the Elapsed event.
```
```
private void t_Elapsed(object sender, ElapsedEventArgs e)
    {
        // Check service statuses
    }
```
```
As for displaying statuses in a text box, you should be able to use the ToString() method on the service status and display that in a regular text box. Remember that you may or may not be on the GUI thread when reacting to the timer events, so you'll need to invoke yourself on to the main thread.
```
```
private delegate void TextUpdateHandler(string updatedText);

    private void UpdateServerStatuses(string statuses)
    {
        if (this.InvokeRequired)
        {
            TextUpdateHandler update = new TextUpdateHandler(this.UpdateServerStatuses);
            this.BeginInvoke(update, statuses);
        }
        else
        {
            // load textbox here
        }
    }
```
```


q:
Do you know what's the format of the DepartureWindow parameter for sabre web-services' OTA_AirLowFareSearch call? Whatever I pass, it shows me an error.

This is the entire documentation for those parameters (I kid you not):

<!--"DepartureDateTime" represents the date and time of departure.-->
<DepartureDateTime>2004-11-22T15:00:00</DepartureDateTime>
<!--"DepartureWindow" represents a window of time to search prior and post departure.-->
<!--Example: JR.DFW/S-OYLAS22NOV1500‡ZRD09001700-->
<DepartureWindow>09001700</DepartureWindow>

I've already tryied passing the number of seconds since DepartureDateTime and a unix timestamp without success. The error message it's:

Error response received. The error was: INVALID TIME WINDOW IN  Z FIELDS

Thanks

[A]
You must specify time within window in DepartureDateTime
```
```
<ns1:DepartureDateTime>2009-01-03T15:00:00</ns1:DepartureDateTime>
 <ns1:DepartureWindow>11001559</ns1:DepartureWindow>
```
```
works fine for me


q:
I'm programming in FORTRAN and C on an SGI running Irix 6.5, but this should be applicable to all Unix-like systems.  How do I find which library I need to link to my program when I get an "unresolved text symbol" link error?  Here's an example of what I'm seeing from the linker:

ld32: ERROR  33 Unresolved text symbol "ortho2_" -- first referenced by ./libfoo.a

Do I just have to know which libraries are required, or is there some tool or command that can help me figure this out?

[A]
You can use the
```
nm
```
command to list the dynamic symbols from a shared library:
```
```
nm -D /lib/libc.so.6
```
```
and then
```
grep
```
for the symbol you are looking for.  Omit the -D for static libraries.  You can use this in a loop or with xargs to scan multiple libraries.
I usually just use google (assuming the symbol is from a publicly available library).


q: Are delegates the same thing as callbacks?  Or are they related somehow?

[A]
generically, a delegate is an object used to access a method external to the object owning the method, while a callback is a variable that holds a delegate
in C#, the terms are used interchangeably


q:
Let's say I have a table:

i j
---
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
b 9

Obvoiusly SELECT a, GROUP_CONCAT(b SEPARATOR ',') GROUP BY a would give me

a  1,2,3,4
b  5,6,7,8,9

But what if I want to get only a LIMITED number of results, like 2, for example:

a  1,2
b  5,6

Any ideas?

[A]
One solution would be to limit the rows in the group to the top two, before computing the aggregate.
```
```
SELECT t.i, GROUP_CONCAT(t.j)
FROM
  (SELECT t1.i, t1.j
   FROM mytable AS t1
     LEFT JOIN mytable AS t2
       ON (t1.i = t2.i AND t1.j >= t2.j)
   GROUP BY t1.i, t1.j
   HAVING COUNT(*) <= 2) AS t
GROUP BY t.i;
```
```
Another solution, if you know the values in
```
j
```
are of a fixed length, is to simply use
```
SUBSTRING()
```
on the result:
```
```
SELECT i, SUBSTRING( GROUP_CONCAT(j), 1, 3 )
FROM mytable
GROUP BY i;
```
```


q: The basics have already been answered here. But is there a pre-built PHP lib doing the same as Lingua::Identify from CPAN?

[A]
There's a PEAR package
```
Text_LanguageDetect
```
that I've used before. Get's the job done well enough. I'm not sure of any other libs that are more mature.


q:
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:

You can either make the non static method static or make an instance of that class to use its properties.

What the reason behind this? Am not concern with the solution, rather the reason.

private java.util.List<String> someMethod(){
    /* Some Code */
    return someList;
}

public static void main(String[] strArgs){
     // The following statement causes the error.
    java.util.List<String> someList = someMethod();
}

[A]
The method you are trying to call is an instance-level method; you do not have an instance.
```
static
```
methods belong to the class, non-
```
static
```
methods belong to instances of the class.


q:
Say I have this simple form:

class ContactForm(forms.Form):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

And I have a default value for one field but not the other.  So I set it up like this:

default_data = {'first_name','greg'}
form1=ContactForm(default_data)

However now when I go to display it, Django shows a validation error saying last_name is required:

print form1.as_table()

What is the correct way to do this?  Since this isn't data the user has submitted, just data I want to prefill.

Note: required=False will not work because I do want it required when the user submits the data. Just when I'm first showing the form on the page, I won't have a default value.

[A]
From the django docs is this:
```
```
from django import forms
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()
    cc_myself = forms.BooleanField(required=False)
```
```
The "required=False" should produce the effect you're after.


q:
How exactly using VB6 can I can call any Windows shell command as you would from the command-line?

For example, something as trivial as:

echo foo

[A]
Shell and ShellExecute?
http://msdn.microsoft.com/en-us/library/aa242087.aspx
```
```
Dim RetVal
RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)   ' Run Calculator.
```
```


q:
I have a file in cvs that has Sticky Options set to -kk.  This replaces all cvs keywords with just the keyword name to facilitate diffs.   For example, $Author: Alex B$ becomes $Author$.

How do I disable the -kk behavior and get back to "normal" cvs where keywords are substituted in?   I've tried rm'ing the file and updating, I've tried cvs update -A and neither changes the flag.

[A]
```
```
cvs update -kkv <filename>
```
```
will reset the sticky options to
```
keyword
```
and
```
value
```
Edit:
Corrected
```
checkout
```
to
```
update
```
, thanks to
Alex B
for the correction.


q:
Is it expensive?

I am developing an HtmlHelper that renders directly to Response.Output in order to save unnecesary string creation and I need to choose between:

<% Validator.RenderClient(Response.Output); %>

and

<% Validator.RenderClient(); %>

and get the textWriter from HttpContext.Current.Response

[A]
from reflector
```
```
public static HttpContext get_Current()
{
    return (ContextBase.Current as HttpContext);
}
```
```
calls ContextBase
which calls
```
```
public static object HostContext
{
    get
    {
        object hostContext =
          Thread.CurrentThread.GetIllogicalCallContext().HostContext;
        if (hostContext == null)
        {
            hostContext = GetLogicalCallContext().HostContext;
        }
        return hostContext;
    }
```
```
...
so there is a bit of threading 'stuff' going on; the specific I don't really know.


q:
Does anyone know if it's possible to determine, using JavaScript, whether the user's browser allows checkboxes and radio buttons to be focused? In other words, whether you can tab to select them.

I can't just use browser detection to do this, because in at least one case (Safari), the user can turn the ability on and off.

Also in Safari, the focus() function is defined even when this ability is turned off, and it doesn't throw an error. So checking that function won't work.

[A]
JavaScript cannot read the browser's settings. Doing so would be a security violation.
That being said, there is no way to test for something
not
happening if it requires the user's interaction without giving them explicit directions so to perform the testable action. So there is no passive way to test for the user having disabled tabbing.
It's rather like changing screen resolution in Windows. The user changes resolution and because VGA is passive there's no way for the OS to tell whether that change was successful unless the user performs an action. You need to ask them, set a timeout and assume it doesn't work if you get a negative result. You can't tell the difference between a negative result an no user interaction.


q:
Writing the code for the user authentication portion of a web site (including account registration, logins, and password resets) is pretty simple, but what do you need to make a really good user authentication setup?  For example, I'd consider not storing plaintext passwords to be a bare minimum requirement for a web site, but that piece of advice seems to be largely transmitted by word of mouth, and plenty of sites still fail to follow it.

What is some other good advice or good requirements for the user auth portion of a web site?  For example, should usernames be user-selected, or should they be email addresses?  Any pitfalls for the user registration portion?  (CAPTCHAs are probably worth a whole topic by themselves.)  Any pitfalls for the password reset portion?  Anything else?

Edit:

Somewhat duplicated here : best-practices-for-login-pages

[A]
On the username topic, it depends on how the username will be used on the site (beyond logging in). If your site is based on user generated content and you display the username with the content, allow the user to pick their own and make sure it is not an email address. Also, if the username will be displayed, I generally provide a bit of a warning on the registration form to let the user know, so they don't use their full name only to be angry later when it is displayed on the site.
I would recommend checking the availability and validity of a username through some type of Ajax call while the user is on the form. Having the form re-load with the password and password confirmation gone, just to have to think of a new username and re-input the data is a pain.
Other things to consider would be to enforce min/max lengths and some rules around passwords... don't make it difficult to sign up though. Also, accept special characters in the password. I have a couple of very strong passwords that I like to use and a lot of sites don't let me use them, so my account ends up being less secure than I would have made it on my own.
CAPTCHA is a good idea, just make sure it isn't super-difficult to figure out, that can be frustrating too.
There are a lot of things to consider and several options for each, but hopefully this will get you started.


q:
Suppose I have #define foo in various header files. It may expand to some different things. I would like to know (when compiling a .cc file) when a #define is encountered, to what it will expand, it which file it is and where it got included from.

Is it possible? If not, are there any partial solutions that may help?

Feel free to add comments with clarification requests.

Edit: current answers seem to concentrate on the case when there is one #define and I just want to jump to definition or know what the definition is. That's the simple case and yes, your solutions work. But when I have the same #define in different files, and want to know which one kicks in first, none of these techniques is useful. Okay, I actually used #warning carefully to find the right place. But this requires much work.

[A]
Use #warning. It's described
here
.


q:
Does anyone have any experience migrating from one DBMS to another?  If you have done this, why did you do it? Features? Cost? Corporate Directive?

At times, I've worked with DBAs who insisted that we not use features specific to a DBMS (for example, CLR Stored Procedures in SQL Server.)  The DBAs point is, if we use these features, it will make it more difficult to switch to another DBMS if we have to.  But so far, I've never been asked to switch.

[A]
In my opinion its silly not to take advantage of all the features of the db your using.  Changing DBMS regardless of how many features you use is going to be difficult.  There are minute differences between the systems (like some record Date and some record date and time) that will cause a huge headache to change.  There is no such thing of just switching to a new dbms.
From a business perspective there is a lot of work to be done.  Analysis on the new dbs to change to.  Figuring out the impact of changing dbs on the new system.  Having development change the existing systems, testing the changes etc.  The list goes on and on.  Making a switch like that on an enterprise system takes months if not years.  The last place I worked had to change dbs, and it took us a solid 11 months to do it and about 2 million dollars for consultants, hardware, software, and employee salaries.  It's a big deal.  If someone is saying not to use features, because that "may" happen someday and it'll be easier to do,  Most likely, that person is off their rocker.  The extra amount of time and money it will take to convert those features is minuscule compared to everything else (most likely).  IMO if it will save time and money now buy using those features, then that is the best course of action.
We did it because the systems we had running on the old dbms were too big.  There was too much data, and we needed something a lot more powerful.  Plus, it wasn't supported anymore.


q:
I'm working on an online tool for students in my faculty to calculate their final grade for their degrees, and for a while I've had little problems. Students seem to like using the new UI and I've suffered no criticism for a while. Now, I need to add some functionality to the program, meaning the UI will have to chance slightly, but in some very noticeable places.

After watching the whole New Facebook thing kick off, along with the slating of applications with bad UI here on SO and the Ribbon on MS Office receiving mixed reviews I've wondered to myself whether a UI should ever really be changed if users seem to like it. Should a UI be updated after a number of years to keep users interested/be more efficient? Should features be held back in sake of a clean UI?

[A] Ideally when you first design your UI you create something flexible enough to add any feature you want in the future.  In the real world, this is seldom the case.  I would say UI updates should be slow and incremental if at all possible (that was the real problem with the facebook change, one big change all of a sudden), and if not then people should be given plenty of notice of the change, and while you're changing you should be sure to plan for future additions so as to not annoy your user base more often than absolutely necessary.


q: How do I get the HTTP status code (eg 200 or 500) after calling curl_easy_perform?

[A]
http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html
```
CURLINFO_RESPONSE_CODE

Pass a pointer to a long to receive the last received HTTP or FTP code. This
option was known as CURLINFO_HTTP_CODE in libcurl 7.10.7 and earlier. This
will be zero if no server response code has been received. Note that a
proxy's CONNECT response should be read with CURLINFO_HTTP_CONNECTCODE
and not this.
```
```
```
curl_code = curl_easy_perform (session);
long http_code = 0;
curl_easy_getinfo (session, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code == 200 && curl_code != CURLE_ABORTED_BY_CALLBACK)
{
         //Succeeded
}
else
{
         //Failed
}
```
```


q:
The JUnit framework contains 2 Assert classes (in different packages, obviously) and the methods on each appear to be very similar. Can anybody explain why this is?

The classes I'm referring to are: junit.framework.Assert and org.junit.Assert.

[A]
I believe they are refactoring from
```
junit.framework
```
to
```
org.junit
```
and
```
junit.framework.Assert
```
is maintained for backwards compatibility.


q:
I need to connect to Outlook through ASP.NET web application using user credentials. What are my options?

FYI: User logs into the web site by using Windows Authentication. I'm working with Outlook 2003.

[A]
I'm going to do something similar, and I don't see a reason it wouldn't work: write an
Outlook Addin
that uses
object remoting
to communicate with whatever other services or tools you're working on.  Since it's an ASP.NET application, maybe you want to use a web service instead of object remoting.
Do you want the ASP.NET application to start Outlook if it's not already running?
Is one Outlook process going to be shared by many users, or do you want to connect to user-specific Outlook processes?  Do you want the ASP.NET application to act as a server that Outlook tries to connect to, or the other way around?
If the edge cases are complicated, you could try writing a Windows Service to act as an intermediary or gateway between the two e.g. a service that runs on each Outlook machine and starts Outlook on demand.


q:
I am new to C#. I wanted to do a simple program with some type of loops.
I wanted my program to loop through the numbers that the user enters and if it is less than a number then write keep guessing,but once they enter the number 25 i wanted it to say Merry Christmas..  Please Help

int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
}  while (number < 25);

C# Beginner

[A]
```
```
int number;

do
{
    Console.WriteLine("Guess a number between 20 through 25");
    number = int.Parse(Console.ReadLine());
} while (number < 25);

if (number == 25)
    Console.WriteLine("Merry Christmas");
```
```


q: I'm creating an asp.net app with just some lite data access from xml files.  However, I need to be able to authenticate administrative users (via forms) to manage that data.  I don't want to stand up a sql db just for authentication purposes.  I'd like to use xml, but not sure about security with that.  Any suggestions?  Custom role provider?  MyOpenID?


q: Are there any things to be careful about when defining the method_missing method in Ruby?  I'm wondering whether there are some not-so-obvious interactions from inheritance, exception throwing, performance, or anything else.

[A]
A somewhat obvious one: always redefine
```
respond_to?
```
if you redefine
```
method_missing
```
.  If
```
method_missing(:sym)
```
works,
```
respond_to?(:sym)
```
should always return true.  There are many libraries that rely on this.
Later:
An example:
```
```
# Wrap a Foo; don't expose the internal guts.
# Pass any method that starts with 'a' on to the
# Foo.
class FooWrapper
  def initialize(foo)
    @foo = foo
  end
  def some_method_that_doesnt_start_with_a
    'bar'
  end
  def a_method_that_does_start_with_a
    'baz'
  end
  def respond_to?(sym, include_private = false)
    pass_sym_to_foo?(sym) || super(sym, include_private)
  end
  def method_missing(sym, *args, &block)
    return foo.call(sym, *args, &block) if pass_sym_to_foo?(sym)
    super(sym, *args, &block)
  end
  private
  def pass_sym_to_foo?(sym)
    sym.to_s =~ /^a/ && @foo.respond_to?(sym)
  end
end

class Foo
  def argh
    'argh'
  end
  def blech
    'blech'
  end
end

w = FooWrapper.new(Foo.new)

w.respond_to?(:some_method_that_doesnt_start_with_a)
# => true
w.some_method_that_doesnt_start_with_a
# => 'bar'

w.respond_to?(:a_method_that_does_start_with_a)
# => true
w.a_method_that_does_start_with_a
# => 'baz'

w.respond_to?(:argh)
# => true
w.argh
# => 'argh'

w.respond_to?(:blech)
# => false
w.blech
# NoMethodError

w.respond_to?(:glem!)
# => false
w.glem!
# NoMethodError

w.respond_to?(:apples?)
w.apples?
# NoMethodError
```
```


q:
  ArrayList filters = new ArrayList();
  filters.Add(new string[] { "Name", "Equals", "John" });

  ObjectDataSource1.SelectParameters.Add("AppliedFilters",
           string.Join(",",(string[])filters.ToArray(typeof(string))));

Am trying to add a parameter to my object data source which is bound to my select method which should accept a string[]. But as the SelectParameters.Add takes in (string,string) or the other 3 overloads which do not seem to function for me correctly.

The select method accepts a string param though i prefer it accept a string[] or arraylist, but for now I can live with accepting a string which i should convert back to string[]

Resolution:
followed this article link text

Closed as duplicate of the question referenced above.


q:
I have a form that contains a bunch of checkboxes.  Before submitting the form, I'd like to grab the values of the checkboxes and stick them into a text field, then submit that.

So I might have:
   Red
   Orange
X  Yellow
   Blue
X  Green

And I'd like my textfield to end up with the content "Yellow, Green" .

This doesn't seem too complicated, but I am totally out of my league.  I already use jQuery for a few other things so I have the framework ready, if that makes it easer.

Thanks for any advice --

[A]
First hack at it (without testing):
```
```
var serializedCheckboxes = '';
$("input type='checkbox'").each(function() {
 if($(this).attr("checked")) {
  serializedCheckboxes += $(this).attr("value") + ',';
 }
});

$("input name='allchecks').attr("value", serializedCheckboxes);
```
```


q: I am trying to use the Event Log to write some debug information and I can't make it works. It complains about not being able to find the Event Source. Do I have to install something on the OS?

[A]
Here a code that I modified from one of our application. This might help you to start with the creation.
```
```
System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog();
string eventLogName = "StackOverFlowEventName";
string eventLogSource = "StackOverFlowWebsite";

//This code HERE will create the Event for you
if (!System.Diagnostics.EventLog.SourceExists(eventLogSource))
{
    System.Diagnostics.EventLog.CreateEventSource(eventLogSource, eventLogName);
}

eventLog1.Source = eventLogSource;
eventLog1.Log = eventLogName;
eventLog1.WriteEntry("This is a test");
```
```


q:
I'm trying to get the following SQL statement to work:

UPDATE myschema.tableA update_tableA
   SET field_id =
   ( SELECT src.field_id
         FROM myschema.srcTable src
         INNER JOIN myschema.tableB tableB ON
            update_tableA.id = tableB.id
            AND SDO_ANYINTERACT( tableB.shape, src.shape ) = 'TRUE' );

When I run this statement, I get the following error:

ORA-00904: "UPDATE_TABLEA"."ID": invalid identifier

Can I not use a variable scoped outside of the nested select within the nested select?  Any thoughts?

P.S. The identifier is indeed valid in the database table.  The problem appears to be scope, but I want to make sure that is indeed an issue.

[A]
Looking at the SQL above, here is what I am thinking
1) myschema.tableA doesn't have ID column (it could be field_id)
2) The SELECT doesn't seem to provide a join condition
```
SELECT src.field_id
         FROM myschema.srcTable src
         INNER JOIN myschema.tableB tableB ON
```
Where is the condition to JOIN src with tableB?


q:
It has to be simple, here's my CSS:

.progressImage
{
  position:relative;
  top:50%;
}

.progressPanel
{
height:100%;
width:100%;
text-align:center;
display:none;
}

<asp:Panel ID="pnlProgress" runat="server" CssClass="progressPanel">
<asp:Image ID="Image1" runat="server" CssClass="progressImage" ImageUrl="~/Images/Icons/loading.gif" />
</asp:Panel>

I toggle panel display depending on user action.

Works great in FireFox, but shows up at the top of the page in Safari.

p.s. "vertical-align:middle;" doesn't work either.

p.p.s. setting "position:relative;" on the panel doesn't work, setting "position:relative;" on the panel and "position:absolute;" on the image breaks it in FF and does nothing in Safari

THIS WORKED:

.progressPanel
{
  height:100%;
  width:100%;
  position:relative;
}

.progressImage
{
  position:absolute;
  top:50%;
  left:50%;
}

[A]
Ensure the parents container is also set to position: relative and has a height specified, without it the position wont work correctly.
```
```
.progressPanel
{
    height:100%;
    width:100%;
    text-align:center;
    display:none;
    position: relative;
}
```
```
alternatively, why not set the background property of the panel to your gif?
```
```
background: url('path/to/image.gif') no-repeat center middle;
```
```
That will always be centered.


q:
I need to store a tree data structure in my database, for which I plan on using django-treebeard or possibly django-mptt.  My source of confusion is that each node could be one of three different possible types: root nodes will always be a type A entity, leaf nodes a type C entity, and anything in between will be a type B entity.  I would like to know the best way to model this situation.

update:  I first tried model inheritance, and I think that this could be the best way to go. Unfortunately django-treebeard's public API isn't really designed to handle this.  I ended up getting it to work with GenericForeignKey.  Thank you very much for the answers.

[A]
Your three types are probably easiest handled as FK associations with the fundamental tree.
The tree can be homogenous -- class
```
MyNode
```
is a direct subclass of
```
treebeard.Node
```
.  Your node can have a flag (Root, Middle, Leaf) and FK's for A or B or C.  This allows you some SQL-like flexibility in querying MyNode instance.
This allows your tree to grow.  A node can start as a type C (leaf) and then morph to a type B (intermediate).  You change the status, and change the FK's.
The alternative is a bit more complex.
```
```
class MyA( treebeard.Node ):
    pass

class MyB( treebeard.Node ):
    pass

class MyC( treebeard.Node ):
    pass
```
```
In this case, you can't "morph" a node.  When a node starts as a
```
MyC
```
, and gets children, you have to remove the original
```
MyC
```
instance, and replace it with a
```
MyB
```
version that has a new node as a child.  This isn't impossible, but it can be painful.


q:
I have an HTML document that is using  to embed a control.  In some cases, IE fails to load the control in the  tag and loads my alternative text.

Only problem... I don't know why it is failing.  It doesn't show up as an error in the exclamation in the lower-left.  I overrode the window.onerror method, but that didn't get fired.  I see nothing in the event log.

How do I get any type of feedback to figure out what my problem is?  Can IE go into a "verbose mode"?  Is there some magic error log somewhere telling me why my object isn't loading into IE?

Thanks,
Brian

[A]
Often a failure in the object tag won't show up as an IE error, since the object is running from its own plugin codebase, not the browser's interpreter.
Are you loading this file locally? Or is it a hosted page? IE has different permissions for execution of objects. What is the type of the object? A code snippet would also help.
You could also use something like Charles Web Debugging proxy to see if the browser is even attempting to connect to the filename. If it's not, you know it's a problem with the code, but if it is making the call, you might be able to see what's returned in the HTTP headers - a server error (404, 500?), blankness, etc.


q:
I am using the Html.TextBox helper to create textboxes.  I want to set attributes on the textbox, which I understand is done using the following overload:

Html.TextBox (string name, object value, object htmlAttributes)

However, I want to maintain the functionality where the HTML helper automatically uses the value from either ViewData or ViewData.Model and I do not see a way to just specify the name and the htmlAttributes.  Is this possible?

[A]
[EDIT]  After looking at the
source code
, it appears that all you need to do is specify the value as null in the signature that takes a name, value, and htmlAttributes.  If the value is null, it will attempt to use the value from the ViewData.
```
```
Html.TextBox( "name", null, new { @class = "css-class" } );
```
```


q: What is the best way to get the TAPI version and additional TAPI information with C#?

[A]
Interop.
Use the
lpdwAPIVersion
parameter of the lineInitializeEx function.
http://msdn.microsoft.com/en-us/library/ms735983(VS.85).aspx
"Upon successful completion of this request, this location is filled with the highest API version supported by TAPI, thereby allowing the application to detect and adapt to having been installed on a system with a different version of TAPI."
You're going to have to start plugging away with Interop calls sooner or later when you're programming TAPI.


q:
I am about to start a web project and have been working almost exclusively with a LAMP stack for the past 5 years.  I would like to build something larger and more scalable and hence have been looking into Java EE.  The division of logic between JSP and EJB seems ideal for what I want to do.

Can anyone recommend resources for getting familiar with Java EE?  And perhaps if anyone knows of technologies that are more scalable than PHP that I should consider as well, I'm all ears.

Thanks a lot!

[A]
I think given your background in Linux and MySQL, the best place to start would be Java's
Servlet API
.  Java Servlets are the basic unit in Java EE for handling HTTP requests and responses on the server side.  In most of the Java EE work that I have done, servlets cover about 50% of development.  The other 50% is database development, which you seem to have done in the past.
For your servlet container, I would recommend
Apache Tomcat
.  Tomcat has a robust development community contributing regularly, and is used at the heart of several enterprise application server solutions, such as JBoss.
Good luck in your project!


q:
I have only recently started working with the MVC approach, so I suppose this is an easy one for you gurus here:

Where do I put access control?

In a view? I don't want to have any logic besides switches and flags in my templates, so that sounds like the least viable option

In the model? Should each business object decide what data it will reveal about itself based on who's asking?

In the controller? That's where I have it now but it makes it hard to keep business rules consistent

Or is there another option?

[A]
This will depend on what framework you're using as that and the language will dictate a lot of the tools you have available to you.
From a high level, you should have access security configured at points-of-entry. And you should double-check access security at every level that could be considered autonomous or reused from multiple parts of your application (who knows if security was checked by your co-worker's portal that uses your logic layer? etc.). The other thing to worry about is data security, and that belongs as close to your data as possible (so, yes to your #2 above, but understand that it's separate).
This is akin to the difference between application logic and domain logic, which I'm fond of talking about. If there is any logic that is specific to one particular application (web app compared to a windows service, or whatever) then that logic should be defined in that application only. If some logic crosses the boundary between applications (is reusable between applications) then it qualifies as domain logic and should be defined in your model. Your applications can make use of domain logic, but they should not own it.


q:
I'm having an issue with JQuery and Safari (Windows Version).  The code works on FF/IE7/Chrome but not Safari.

I have a simple <li> that has a <div> embedded in to - clicking the <li> should expose the hidden div, but not in Safari.

The HTML:

<ul>
<li>something</li>
<li>something2</li>
<li class="more">
        <a href="" class="moreFacetsLink">Click to see more options</a>
        <div class="moreFacets">bunch of text</div>
</li>
</ul>

Here is the JQuery code:

     $('.moreFacetsLink').click(function () {

        $(this).siblings('div').toggle();
     });

Any thoughts as to what may be going on here?  Again - this seems to work on all other browsers!

I'm a newbie when it comes to JQuery.

Thanks!

[A]
How accurate is your HTML pasting?
You never closed your "moreFacetsLink" anchor tag, which probably makes Safari think that it was implicitly closed, and the "bunch of text" is surrounded by an additional, HREF-less Class-less Unclosed anchor tag... evidenced by the fact that this:
```
```
$(".moreFacetsLink").click(function () {
    $(this).siblings("a").children("div").toggle();
});
```
```
... does what you want with your submitted markup.
Close off your anchor tag properly (bonus points for including the href attribute) and you should be good to go.


q:
I am trying to create a delegate protocol for a custom UIView. Here is my first attempt:

@protocol FunViewDelegate
@optional
- (void) funViewDidInitialize:(FunView *)funView;
@end

@interface FunView : UIView {
@private
}

@property(nonatomic, assign) id<FunViewDelegate> delegate;

@end

This doesn't work because the FunView interface has not been declared at the time of the FunViewDelegate declaration. I have tried adding a prototype ala C++ before the @protocol:

@interface FunView;

But this just drives the compiler nuts. How am I supposed to do this?

[A]
It would seem that you can forward declare protocols:
```
```
@protocol FunViewDelegate;

@interface FunView : UIView {
@private
    id<FunViewDelegate> delegate;
}
@property(nonatomic, assign) id<FunViewDelegate> delegate;
@end

@protocol FunViewDelegate
@optional
- (void) funViewDidInitialize:(FunView *)funView;
@end
```
```


q: I have a folder in NTFS that contains tens of thousands of files. I've deleted all files in that folder, save 1. I ran contig.exe to defragment that folder so now it's in 1 fragment only. However, the size of that folder is still 8MB in size. This implies that there's a lot of gap in the index. Why is that? If I delete that one file, the size of the index automatically goes to zero. My guess is because it gets collapsed into the MFT. Is there any way to get NTFS to truly defragment the index file by defragmenting it based on the content of the file? Any API that you're aware of? Contig.exe only defragment the physical file.

[A]
I guess this is one way in which NTFS is just like almost every other FS - none of them seem to like shrinking directories.
So you should apply a high-tech method that involves using that advanced language, "BAT" :)
collapse.bat
```
```
REM Invoke as "collapse dirname"
ren dirname dirname.old
mkdir dirname
cd dirname.old
move * ../dirname/
cd ..
rmdir dirname.old
```
```


q:
Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET?  Ideally this would also check at compile time to make sure the literal null isn't being used anywhere for it and at run-time throw ArgumentNullException.

Currently I write something like ...

if (null == arg)
  throw new ArgumentNullException("arg");

... for every argument that I expect to not be null.

On the same note, is there an opposite to Nullable<> whereby the following would fail:

NonNullable<string> s = null; // throw some kind of exception

[A]
There's nothing available at compile-time, unfortunately.
I have a bit of a
hacky solution
which I posted on my blog recently, which uses a new struct and conversions.
In .NET 4.0 with the
Code Contracts
stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
I also have an extension method in
MiscUtil
called ThrowIfNull which makes it a bit simpler.
One final point - any reason for using "
```
if (null == arg)
```
" instead of "
```
if (arg == null)
```
"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.


q:
I am writing a Clone method using reflection. How do I detect that a property is an indexed property using reflection?  For example:

public string[] Items
{
   get;
   set;
}

My method so far:

public static T Clone<T>(T from, List<string> propertiesToIgnore) where T : new()
{
    T to = new T();

    Type myType = from.GetType();

    PropertyInfo[] myProperties = myType.GetProperties();

    for (int i = 0; i < myProperties.Length; i++)
    {
        if (myProperties[i].CanWrite && !propertiesToIgnore.Contains(myProperties[i].Name))
        {
            myProperties[i].SetValue(to,myProperties[i].GetValue(from,null),null);
        }
    }

    return to;
}

[A]
```
```
if (propertyInfo.GetIndexParameters().Length > 0)
{
    // Property is an indexer
}
```
```


q:
I am looking for the VB.NET equivalent of

var strings = new string[] {"abc", "def", "ghi"};

[A]
```
```
Dim strings As String() = New String() {"abc", "def", "ghi"}
```
```


q: In a Windows program, what is the canonical way to parse the command line obtained from GetCommandLine into multiple arguments, similar to the argv array in Unix?  It seems that CommandLineToArgvW does this for a Unicode command line, but I can't find a non-Unicode equivalent.  Should I be using Unicode or not?  If not, how do I parse the command line?

[A]
```
CommandLineToArgvW()
```
is in shell32.dll.  I'd guessthat the Shell developers created the function for their own use, and it was made public either because someone decided that 3rd party devs would find it useful or because some court action made them do it.
Since the Shell developers only ever needed a Unicode version that's all they ever wrote.  It would be fairly simple to write an ANSI wrapper for the function that converts the ANSI to Unicode, calls the function and converts the Unicode results to ANSI (and if Shell32.dll ever provided an ANSI variant of this API, that's probably exactly what would do).


q:
I have an XSD file that is encoded in UTF-8, and any text editor I run it through doesn't show any character at the beginning of the file, but when I pull it up in Visual Studio's debugger, I clearly see an empty box in front of the file.

I also get the error:

Data at the root level is invalid. Line 1, position 1.

Anyone know what this is?

Update: Edited post to qualify type of file. It's an XSD file created by Microsoft's XSD creator.

[A]
It turns out, the answer is that what I'm seeing is a
Byte Order Mark
, which is a character that tells whatever is loading the document what it is encoded in.  In my case, it's encoded in utf-8, so the corresponding BOM was
```
EF BB BF
```
, as shown below.  To remove it, I opened it up in
Notepad++
and clicked on "Encode in UTF-8 without BOM", as shown below:
.
To actually see the BOM, I had to open it up in
TextPad
in Binary mode:, and conducted a
Google search for "
```
EF BB BF
```
"
.
It took me about 8 hours to find out this was what was causing it, so I thought I'd share this with everyone.
Update
: If I had read Joel Spolsky's blog post:
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
, then I might not have had this problem.


q:
When implementing the ViewModel in a Model-View-ViewModel architecture WPF application there seem to be two major choices how to make it databindable. I have seen implementations that use DependencyProperty for properties the View is going to bind against and I have seen the ViewModel implementing INotifyPropertyChanged instead.

My question is when should I prefer one over the other? Are there any performance differences? Is it really a good idea to give the ViewModel dependencies to WPF? What else do I need to consider when make the design decision?

[A]
The choice is totally based on your business logic and UI abstraction level. If you dont want a good separation then DP will work for you.
DependencyProperties will be applicable mainly at the VisualElements level so it won't be good idea if we create lot of DPs for each of our business requirements. Also there is a greater cost for DP than a INotifyPropertyChanged. When you design a WPF/Silverlight try to design UI and ViewModel totally separate so that at any point of time we can change the Layout and UI controls (Based on theme and Styles)
Refer this post also -
https://stackoverflow.com/questions/275098/what-applications-could-i-study-to-understand-datamodel-view-viewmodel
. The link has a lot of reference to Model-View-ViewModel pattern, which is very relevant to this discussion.


q:
In the Windows registry, how does CurrentControlSet differ from
ControlSet001 and ControlSet002? Which should be set when installing for all
users?

We are trying to add an environment variable for all users. Is this correct?

HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Envinronment

[A]
Yes, you only need to update the
```
CurrentControlSet
```
key...
```
ControlSet001
```
and
```
ControlSet002
```
are alternating backups of
```
CurrentControlSet
```
, you don't need to update them.
Edit: As K noted,
```
CurrentControlSet
```
is an alternating symbolic link to either
```
ControlSet001
```
or
```
ControlSet002
```
. The other key is kept as a backup for the
Load Last Known Good Configuration boot option.
Edit 2: See Microsoft KB Article 100010: What are Control Sets? What is CurrentControlSet?
Original page link broken
, see
archive.org backup page
instead.


q:
I have a simple WPF application with a menu.  I need to add menu items dynamically at runtime.  When I simply create a new menu item, and add it onto its parent MenuItem, it does not display in the menu, regardless of if UpdateLayout is called.

What must happen to allow a menu to have additional items dynamically added at runtime?

Note: the following code doesn't work.

            MenuItem mi = new MenuItem();
            mi.Header = "Item to add";
            mi.Visibility = Visibility.Visible;
            //addTest is a menuitem that exists in the forms defined menu
            addTest.Items.Add(mi);
            addTest.UpdateLayout();

At the moment, the default menu items are defined in the xaml file.  I want to add additional menu items onto this menu and its existing menu items.  However, as stated, the above code does nothing.

[A]
```
```
//Add to main menu
MenuItem newMenuItem1 = new MenuItem();
newMenuItem1.Header = "Test 123";
this.MainMenu.Items.Add(newMenuItem1);

//Add to a sub item
MenuItem newMenuItem2 = new MenuItem();
MenuItem newExistMenuItem = (MenuItem)this.MainMenu.Items[0];
newMenuItem2.Header = "Test 456";
newExistMenuItem.Items.Add(newMenuItem2);
```
```


q: I moved a bunch of projects to Solution Folders to chop up our list of projects into manageable folders, now each of the folders projects are not in alphabetical order. This only occurs on machines other than my own. Any ideas how to alleviate this?

[A]
See the following bug information on MS Connect:
https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=312252&wa=wsignin1.0
To summarize:
"
The order they show up in solution explorer is the order in which they were written to the solution file.   However, if the folder is collapsed on startup it will be sorted when you expand it.
"
Therefore, the fast solution would be to hand edit the solution file and put the projects in the order you wish.


q:
I am currently looking at the "unload" event of a window to try to determine how the "unload" event was triggered, but am having little success. Is there a way to determine how the javascript event was triggered?

Page Refresh

Back Button (or navigate away from the page)

Closing the Browser

Essentially I need to execute some code only when the browser window is being closed, not refreshed or navigated away from.

Purpose: When a customer does an update of our software, the update will redirect their first Internet request to an offer page. There is a button for a "Do Not Bother" option, but some users will simply close their browser. Upon closing the browser, I need to duplicate the "Do Not Bother" functionality so the user no longer gets redirected to the offer page. Simply attaching to the "unload" event will not work due to the different ways of leaving a page.

[A]
No, and if there was it would be browser dependent.
What kind of code are you trying to run when the user closes the page?
Is it to logout the user?
Then the user would not be logged out if the browser crashes or the network connection breaks (and probably not if the computer goes to sleep/hibernation mode).
If it is for logout-purposes you should probably use a timestamp variable at the server that gets updated with every request (or use a ajax-ping), and logout the user if it hasn't been seen for a specified time.
Update: Found
this answer
here at stackoverflow.


q:
I want a query that returns a list of all the (user) stored procedures in a database by name, with the number of lines of code for each one.

i.e.

sp_name     lines_of_code
--------    -------------
DoStuff1    120
DoStuff2    50
DoStuff3    30

Any ideas how to do this?

[A]
```
```
select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc
from
(
    select o.name as sp_name,
    (len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code,
    case when o.xtype = 'P' then 'Stored Procedure'
    when o.xtype in ('FN', 'IF', 'TF') then 'Function'
    end as type_desc
    from sysobjects o
    inner join syscomments c
    on c.id = o.id
    where o.xtype in ('P', 'FN', 'IF', 'TF')
    and o.category = 0
    and o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams')
) t
group by t.sp_name, t.type_desc
order by 1
```
```
Edited so it should also now work in SQL Server 2000- 2008 and to exclude Database Diagram-related sprocs and funcs (which appear like user created objects).


q:
I want to store a very large amount of vector data on a server and only poll the parts I need at a given point...

This shouldn't be a problem.

Is there any way to take a vector file like an svg file and import it into a database? I could always write an svg parser to import it into my database, but is there any standard way of doing this or storing vector data in a database ?

[A]
I don't think you can call it a standard, but here is an interesting link to an academic paper:
A Design and Implementation of Spatial Database Based on XML-SVG
Abstract:
SVG, which stands for Scalable Vector Graphics, is an open standard in text that makes it possible to represent graphic information in compact, portable form and mostly faces on publishing the spatial vector graphics in network environment. In practice, it's impossible to avoid a great capacity of spatial data processing, which had made SVG document is too big to be implemented during publishing on the Internet.
It is slowed down the executing speed of the system on client side and is weaken its advantages and superiority. Such SVG database has been proposed as the solution for managing all the graphics and its attributes in a Web server. SVG document is mapped into SVG database that works as a buffer in the server. The issuance efficiency has been improved to a great extent.


q: Using strictly SQL (no PHP or anything else), is it possible to create a table and insert default data into that table only if that table doesn't exist?

[A]
Use the CREATE TABLE ... SELECT format:
```
create table if not exists tablename as
select * from defaultdata;
```


q:
How can I tell the preprocessor not to replace a specific macro?

The specific problem is the following: Windows header files define the GetMessage macro.

My C++ header files with my API have a GetMessage method. I do not want to rename my method. But when using the API on Windows, including windows.h replaces my GetMessage method call with GetMessageA.

[A]
have you tried just doing an
```
#undef GetMessage
```
or even
```
#ifdef GetMessage
#undef GetMessage
#endif
```
and then calling the windows GetMessageA or GetMessageW directly, whichever is appropriate.
you should know if you are using char* for wchar_t8..
(thanks don.neufeld)
Brian also says that
Jus some useful info, you can also use the #pragma push_macro/pop_macro to push and pop macro definitions. This is great if you want to override a macro definition in a block of code:
```
```
#pragma push_macro("GetMessage")
#undef GetMessage

// Your GetMessage usage/definition here

#pragma pop_macro("GetMessage")
```
```
I suspect this is an MS specific feature though, so keep that in mind.


q:
When you assign a date to a named SQL parameter Hibernate automatically converts it to GMT time. How do you make it use the current server timezone for all dates?

Lets say you have a query:

Query q = session.createQuery("from Table where date_field < :now");
q.setDate("now", new java.util.Date());

"now" will be set to GMT time, while "new Date()" gets your current server time.

Thanks.

[A]
Hibernate is ignorant of timezones. Any timezone conversion should be done prior to executing the query.
E.g., if your database server is set to CST, but the user is on EST, you'll need to add 1 hour to any timestamps which are the input to a query.


q:
I am trying to design a location lookup in which the user can specify a location to any desired level of accuracy. eg. one of Country, State, City, Borough etc,

I have a used a common location table, which will then be used in a lookup with the table name selected dynamically, but was wondering if there is a feasible alternative way to do this.

alt text http://img386.imageshack.us/img386/3842/locationschemadh6.png

Edit The hierarchical table looks like the way to go. Thanks for the tip.

[A]
You might consider something like:
```
```
locations
  id int
  parentId int
  name varchar(45)
```
```
From this perspective you could load any type of location with any level depth.


q:
I embedded a swf in my html page, but I would like it to swap to another swf when I clicked on a button in html. I used swfobject.js to embed the swf, and I use prototype to write the javascript. I thought I can just do this

$('movie').value = 'swf/bhts.swf';
alert($('movie').value);

the value did change to swf/bhts.swf, but it is still playing the original swf file...
this is the code I use to embed swf

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="530" height="298" id="flashcontent">
<param id="movie" name="movie" value="swf/trailer.swf" />
</object>

thanks.

[A]
Using swfObject:
```
```
<div id='flashContent'>
</div>

<script type='text/javascript'>
    // Setup your initial flash
    var so = new SwfObject(.....);
    so.write ('flashContent');

    // Some event handler
    someElement.onclick = function ()
    {
         // Load up the new SWF
         so = new swfObject(....);
         so.write('flashContent');
    }
</script>
```
```


q:
I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.

I have an application that is pulling email via POP3.  I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email.  I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc.  I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.

Hope this makes some amount of sense and that someone can shed some light on this.  In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.

[A]
Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead.
This great Codeproject article by Peter Huber SG, entitled
'POP3 Email Client with full MIME Support (.NET 2.0)'
will give you an understanding of how MIME processing can be implemented, and the related RFC specification articles.
You can use the Codeproject article as a start for writing your own parser, or appraise a library like
SharpMimeTools
, which is an open source library for parsing and decoding MIME emails.
http://anmar.eu.org/projects/sharpmimetools/
Hope this helps!


q:
Suppose I have a page that I am writing a javascript plugin for on the domain first.com.  The javascript plugin injects an iframe pointing to a login page (of domain second.com) into the first.com page and displays it as a popup so that the user can login.

Is there anyway for me to hide/close the iframe after the user logs in with it?  I can inject any javascript necessary into the first.com page and I control both the client and server side code on the login page within the iframe.

The main issue is that the iframe cannot access it's parent window to hide itself and the parent window cannot see any changes made in the contents of the iframe because of the same origin policy.  Is there anyway around this or should I just lose the iframe idea and instead open a new window?

[A]
I think the issue you're running into is the browser stopping the cross-domain communication from happening.  There is a way to
sign your javascript
but it is pretty much breaking the browser security model and isn't suggested unless absolutely necessary.
Is there any way that the login form is based on URL submition?  You could create a simple sign in form and use AJAX to get your response back to ensure a successful login.  This solution depends on having a RESTful login and again, I'm not sure about the implementation of your second.com.
If you're wondering about how to use the ajax to submit a form, I'd check
this
out (it is in jQuery but it applies to just about any framework.)  View the source on that and see if that could work in your situation.


q: How can I take full advantage of 64-bit architecture in my .NET 2.0 Web Applications and Console/Forms Applications?

[A]
I think there is not too much you can optimize in your managed .NET code regarding 32bit vs. 64bit architectures. This is because most of the differences and optimizatinons are most likely already implemented by the underlying VM. As mentioned in
Programming for the 64 bit platform
, the 64bit VM may perform better on larger data types (as
```
long
```
stored in one register).


q:
Have you ever had alternating background colors in a Jasper report and then exported it to Excel?  The Excel export seems to ignore the alternating color.

I've got a Jasper report where the rows alternating background color using the procedure referenced HERE.  When I preview it using the viewer or export to PDF it works -- but not when I export to Excel.  I've tried using JRXlsExporter and JExcelApiExporter both to no avail.

I think it might be a side-effect of how you have to make alternating row colors in Jasper, which I despise to begin with, but have found no other way.

Thanks in advance!

[A]
Did you try the idea suggested in the
comment
of the very procedure you are referring to ?
First how to create new report style with condition:
Recent releases of JasperReports include report styles, which make this a bit easier - you no longer have to create the rectangle.
I use iReport to create my styles - there is a “styles” pane that by default is docked with the “Library” pane. If you make it visible you can create a new style in the styles library. In the screen that pops up give the style a name (say “EvenOddRowStyle” and press “Add” under “Style Conditions”. Use one of the expressions that Brian gave and press Apply. and in the “Common” section press the “…” button next to “Backcolor” and pick the background color you want. Finally, when done with your report apply that style to all the fields in the rows you want to highlight. Just drag the style from the styles pane onto the field.
Then how to define a style which will be applied when exported to Excel:
defining a new style with the condition expression:
```
```
Boolean.valueOf( $V{PAGE_COUNT}.intValue() % 2 == 0 )
```
```
on it
without using a rectangle and a print when expression on it
!


q:
We have an advanced webpage (ASP.NET, C#), and a application which needs to be installed on the client computer in order to utilize the webpage to its fullest. The application is a tray app, and has primarily two tasks. Detect when certain events happen on the webserver (for instance invited to a meeting, or notify of an upcoming meeting). The other task the trayapp has is to use a custom protocol (trayapp://) to perform some ajax calls back to the server.

One problem we have is how to determine if the application is installed on the local machine or not. Now the user has to tick a checkbox to inform the website that the application is installed, and that it's safe to call the trayapp:// url calls.

Is there any way, for instance through a JavaScript or similar to detect if our application is installed on the local machine?

The check needs to work for IE, FF and Opera browsers.

[A]
When installing your client-side app you could modify the browser configuration to include another request header in HTTP requests and then have the server code look for that header, for example as a supported mime type using the following registry key (for Internet explorer)
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\
                                                      Internet Settings\Accepted Documents
```
```
I am not sure if Opera and FF use this same key, but they likely have similar configuration options, but this should at least get you on the right track.


q:
Someone posted a great little function here the other day that separated the full path of a file into several parts that looked like this:

Function BreakDown(Full As String, FName As String, PName As String, Ext As String) As Integer
 If Full = "" Then
 BreakDown = False
 Exit Function
 End If
 If InStr(Full, "\") Then
 FName = Full
 PName = ""
 Sloc% = InStr(FName, "\")
 Do While Sloc% <> 0
   PName = PName + Left$(FName, Sloc%)
   FName = Mid$(FName, Sloc% + 1)
   Sloc% = InStr(FName, "\")
 Loop
 Else
 PName = ""
 FName = Full
 End If
Dot% = InStr(Full, ".")
If Dot% <> 0 Then
 Ext = Mid$(Full, Dot%)
Else
 Ext = ""
End If
BreakDown = True

End Function

However if the line continues past that point it counts it as part of the extension, is there anyway to make this only count to 3 characters after the last period in a string?

[A]
If you just have blank characters then just add this as the first line
```
```
Full = Trim(Full)
```
```
If you have other characters then
Change:
```
```
Ext = Mid$(Full, Dot%)
```
```
to:
```
```
Ext = Mid$(Full, Dot%, 3)
```
```


q: I have set of names and addresses that have been entered into and excel spreadsheet, but the problem is that the many people that entered the addresses entered them in many different non-standard formats.  I want to scrub the addresses before transferring all of of them to my database.  Looking around, all I really found in the way of address scrubbers(parsers or formatters) is the one that is put out by Semaphore.  For my purposes, I don't really need all of that and I don't want to pay for the licensing fees for the software.  Is there anything out there that is Free and/or Open Source that will do the scrubbing for me?

[A]
Most of the software that I've worked with to do this is very expensive (or to put it another way, marketing departments are naive and have huge budgets).
This sort of work is a precursor to Geo-coding.  This
linked Wiki article
includes a list of Geocoding software, some of which is free.  If you're lucky, some of the free ones may include address standardizing routines.
If you find a good one, let me know.


q:
I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file.  However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it.

What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a filename.nnn output file, then read up-to the next line-break and write that, then close the output file, etc.  Obviously the last output file just copies to the end of the input file.

Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break?

I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)

[A]
Check out
```
os.stat()
```
for file size and
```
file.readlines([sizehint])
```
. Those two functions should be all you need for the reading part, and hopefully you know how to do the writing :)


q: What is the regex for a alpha numeric word, at least 6 characters long (but at most 50).

[A]
With PCRE regex you could do this:
```
```
/[a-zA-Z0-9]{6,50}/
```
```
It would be very hard to do in regex without the min/max quantifiers so hopefully your language supports them.


q:
I am creating my textbox with these options. I can Copy / Cut / Paste / Undo, but when I hit Select All it doesn't select all. I can right click and click Select All but CTRL + A doesn't do anything. Why?

wnd = CreateWindow("EDIT", 0,
    WS_CHILD | WS_VISIBLE | ES_MULTILINE | WS_HSCROLL | WS_VSCROLL | ES_AUTOHSCROLL | ES_AUTOVSCROLL,
    x, y, w, h,
    parentWnd,
    NULL, NULL, NULL);

[A]
You need to capture that keystroke and do the select all yourself.
Here is some C# code for use with a RichTextBox:
```
```
protected override void OnKeyDown(KeyEventArgs e)
    {
        // Ctrl-A does a Select All in the editor window
        if (e.Control && (e.KeyCode == Keys.A))
        {
            this.SelectAll();
            e.Handled = true;
        }
    }
```
```
Sorry, I don't have Win32 code for you.


q:
Is there a way to recursively add all "non added" files to SVN?

I want to do something like

svn add trunk/

to add all new files, without getting:

svn: warning: 'trunk' is already under version control

If this is not possible, is there a way to get a list of all files that are not under version control in the directory?

Note that I am only interested in using the command line.

[A]
Use the --force option.
Example:
```
```
svn add * --force
```
```


q:
I have a file with several thousand rows and several columns separated with tabs What I'd like to do is loop through each individually, Drop the columns into an array so that I can place them in another application individually, then move onto the next line.  Unfortunately I got about as far as this:

Open mytextfile.txt For Input As #FileHandle
 Do While Not EOF(FileHandle)
 Line Input #FileHandle, IndividualLine
 StringToBreakup = IndividualLine
Loop

So how would I go about breaking individual line up into an array

[A]
Use the split command
```
```
Dim StringArray as Variant

Open mytextfile.txt For Input As #FileHandle
 Do While Not EOF(FileHandle)
 Line Input #FileHandle, IndividualLine
 StringToBreakup = IndividualLine

 StringArray = Split(StringToBreakup, CHR(9))

 Process array here...

Loop
```
```


q:
Has anyone found any documentation or research about what data is transfered to Google Analytics when it's added to a site. The main thing I'm wondering about is post data, but the details of exactly what is sent would be useful.

I'm considering implementing it on a sites that have a lot of private data on them. I'm wondering what data Google will capture, if any. (The sites are login only.) I'm needing proof so I can provided to the users.

[A]
The official information can be found
here
The visitor tracking information that you can get in the Google Analytics reports depends on Javascript code that you include in your website pages, referred to as the Google Analytics Tracking Code (GATC). Initial releases of the GATC used a Javascript file called urchin.js.
That script is then discussed in detail in
that blog
, and Google Analytics Help group can also provide
some details
.
a More detailed list of what that javascript collect is
listed here
.


q:
For example, will the first piece of code perform a full search twice, or is it smart enough to cache results if no DOM changes have occurred?

if ($("#navbar .heading").text() > "") {
  $("#navbar .heading").hide();
}

and

var $heading = $("#navbar .heading");

if ($heading.text() > "") {
  $heading.hide();
}

If the selector is more complex I can imagine it's a non-trivial hit.

[A]
i don't believe jquery does any caching of selectors, instead relying on xpath/javascript underneath to handle that. that being said, there are a number of optimizations you can utilize in your selectors. here are a few articles that cover some basics:
Optimizing jQuery selector performance
Performance analysis of selectors


q: Is it possible to programmatically either via the win32API (python) or via a command line option set the processor affinity for a process?

[A]
In C/C++ you can use
SetThreadIdealProcessor()
.  I have no idea if this is accessible in python.
```
```
DWORD processorId = 0;
SetThreadIdealProcessor(GetCurrentThread(),processorId);
```
```


q: What is the simplest way in VB6 to loop through all the files in a specified folder directory and get their names?

[A]
```
```
sFilename = Dir(sFoldername)

Do While sFilename > ""

  debug.print sFilename
  sFilename = Dir()

Loop
```
```


q:
I've got a stock standard ASP.NET website. Anyone can read/view any page (except the admin section) but when someone wants to contribute, they need to be logged in. Just like most contribution sites out there.

So, if i have my OWN login control or username/password/submit input fields, why would i want to have forms auth turned on instead of just none? what does forms auth give me, which having my own code that check my database for a user/pass and my own two input fields + a submit button, does the job perfectly?

(NOTE: i really dislike the asp.net membership stuff that creates all those tables and usp's in the database, so please don't suggest I use that).

Like, with my code, when i authenticate a user (with my own database code), i manually create my own identity, etc.

is all this required? what is the main purpose of this?

cheers!

[A]
You can authorize your users how ever you want.  FormAuthentication is used to set the session identity and the authentication cookie that allows users to stay logged in until they logout or the session expires.  You don't need to use the membership providers to use FormsAuthentication.  It sounds like you are just replicating this functionality.
```
```
...do your authentication against your DB or Active Directory

if (Request.QueryString["ReturnUrl"] != null)
{
    FormsAuthentication.RedirectFromLoginPage(userName.Text, false);
}
else
{
    FormsAuthentication.SetAuthCookie(userName.Text, false);
}
```
```
Then you need to set up to use it in the web.config
```
```
<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx"
           protection="All"
           timeout="30"
           name="my-auth-cookie"
           path="/"
           requireSSL="false"
           slidingExpiration="true"
           defaultUrl="default.aspx" />
  </authentication>
</system.web>
```
```
You get all the benefits of doing your own authorization and not having to implement the cookie infrastructure.  Note, since your web site only needs to authorize when editing, you'll need to set the permissions that allow everyone to read all pages and implement your own logic to redirect them to the login page when they want to edit.
More information
here
.


q:
I am using the dojo.io.iframe.send method to send a file to my server. I want to provide a way that the user can cancel the send once it is in progress, in case it is taking too long or the user realizes she sent the wrong file.

I can't figure a way to do this. I could use a timeout to terminate the send if it is taking a long time (that is, the server does not respond quickly), but that is not what I want. I want to terminate any time the user makes a gesture (such as clicking a "Cancel" button.

Thanks!

[A]
For security reasons JavaScript cannot even access the file you are sending up. All file uploads are done using a form and handled by the browser directly. To my best knowledge there is no direct interface to monitor the progress of upload, nor the way to affect it (e.g., cancel it).
Navigating away may help, but it is still up to the browser to interrupt the transfer or not — there is no specification for that.
To sum it up: not possible to do it reliable in JavaScript in the portable fashion. That means Dojo does not provide this functionality.


q:
I have to include Groovy classes into existing Java apps, and include Groovy into Ant's build.xml file.

What is the best way to configure Ant's build.xml for it?

Update: Are there more specifics in combining Java and Groovy compilations? Sequence of tasks?

[A]
To use Groovy in your ant script, you basically have to
declare the Groovy ant task
:
```
```
<project name="groovy-build" default="listSourceFiles">

<taskdef name="groovy"
     classname="org.codehaus.groovy.ant.Groovy"/>
<groovy>
    ant.... // some ant groovy directives
</groovy>
</target>
</project>
```
```
However, you have to be careful, in your ant.xml, to refer to fileset within your
current target
.


q:
I have a nested function to show/hide paragraphs news-ticker-style.

The problem is that when the loop starts over (line 4), the opacity effects stop working correctly so the paragraphs appear abruptly.

Any jquery masters know about this? Am I making this too hard?

$('#special-ticker p').hide();
var a=0;
function outer() {
    function inner() {
        if(a===$('#special-ticker p').length) { a = 0; }
        $('#special-ticker p').
        eq(a).
        fadeIn(800, function(){
            $(this).animate({opacity:100},10000,null,function(){
                $(this).hide(800,function(){
                    a++;
                    outer();
                });
            });
        });
    }
    return inner();
}
$(function(){
    outer();
});

[A]
the problem is line 9:
```
```
$(this).animate({opacity:100},10000,null,function(){
//...
```
```
opacity should be "1" (opacity is a value between 0 and 1)
```
```
$(this).animate({ opacity : 1 }, 10000, null, function() {
```
```


q:
I have a Canvas in a Flex application which has items inside it that cover only about 50% of the area of the main canvas.

i want the canvas to respond to rollOver events for the full area, and not just the area that is covered by the items inside.

I have been setting the following attributes to achieve this :

<mx:Canvas backgroundColor="white"
backgroundAlpha=".01"
rollOver="rollOver(event)">...

This causes the entire canvas to respond to rollOver events. It works great - I'm just not happy with it and figure there must be a better way to achieve it.

Is there a way to force mouse events to act on the entire area of a UIComponent?

[A]
You could do this:
```
```
import flash.event.MouseEvent;
...
canvas.addEventListener(MouseEvent.ROLL_OVER,function(event:MouseEvent):void {
    ...
});
```
```
where "canvas" is the ID of the canvas in your mxml.


q:
i did this in msvc 2005.

typedef void (*cleanup_t)();

void func(cleanup_t clean)
{
    cleanup_t();
}

Why does this compile? and not give me a warning? ok, it gave me a unreferenced formal parameter warning but originally i did this when clean was in a class no there was no unreferenced formal parameter when this code gave me problems.

What is cleanup_t(); really doing and what is the point? now for laughs i tried int() and that worked also.

[A]
I think it's an expression that evaluates to a default value for a cleanup_t type.  In other words, an expression that returns a NULL pointer to a function that returns void.
In C/C++, expressions with no side effects (which this is - I think) are valid statements, just like you can have a statement like:
```
```
1 + 2;
```
```
That's not a syntax error, but some compilers might give a warning.  They don't often give a warning for side-effect-less expressions that return NULL values or are simply variable names because that type of expression is often used in macros for debugging purposes (like the assert() macro).
You can think of it as calling the default constructor for the
```
cleanup_t
```
type.  Having this default constructor-like syntax for built-in types (or typedef's of them) was added to C++ so that templates could set items of the type passed in as a template parameter to default values while still allowing the template type parameter to be a non-user defined type. There might other reasons, but I believe that to be one of them.
Something like:
```
```
template <class T>
class foo
{
    T myT;

    public:

    foo() {
        myT = T();
    };
};

typedef void (*cleanup_t)();

class bar
{
};

int not_quite_a_cleanup_t_func()
{
    return 1;
}

int main()
{
    foo<int> intFoo;
    foo<cleanup_t> cleanup_t_foo;
    foo<bar> barFoo;

    // here I'm going to harp on one of the things I don't like about C++:
    //
    //  That so many things that look like function calls are not or that
    //  the parens cause subtle behavior changes.
    //
    //  I believe this is the reason this question was posted to
    //  stackoverflow, so it's not too far off topic.
    //
    //  Many of these things exist because of backwards compatibility with C or
    //  because they wanted to fit in new features without adding keywords or
    //  new reserved tokens or making the parser even more complex than it already
    //  is.  So there are probably good rationales for them.
    //
    //  But I find it confusing more often than not, and the fact that there
    //  might be a rationale for it doesn't mean I have to like it...

    cleanup_t cleanup1();    // declares a function named cleanup1 that returns a cleanup_t

    cleanup_t cleanup2 = cleanup_t();   // cleanup2 is a variable of type cleanup_t that
                                        //  is default initialized

    cleanup_t* cleanup3 = new cleanup_t;    // cleanup3 is a pointer to type cleanup_t that
                                            //  is initialized to point to memory that is
                                            //  *not* initialized

    cleanup_t* cleanup4 = new cleanup_t();  // cleanup4 is a pointer to type cleanup_t that
                                            //  is initialized to point to memory that *is*
                                            //  initialized (using default intialization)

    cleanup2 = cleanup_t( not_quite_a_cleanup_t_func);  // explicit type conversion using functional notation

    cleanup_t();    // the OP's problem
    cleanup2();     // call the function pointed to by cleanup2
    (*cleanup2)();  // same thing

    class cleanup_class
    {
        cleanup_t cleanup5;

    public:
        cleanup_class() :
            cleanup5() // class member default initialization
        { };
    };
}
```
```


q:
while exploring jQuery I came up with the following weird script. I don't see myself doing this really however concatenating strings to achieve a variable name is not unusual in JavaScript.

Any feedback welcome.

...
    <script type="text/javascript">
        var a = 'y';
        $(document).ready(function() {
            $('p[id^=' + $('p[id=x]').html() + a + "]").css('color','blue');
        });
    </script>
...

<p id="x">2a</p>
<p id="2ay_">mytext</p>

[A]
Short answer is no, there aren't side-effects.  Your example is quirky, but as you said you were just exploring to see what you could do.  I have used string concatenation and function value returns inside jQuery selectors before, it can be a useful technique for managing sets of related elements which reside in different parts of the DOM.
I admit I haven't used
```
jQuery.html()
```
inside a selector, but there isn't any inherent reason why that's "bad".  I just can't think of a situation where that'd be strictly necessary.  It does make the code rather... unusual, and hence more difficult to understand and maintain.
If you actually find a use for this in production code, please let us know.  I'd be fascinated to see what it is. :)


q: Having a relative path, how do I turn it into an absolute one from the location where the elisp file that I'm loading is. That is, I have an elisp file that I'm loading, it has an relative path and I need an absolute one.

[A]
You can use the
```
expand-file-name
```
function to convert a relative filename or path into an absolute filename/path.  Look
here
for additional information.


q:
What exactly are the Python scoping rules?

If I have some code:

code1
class Foo:
   code2
   def spam.....
      code3
      for code4..:
       code5
       x()

Where is x found?  Some possible choices include the list below:

In the enclosing source file

In the class namespace

In the function definition

In the for loop index variable

Inside the for loop

Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?

There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.

[A]
Python resolves your variables with -- generally -- three namespaces available.
At any time during execution, there
  are at least three nested scopes whose
  namespaces are directly accessible:
  the innermost scope, which is searched
  first, contains the local names; the
  namespaces of any enclosing functions,
  which are searched starting with the
  nearest enclosing scope; the middle
  scope, searched next, contains the
  current module's global names; and the
  outermost scope (searched last) is the
  namespace containing built-in names.
There are two functions:
```
globals
```
and
```
locals
```
which show you the contents two of these namespaces.
Namespaces are created by packages, modules, classes, object construction and functions.  There aren't any other flavors of namespaces.
In this case, the call to a function named
```
x
```
has to be resolved in the local name space or the global namespace.
Local in this case, is the body of the method function
```
Foo.spam
```
.
Global is -- well -- global.
The rule is to search the nested local spaces created by method functions (and nested function definitions), then search global.  That's it.
There are no other scopes.  The
```
for
```
statement (and other compound statements like
```
if
```
and
```
try
```
) don't create new nested scopes.  Only definitions (packages, modules, functions, classes and object instances.)
Inside a class definition, the names are part of the class namespace.
```
code2
```
, for instance, must be qualified by the class name.  Generally
```
Foo.code2
```
.  However,
```
self.code2
```
will also work because Python objects look at the containing class as a fall-back.
An object (an instance of a class) has instance variables.  These names are in the object's namespace.  They must be qualified by the object.  (
```
variable.instance
```
.)
From within a class method, you have locals and globals.  You say
```
self.variable
```
to pick the instance as the namespace.  You'll note that
```
self
```
is an argument to every class member function, making it part of the local namespace.
See
Python Scope Rules
,
Python Scope
,
Variable Scope
.


q: Is the jQuery intellisense plugin available for Visual Studio now?

[A]
Yes, it is.
Rich Intellisense for JQuery
.


q:
I've been seeing so much recently about functional programming and Clojure looks particularly interesting. While I 'understand' the basic description of what it is, I can't figure out how I would use it on a day to day basis as a web developer, if I can at all. A lot of what I have read focuses on the maths side of functional programming rather then typical programming situations found in regular OO.

Have I got the wrong end of the stick? Is functional programming totally un-related to web development? If not, are there any examples of it being used 'for the web'?

[A]
A few examples off the top of my head:
Yahoo! Store is powered by Lisp (originally named
Viaweb
prior to acquisition)
Reddit
was fully prototyped in Lisp, although they
switched to Python
in 2005
Hacker News
is written entirely in Arc (a Lisp dialect)


q:
I'd like to add a custom title to one of the predefined UITabBarItems. Whenever I select the particular instance I like in Interface Builder -- if I modify the the title it gets preset back to a 'custom' identifier. Ideally I'd like the book icon from the 'Bookmarks' identifier with my own custom title.

Is this level of customization currently supported by the SDK? Am I going to have to ultimately screen scrape the image and apply it as a custom image?

Thanks for any insight or documentation which points me in the right direction.

[A]
Unfortunately, the only types of UITabBarItems are those supplied and described entirely by the OS (ie, it assigns them icons and titles), and those described entirely by the app, as you've discovered. By far the simplest solution is to pull the icon out of somewhere else and use it with
```
-initWithTitle:image:tag
```
.
http://img369.imageshack.us/img369/8388/openbookwp4.png


q:
I have seen a lot of ob_get_clean() the last while. Typically I have done $test .= 'test'

I'm wondering if one is faster and/or better than the other.

Here is the code using ob_get_clean():

ob_start();

foreach($items as $item) {
    echo '<div>' . $item . '</div>';
}

$test = ob_get_clean();

Here is the code using $test .= 'test':

$test = '';

foreach($items as $item) {
    $test .= '<div>' . $item . '</div>';
}

Which is better?

[A]
The results are the same, and I'd imagine the performance differences are negligible if any. Basically, a matter of personal style preference. I would go with concatenation myself - I use output buffering only when concatenation is not an option.
Also, instead of running both
```
ob_get_contents()
```
and
```
ob_clean()
```
simply run
```
ob_get_clean()
```
which performs both at once.


q:
I stumbled upon this javascript obfuscator called Squash, I want to use it on my ExtJS project to obfuscate my javascript files. I've tried it and the result are totally obfuscated codes. But it seems that I have to obfuscate the ExtJS library too because I got warnings that it couldn't find functions such as Ext.onReady(), Ext.form.FormPanel(), etc.

I just want to ask if any of you guys have successfully used Squash + ExtJS in a project and how did you manage to make it work.

[A]
Typical rtfm: The
```
@Public
```
annotation on the
```
setDocumentTitle
```
function prevents the function name from being obfuscated so that it can be accessed from unobfuscated code.


q: How can I delete all the tables in a web page? The tables don't have any ids associated with them.

[A]
If you're using jQuery it is pretty easy ...
```
```
$(document).ready(function() {
  $("table").remove();
});
```
```
not sure how's you do it in other libraries.
if you're not using a js library, you should be.


q:
I wanted to grep for java process and then find the max heap memory used.
I tried this

def ex =['sh','-c','ps -aef | grep Xmx']
String str =  ex.execute().text

while str has something like java -Xmx1024M /kv/classes/bebo/ -Xms512M
How do I extract the value 1024M? I was planning to user java regex but thought someone might know a cool way in groovy.

[A]
In Java:
```
```
String ResultString = null;
Pattern regex = Pattern.compile("-Xmx(\\d+M)");
Matcher regexMatcher = regex.matcher(str);
if (regexMatcher.find()) {
    ResultString = regexMatcher.group(1);
}
```
```


q: VB 6: How can I execute a .bat file but wait until its done running before moving on?

[A]
You will need to use Win32 API calls to
ShellExecuteEx
and WaitForSingleObject on the process handle returned from ShellExecuteEx in the SHELLEXECUTEINFO structure.  This is old code which I've pulled out of a project. It was working 100% but I may not have included all dependencies. You should be able to edit to your requirements:
```
```
Type SHELLEXECUTEINFO
                cbSize As Long
                fMask As Long
                hwnd As Long
                lpVerb As String
                lpFile As String
                lpParameters As String
                lpDirectory As String
                nShow As Long
                hInstApp As Long
                '  Optional fields'
                lpIDList As Long
                lpClass As String
                hkeyClass As Long
                dwHotKey As Long
                hIcon As Long
                hProcess As Long
        End Type

        Public Declare Function ShellExecuteEx Lib "shell32.dll"
            (lpExecInfo As SHELLEXECUTEINFO) As Long

        Public Declare Function apiShellExecute Lib "shell32.dll" _
            Alias "ShellExecuteA" _
            (ByVal hwnd As Long, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As Long) _
                As Long

        Declare Function WaitForSingleObject Lib "kernel32"
             (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long

        Public Const SEE_MASK_NOCLOSEPROCESS As Long = &H40
        Public Const SEE_MASK_FLAG_DDEWAIT As Long = &H100

        '***App Window Constants***'
        Public Const WIN_NORMAL = 1         'Open Normal'
        Public Const WIN_MAX = 2            'Open Maximized'
        Public Const WIN_MIN = 3            'Open Minimized'

        '***Error Codes***'
        Private Const ERROR_SUCCESS = 32&
        Private Const ERROR_NO_ASSOC = 31&
        Private Const ERROR_OUT_OF_MEM = 0&
        Private Const ERROR_FILE_NOT_FOUND = 2&
        Private Const ERROR_PATH_NOT_FOUND = 3&
        Private Const ERROR_BAD_FORMAT = 11&

' Returns 'True' if file was opened ...'
Public Function fHandleFile(ByVal stFile As String, _
                            ByVal lShowHow As Long, _
                            ByRef stRet As String, _
                            Optional ByVal bWaitForClose As Boolean = False) As Boolean
On Error GoTo err_Handler
    Dim lRet As Long
    Dim ret As Long
    Dim lngProcessHandle As Long
    Dim varTaskID As Variant
    Dim shInfo As SHELLEXECUTEINFO
    Dim retval As Long

    'First try ShellExecute'
    With shInfo
        .cbSize = LenB(shInfo)
        .lpFile = stFile
        .nShow = lShowHow
        If bWaitForClose Then
            .fMask = SEE_MASK_FLAG_DDEWAIT + SEE_MASK_NOCLOSEPROCESS
        End If
        .lpVerb = "open"
    End With

    Call ShellExecuteEx(shInfo)
    lRet = shInfo.hInstApp

    If lRet > ERROR_SUCCESS And bWaitForClose = True Then
        lngProcessHandle = shInfo.hProcess

        Do
            retval = WaitForSingleObject(lngProcessHandle, 0)
            DoEvents
        Loop Until retval <> 258
        ret = CloseHandle(lngProcessHandle)
    End If

    fHandleFile = (lRet > 0)

exit_handler:
    Exit Function

err_Handler:
    RaiseError Err.Number, Err.Source, Err.Description
End Function
```
```


q:
I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the standard, even as documented on the MSDN site.

My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?

Call the add method differently based on the value of the user agent?

Wrap the select object in a class that provides the proper method signature?

Use a javascript library which does this for you (specify which library)?

[A]
Adding a new Option type works at least IE6 and up
```
```
function addOption(selectID, display, value)
{
  var obj = document.getElementById(selectID);
  obj.options[obj.options.length] = new Option(display, value);
}
```
```
Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully.  IE4 failed :(


q:
Is there any real reason not to make a member function virtual in C++?  Of course, there's always the performance argument, but that doesn't seem to stick in most situations since the overhead of virtual functions is fairly low.

On the other hand, I've been bitten a couple of times with forgetting to make a function virtual that should be virtual.  And that seems to be a bigger argument than the performance one.  So is there any reason not to make member functions virtual by default?

[A]
One way to read your questions is "Why doesn't C++ make every function virtual by default, unless the programmer overrides that default."  Without consulting my copy of "Design and Evolution of C++": this would add extra storage to every class unless every member function is made non-virtual.  Seems to me this would have required more effort in the compiler implementation, and slowed down the adoption of C++ by providing fodder to the performance obsessed (I count myself in that group.)
Another way to read your questions is "Why do C++ programmers do not make every function virtual unless they have very good reasons not to?"  The performance excuse is probably the reason.  Depending on your application and domain, this might be a good reason or not.  For example, part of my team works in market data ticker plants.  At 100,000+ messages/second on a single stream, the virtual function overhead would be unacceptable.  Other parts of my team work in complex trading infrastructure.  Making most functions virtual is probably a good idea in that context, as the extra flexibility beats the micro-optimization.


q:
I have an idea for a web-based service. The implementation is very complex. There will be very few users, and the traffice will be fairly low, but the server-side code could require a lot of resources. Ideally I'd need to have as much control over the servers as possible.

How should I arrange hosting for this, when it comes time to release it to the public?

Should I do the hosting myself, from my own servers? Trouble is, since I'm not quite an expert on .NET hosting, it might take time to learn and I might make big mistakes.

The trouble with using a hosting company is, they might steal my idea, or else, it might cost a lot. Since I'm an un-funded startup I don't have a lot of money to throw at this.

[A]
A lot of hosting providers are able to provide you with a dedicated server or VPS (Virtual Private Server) where you run a virtual machine on shared hardware. I have used
HostMySite
for VPS in the past and the service was very good. Dedicated and VPS hosting will cost much more than a shared hosting situation, but probably a safer bet than buying your own hardware, running in the high-speed backbone, dealing with backups, climate control, generators for power outages, etc.
update:
I missed the part about the hosting company stealing your idea. Somebody will take your idea, but ideas alone are worthless... it's all about the execution, and I don't think people at your hosting company would copy your code directly.


q: I have a team of junior developers and they want to have better understanding and usages of generics.  Anyone recommend good tutorial or articles samples that are good places to start.

[A]
A few links:
An Introduction to C# Generics
Generics (C# Programming Guide)
Recommended books:
Professional .NET 2.0 Generics
C# in Depth