q: I'm using NuSOAP on PHP 5.2.6 and I'm seeing that the max message size is only 1000 bytes (which makes it tough to do anything meaningful). Is this set in the endpoint's WSDL or is this something I can configure in NuSOAP?

[A]
I am only passingly-familiar with PHP, and have never used the NuSOAP package at all. However, a SOAP message's size should only be limited by the transport medium. In the case of HTTP, it should be pretty much unbounded (the limitation of 16384 bytes in form POST requests isn't due to SOAP, it's from browser limitations (which may actually not exist anymore, but I don't know for certain)).
I would recommend finding a contact address for the authors/maintainers of NuSOAP and ask them directly. Unless there's something in the WSDL (and I don't recall anything in the WSDL spec that would limit a whole message-body-size... individual parameters (via XML Schema facets), but not the overall body), then the limitation would seem to be in the toolkit.


q:
For some weeks now I simply can't run gem install in windows.
It sticks on this line:

C:\Windows\System32>gem install rails --version 2.1.2
Bulk updating Gem source index for: http://gems.rubyforge.org/

Any ideas what it could be?

[A] It worked fine on my Windows Server 2003 machine. I am using gem version 1.3.0.

s: huggingface

c: devops

d: intermediate


q: Which are the most advanced frameworks and tools there are available for python for practicing Behavior Driven Development? Especially finding similar tools as rspec and mocha for ruby would be great.

[A]
I am probably completely missing the point, but what I retained of the
original BDD paper
was that BDD was just
TDD
repackaged to emphasize some best practices.
If my interpretation is correct, you can get a BDD framework just by renaming methods around in any
xUnit
implementation. So just go ahead and use the standard library's
unittest
.
EDIT: A quick google turned up a
Behaviour
module in the
Cheese Shop
. Further
searching
for BDD there did not find anything else.


q: What is the default XSLT processor for IE6. Does it support EXSLT? Is there anyway to make it support it?

[A]
You have awakened a tormentor from my past.
MSXML, it was installed as a service update, and the XSLT processor originally included in MSIE6 did not support much of anything other than a very general level of draft functionality.  The service update improved on it greatly.
Because of requiring the presence of a service update we never considered performing any client-side XSLT with MSIE6 and instead performed transformations server-side when the client browser was MSIE6 and relayed the transformed content.


q:
I would like to use JavaScript to manipulate hidden input fields in a JSF/Facelets page. When the page loads, I need to set a hidden field to the color depth of the client.

From my Facelet:

<body onload="setColorDepth(document.getElementById(?????);">

<h:form>
  <h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>

When JSF processes the page, it is of course changing the IDs of the elements. What's the best way to reference these elements from my JavaScript code?

[A]
You'll want to set the ID of the form so you'll know what it is. Then you'll be able to construct the actual element ID.
```
```
<body onload="setColorDepth(document.getElementById('myForm:colorDepth');">

<h:form id="myForm">
  <h:inputHidden value="#{login.colorDepth}" id="colorDepth" />
</h:form>
```
```
If you don't want to set the form's ID field, you could find it at runtime, like so:
```
```
<body onload="setColorDepth(document.getElementById(document.forms[0].id + ':colorDepth');">
```
```


q: Should my ajax calls talk to webservices or to simple webpages? It seems to be so much easier to simply Response.Write() the content. Are webservices more reliable or secure?

[A]
Since the pages have a more complicated lifecycle, there is more overhead in calling a web page.
That said, I doubt it really matters in the end, but semantically and practically, a web page is not as efficient.
UPDATE: Can you clarify? Are you talking about typical ASP.NET pages? Or "Classic" ASP? As someone in comments on this answer pointed out, if we are talking "Classic" ASP, then it would be more simple than an ASP.NET page, but I think that goes without saying...


q: Looking for a good choice of .NET-based Wiki Platform.  Doesn't need to be Open Source, but the cheaper the better.

[A]
Linked Note
SharpForge
is an asp.net 2.0(c#) project management application, released under the new BSD license. Each project has its own wiki. Rather than using a special syntax the wiki uses standard HTML. Content is versioned in the version control system.
FlexWiki
is written in C#, uses the .NET framework, and stores data in files or Microsoft SQL Server. FlexWiki is an open source wiki software, released under the CPL (binaries and source code available for download).
Perspective
is written in C#, uses the .NET framework, and stores data in XML files. Binary and Source Code are available for download.
SharpForge
is an asp.net 2.0(c#) project management application, released under the new BSD license. Each project has its own wiki. Rather than using a special syntax the wiki uses standard HTML. Content is versioned in the version control system.


q:
Does anybody have an implementation of Cuckoo hashing in C? If there was an Open Source, non GPL version it would be perfect!

Since Adam mentioned it in his comment, anyone knows why it is not much used? Is it just a matter of implementation or the good theoretical properties do not materialize in practice?

[A]
Cuckoo hashing is relatively unused outside of academia (aside from hardware caches, which sometimes borrow ideas from, but don't really implement fully).  It requires a very sparse hash table to get good time on insertions - you really need to have 51% of your table empty for good performance.  So it is either fast and takes a lot of space, or slow and uses space efficiently - never both.  Other algorithms are both time and space efficient, although they are worse than cuckoo when only time or space is taken into account.
Here is a
code generator for cuckoo hash tables
.  Check the license of the generator to verify that the output is non GPL.  It should be, but check anyway.
-Adam


q:
I have a site, foo.com, that makes ajax requests to bar.foo.com. Will this work.

Also, if foo is a secure connection, https, does bar.foo.com need to be https too? Can these two sites use different certificates?

[A]
Most browsers will, depending on their security/privacy setting, block any outside call made - and only allow AJAX calls made to the same domain. Even subdomains are blocked, because on shared environments they might pose a real threat.
In short: only make AJAX calls through the same domain (perhaps call a page, that in turn calls another page from another domain - through curl/fopen/...), or you'll run into troubles. That also answers your SSL question - it doesn't matter what SSL you're using, or whether they're the same - calls will get blocked, despite the SSL.


q:
Is there an elegant way to create and initialize a const std::vector<const T> like const T a[] = { ... } to a fixed (and small) number of values?

I need to call a function frequently which expects a vector<T>, but these values will never change in my case.

In principle I thought of something like

namespace {
  const std::vector<const T> v(??);
}

since v won't be used outside of this compilation unit.

[A]
For C++11:
```
```
vector<int> luggage_combo = { 1, 2, 3, 4, 5 };
```
```
Original answer:
You would either have to wait for C++0x or use something like
Boost.Assign
to do that.
e.g.:
```
```
#include <boost/assign/std/vector.hpp>
using namespace boost::assign; // bring 'operator+=()' into scope

vector<int> v;
v += 1,2,3,4,5;
```
```


q:
I am using RedCloth with Rails 2.1.1. The Textile <del> tag markup format (i.e. -delete-) was not translating at all.  Tried a few choice options.

> x=RedCloth.new('foobar -blah-')
=> "foobar -blah-"
> x.to_html
=> "<p>foobar <del>blah</del></p>"  # WORKED!
> x=RedCloth.new('foobar * -blah-')
=> "foobar * -blah-"
> x.to_html
=> "<p>foobar * <del>blah</del></p>"  # WORKED!
> x=RedCloth.new("foobar\n* -blah-")
=> "foobar\n* -blah-"
> x.to_html
=> "<p>foobar</p>\n<ul>\n\t<li>-blah-</li>\n</ul>"  # DID NOT WORK!

It appears to me that newlines are the culprit in throwing RedCloth up-in-arms. Any solutions to getting RedCloth to properly recognize '-delete-'?  I have tried RedCloth 4.0.1, 4.0.3, and 4.0.4.

[A]
Looks like RedCloth needs a little more syntax to interpret the delete tag as the first element after a list item...
```
```
>> RedCloth.new("foobar\n* [-blah-]").to_html
=> "
foobar
\n
\n\t
blah
\n
"
```
```


q:
I've created a list using the SharePoint (MOSS 2007) Issue Tracking List.  A "Comments" field is automatically created in this list.  The Comments column has extra functionality that provides a sort of history/log whenever an edit is made to a list item.  Unfortunately, a comment entry is created even when an insignificant edit is made.  For example, I could edit the title of the list item and leave the comment field blank.  This results in a blank entry being saved for the Comments field (except the date/time of the edit and the person making it).  If there are several edits made (with the Comments field left empty), then several blank entries appear to be stored in the data (for the Comment field).  Is there a way to not save a comment entry if it's blank?

Also, is there a way to have a Comments field in a Custom List?  This column seems to only be available in the Issues Tracking List.

[A]
The "Comments" field is actually an "Append-Only Comments" Column .  You should be able to add this to any custom list.  (You will need versioning turned on on the list to operate in the same manner as it does in issue tracker.)
As far as not getting "blank" entries, the only way to do this, would be to turn off "Append Changes to Existing Text" option on the column under list settings.  Doing this would turn it into just another multi-line text box.
I think you are missing the point of this column.  After an edit is made, you can click on the Date/time in this column and it will show you that version of the list item.  I realize that you could do this in version history as well, but this gives you a quick link inside the item.  Also, trained users should be documenting what they changed inside this box.  Might help to rename the column to "Note Changes Made Here." :)
Good Luck


q:
So I have a snazzy custom route for login

# routes.rb
map.login '/login', :controller => 'sessions', :action => 'new'

Visit www.asite.com/login and you're there.  As is custom with failed login, however, we'll do the following in our action.  Note what happens on failed login.

 # sessions_controller.rb

 def create
   self.current_user = User.authenticate(params[:email], params[:password])
   if logged_in?
     # some work and redirect the user
   else
     flash.now[:warning] = "The email and/or password you entered is invalid."
     render :action => 'new'
   end
 end

This is very typical.  Simply render the new action and prompt for login again.  Unfortunately you also get with it an ugly URL: www.asite.com/session. Ick! Is it possible to get rendering to respect the original URL?

[A]
Change
```
render :action => 'new'
```
to
```
redirect_to login_path
```


q:
I'd like to use the Rhino JavaScript compiler to compile some JavaScript to .class bytecode files for use in a project. It seems like this should already exist, since there are groovyc, netrexxc, and jythonc tasks for Groovy, NetREXX(!) and Jython, respectively. Has anyone used or written such an Ant task, or can anyone provide some tips on how to write one?

Ideally it would have some way to resolve dependencies among JavaScript or Java classes.

[A]
Why not simply use java task?
```
```
<java fork="yes"
  classpathref="build.path"
  classname="org.mozilla.javascript.tools.jsc.Main"
  failonerror="true">
    <arg value="-debug"/>
        ...
    <arg value="file.js"/>
</java>
```
```
Any objections?


q: How do you set the timeout for blocking operations on a Ruby socket?

[A]
The solution I found which appears to work is to use
Timeout::timeout
:
```
```
require 'timeout'
    ...
begin
    timeout(5) do
        message, client_address = some_socket.recvfrom(1024)
    end
rescue Timeout::Error
    puts "Timed out!"
end
```
```


q: With common lisp and I am assuming the introspection properties.  How can I add code to common lisp code that will tell me when a function is called and when has finished executing.  I want to take any lisp code and this particular modification to the code.  I figure with lisp's AST analysis, this should be possible.

[A]
Common lisp has a TRACE function that reports the function, arguments and resulting value of each call specified. Here is the doc page for Steel Bank's version, but you should find something similar in most implementations:
http://www.sbcl.org/manual/Function-Tracing.html
The system also includes a profiler:
http://www.sbcl.org/manual/Deterministic-Profiler.html


q:
Given this in a grails action:

def xml = {
    rss(version: '2.0') {
        ...
    }
}
render(contentType: 'application/rss+xml', xml)

I see this:

<rss><channel><title></title><description></description><link></link><item></item></channel></rss>

Is there an easy way to pretty print the XML? Something built into the render method, perhaps?

[A]
This is a simple way to pretty-print XML, using Groovy code only:
```
```
def xml = "<rss><channel><title></title><description>" +
   "</description><link></link><item></item></channel></rss>"

def stringWriter = new StringWriter()
def node = new XmlParser().parseText(xml);
new XmlNodePrinter(new PrintWriter(stringWriter)).print(node)

println stringWriter.toString()
```
```
results in:
```
```
<rss>
  <channel>
    <title/>
    <description/>
    <link/>
    <item/>
  </channel>
</rss>
```
```


q:
To add a svg graphics in html page, it is common to use object tag to wrap it like this:

<object id="svgid" data="mysvg.svg" type="image/svg+xml"
  wmode="transparent" width="100" height="100">

this browser is not able to show SVG: <a linkindex="3"
href="http://getfirefox.com">http://getfirefox.com</a>
is free and does it!
If you use Internet Explorer, you can also get a plugin:
<a linkindex="4" href="http://www.adobe.com/svg/viewer/install/main.html">
http://www.adobe.com/svg/viewer/install/main.html</a>

</object>

If you do not use width and height attributes in the object tag, the svg will be displayed in full size. Normally I get svg files from Open Graphics Library for testing. Is there any way to get svg's size by using JavaScript? Or maybe I should just look at the svg xml file to find out the size from the top svg tag?

[A]
> Is there any way to get svg's size by using JavaScript?
No and yes.
No:
JavaScript won't be able to access the SVG file contents that are sitting in the browser.
So it wouldn't be possible to have a page containing an arbitrary SVG image and then have JavaScript determine anything from the SVG file itself.
The only data JS can access it that contained within the page's DOM: the original markup plus any JS-related modifications to the DOM. You could access the
```
object
```
element's attributes and descendant nodes, but that won't give you visibility of anything more than what you can see if you look at the page markup yourself.
Yes:
JS (in modern browsers) can parse any XML string into a DOM and then access the content using DOM-based methods.
You could get the SVG file contents by issuing an xmlHttpRequest-style request (i.e. JS performs an HTTP GET on the SVG file's URL). JS would then have the SVG file's full XML string and you can then access anything you like.
> Or maybe I should just look at the svg xml file to find out the size from the top svg tag?
This would be more feasible by far.
The only JS-based solution would require JS to perform a GET request on the SVG file's URL (as above), which is unlikely to be feasible - each page load might result in double-downloading each SVG file, and the parsing of the SVG's XML into a DOM by JS might be too resource intensive.
Having JS retrieve the SVG's XML content and parse it into a DOM to retrieve only the image dimensions is a bit overkill. It's perfectly possible, but generally not practical.
Querying the SVG's XML content server-side, determining a suitable width and height and then dynamically adding the
```
width
```
and
```
height
```
attributes prior to returning markup to the browser would be your best bet.


q:
I have created a pretty basic Flash website for a client and am having an issue programming a Client Login feature that he would like. Currently, if I navigate to the site and click Client Login, it takes me to a login page. The way I need this to work is -- within the Flash, using ActionScript 2.0 -- have the user enter their UserID and Password and click to login, which submits POST vars to the form action of the Client Login website.

Is this possible/legal to do from a different domain? How would I go about doing this, assuming it's possible?

[A]
Try this:
```
```
myVars = new LoadVars();
myVars.username = username.text;
myVars.password = pwd.text;
myVars.onLoad = function(success) {
        trace("yay!");
    else {
        trace("try again");
    }
}
myVars.sendAndLoad("login.php", myVars, "POST");
```
```


q:
We have a large management software that is producing big reports of all kinds, based on numerous loops, with database retrievals, objects creations (many), and so on.

On PHP4 it could run happily with a memory limit of 64 MB - now we have moved it on a new server and with the same database - same code, the same reports won't come up without a gig of memory limit...

I know that PHP5 has changed under the hood quite a lot of things, but is there a way to make it behave ?

The question at the end is, what strategies do you apply when you need to have your scripts on a diet ?

[A]
Since moving to the new server, have you verified that your MySQL and PHP system variables are identical to the way they were on your old server?
PHP5 introduced a lot of new functionality but due to its backward compatibility mantra, I don't believe that the differences between PHP5 and PHP4 should be causing this large an affect on the performance of an application who's code and database has not been altered.
Are you also running on the same version of Apache or IIS?
It sounds like a problem that is more likely related to your new system environment than to an upgrade from PHP4 to 5.


q:
This seems like a simple question, but I can't find it with the Stack Overflow search or Google. What does a type followed by a _t mean? Such as

int_t anInt;

I see it a lot in C code meant to deal closely with hardware—I can't help but think that they're related.

[A]
It means type.
```
size_t
```
is the size type.


q:
Oracle purchased BEA and their WebLogic suite of tools. They still have a competing product in their own 10gAS Application Server. Both are Java EE, enterprise grade, servers. While it make take some time due to maintenance agreements, it would be unusual for them to continue to produce two products within the same architectural space. So...

Will they retire their previous application server in favor of WebLogic?

Is WebLogic the one that will be retired?

How long of a process is this likely to be? Years?

What have they done with PeopleSoft vs. Oracle Applications? Likely the same pattern will be followed.

[A] As you say, it would be unusual for them to maintain two products within the same architectural space. I don't know Java application servers, but given the climate of financial markets, and that it would probably take lots of money to maintain two such application servers, I would say it's a foregone conclusion that one of the products will be cut, and sooner rather than later at that (as soon as the cost of settling breach of maintenance contracts falls below what it costs to maintain the outgoing product). As for which one will go, my bet will be on WebLogic because it "wasn't invented here"...


q:
I am working on a VB.NET WinForms app that was "upgraded" by Visual Studio (originally 1.0 or 1.1) from VB6 code (which was itself upgraded from VB5). Except for the few new forms I've created since taking over maintenance of this app, all of the forms in the application have a method called DefInstance which allows you to grab an in-memory copy of the form if there is one. What I can't figure out is why: when would I ever need to reference a form object in memory when it's not immediately in scope where I'm working. To my mind this violates all kinds of sound programming principles and seems like an invitation for memory leaks or worse.

The questions: (1) is this DefInstance thing an merely unfortunate remnant of the VB6 heritage of this app, and (2) should I make a point of removing DefInstance methods throughout the application?

[A]
As you mention, it lets you get a reference to the form.
I've seen lots of VB written like this:
```
```
Private Sub Command_Click()
   Call DoStuff
End Sub

Private Sub DoStuff()
   Form1.myTextbox.Text = "Bad Idea"
End Sub
```
```
DefInstance allows DoStuff() to continue working without passing controls around.
See here:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/6d7985b5-6db6-47a8-9e11-cbf114a48d37/
for more info.


q: In C++ you can disable a function in parent's class by declaring it as private in the child class. How can this be done in Python? I.E. How can I hide parent's function from child's public interface?

[A]
```
```
class X(object):
    def some_function(self):
        do_some_stuff()

class Y(object):
    some_function = None
```
```
This may lead to some nasty and hard to find exceptions being thrown though, so you might try this:
```
```
class X(object):
    def some_function(self):
        do_some_stuff()

class Y(object):
    def some_function(self):
        raise NotImplementedError("function some_function not implemented")
```
```


q:
The follow code (running in ASP.Net 2.0) displays the contents of the requested URL twice. I only want it to display the contents of the requested URL once. I can't figure out what I'm doing wrong. The URL requested is returning XML and if I visit the URL directly, it works fine.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
byte[] postDataBytes = Encoding.UTF8.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/xml";
request.ContentLength = postDataBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
requestStream.Close();

// get response and write to console
response = (HttpWebResponse) request.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
try {
   Response.Write(responseReader.ReadToEnd());
}
finally {
   responseReader.Close();
}
response.Close();


q:
Ok so I've implemented both REST and SOAP services and I like both depending on the context. For me, WS* is great when I want an explicit contract between the server and the client e.g. for sensitive information or for mission critical stuff. REST on the other hand whilst flexible in terms of the schema definition, is in my mind more ideal for content services or data which is not required to undergo any serious business logic.

REST seems to be very much the flavour of the day, and I was somewhat put out when Martin Fowler et al from Thoughworks gave this podcast: http://www.thoughtworks.com/what-we-say/podcasts.html on REST and were derisive toward WS*. Whilst the man himself is well respected, am I right in thinking that there still is very much a place for SOAP and pinch of salt is required here? And has anyone used REST in a serious business application?

[A]
Can you document your REST api by providing someone a description of the media types you use and a single URL?
If you find yourself providing a list of URLs and what verbs can be used on those URLs then you probably don't have a
REST api
.
Once you have created a true REST api then go back and compare it to WS* api.  You will see they are very different.
REST apis can easily handle "serious business logic" and yes I have used REST in a serious business application.


q: I was about to add an extra signal handler to an app we have here and I noticed that the author had used sigaction() to set up the other signal handlers. I was going to use signal(). To follow convention I should use sigaction() but if I was writing from scratch, which should I choose?

[A]
I'd use signal() since it's more portable, in theory at least.  I'll vote up any commenter who can come up with a modern system that doesn't have a POSIX compatibility layer and supports signal().
Quoting from the
GLIBC documentation
:
It's possible to use both the signal and sigaction functions within
  a single program, but you have to be careful because they can
  interact in slightly strange ways.
The sigaction function specifies more information than the signal
  function, so the return value from signal cannot express the full
  range of sigaction possibilities. Therefore, if you use signal to
  save and later reestablish an action, it may not be able to
  reestablish properly a handler that was established with sigaction.
To avoid having problems as a result, always use sigaction to save
  and restore a handler if your program uses sigaction at all. Since
  sigaction is more general, it can properly save and reestablish any
  action, regardless of whether it was established originally with
  signal or sigaction.
On some systems if you establish an action with signal and then
  examine it with sigaction, the handler address that you get may not
  be the same as what you specified with signal. It may not even be
  suitable for use as an action argument with signal. But you can rely
  on using it as an argument to sigaction. This problem never happens
  on the GNU system.
So, you're better off using one or the other of the mechanisms
  consistently within a single program.
Portability Note: The basic signal function is a feature of ISO C,
  while sigaction is part of the POSIX.1 standard. If you are
  concerned about portability to non-POSIX systems, then you should
  use the signal function instead.
Copyright (C) 1996-2008 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this
    document under the terms of the GNU Free Documentation License,
    Version 1.2 or any later version published by the Free Software
    Foundation; with no Invariant Sections, with no Front-Cover Texts,
    and with no Back-Cover Texts. A copy of the license is included in
    the section entitled "GNU Free Documentation License".


q:
I am trying to show and hide an inline element (eg a span) using jQuery.

If I just use toggle(), it works as expected but if I use toggle("slow") to give it an animation, it turns the span into a block element and therefore inserts breaks.

Is animation possible with inline elements?  I would prefer a smooth sliding if possible, rather than a fade in.

<script type="text/javascript">
    $(function(){
        $('.toggle').click(function() { $('.hide').toggle("slow") });
    });
</script>
<p>Hello <span class="hide">there</span> jquery</p>
<button class="toggle">Toggle</button>

[A]
I don't think it is possible like that. The only way I could think to do it would be to animate its opacity between 0 and 1, and, using a callback on the animation, then turn it on or off.
```
```
$('.toggle').click(function() {
    $('.hide:visible').animate(
        {opacity : 0},
        function() { $(this).hide(); }
    );
    $('.hide:hidden')
        .show()
        .animate({opacity : 1})
    ;
});
```
```


q:
I have a project that is based on the Navigation Based Application template.
In the AppDelegate are the methods -applicationDidFinishLoading: and -applicationWillTerminate:.  In those methods, I am loading and saving the application data, and storing it in an instance variable (it is actually an object-graph).

When the application loads, it loads MainWindow.xib, which has a NavigationConroller, which in turn has a RootViewController.  The RootViewController nibName property points to RootView (my actual controller class).

In my class, I wish to refer to the object that I created in the -applicationDidFinishLoading: method, so that I can get a reference to it.

Can anyone tell me how to do that?  I know how to reference between objects that I have created programmatically, but I can't seem to figure out to thread my way back, given that the middle step was done from within the NIB file.

[A]
If I understand your question, you want to reference member variables/properties in your AppDelegate object? The simplest way is to use [[UIApplication sharedApplication] delegate] to return a reference to your object.
If you've got a property called window, you could do this:
```
```
UIWindow   *mainWindow = [[[UIApplication sharedApplication] delegate] window];
//do something with mainWindow
```
```


q: How to capture user clicks in a winform application without making the code very complicated?  is AOP the answer?  How to track instrumentations?

[A]
The general method for capturing clicks in winforms is handling
Control.MouseClick
. You can also look at
Control.MouseDown
and
Control.MouseUp
if you want more detailed information.
If you provide more details about what you're trying to do, we can probably come up with a more targeted answer.


q:
For the moment the best way that I have found to be able to manipulate DOM from a string that contain HTML is:

WebBrowser webControl = new WebBrowser();
webControl.DocumentText = html;
HtmlDocument doc = webControl.Document;

There are two problems:

Requires the WebBrowser object!

This can't be used with multiple threads; I need something that would work on different thread (other than the main thread).

Any ideas?

[A]
Depending on what you are trying to do (maybe you can give us more details?) and depending on whether or not the HTML is well-formed, you
could
convert this to an
```
XmlDocument
```
:
```
```
System.Xml.XmlDocument x = new System.Xml.XmlDocument();
x.LoadXml(html); // as long as html is well-formed, i.e. XHTML
```
```
Then you could manipulate it easily, without the
```
WebBrowser
```
instance. As for threads, I don't know enough about the implementation of
```
XmlDocument
```
to know the answer to that part.
If the document isn't in proper form, you could use
NTidy
(.NET wrapper for
HTML Tidy
) to get it in shape first; I had to do this very thing for a project once and it really wasn't too bad.


q:
I am working on a project that I need to use the Infragistics WebGrid control for some lists of data. I am loading the data on the client-side using JavaScript for display on a Map, and then I need to display that same data within multiple WebGrids. All the data available will be displayed in the WebGrids, but only a subset of the data (only that which is currently within view) will be plotted on the Map at any given time. Since I am loading the data using JavaScript/Ajax, I would like to only load it once, and use the same mechanism to populate the WebGrid control with data too.

Does anyone have any tips/pointers on working with the WebGrid completely from within client-side JavaScript/Ajax code?

[A]
The only thought that comes to mind is performance-related. We found that dynamically creating and populating rows for an UltraWebGrid was appreciably slower than we would have liked.  (In our case we were moving rows from one grid to another and hit performance issues when the number of rows was too great.)
If I was doing something like you describe today, I would populate the grid from the server side if at all possible, and the display the relevant values on the Map from there.
As an added disclaimer, we used Infragistics 2007.1; I do not know if 2008.x is better in this area.


q:
Sam Ruby, author of "RESTful Web Services" seems to come out against the use of HTTP PUT for partial updates: http://intertwingly.net/blog/2008/02/15/Embrace-Extend-then-Innovate

What isn't clear is how partial updates should take place. As I commented near the bottom of his blog, it isn't clear how using HTTP PATCH is any better than using a "patch document" against HTTP PUT.

It is worth noting that although Sam comes out against misusing HTTP PUT he doesn't seem to advocate the use of HTTP PATCH either.

How should one submit RESTful partial updates?

[A]
As you can see from the comments in the blog post you referenced there is no agreed upon way to do partial updates.  If heavyweights like Sam Ruby, Joe Gregario, Mark Nottingham, Mark Pilgrim, Bill de hÓra, etc cannot come to an agreement, what hope do we have.
As far as I am concerned, I wouldn't worry too much.  Create a partial update media type that works for you, use PATCH to indicate your intent and when agreement is finally reached on a general purpose media type, change your server to accept both formats.
Be thankful that if the worst sin your REST api commits is abusing PUT/PATCH then you are doing pretty well.


q:
I'm writing javascript code that is read in as a string and executed via eval() by a firefox extension. Firebug does "see" my script so I am not able to use breakpoints, see objects, etc.

I am currently using Firefox's error console which I'm starting to find limiting. What are my other options? Ideally, I would be able to use Firebug or something similar to it. How do people generally debug Greasemonkey scripts?

I've tried using Lint and other validators, but my script uses a lot of objects and functions provided by the extension environment, making of a lot of the errors reported irrelevant. Also, the output tends to be too nitpicky (focusing of spacing issues, etc).

[A]
As far as I know, Firebug supports
```
eval()
```
debugging since 1.1, specifically for GreaseMonkey, you can use
GM_log
for basic logging, you might find useful this tools also:
Web Developer Extension
JSUnit
JSLint


q:
In C and C++ a variable can be marked as volatile, which means the compiler will not optimize it because it may be modified external to the declaring object.  Is there an equivalent in Delphi programming?  If not a keyword, maybe a work around?

My thought was to use Absolute, but I wasn't sure, and that may introduce other side effects.

[A]
I don't know of any equivalent, nor do I think that the
absolute
directive will help you.
absolute
allows you to have two variables that use the same address, but I do not think it will prevent the compiler from optimising references to that memory.
I imagine you could use a pointer and manage it yourself. That way whatever the compiler does as far as optimising retrival of the pointer value, it should not assume the value stored at the address is the same as last time it read it, but this is pure speculation.


q:
Is there a way to know which file is being selected in windows explorer? I've been looking at the tutorial posted here Idiots guide to ... but the actions described are:

hover

context

menu properties

drag

drag and drop

I wonder if is there a method that get invoked when a file is selected. For instance to create a thumbnail view of the file.

Thanks.

[A]
I could be way off, but it might be a security thing... I've gotten that error before, and I solved it... but I was up for days trying to get a lot of different bugs worked out.
I have a sample article doing something basic, but I'm using net.tcp (with security set to "None") here:
Duplex WCF Services Hosted in IIS Using Net.Tcp
Also, where are you getting the error... is it on the ".Close()" line, or the ".GetTasks().ToString()" line?
Another thing you can check is to simply telnet to localhost on port 9999 to see if the service is listening for incomming connections altogether.


q:
My workplace is planning on moving to Team Foundation Server and it's not a moment too soon - anything to get away from the cancer that is Visual SourceSafe.

However, I must ask - is the source control in TFS significantly different (and better) than VSS or is it just a "beefed up" version of the same thing?

I ask this now since this is probably my last window to suggest something like Subversion.

[A] TFS source control is backended with SQLServer.  I've used CVS and SVN in the past and TFS source control provides me with everything I need.  Note that I don't do a lot of branching, mainly straight-line development with tags for releases.   I have used it with multiple developers and I like the merge features -- side-by-side GUI allowing me to choose which version of conflicts to apply.  I haven't run into any insoluble problems yet.  I'm happy enough that I'm not looking for anything else.  I much prefer it over VSS.


q:
I’m listening to the Hanselminutes Podcast; "StackOverflow uses ASP.NET MVC - Jeff Atwood and his technical team". During the course of the Podcast they are speaking about SQL server and say something along the lines of 'The days of the Stored Procedure are over'.

Now I'm not a DBA but this has taken me a bit by surprise. I always assumed that SPs were the way to go for speed (as they are complied) and security not to mention scalability and maintainability. If this is not the case and SPs are on their last legs, what will replace them or what should we be doing in the future?

[A]
On modern systems, parameterized queries are compiled and cached at the server, so they're just as fast as a stored procedure. They have most of the same security features as well.
For databases that serve a single application, it makes more sense to have the query logic there at the relevant location in the code.  If nothing else it makes it easier to do source control.  If you keep stored procedures on the server keeping track of them can quickly become a mess.  Additionally, if you're using an ORM tool you may not have much in the way of real SQL anyway.
If your database serves several different applications, then you may still want to use stored procedures to enforce business rules between application.


q:
I have a bunch of C files that are generated by a collection of python programs that have a number of shared python modules and I need to account for this in my make system.

It is easy enough to enumerate which python program need to be run to generate each C file. What I can't find a good solution for is determining which other python files those programs depend on. I need this so make will know what needs regenerating if one of the shared python files changes.

Is there a good system for producing make style dependency rules from a collection of python sources?

[A]
The
```
import
```
statements are pretty much all the dependencies there are.  There are are two relevant forms for the import statements:
```
```
import x, y, z
from x import a, b, c
```
```
You'll also need the
```
PYTHONPATH
```
and
```
sites
```
information that is used to build
```
sys.path
```
.  This shows the physical locations of the modules and packages.
That's kind of painful to process, since you have to do the transitive closure of all imports in all modules you import.
As an alternative approach, you can use the
```
-v
```
option to get the complete list of imports and physical files.  This produces a log that you can edit into a flat list of dependencies.
For instance, when I do
```
```
>>> import math
```
```
I see this in the log
```
```
dlopen("/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload/math.so", 2);
import math # dynamically loaded from /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload/math.so
```
```


q:
I'm trying to get a file with ant, using the get property. I'm running apache 2, and I can get the file from the indicated URL using wget and firefox, but ant gives me the following error:

[get] Error opening connection java.io.IOException:
 Server returned HTTP response code: 503 for URL: http://localhost/jars/jai_core.jar

This is what I'm doing in my build.xml:

<get src="http://localhost/jars/jai_core.jar"
     dest="${build.dir}/lib/jai_core.jar"
     usetimestamp="true"/>

Any idea what could be going wrong?

EDIT: On to something. When I provide the full host name of my box instead of localhost, it works.

[A]
503 is
Service Unavailable
, which probably means that the
```
src
```
URL isn't getting interpreted properly and sent by the ANT task or perhaps the JRE.
Here are some things to try:
As always, with ANT, execute the smallest possible build.xml with
-verbose
to see if that gives any more information,
-debug
for even more information.
Try the
```
verbose="true"
```
attribute on the task.
use "
http://127.0.0.1/jars/jai_core.jar
" - depending on what version of the java runtime ANT is executing under, 'localhost' may not be getting resolved correctly.
Drop the
```
usetimestamp
```
attribute just to see if it changes behavior.
Use another Java based application to try to perform the GET and compare results.


q:
I was planning to implememt owner-drawn of CListCtrl. I thought that drawing an item is after the item is inserted into the control. So my method is declare a class which is derived from CListCtrl and override its DrawItem() method. The problem is DrawItem is never invoked after inserting an item. Is there anything wrong with my method?

Thank you!

[A]
You need to set the LBS_OWNERDRAWFIXED style on the control. You can do that in the resource template or programmatically using the ModifyStyle() function.
example:
```
```
m_myListbox.ModifyStyle(0, LBS_OWNERDRAWFIXED, 0);
```
```


q:
I would guess most people on this site are familiar with tail, if not - it provides a "follow" mode that as text is appended to the file tail will dump those characters out to the terminal.

What I am looking for (and possibly to write myself if necessary) is a version of tail that works on binary files. Basically I have a wireless link that I would like to trickle a file across as it comes down from another network link. Looking over the tail source code it wouldn't be too hard to rewrite, but I would rather not reinvent the wheel! This wouldn't strictly be "tail" as I would like the entire file to be copied, but it would watch as new bytes were added and stream those.

Ideas?

[A]
Pipe it to hexdump:
```
```
tail -f somefile | hexdump -C
```
```


q:
I plan on using MySQL and it's built-in encryption functionality to encrypt / decrypt certain columns in certain tables.  The concern I have is that I need to store the key somewhere.  I could certainly store the key in a file and control the permissions of that file and the permissions of the application that accesses it, but is that enough?  I could also create a web service to get the key or something.

I am in a small shop where I would be the only one (possibly one other person) that would have access to the machine that the application was on.  Edit:  I should add that there is a web facing part of this application that would need to decrypt the data unless I added a tier.

I have looked ad nauseum, but no one seems to have a bulletproof answer.

Is this one of those problems where you have to settle for good enough?  Given that I am using MySQL and PHP (possibly Python) is there a better way to approach this?

[A]
It seems that you are considering the use of a 'column-specific' key to use with 'AES_ENCRYPT' and 'AES_DECRYPT'.  As the commenter said, this is a bad idea, because any intrusion will have access to all the data.
If you use a 'user-supplied' password, with/without a salt, you are being much more secure.
That said, if the encryption key is only readable by the application using it, you are probably 'good enough'.  If the machine is broken into, they're going to get your data faster with a single key though.


q:
Who has their email fully encrypted ?

I would like to encrypt my email but I am not sure how to start. If I use encrypted email and I send an email to someone who does not encrypt his email how can the receiver read the email ?

What email client would you recommend to run on a windows systems for encrypted email ? I am using Thunderbird at the moment.

As I understand you have to generate 2 keys (one public and one private) but how do you generate this key?  I also think that you have to put your key somewhere to download but I don't understand how you can trust the downloaded keys.

Any links to a good (not too complicated) guide about the working an implementing of email encryption would be very much appreciated.

kind regards
wim hendrix
anatak

[A]
Thunderbird with Enigmail is a great free solution for what you’d like to do. I use Outlook and PGP, but I think they’re approximately the same.
For a detailed explanation of
public/private key encryption
check out the wiki page, but I’ll try to sum up here.
To encrypt a message so that nobody else but the receiver (bob) can view it you encrypt the message using Bob’s public key. The public key allows you to encrypt but not to decrypt. Without a public key you cannot encrypt a message, so there is no worry about encrypting a message that nobody can decrypt.
When Bob receives your message he will use his private key to decrypt the message. He keeps this private key very secret so that nobody else can decrypt his mail.
To send an encrypted message back Bob will use _your public key (which you have sent him before) to encrypt a message. Then he will send it to you and you can decrypt it using your private key.
That said the solution that I use for my mail is to use opportunistic encryption, so if I have the public key of any recipient of my mail message it gets automatically encrypted, if I do not, it doesn’t. This doesn’t protect me from accidentally sending out a secret message to a person that I don’t have a public key for however. For that I have to be very careful to always verify I have all the keys I need to have for secret messages.
In order to do this I have an e-mail rule setup that says that if I have the word [PGP] in the subject line it will not allow the message to be sent unencrypted. If I try to it will throw an error and warn me of my mistake.
The
enigmail
site has a good description on how to setup thunderbird to encrypt your messages.


q:
What's the best way to return a random line in a text file using C? It has to use the standard I/O library (<stdio.h>) because it's for Nintendo DS homebrew.

Clarifications:

Using a header in the file to store the number of lines won't work for what I want to do.

I want it to be as random as possible (the best being if each line has an equal probability of being chosen as every other line.)

The file will never change while the program is being run. (It's the DS, so no multi-tasking.)

[A]
This method is good because:
i) You can keep generating random lines at no big cost
ii) You only have to read the file a total of 1 time + 1 line at a time per random line you want.  The excess read data is only equal to the size of the file.
iii) It gives each line a fair chance no matter what its position is in the file.
iv) It gives each line a fair chance no matter what its length is in the file.
The suggestion:
I would suggest a 2 pass algorithm.  Well really it's a 1 pass + N lines.  Where N is the number of random lines you want.
The first pass you would use to calculate how many lines and the start positions of each line.
You then take a random number from 0 to the number of lines minus 1.  Use that random number, which is your line index, get the start position for that line index.  Seek to that position.
You then have only 1 more read needed, and you know the exact size.  (until the start index of the next line)
How to store the number of lines and the index of each line:
To store the number of lines, you can obviously just use an int.
If you can use a vector then you can add each line index into the vector.  If not you can just create an array of ints with the max number of lines you think there will be. Then index into that array.
Other answers:
Another answer mentioned that you can pick a random number from 1 to the size of the file, and then use the closest newline.  But this won't work.  For example you might have 1 line that is really long and the others that are not that long.  In that case you would have an uneven distribution.


q: I have an undefined number of display context and each will display a texture. When I call glGenTextures I get the same name returned across all display contexts. Will this work? Even though they have the same name will they still store and display different textures? If not what should do to get around this?

[A]
Textures are not (by default) shared across contexts - you have to explicitly enable this, but how you do so is platform-specific.
On win32, it's
```
wglShareLists
```
, and on most other platforms it's specified when you create the context (eg. with the
```
share
```
parameter to
```
aglCreateContext
```
on OS-X).


q:
When I browse code in Vim, I need to see opening and closing parenthesis/
brackets, and pressing % seems unproductive.

I tried :set showmatch, but it makes the cursor jump back and forth
when you type in a bracket. But what to do if I am browsing already written code?

[A]
```
set showmatch
```
is your best bet.  you can also use the
%
command to jump between matching parenthesis, braces, brackets, quotes, etc.


q:
I'm tinkering with Silverlight 2.0.

I have some images, which I currently have a static URL for the image source.
Is there a way to dynamically load the image from a URL path for the site that is hosting the control?

Alternatively, a configuration setting, stored in a single place, that holds the base path for the URL, so that each image only holds the filename?

[A]
In the code behind or a value converter you can do
```
```
Uri uri = new Uri("http://testsvr.com/hello.jpg");
  YourImage.Source = new BitmapImage(uri);
```
```


q:
I have a core .NET application that needs to spawn an arbitrary number of subprocesses. These processes need to be able to access some form of state object in the core application.

What is the best technique? I'll be moving a large amount of data between processes (Bitmaps), so it needs to be fast.

[A]
I have similar requirements and am using
Windows Communication Foundation
to do that right now. My data sizes are probably a bit smaller though.
For reference I'm doing about 30-60 requests of about 5 KB-30 KB per second on a quad-core machine.
WCF
has been holding up quite well so far.
With WCF you have the added advantages of choosing a transport protocol and security mode that is suitable for your application.


q:
How long should it take to run

ALTER DATABASE [MySite] SET READ_COMMITTED_SNAPSHOT ON

I just ran it and it's taken 10 minutes.

How can I check if it is applied?

[A]
You can check the status of the READ_COMMITTED_SNAPSHOT setting using the
```
sys.databases
```
view.  Check the value of the
```
is_read_committed_snapshot_on
```
column.  Already
asked and answered
.
As for the duration, Books Online states that there can't be any other connections to the database when this takes place, but it doesn't require single-user mode.  So you may be blocked by other active connections.  Run
```
sp_who
```
(or
```
sp_who2
```
) to see what else is connected to that database.


q:
I have some code which ignores a specific exception.

try
{
    foreach (FileInfo fi in di.GetFiles())
    {
        collection.Add(fi.Name);
    }
    foreach (DirectoryInfo d in di.GetDirectories())
    {
        populateItems(collection, d);
    }
}
catch (UnauthorizedAccessException ex)
{
   //ignore and move onto next directory
}

of course this results in a compile time warning as ex is unused.  Is there some standard accept noop which should be used to remove this warning?

[A]
Just rewrite it as
```
```
catch (UnauthorizedAccessException) {}
```
```


q: What's the best way to pass data from one Windows Forms app (an office plugin) to another (exe written in C#) in C#?

[A]
WCF
is one of the easiest ways to do this. You can register a service endpoint in each app, or if one is the service and another is the client you can just use a single service host.
Check out the getting started tutorials.


q:
Suppose I have a table with a numeric column (lets call it "score").

I'd like to generate a table of counts, that shows how many times scores appeared in each range.

For example:

score range  | number of occurrences
-------------------------------------
   0-9       |        11
  10-19      |        14
  20-29      |         3
   ...       |       ...

In this example there were 11 rows with scores in the range of 0 to 9, 14 rows with scores in the range of 10 to 19, and 3 rows with scores in the range 20-29.

Is there an easy way to set this up?  What do you recommend?

[A]
```
```
create table scores (
   user_id int,
   score int
)

select t.range as [score range], count(*) as [number of occurences]
from (
      select user_id,
         case when score >= 0 and score < 10 then '0-9'
         case when score >= 10 and score < 20 then '10-19'
         ...
         else '90-99' as range
     from scores) t
group by t.range
```
```


q:
I have a two way foreign relation similar to the following

class Parent(models.Model):
  name = models.CharField(max_length=255)
  favoritechild = models.ForeignKey("Child", blank=True, null=True)

class Child(models.Model):
  name = models.CharField(max_length=255)
  myparent = models.ForeignKey(Parent)

How do I restrict the choices for Parent.favoritechild to only children whose parent is itself?  I tried

class Parent(models.Model):
  name = models.CharField(max_length=255)
  favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"})

but that causes the admin interface to not list any children.

[A]
This isn't how django works. You would only create the relation going one way.
```
```
class Parent(models.Model):
  name = models.CharField(max_length=255)

class Child(models.Model):
  name = models.CharField(max_length=255)
  myparent = models.ForeignKey(Parent)
```
```
And if you were trying to access the children from the parent you would do
```
parent_object.child_set.all()
```
. If you set a related_name in the myparent field, then that is what you would refer to it as. Ex:
```
related_name='children'
```
, then you would do
```
parent_object.children.all()
```
Read the
docs
http://docs.djangoproject.com/en/dev/topics/db/models/#many-to-one-relationships
for more.


q:
I wanted to see if folks were using decimal for financial applications instead of double.  I have seen lots of folks using double all over the place with unintended consequences . .

Do you see others making this mistake . . .

[A]
We did unfortunately and we regret it. We had to change all doubles to decimals. Decimals are good for financial applications. You can look at this article
A Money type for the CLR
:
A convenient, high-performance money
  structure for the CLR which handles
  arithmetic operations, currency types,
  formatting, and careful distribution
  and rounding without loss.


q:
In C and C++ what do the following declarations do?

const int * i;
int * const i;
const volatile int ip;
const int *i;

Are any of the above declarations wrong?

If not what is the meaning and differences between them?

What are the useful uses of above declarations (I mean in which situation we have to use them in C/C++/embedded C)?

[A]
```
const int * i;
```
```
i
```
is a pointer to constant integer.
```
i
```
can be changed to point to a different value, but the value being pointed to by
```
i
```
can not be changed.
```
int * const i;
```
```
i
```
is a constant pointer to a non-constant integer.  The value pointed to by
```
i
```
can be changed, but
```
i
```
cannot be changed to point to a different value.
```
const volatile int ip;
```
This one is kind of tricky.  The fact that
```
ip
```
is
```
const
```
means that the compiler will not let you change the value of
```
ip
```
.  However, it could still be modified in theory, e.g. by taking its address and using the
```
const_cast
```
operator.  This is very dangerous and not a good idea, but it is allowed.  The
```
volatile
```
qualifier indicates that any time
```
ip
```
is accessed, it should always be reloaded from memory, i.e. it should NOT be cached in a register.  This prevents the compiler from making certain optimizations.  You want to use the
```
volatile
```
qualifier when you have a variable which might be modified by another thread, or if you're using memory-mapped I/O, or other similar situations which could cause behavior the compiler might not be expecting.  Using
```
const
```
and
```
volatile
```
on the same variable is rather unusual (but legal) -- you'll usually see one but not the other.
```
const int *i;
```
This is the same as the first declaration.


q:
I need to add unit testing to some old scripts, the scripts are all basically in the following form:

#!/usr/bin/perl

# Main code
foo();
bar();

# subs
sub foo {

}
sub bar {

}

If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to be able to just test "foo" in isolation.

Is there any way to do this without moving foo,bar into a seperate .pm file?

[A]
Assuming you have no security concerns, wrap it in a sub { ... } and eval it:
```
```
use File::Slurp "read_file";
eval "package Script; sub {" . read_file("script") . "}";

is(Script::foo(), "foo");
```
```
(taking care that the eval isn't in scope of any lexicals that would be closed over by the script).


q:
I have a WCF service up and running and am able to communicate between the service and a .Net 2.0 Client using basicHttpBinding.

I now need to lock down the WCF service so that it can only be called by authenticated clients.

I have control over the clients that will be calling my service. The clients are part of a product that will be installed in the wild and "phoning home" to push and pull data.  The client app is written for .Net 2.0 framework and cannot be upgraded to 3.0 or 3.5 at this time.  I cannot add windows user accounts to the client machines.

What are my options for securing the WCF Service and being able to authenticate from my .Net 2.0 clients?  Also, data needs to be passed over https.

I've been searching the web, and feel like I'm on a wild goose chase.

[A]
Using SSL certificate is the only option for .NET 2.0 client accessing WCF service as basicHttpBinding provides no security. By using SSL, you are securing the whole transport channel.
Check the link
http://www.codeplex.com/WCFSecurityGuide/Release/ProjectReleases.aspx?ReleaseId=15892
. It covers WCF Security covering all scenarios.
To get free SSL certificate please visit
http://www.comodo.com/
or
http://www.instantssl.com/
and try out in your application.


q:
What tips and "standards" do you use in your Redmine project management process?

Do you have a standard wiki insert template you could share or a standard way to work a project using bugs features tasks and support issues?

Do you let issues and updates get emailed into Redmine?
Do you use the forums?
Do you use SVN repository?
Do you use Mylyn in eclipse to work the task lists?

I'm trying to drag our dept. into some web based PM instead of emailed Word docs of vague requirements followed by Word docs explaining how to QA and Deploy that all get lost in a pile of competing updates and projects so that by the time I have to fix something, no one can find any documentation on how it works.

[A]
We are using the Roadmap section as a clear way to display:
bugs
features (that would be references to your word document, or link to html requirement pages)
reconciliations (differences between production values and test values)
and so on...
That is the main point of consolidation for us. The rest is used in relation with that (for instance, the 'announce' section is used to define the main milestone/release dates used in the roadmap)


q:
I'm a rookie designer having a few troubles with this page: http://www.resolvegroup.co.nz/javasurvey.php

There are problems with the javascript operation of the expanded questions. For Internet Explorer (Version 7) the first question when expanded gets partly hidden under question 2. This happens to varying degrees with all questions, at times making the next question completely hidden and other problems.

Firefox (Version 3.03) does not have the problem as above, but you cannot get access to the explanations or select next question as in IE7.

Does anyone know what's going on with this, and how to fix it?

[A]
I'd recommend looking at using a pre-built Accordion script, like that built into the jQuery UI library:
http://docs.jquery.com/UI/Accordion
Also, there's a few things I could suggest. This code of yours:
```
```
$(".score-list").slideUp(speed);
$(".score-list").removeClass("open");
$("a.open-answer").removeClass("hidden");
$(this).parent().children(".score-list").slideDown(speed);
$(this).parent().children(".score-list").toggleClass("open");
$(this).toggleClass("hidden");
```
```
could be made a lot more efficient by storing the results from a jQuery query, as well as taking advantage of jQuery's chaining abilities: quite a lot of jQuery's functions return the jQuery object itself, which means you can call a number of functions in a row without having to reference the object again and again. Here's what I mean:
```
```
$(".score-list")        // my own preference is to split the calls onto
    .slideUp(speed)     // multiple lines to make it easier to read.
    .removeClass("open")
;
$("a.open-answer").removeClass("hidden");

var $this = $(this);    // store the result from a query in an object so you
                        // don't have to go through that again.
$this
    .parent()
    .children(".score-list")
    .slideDown(speed);
    .toggleClass("open")
;
$this.toggleClass("hidden");
```
```


q:
I am currently using a dotted border for certain UI stuff such as instructions, notes, error boxes, etc.

But recently I changed to a solid border, due to a requirement, but I just find it kind of strange.

It seems that by making it solid it puts too much emphasis on page elements which are just informational.

What are your views?

[A]
This is a difficult question because it is very subjective.  Many newer websites these days (Stack Overflow included) fore go the border completely and use a more subtle background color difference between the main body color for accented content sections like you mentioned (instructions, notes, etc.).  When I see dotted lines, I intrinsically relate them to abbreviations or acronyms like this:
```
```

    CSS

```
```
Therefore I would recommend staying away from dotted borders.


q:
How does one go about creating a virtual CD driver on Mac OS X programatically?

I can't find any relevant Cocoa APIs or any pure C BSD solutions.

Any help or information is appreciated.

[A]
If you're simply looking to mount an ISO or something then it's done through the Disk Utility, simply drag it into the side-bar and then select it and choose mount.
If you want to do it from code you can issue the hdiutil command, as shown
here
. I'm not sure if there's an API call to do it, but getting that command to do the work is quite painless.


q:
What's the best way to call a generic method when the type parameter isn't known at compile time, but instead is obtained dynamically at runtime?

Consider the following sample code - inside the Example() method, what's the most concise way to invoke GenericMethod<T>() using the Type stored in the myType variable?

public class Sample
{
    public void Example(string typeName)
    {
        Type myType = FindType(typeName);

        // What goes here to call GenericMethod<T>()?
        GenericMethod<myType>(); // This doesn't work

        // What changes to call StaticMethod<T>()?
        Sample.StaticMethod<myType>(); // This also doesn't work
    }

    public void GenericMethod<T>()
    {
        // ...
    }

    public static void StaticMethod<T>()
    {
        //...
    }
}

[A]
You need to use reflection to get the method to start with, then "construct" it by supplying type arguments with
MakeGenericMethod
:
```
```
MethodInfo method = typeof(Sample).GetMethod(nameof(Sample.GenericMethod));
MethodInfo generic = method.MakeGenericMethod(myType);
generic.Invoke(this, null);
```
```
For a static method, pass
```
null
```
as the first argument to
```
Invoke
```
. That's nothing to do with generic methods - it's just normal reflection.
As noted, a lot of this is simpler as of C# 4 using
```
dynamic
```
- if you can use type inference, of course. It doesn't help in cases where type inference isn't available, such as the exact example in the question.


q:
Say I have a rectangular string array - not a jagged array

string[,] strings = new string[8, 3];

What's the best way to extract a one-dimensional array from this (either a single row or a single column)?  I can do this with a for loop, of course, but I'm hoping .NET has a more elegant way built in.

Bonus points for converting the extracted string array to an object array.

[A]
LINQ is the answer
```
```
static object[] GetColumn(string[][] source, int col) {
    return source.Iterate().Select(x => source[x.Index][col]).Cast<object>().ToArray();
}
static object[] GetRow(string[][] source, int row) {
    return source.Skip(row).First().Cast<object>().ToArray();
}
public class Pair<T> {
    public int Index;
    public T Value;
    public Pair(int i, T v) {
        Index = i;
        Value = v;
    }
}
static IEnumerable<Pair<T>> Iterate<T>(this IEnumerable<T> source) {
    int index = 0;
    foreach (var cur in source) {
        yield return new Pair<T>(index, cur);
        index++;
    }
}
```
```


q:
I noticed that the generic IEnumerator<T> inherits from IDisposable, but the non-generic interface IEnumerator does not. Why is it designed in this way?

Usually, we use foreach statement to go through a IEnumerator<T> instance. The generated code of foreach actually has try-finally block that invokes Dispose() in finally.

[A]
IIRC The whole thing about having
```
IEnumerable<T>
```
and
```
IEnumerable
```
is a result of
```
IEnumerable
```
predating .Net's template stuff. I suspect that your question is in the same way.


q: How do I check if a column exists in SQL Server 2000?

[A]
```
```
IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.COLUMNS
WHERE  TABLE_NAME='tablename' AND COLUMN_NAME='columname' )
```
```


q:
For e.g. if i am storing some files on a network server which is under many hierarchical folders.

Then i want to do backup. But i always encounter issue because the file path is more than 255?

How can i resolve this issue or work around it?

[A]
Maybe upgrade to an Operating System that's been updated in the last decade or so? Seriously, though - what OS and file system are you using? Even FAT32 supports long path and file names, though any single component of the path is limited to 255 characters.
If you've got directories with more than 255 characters in their name, then that's problematic (and a little weird). To work around that issue, you could consider using an archiving utility (tar or zip) run on the server, then ship the archive over to yuor desktop machine.


q:
What is the best way to design a user login mechanism using Java? What are the best practices to be followed to architect a secure and robust login mechanism?

What is the difference between JAAS, JNDI and GSSAPI? How do you decide which one to choose?

[A]
It depends on your user referential.
You need to be able to connect your login java module with that base. it is is LDAP, you might consider framework like
OpenLDAP
.
Plus you have to consider what is include in your "login" perimeter: It is is an "habilitation" login process, you need to have more that just the user name, but also other parameters helping your java module to grant him access (its group, which might be in LDAP, but also the kind of action he wants to make, in order to check if he has the required accreditation level)


q:
Do you all add revision fixed to your custom fields?

And what is the point of have Work Start? I thought resolve issue is good enough?

[A]
We use revision fixed. Makes producing change logs etc much easier.
Never used the work tracking at all. Always just seems like too much hassle, and the teams we've been on we haven't needed to track it that closely. It's different than resolving an issue - that just marks that something is complete. Work start tracks how much time was spent, and if someone is still looking at it.


q:
Let say I run this command:

makecert testcert.cer

Is a private key created? If so, where is it automatically stored in the system even though I did not tell makecert to install this certificate in any certificate store?

[A]
It looks like the private key is stored in the file itself.  From the documentation at
http://msdn.microsoft.com/en-us/library/bfsktky3(VS.80).aspx
it states...
Caution
You should use a certificate store to securely store your certificates. The .snk files used by this tool store private keys in an unprotected manner. When you create or import a .snk file, you should be careful to secure it during use and remove it when you are done.


q:
I'm building a webpage that queries a MySQL database and (currently) produces a text-only list of the findings. The queries to complete a single record are similar to:

movie (title, description, etc)

actors in the movie (name, gender)

related movies

Out of curiosity I've used memory_get_peak_usage() and memory_get_usage():

start   110,440 bytes
peak    656,056 bytes
end 637,976 bytes
time    0.008 seconds

The above is with no records found!

With 40 records I'm reaching approximately 2MB, though the time remains the same.

I know that premature optimization is evil and all, but I have to ask:

Do I need to do some reworking? Is this memory usage normal? What is considered excessive?

[A] Ultimately it's preferable to optimize when convenient of course, but 2MB of memory use sounds fine. PHP4 has a default config of 8mb, and PHP5 16mb. A lot of pre-packaged PHP builds will have different configs, of course, but generally speaking, if you can keep your app under 8mb, you can be sure it'll be highly portable in that regard.


q: How to invoke the default browser with an URL from C#?

[A]
```
```
System.Diagnostics.Process.Start("http://mysite.com");
```
```


q: I need to create reports in a C# .NET Windows app. I've got an SQL Server 2005 .I want to display  two more field to report(not available in data base table. I want to create these field by adding some data from existing field of data base table)

[A]
If you look at the .NET API exposed by Crystal Reports, you'll find that you can inject a DataSet into a report - this gives your application full control over the data used by the report, leveraging Crystal Reports as a presentation engine.
I've used this technique to generate reports over data soures not natively supported by Crystal Reports - it also helps to ensure that all the data comes from the sames source (as the API for changing the connection used within a normal Crystal report is somewhat flakey).
So, what I'd do in your situation is to load all the required data into a DataSet, add the extra columns, and then pass the dataset into the report. Only complex bit is that you need to save out the XML schema of the dataset and import it into Crystal Reports so that it is aware of the shape of your data.


q:
Could you tell me, please, if it's possible to preview (or at least retroview, for example, in a kind of a log file) SQL commands which SQL Server Management Studio Express is about to execute (or has just executed)?

In the past I used Embarcadero DBArtisan which shows SQL queries to be executed before actually running them on the server, so I am eager for this feature in Management Studio.

I have found an option "Auto generate change scripts", but it shows only DDL SQL queries
(structure change), not data change.

[A]
You can use Query Profiler (from SQL) to view the queries and in your SQL Query embed in a transaction and at the end do a rollback.
```
```
BEGIN TRAN

 INSERT INTO Clients
 SELECT 'Bruno', 'Alexandre';

END

ROLLBACK TRAN
```
```
when you rollback a transaction the process will go back to the begining of the BEGIN TRAN and you can be sure that nothing was made, this is the way to commit queries and to safe rollback if the SQL encounter an error...
like:
```
```
IF @@ERROR > 0 GOTO Error

:Error
ROLLBACK TRANSACTION
```
```


q: Can any body tell me the differences between them?

[A] Basically, there isn't one.  Embedded refers to the hosting computer / microcontroller, not the language.  The embeddded system might have fewer resources and interfaces for the programmer to play with, and hence C will be used differently, but it is still the same ISO defined language.


q: Is it OK (or even recommended/good practice) to #include a .c file in another .c file?

[A]
No.
Depending on your build environment (you don't specify), you may find that it works in exactly the way that you want.
However, there are many environments (both IDEs and a lot of hand crafted Makefiles) that expect to compile *.c - if that happens you will probably end up with linker errors due to duplicate symbols.
As a rule this practice should be avoided.
If you absolutely must #include source (and generally it should be avoided), use a different file suffix for the file.


q:
When querying ntp servers with the command ntpdate, I can use the -u argument to make the source port an unrestricted port (port 1024 and above).

With ntpd, which is meant to run in the background, I can't seem to find a way to turn this option on. So the source port is always 123.  It's playing around horribly with my firewall configuration.

Is there a configuration option in ntp.conf to make it use a random source port?

[A]
Doesn't sound look this is possible...see the
ntp troubleshooting page
:
If you're going to run ntpd, you need to fix your network/firewall/NAT so that ntpd can have full unrestricted access to UDP port 123 in both directions.
If this is not possible, you may need to run ntpd on the firewall itself, so that it can have full unrestricted access to UDP port 123 in both directions, and then have it serve time to your internal clients.
If that's not possible, your only other option may be to buy the necessary hardware to connect to one or more of your own computers and run your own Stratum 1 time server or buy a pre-packaged Stratum 1 time server.


q:
How do I convert a string to DateTime format? For example, if I had a string like:

"24/10/2008"

How do I get that into DateTime format ?

[A]
Use
DateTime.ParseExact
:
```
```
string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy",
                                  Thread.CurrentThread.CurrentCulture);
```
```
(You should consider what culture you actually want to parse it in, admittedly.)
EDIT: Other answers have specified "null" as the third parameter - this is equivalent to using
```
Thread.CurrentThread.CurrentCulture
```
.
For other formats, see
"Custom Date and Time Format Strings"
in MSDN.


q: Sometimes gdb prints "incomplete type" for some type of variables. What does this mean and how can we see that value?

[A]
It means that the type of that variable has been incompletely specified. For example:
```
```
struct hatstand;
struct hatstand *foo;
```
```
GDB knows that
```
foo
```
is a pointer to a
```
hatstand
```
structure, but the members of that structure haven't been defined. Hence, "incomplete type".
To print the value, you can cast it to a compatible type.
For example, if you know that
```
foo
```
is really a pointer to a
```
lampshade
```
structure:
```
```
print (struct lampshade *)foo
```
```
Or, you could print it as a generic pointer, or treat it as if it were an integer:
```
```
print (void *)foo
print (int)foo
```
```
See also these pages from the GDB manual:
http://sourceware.org/gdb/current/onlinedocs/gdb/Data.html#Data
http://sourceware.org/gdb/current/onlinedocs/gdb/Symbols.html#Symbols


q:
User A logs into a ticket management system to edit content on "SomePage.aspx"

User B logs in 30 seconds later to edit the same ticket on "SomePage.aspx"

What are some of the best known practices(in a 3-tier architecture) for notifying each of the users that someone else is modifying the same content?

[A]
In a request/response system like HTTP, there isn't much of a concept of what a user is currently doing. You could notify them that someone else opened the ticket for edit "within the last two minutes" (or even prevent them from opening it in such a case) but user A could edit for half an hour - unless you prohibit that as well. You could keep a note of the fact that you believe user A has effectively "got" the item for edit, but with a web app there's nothing to stop the user from just walking away from the computer and never either saving/canceling.
Before thinking about the technological solutions, I suggest thinking about the technological
restrictions
(the asynchronous and request/response nature of the web, basically) and work out the desired behaviour. Some common behaviours are:
First edit wins (tell second editor that their changes have been rejected, basically)
Second edit wins (overwrite first edit - it's too late to tell the first editor)
Merge (can be insanely difficult and/or impossible, depending on the content). This may be automatic or manual (on the part of the second editor).
Prevent a second person from editing while you think a first person may be editing (rarely appropriate for web apps due to the issue mentioned in the first paragraph)


q:
I recently baselined my machine and installed VS2008 and I am trying to import my settings file: http://naspinski.net/file.axd?file=naspinski.vssettings

I click Tools->Import Settings, select Import selected environment settings and click on Next

Next screen I select No, just import new settings, overwrite my current settings and click Next

I browse to my file and click Open -or- double-click on the file and it just dumps out... I don't get the option to click Finished, it just dumps out?

Any ideas what is wrong?

[A]
try only importing by section - you should then see which bits seem to be wrong...
Imports fine on my machine. = VS2008 sp1 - there are warnings on
Command Window Alises
External Tools
Might want to check them out.
Would also suggest changing to Monaco font - easier reading...
have a look at
http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx


q:
This is one of those ajax "alternate flow" questions. Normally I expect my ajax request to return a part of the page. But sometimes it may return a full page with html, head and body tag.

At the time I return from my ajax-request I can detect if this is a full page, but is it possible to trigger a full page reload (with full event cycle) based on the string content I have ?

(And yes, I have tried replacing the body element, but that does not give me the events and does not allow me to change the content in the head block)

Any framework reference is ok

[A]
I don't think it's possible to do directly.
You'd be better off saving the HTML somewhere and sending back a URL where it can be retrieved, then using
```
location.href = ...
```
;


q:
can anybody show me how to build a string using checkbox. what would be the best way to do this.

for example i have 4 checkbox's each with its own value (valueA, valueB, valueC, valueD)
the thing is i want to display each result in different lines.

result if B & C is selected :

valueB

valueC

and how would i display this again if i saved this into a database?

[A]
```
```
"if I saved this into a database" ?
```
```
You'll need to be a bit more specific with your homework assignments if you're actually going to receive any help here ...
Edit:
ok, it
might
not be homework but it certainly read like it - after all, manipulating a GUI to generate a view of the user's choices is Interfaces 101 - and even it wasn't it was a terrible question without enough detail to have any chance of getting a decent answer.


q: What are some uses of #pragma in C, with examples?

[A]
Putting
```
#pragma once
```
at the top of your header file will ensure that it is only included once. Note that
```
#pragma once
```
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g.
```
#ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
```
)


q:
After installing asp.net (and aspnet_regIIS.exe -i) the site doesn't accept my default.aspx page. When trying to access it I get a 404.
When hitting directly to my mvc pages (/search.mvc for example) it works like a charm.

We checked the website configuration and noted that there are no .aspx references in the scriptmaps node.

What am I missing?

[A]
Probably you are missing the .aspx references in the scriptmaps. SCNR. ;-)
More seriously, are they there at the "Web Sites" properties level in IIS manager? What is the output you get when running
```
aspnet_regIIS.exe -i
```
?
Mine says:
```
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>aspnet_regiis.exe -i
Start installing ASP.NET (2.0.50727).
..............................
Finished installing ASP.NET (2.0.50727).

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727>
```


q:
I'm writing code like this, doing a little quick and dirty timing:

var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
    b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

Surely there's a way to call this bit of timing code as a fancy-schmancy .NET 3.0 lambda rather than (God forbid) cutting and pasting it a few times and replacing the DoStuff(s) with DoSomethingElse(s)?

I know it can be done as a Delegate but I'm wondering about the lambda way.

[A]
You could try writing an extension method for whatever class you're using (or any base class).
I would have the call look like:
```
```
Stopwatch sw = MyObject.TimedFor(1000, () => DoStuff(s));
```
```
Then the extension method:
```
```
public static Stopwatch TimedFor(this DependencyObject source, Int32 loops, Action action)
{
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < loops; ++i)
{
    action.Invoke();
}
sw.Stop();

return sw;
}
```
```
Any object deriving from DependencyObject can now call TimedFor(..). The function can easily be adjusted to provide return values via ref params.
--
If you didn't want the functionality to be tied to any class / object you could do something like:
```
```
public class Timing
{
  public static Stopwatch TimedFor(Action action, Int32 loops)
  {
    var sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < loops; ++i)
    {
      action.Invoke();
    }
    sw.Stop();

    return sw;
  }
}
```
```
Then you could use it like:
```
```
Stopwatch sw = Timing.TimedFor(() => DoStuff(s), 1000);
```
```
Failing that, this answer looks like it has some decent "generic" ability:
Wrapping StopWatch timing with a delegate or lambda?


q:
Generate the Fibonacci sequence in the fewest amount of characters possible. Any language is OK, except for one that you define with one operator, f, which prints the Fibonacci numbers.

Starting point: <s>25</s> 14 characters in Haskell:

<s>  f=0:1:zipWith(+)f(tail f) </s>

f=0:scanl(+)1f

[A]
22 characters with dc:
```
```
1[pdd5**v1++2/lxx]dsxx
```
```
Invoke with either:
```
dc -e'1[pdd5**v1++2/lxx]dsxx'
```
Or:
```
echo '1[pdd5**v1++2/lxx]dsxx' | dc
```
Note: not my work, poached from
perlmonks
.


q:
In VS2005 and up, is it possible to specify which configuration should be selected by default?

I have several configurations in my solution but one of them should be used in most cases. Hence I'd like to make sure that devs who pull it out of Source Control use the right configuration(unless of course they specifically choose another one).

Ideally, this setting should be in the .sln file since that one is under Source Control.

[A]
I don't know if I understand the complete situation behind your question, but there is a way to "externalize" some of VS.Net's project configuration values such as FxCop settings into a separate file. Then you could have all projects in a solution point to that file. However, I don't think it would allow for your devs to chose their own configuration after doing the "externalization"
If this seems like the right path for you, check out these posts from me in regards to coding standards on how to make similar changes for configuration.
My Seattle Code Camp Presentation on Coding Standards and Code Review
Automating Standards and Best Practices


q:
I came across an interesting article which shows how we can transparently encrypt jdbc connections using java thin client.

http://javasight.wordpress.com/2008/08/29/network-data-encryption-and-integrity-for-thin-jdbc-clients/

However I want to know how this can be achieved for application servers (like oc4j) datasources.

[A]
It can be similarly done. I believe on the Oracle AS there is an option at the bottom of the page when you create datasource which says add properties. I believe you can add the following over there and give it a try.
```
```
// Set the Client encryption level
"oracle.net.encryption_client" = Service.getLevelString(level)

// Set the Client encryption selected list
"oracle.net.encryption_types_client"= "(RC4_40)"

// Set the Client integrity level
"oracle.net.crypto_checksum_client"= Service.getLevelString(level)

// Set the client integrity selected list
"oracle.net.crypto_checksum_types_client"="( MD5 )"
```
```
If it works out. Please let us know.
Thanks,
Franklin.


q:
For instance, winsock libs works great across all versions of the visual studio. But I am having real trouble to provide a consistent binary across all the versions. The dll compiled with VS 2005 won't work when linked to an application written in 2008. I upgraded both 2k5 and 2k8 to SP1, but the results haven't changed much. It works some what ok. But when they include this with a C# app, the C# app gets access violation errors, but with classic C++ application it works fine.

Is there a strategy that I should know when I provide dlls ?

[A]
First, dont pass anything other than plain old data accross DLL boundries. i.e. structs are fine. classes are not.
Second, make sure that ownership is not transferred - i.e. any structs passed accross the dll boundry are never deallocated outside the dll. So, if you dll exports a X* GetX() function, there is a corresponding FreeX(X*) type function ensuring that the same runtime that allocated is responsible for de-allocation.
Next: Get your DLLs to link to the static runtime. Putting together a project comprimising dls from several 3rd parties, each linked to and expecting different runtimes, potentially different to the runtime expected by the app, is a pain, potentially forcing the installer software to install runtimes for 7.0, 7.1, 8.0 and 9.0 - several of which exist in different service packs which may or may not cause issues. Be kind - statically link your dll projects.
-- Edit:
You cannot export a c++ class directly with this approach. Sharing class definitions between modules means you MUST have a homogeneous runtime environment as different compilers or versions of compilers will generate decorated names differently.
You
can
bypass this restriction by exporting your class instead as a COM style interface... which is to say, while you cannot export a class in a runtime independent way, you CAN export an "interface", which you can easilly make by declaring a class containing only pure virtual functions...
```
```
struct IExportedMethods {
    virtual long __stdcall AMethod(void)=0;
  };
  // with the win32 macros:
  interface IExportedMethods {
    STDMETHOD_(long,AMethod)(THIS)PURE;
  };
```
```
In your class definition, you inherit from this interface:
```
```
class CMyObject: public IExportedMethods { ...
```
```
You can export interfaces like this by making C factory methods:
```
```
extern "C" __declspec(dllexport) IExportedClass* WINAPI CreateMyExportedObject(){
    return new CMyObject;
  }
```
```
This is a very lightweight way of exporting compiler version and runtime independent class versions. Note that you still cannot delete one of these. You Must include a release function as a member of the dll or the interface. As a member of the interface it could look like this:
```
```
interface IExportedMethods {
    STDMETHOD_(void) Release(THIS) PURE; };
  class CMyObject : public IExportedMethods {
    STDMETHODIMP_(void) Release(){
      delete this;
    }
  };
```
```
You can take this idea and run further with it - inherit your interface from IUnknown, implement ref counted AddRef and Release methods as well as the ability to QueryInterface for v2 interfaces or other features. And finally, use DllCreateClassObject as the means to create your object and get the necessary COM registration going. All this is optional however, you can easilly get away with a simple interface definition accessed through a C function.


q:
How do I multiply the values of a multi-dimensional array with weights and sum up the results into a new array in PHP or in general?

The boring way looks like this:

$weights = array(0.25, 0.4, 0.2, 0.15);
$values  = array
           (
             array(5,10,15),
             array(20,25,30),
             array(35,40,45),
             array(50,55,60)
           );
$result  = array();

for($i = 0; $i < count($values[0]); ++$i) {
  $result[$i] = 0;
  foreach($weights as $index => $thisWeight)
    $result[$i] += $thisWeight * $values[$index][$i];
}

Is there a more elegant solution?

[A]
Hm...
```
```
foreach($values as $index => $ary )
  $result[$index] = array_sum($ary) * $weights[$index];
```
```


q:
I want to subclass the built-in DropDownList in ASP.NET so that I can add functionality to it and use it in my pages. I tried doing this with a UserControl but found that it doesn't expose the internal DropDownList (logically, I guess). I've googled for the answer but can't find anything.

I've come as far as writing the actual class, and it's possible to subclass from DropDownList but I'm unable to register the file in my ASP.NET page and use it in the source view. Maybe I'm missing some properties in my class?

Any ideas?

[A]
You want to extend DropDownList in a Custom Control... not in a usercontrol.
Create a new Class Library Project called MyLibrary.
Add a class called MyDropDownList.cs
```
```
namespace My.Namespace.Controls
{
[ToolboxData("<{0}:MyDropDownList runat=\"server\"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
    // your custom code goes here
    // e.g.
    protected override void  RenderContents(HtmlTextWriter writer)
    {
        //Your own render code
    }
}
}
```
```
Once you compile your library, you can add a reference to it in your web application.
And a tagprefix in your web.config
```
```
<add tagPrefix="my" namespace="My.Namespace.Controls" assembly="MyLibrary" />
```
```
That should allow you to add this to your aspx/ascx's
```
```
<my:MyDropDownList ID="myDDl" runat="server">
    ...
</my:MyDropDownList>
```
```


q:
I have a .rc file which is used to include some text data in my executable, like this:

1234 RCDATA myfile.txt

This works fine: the content of the 'myfile.txt' is included in my executable.
The problem is that no 0-terminator is added to the string, and I cannot add it to the file. Is there any way of adding a 0-terminator from within the .rc file? Something like this:

1234 RCDATA { myfile.txt, "\0" }         // error RC2104

Note that I already found this solution, but I am looking for something more elegant.

1234 RCDATA myfile.txt
1235 RCDATA { "\0" }

Thanks alot,
eli

[A]
I don't think so, unless you write your own resource compiler.
I have not meet one which allowed to build one resource from several sources.
You may write a small utility to add a trailing '\0' to a file, say makeZ.exe,
and set an additional build step:
```
```
makeZ myfile.txt myfileZ.txt
```
```
In you .rc there will be
```
```
1234 RCDATA myfileZ.txt
```
```


q:
Where to read up on (the best-practice in) source code formatting, for individual languages i.e. what are the conventions for naming variables etc., for indentation and where to place braces, how and where to include comments, etc.

For example for C Kernighan and Ritchie's book The C Programming Language and Linus Torvalds' Linux kernel coding style guide or Google's C++ Style Guide and for Perl at least perlstyle - Perl style guide.

Edit: Perhaps I should have asked "How to get a good start with coding styles".

[A]
I wouldn't give too much on such style-guides. They are a good start, but in the end you or your team will develop own coding-styles.
EDIT: Rob Kam made a comment, that he want to find out more about these 'starting-conventions'.
That's a good point. But mostly you will join existing projects, open-source-projects or commercial, and the people working on it already have a code-convention. In a company probably exists already a code convention. If you start a new project, start with the conventions of another project you did before.
If you really start a new project with a new language you didn't used before ... then you might start with conventions of another language that is somehow similar (i.e. for a new oo-language you can use conventions from Java or Smalltalk) and adjust your conventions as you gain experience for the new language. As I started programming in Java I used my Pascal-coding-conventions. Some of the pascal-conventions didn't work very good for Java, but with the time I dropped some old conventions and developed new.
S.Lott had the idea to look into an open-source-project written in the language of your choice. That's a good idea to get some suggestions about good conventions. Srikanth had the good idea to ask for good conventions here at Stackoverflow. A very good idea, because with the time Stackoverflow will become a good reference for coding-conventions this way.


q: I'm looking to get data such as Size/Capacity, Serial No, Model No, Heads Sectors, Manufacturer and possibly SMART data.

[A]
You can use
WMI
to get most of the information you want, and there's an introduction to WMI
here
.


q:
I'm looking to create an Intellij IDEA language support plugin for Erlang.

The first and biggest problem I've had is in making the JFlex Erlang syntax definition.

Does anyone know where can I get the EBNF or BNF for Erlang?

[A]
Why not go
straight to the source
?  The
Erlang 4.7 specification
lists productions in a grammar.


q:
Ok: This is some of my table structure that matters here

CaseStudyID int
Title nvarchar(50)
OverrideTitle nvarchar(50)

Part of my procedure

Declare @Temp table(CaseStudyID int,
            Title nvarchar(50))

Insert Into @Temp
SELECT CaseStudyID,Title
FROM CaseStudy
WHERE Visible = 1 AND DisplayOnHomePage = 1
ORDER BY Title

Update @Temp Set Title = TitleOverride
--Here is where im lost if the title occurs more than once
--I need to replace it with the override
--Schoolboy error or leaking brain I cant get it going

Select * From @Temp

Can anyone help?

[A]
You could achieve it without using tempory table this way:
```
```
SELECT
    MIN(CaseStudyID) AS CaseStudyID,
    CASE WHEN count(*) = 1 THEN
       MIN(Title)
    ELSE
       MIN(OverrideTitle)
    END AS Title
FROM CaseStudy
GROUP BY Title
ORDER BY Title
```
```


q:
How to set the turbo c path in windows globally so that i can compile and run my C programs (which are in other drives) using command prompt in windows XP?
Can any one tell me how to get commands at every drive in the command prompt just by typing in

c:\tcc

in command prompt in windows and turbo c environment?

[A]
Go to the Start Menu, then Control Panel.
Choose the "System" applet.
Click on the "Advanced" tab.
Click on "Environment Variables"
Find the "Path" variable, and press "Edit"
Append a semicolon, then the path to Turbo C
For setting the include and library paths, go to the same place, but instead of editing the "Path" variable, create a new variable called "INCLUDE", and set it to the location of your turboc "\include" directory; and create one called "LIB" and one called "CLASSPATH", and set them to your turboc "\lib" directory.


q:
I was hoping someone could send me in the direction of a regularily updating time zone database.

I have found one, but apologies i cant remember where it was from, however with the current GMT clock change fast approaching, i fear all my data will be incorrect, ie the differences from UK to New Yrok will change from 5 hours behind to 6 hours behind.

Any help on this matter would be much appreciated.

Cameron

[A]
Do you mean like the
Olson database
?
For instance, the
fleegix.js
javascript library is a timezone-enabled, drop-in replacement for the stock JavaScript Date, giving you full-blown timezone support, independent from the timezone set on the end-user's machine running the browser. It uses the Olson zoneinfo files for its timezone data.
I believe the
time-converter
uses also such a database, as well as
timeanddate.com
, e.g. for
London
or
New-York
.
Any DST information (Daylight Saving times) can be deduced from
timeanddate.com
, but also from
daylight-savings-time.info
Here is a
javascript program
that does exploit DST informations in order to apply the correct time shift.
And also another script for
SimpleTimeZone
.
You can also query DST data from
global-time-zones.com
, as in
wwp.britishsummertime.co.uk
. You have also informations in
webexhibits.org
See
this forum
for a lengthy discussion about how to retrieve DST informations.
Finally, see that
SO question
for a tar.gz Olson database example.


q:
How to include any assembly code lines into my C program ?

In turbo c is there a possibility to add an assembly code file (.asm) to a project of few .c files?

[A]
One way to include assembly code is to add a wrapper function and write the assembly code in the asm block, as shown in the example below:
```
```
void wrapper_function()
{
    asm
    {
        /* your assembly code */
    }
}
```
```


q:
Please could someone help me with writing a regex expression to replace 0044 token which will be at the start of the string with a 0. Please note that I do not want to replace all 0044 tokens with 0, only those that appear at the start of the string.

Thanks a lot

[A]
In perl:
```
```
s/^0044/0/;
```
```
The
```
^
```
means that the match will only happen at the beginning of the string.


q: What exactly is the purpose of the 'obj' directory in .NET?

[A]
The
"obj" folder
is used to store temporary object files and other files used in order to create the final binary during the compilation process.
The
"bin" folder
is the output folder for complete binaries (assemblies).