q:
I have a swf file that is not controlled by me. The swf expects a javascript call to set some variables after initialization.

The swf is embedded using the swfobject and I'm trying to call the as function right after the embed. This appears to be too soon because I get an error. Everything else should be fine since calling the as function manually via firebug does not produce the error.

So the question is how do I call the function when the embed is complete?

[A]
Are you doing this while the page is still loading? Or from am onload handler?
If it's inline javascript I would suggest doing it in the onload handler from javascript which you can do like this -
```
```
window.onload = function() {
  // your code here
}
```
```
it will run your code once the page is fully loaded.
This doesn't guarentee that the flash is initialised though. You could do that by having the flash make a callback to javascript once it is ready, but you said that the swf is not in your control. All I can really think of us using the onload method to make sure the page is finished loading, and then insert a short delay before trying to use it. Look at the setTimeout javascript function for that. Not a great solution though.


q:
We have an Access DB which has a set of local tables and input forms etc. in which a user maintains their data.

We also have a SQL DB with the same tables which is used to displays the data in a web search form.

What is the best way to allow the user to udate his changes to the SQL db while keeping the working copy local so he can work offline and then push the files when he is happy with new version of the data?

My first thought was add the SQL tables as linked tables I could then truncate (access does like that) or delete the content in each table and then do an insert for each table.

Can I call a SP from access on the SQL to truncate the tables as I am have problem running deletes

I really do want to get it down to the user running a macro/sql call that is repeatable etc.

Thanks for your help

[A]
Often your operating system will help you with these things, at least in (most distributions of) Linux. As soon as a piece of software is available as an installable package, and installed, your package management system will keep track of it and it will be possible to find out that a new version is available.
For instance, in
Gentoo Linux
, you would do the following from the command line to get a list of possible package updates:
```
```
emerge --sync && emerge -p world
```
```
The first command makes sure you have an up-to-date list of available packages, the latter compares all your installed packages (your "world") to the list, and reports back with one line per installable package. These lines contain the version you have, and the version available, so you can decide if it's worth upgrading.
There are probably several other ways of doing it, this is just what I use.

s: huggingface

c: devops

d: intermediate


q:
I created an ASMX file with a code behind file. It's working fine, but it is outputting XML.

However, I need it to output JSON. The ResponseFormat configuration doesn't seem to work. My code-behind is:

[System.Web.Script.Services.ScriptService]
public class _default : System.Web.Services.WebService {
    [WebMethod]
    [ScriptMethod(UseHttpGet = true,ResponseFormat = ResponseFormat.Json)]
    public string[] UserDetails()
    {
        return new string[] { "abc", "def" };
    }
}

[A]
From
WebService returns XML even when ResponseFormat set to JSON
:
Make sure that the request is a POST request, not a GET.  Scott Guthrie has a
post  explaining why
.
Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services


q:
I'm writing a MFC app that uses the MS Mappoint OCX. I need to display the locations of people and vehicles on the map and the best of doing this appears to be with Pushpin objects. I have no problem displaying a stock pushpin icon with some text but want to change the icon to a custom designed one. From the limited amount of Mappoint programming info out there it appears the way to do this is to create a symbol object from a symbols object then assign this to a pushpin like this ..

CSymbols symbols;
CSymbol symbol;

symbol=symbols.Add("c:/temp/myicon.ico");
pushpin.put_Symbol(symbol.get_ID());

But the program crashes with a unhandled exception on the symbols.add instruction.

Can anyone tell me what I am doing wrong here ? or am I on totally the wrong track ?

Thanks for your time

Ian

[A]
I found the solution to this one myself. The following code works ..
```
```
CSymbols symbols;
CSymbol symbol;

symbols=map.get_Symbols();
symbol=symbols.Add("c:/temp/myicon.ico");
pushpin.put_Symbol(symbol.get_ID());
```
```
Where map is the Mappoint control.


q: I've written an Access 2003 application to handle internal things at my company over the past couple years and we are talking about upgrading all of our computers to Office 2007 which means Access will be updated.  Is this going to cause a problem for me?

[A]
Allen Browne, Microsoft access MVP, has written a comprehensive article on Microsoft Access 2007 and upgrading:
Converting to Access 2007
Here is an article by Microsoft:
Transitioning Your Existing Access Applications to Access 2007
In case you are not aware, it is possible to
try 2007 for free
. I would not recommend trying on a PC that you use regularly for other Access work, it is not impossible, but things get awkward.
If you wish to run your 2003 version on 2007, make sure that you create an mde, otherwise you will run into problems. Access 2007 treats several controls in a different way, for example, textboxes with date fields get calendars attached. You will also need to check your references. I also recommend that you
self-certify
your projects. Other than that, I have seen posts on a number of problems, but these are usually specific to the poster.


q: In my database, in one of the table I have a GUID column with allow nulls. I have a method  with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'."

[A]
The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g.
```
```
myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value
```
```
It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly.
We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword
```
DEFAULT
```
instead of
```
NULL
```
for the value so I'd recommend the same approach when building parameters.


q:
Installed Tomcat 6 on WinXP 64. It installed just fine. But when I try to launch it ( from Windows Services) I get the following error :
"Can not start an the Apache Tomcat Service on Local computer."
 error 216:0xd8

[A]
It's well known issue.
Tomcat wrapper for windows service is compiled for 32 bits JDK.
Steps that should allow you to install Tomcat as windows service under JDK64bits.
Download Tomcat binary installation (zip file; exe file will not find 64 bits JDK/JRE).
Extract files from the archive.
Rename tomcat5.exe (tomcat6.exe) to tomcat5.exe.32bits to (tomcat6.exe.32bits)
Extract 64 bits Tomcat wrapper from tomcat5_5_64bits_wrapper.zip and rename it to tomcat5.exe (tomcat6.exe). See
details are here
. (Update: The Bugzilla post seems to be down, but I believe an updated exe file can be found in the
Tomcat SVN Repository
).
Install it as Windows service executing "service.bat install [Tomcat instance name]", where [Tomcat instance name] is optional windows service name.
Under certain conditions tomcat is not correctly configure service registry values. It points out itself to 32 bits version of JRE/JDK instead of 64 bits. It can be done explicitly (path to wrong JDK/JRE) or implicitly ("auto" value that imply using of JAVA_HOME or JRE_HOME that point out to 32 bits version). Anyway, it's highly recommented check registry value that define which version of JDK/JRE will be used for tomcat windows service, see key HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Procrun 2.0[Tomcat instance name]\Parameters\Log\jvm and point it out to correct 64 bits JDK/JRE (e.g. jvm=C:\Program Files\Java\jdk1.5.0_15\jre\bin\server\jvm.dll).


q:
I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().

My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.

[A]
I'd expect
BCEL
to be able to do this. From the web site:
The Byte Code Engineering Library is
  intended to give users a convenient
  possibility to analyze, create, and
  manipulate (binary) Java class files
  (those ending with .class).
The "analyze" part being the important bit here. The JavaDoc isn't visible on the web site (as far as I can see) so I can't easily be sure whether or not it'll help you, but it's a reasonable starting point.


q:
I'm just in the process of upgrading my Preview 5 application to Beta 1, and I'm nearly there save for this one error when trying to render a control:

'System.Web.Mvc.HtmlHelper' does not
  contain a definition for
  'RenderPartial' and no extension
  method 'RenderPartial' accepting a
  first argument of type
  'System.Web.Mvc.HtmlHelper' could be
  found (are you missing a using
  directive or an assembly reference?)

My markup (in the .aspx View Content Page) is:

<% Html.RenderPartial("Controls/UserForm", ViewData); %>

I've tried using Microsoft.Web.Mvc but to no avail.  Does anyone know where Html.RenderPartial has gone, or what alternative I could use?

[A]
Now fixed - the conflict was a difference in Web.config requirements between Preview 5 and Beta 1.  The following needs to be added into the system.web compilation assemblies node:
```
```
<add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
```
```
After this change, all of my old HtmlHelper methods magically came back!


q:
Is using a handrolled POCO queue class using pseudo code

T Dequeue() {
   lock(syncRoot) {
      if(queue.Empty) Thread.Wait();
   }
}

void Enqueue(T item) {
   queue.Enqueue(item);
   Thread.Notify();
}

For WCF is request queueing a scalable approach?


q:
Is there an easy way to tell Windows not to display popups on a headless server machine?

Currently occasional application popups are causing my app to freeze because no one is available to press 'Okay' on the console. Just logging to the eventlog would be more than sufficient.

[A]
It all depends on the kind of popup, from system's message box to custom dialog. So I don't think there is a generic solution to this.
Should I have the problem, I would use a macro language, like AutoHotkey (or AutoIt), to detect the activation of the popup and automate the click on the discard button.
[EDIT] Found a ready to use AHK popup blocker:
New window (popup) blocker
Perhaps usable as is, or as a starting point.


q: And how to fix it. I'd like to log every thrown exception for maintenance purpose.

[A]
This is a known issue in .Net - Application_Error never fires for a web service. Not sure if there's any reason it would be by design, but it just doesn't work.
Jeff Atwood had a
post
(and
follow-up
) about this a few years ago, with the following ideas:
Put a try-catch block around each web service method
Use a facade design pattern and include the try-catch in parent objects
Write a custom SOAP extension or HTTPModule
The only one I care for is the first one, even though it seems like a lot of work.


q:
How can I change the system-default regional settings in windows XP for use by services (run by the system user)?

Regional and Language Options in the control panel modify the settings for the logged-in user. However, services don't use the user's settings - they use the system settings. I know that they can be found in the registry here:

HKEY_USERS\.DEFAULT\Control Panel\International

My question is: What mechanism is there for changing the system-language/date/etc from en-us to en-gb?

[A]
IM not sure if this will help
First type in gpedit.msc from the run command and a dialog box should now open.
Navigate to User Configuration > Administrative Templates > Control Panel > Regional Settings.
This shows the group polcies for the PC/s, maybe you can just set it so en_gb is the only option!!
Group Policy is not my strong point, but do a google search and go from there, I would imagine that you should be able to set up who and what can do what from here.
HTH


q:
I am using a microcontroller with a C51 core. I have a fairly timeconsuming and large subroutine that needs to be called every 500ms. An RTOS is not being used.

The way I am doing it right now is that I have an existing Timer interrupt of 10 ms. I set a flag after every 50 interrupts that is checked for being true in the main program loop. If the Flag is true the subroutine is called. The issue is that by the time the program loop comes round to servicing the flag, it is already more than 500ms,sometimes even >515 ms in case of certain code paths. The time taken is not accurately predictable.

Obviously, the subroutine cannot be called from inside the timer interrupt due to that large time it takes to execute.The subroutine takes 50ms to 89ms depending upon various conditions.

Is there a way to ensure that the subroutine is called in exactly 500ms each time?

[A]
I think you have some conflicting/not-thought-through requirements here.  You say that you can't call this code from the timer ISR because it takes too long to run (implying that it is a lower-priority than something else which would be delayed), but then you are being hit by the fact that something else which should have been lower-priority is delaying it when you run it from the foreground path ('program loop').
If this work
must
happen at exactly 500ms, then run it from the timer routine, and deal with the fall-out from that.  This is effectively what a pre-emptive RTOS would be doing anyway.
If you want it to run from the 'program loop', then you will have to make sure than nothing else which runs from that loop ever takes more than the maximum delay you can tolerate - often that means breaking your other long-running work into state-machines which can do a little bit of work per pass through the loop.


q:
I have a Windows Forms TreeView (node, subnodes). Each node contains some additional information in its Tag. Also, each nodes maps a file on the disk. What's the easiest way copy/cut/paste nodes/files in C#?

It would be nice to have some sample code.

[A]
Consider using the
Clipboard class
. It features all the methods necessary for putting data on the Windows clipboard and to retrieve data from the Windows clipboard.
```
```
StringCollection paths = new StringCollection();
paths.Add("f:\\temp\\test.txt");
paths.Add("f:\\temp\\test2.txt");
Clipboard.SetFileDropList(paths);
```
```
The code above will put the files test.txt and test2.txt for copy on the Windows Clipboard. After executing the code you can navigate to any folder and Paste (
Ctrl
+
V
) the files. This is equivalent to selecting both files in Windows Explorer and selecting copy (
Ctrl
+
C
).


q:
There are a dozen Rails plugins whose goal is to replace fixtures in testing. Here are a few I can think of:

fixture replacement

factory girl

factories and workers

rails scenarios

fixture-scenarios

object daddy

There are probably others. Which of these plugins do you prefer and why?

[A]
I personally use
Faker
with a custom Factory class. This allows me to create my factories, and populate the generated instances with non-static data.
```
```
# spec/factory.rb
module Factory
  def self.create_offer(options={})
    Offer.create({
      :code => Faker::Lorem.words(1),
      :expires_on => Time.now + (rand(30) + 1).day
    }.merge(options))
  end
end

# spec_helper.rb
require 'faker'
require 'spec/factory'

# In the specs
@offer = Factory.create_offer(:code => 'TESTING')
```
```


q:
Objective-C is getting wider use due to its use by Apple for Mac OS X and iPhone development. What are some of your favourite "hidden" features of the Objective-C language?

One feature per answer.

Give an example and short description of the feature, not just a link to documentation.

Label the feature using a title as the first line.

[A]
Posing
Objective-C permits a class to
entirely replace another class
within an application. The replacing class is said to "pose as" the target class. All messages sent to the target class are then instead received by the posing class. There are some restrictions on which classes can pose:
A class may only pose as one of its direct or indirect superclasses
The posing class must not define any new instance variables which are absent from the target class (though it may define or override methods).
No messages must have been sent to the target class prior to the posing.
Posing, similarly to categories, allows
globally augmenting existing classes
. Posing permits two features absent from categories:
A posing class can call overridden methods through super, thus incorporating the implementation of the target class.
A posing class can override methods defined in categories.
An example:
```
```
@interface CustomNSApplication : NSApplication
@end

@implementation CustomNSApplication
- (void) setMainMenu: (NSMenu*) menu
{
     // do something with menu
}
@end

class_poseAs ([CustomNSApplication class], [NSApplication class]);
```
```
This intercepts every invocation of setMainMenu to NSApplication.


q:
I would like to have some kind of catch-all exceptions mechanism in the root of my code, so when an app terminates unexpectedly I can still provide some useful logging.

Something along the lines of

static void Main () {
    if (Debugger.IsAttached)
        RunApp();
    else {
        try {
            RunApp();
        }
        catch (Exception e) {
            LogException(e);
            throw;
        }
    }
 }

While this all works fine, my problem is when I want to attach the debugger after the exception has been raised.

Since the exception escapes to the runtime, windows will prompt to attach visual studio, except, since it has been rethrown, all locals and parameters further up the stack have been lost.

Is there anyway to log these exceptions, while still providing a way to attach the debugger and retain all useful information?

[A]
Shouldn't simply do a
```
```
Exception e1 = e;
LogException(e);
throw(e1);
```
```
inside the catch do the trick (at least you can examine the outer exception)?


q:
I'm using xsd.exe to make the C# classes for our settings.  I have a setting that is per-server and per-database, so I want the class to behave like Dictionary<string, string[][]>.  So I want to be able to say

string serverName = "myServer";
int databaseId = 1;
FieldSettings fieldSettings = getFieldSettings();

string[] fields = fieldSettings[serverName][databaseId];

how do I represent that in XSD?

[A]
This not what
```
xsd
```
is used for. You can always just add your own indexer to a partial class, and mark it with
```
[XmlIgnore]
```


q: What steps do I need to take to get HTML documentation automatically building via the build step in Visual Studio? I have all the comments in place and the comments.xml file being generated, and Sandcastle installed. I just need to know what to add to the post-build step in order to generate the docs.

[A]
I recommend you install Sandcastle Help File Builder from
Codeplex
.
You can run this from the command line, e.g. from a Post-Build event.  The simplest command line is:
```
```
<install-path>\SandcastleBuilderConsole.exe ProjectName.shfb
```
```
Sandcastle is very slow, so I only run it for Release Builds.  To do this, create a Post-Build event with a command something like the following, which passes the configuration name to a batch file:
```
```
CALL "$(ProjectDir)PostBuild.cmd" $(ConfigurationName)
```
```
Then inside the batch file you can test if the first argument is "Release" and if so run SandcastleBuilderConsole.exe.


q: Is this doable in either IE7 or Firefox?

[A]
Try
the dimensions jQuery plugin
.  See
this demo
.
```
```
$('#myelement.').offset();
```
```


q: How does one execute some VBA code periodically, completely automated?

[A]
There is an application method that can be used for timing events.  If you want this to occur periodically you'll have to 'reload' the timer after each execution, but that should be pretty straightforward.
```
```
Sub MyTimer()
   Application.Wait Now + TimeValue("00:00:05")
   MsgBox ("5 seconds")
End Sub
```
```
-Adam


q:
We are about to start a new part of the project and there doesn't seem to be a lot of interest in unit testing (and it doesn't feel like they have experienced TDD). I believe it's nearly essential and it makes maintainance much easier.
So what are your views?

Thanks

BTW: this is a language agnostic question, however the new project is in Java.

[A]
Yes. We have been using TDD for a while now. Somehow TDD has grown found on us and we like this incremental approach in order to achieve better code quality. In spite of the initial denial curve where you think it will slow development having consistent and progressive unit testing while writing code is essential in many ways. Writing breaking changes is very difficult to happen because of the framework of regression testings that is being incrementally built. When done right the code is more robust and the confidence in the code and in the whole project is positively affected.
Writing unit tests nowadays is not for a mere elite. It should be every developer responsibility. The later a bug is found on the code the more it will cost to fix and harder it will be to find. This easily becomes a maintenance nightmare. Having a strong support of unit tests highly reduces this risk.
Combining the power of unit tests and TDD with a well configured continuous integration system allows for rapid discovery of problems in early phases of the project. A daily build is a must to avoid future and almost sure hassles.


q:
I have a sproc that returns a single line and column with a text, I need to set this text to a variable, something like:

declare @bla varchar(100)
select @bla = sp_Name 9999, 99989999, 'A', 'S', null

but of course, this code doesn't work...

thanks!

[A]
If the stored procedure is returning a single value you could define one of the parameters on the stored procedure to be an OUTPUT variable, and then the stored procedure would set the value of the parameter
```
```
CREATE PROCEDURE dbo.sp_Name
    @In INT,
    @Out VARCHAR(100) OUTPUT

AS
BEGIN
    SELECT @Out = 'Test'
END
GO
```
```
And then, you get the output value as follows
```
```
DECLARE @OUT VARCHAR(100)
EXEC sp_name 1, @Out OUTPUT
PRINT @Out
```
```


q:
For a Silverlight 2 webapp. I added a combobox. I have an IEnumerable as Itemsource to populate the combobox. Works fine.

But I would like to add an extra item ("please select a....") to the combobox, anyone an idea how this can be done using the Silverlight 2 combobox.

Any more info about using a template for the ComboxboxItems is welcome as well.

[A]
You can easily insert an item at a desired index location in the Items collection of the ComboBox using the following code.
TextBlock t = new TextBlock();
            t.Text = "Please select....";
            combo.Items.Insert(0, t);
Setting the selected index will set the ComboBox to show your added item by default:
combo.SelectedIndex = 0;


q: What are the established coding standards for JavaScript?

[A]
I never saw a widely acknowledged JavaScript coding standard out there. We did write our own some time ago and I
published it on my blog
in accordance with my employer.
Keep in mind that some of the guidelines might be a bit outdated.


q:
When doing a cvs update, you get a nice summary of the state of the repository, for example:

M src/file1.txt
M src/file2.txt
C src/file3.txt
A src/file4.txt
? src/file5.txt

Is there a way to get this without actually updating? I know there is cvs status, but this is way to verbose:

===================================================================
File: file6.txt        Status: Up-to-date

Working revision:    1.2
Repository revision: 1.2     /var/cvs/cvsroot/file6.txt,v
Sticky Tag:          (none)
Sticky Date:         (none)
Sticky Options:      (none)

I could of course make a script to do the transformation from the latter to the former, but it seems a waste of time since cvs can obviously produce the former.

[A]
You can use the -n flag to get the update output without actually updating the files. You can also add -q (quiet) to suppress any server messages.
```
```
cvs -q -n update
```
```


q:
And by donut caching, I'm refering to Scott Guthrie's blog post which is awesome.

Does anyone know if that works properly?

[A] Note that this technique no longer works as of MVC 2.0. Which sucks.


q: I need a nice JSP editor plugin for Eclipse. What are my choices?

[A]
Check out this one, it's open source
http://amateras.sourceforge.jp/cgi-bin/fswiki_en/wiki.cgi?page=EclipseHTMLEditor


q:
I have a string column in a database table which maps to an Enum in code.  In my dbml file when I set the "Type" to MyTypes.EnumType I get the following error:

Error 1   DBML1005: Mapping between DbType 'VarChar(50) NOT NULL' and
  Type 'MyTypes.EnumType' in Column 'EnumCol' of Type 'Table1' is not
  supported.

This question:
LINQ to SQL strings to enums
indicates that what I am trying to do is possible, but how is it done?

[A]
Curious - it should work IIRC; I'll see if I can do a quick example - however, you might want to check that you have the fully-qualified enum name (i.e. including the namespace).
[update] From
here
it seems that the RTM version shipped with a bug when resolving the enum. One workaround suggested (on that page) was to add the
```
global::
```
prefix. It works fine for me without this workaround, so maybe it is fixed in 3.5 SP1? It also allegedly works fine in 3.5 if you use the unqualified name if the enum is in the same namespace.
[example] Yup, worked fine: with Northwind, I defined an enum for the shipping country:
```
```
namespace Foo.Bar
{
    public enum MyEnum
    {
        France,
        Belgium,
        Brazil,
        Switzerland
    }
}
```
```
I then edited the dbml to have:
```
```
<Column Name="ShipCountry" Type="Foo.Bar.MyEnum" DbType="NVarChar(15)" CanBeNull="true" />
```
```
This generated:
```
```
private Foo.Bar.MyEnum _ShipCountry;
//...
[Column(Storage="_ShipCountry", DbType="NVarChar(15)", CanBeNull=true)]
public Foo.Bar.MyEnum ShipCountry
{ get {...} set {...} }
```
```
And finally wrote a query:
```
```
using (DataClasses1DataContext ctx = new DataClasses1DataContext())
{
    var qry = from order in ctx.Orders
              where order.ShipCountry == Foo.Bar.MyEnum.Brazil
                || order.ShipCountry == Foo.Bar.MyEnum.Belgium
              select order;
    foreach (var order in qry.Take(10))
    {
        Console.WriteLine("{0}, {1}", order.OrderID, order.ShipCountry);
    }
}
```
```
Worked fine; results:
```
```
10250, Brazil
10252, Belgium
10253, Brazil
10256, Brazil
10261, Brazil
10287, Brazil
10290, Brazil
10291, Brazil
10292, Brazil
10299, Brazil
```
```


q:
When a script runs under Apache, I insert $_SERVER['SERVER_NAME'] value into an error reporting e-mail message.

However, if a Web script forks a "worker" job with nohup php ..., $_SERVER['SERVER_NAME'] appears to be empty there. Thus, if an error occurs, it's reported without a host name.

Can I reliably get the host name by means of PHP, without calling Unix hostname command?

[A]
php_uname("n")
(PHP 4 >= 4.0.2, PHP 5)
php_uname — Returns information about the
  operating system PHP is running on
php_uname() returns a description of the operating system PHP is
  running on. This is the same string you see at the very top of the
  phpinfo() output. For the name of just the operating system, consider
  using the PHP_OS constant, but keep in mind this constant will contain
  the operating system PHP was built on.
On some older UNIX platforms, it may not be able to determine the
  current OS information in which case it will revert to displaying the
  OS PHP was built on. This will only happen if your uname() library
  call either doesn't exist or doesn't work.


q:
I'm sure this problem has been solved before and I'm curious how its done. I have code in which, when run, I want to scan the contents of a directory and load in functionality.

Specifically, I am working with a scripting engine that I want to be able to add function calls to. I want the core engine to provide very limited functionality. The user should be able to add additional functions through 3rd party libraries, which I want the engine to scan for and load. How is this done?

[A]
It depends on the platform. On win32, you call
```
LoadLibrary
```
to load a DLL, then get functions from it with
```
GetProcAddress
```
. On Unixy platforms, the equivalents are
```
dlopen
```
and
```
dlsym
```
.


q:
WPF, Browserlike app.

I got one page containing a ListView. After calling a PageFunction I add a line to the ListView, and want to scroll the new line into view:

  ListViewItem item = ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
  if (item != null)
    ScrollIntoView(item);

This works. As long as the new line is in view the line gets the focus like it should.

Problem is, things don't work when the line is not visible.

If the line is not visible, there is no ListViewItem for the line generated, so ItemContainerGenerator.ContainerFromIndex returns null.

But without the item, how do I scroll the line into view? Is there any way to scroll to the last line (or anywhere) without needing an ListViewItem?

[A]
I think the problem here is that the ListViewItem is not created yet if the line is not visible. WPF creates the Visible on demand.
So in this case you probably get
```
null
```
for the item, do you?
(According to your comment, you do)
I have found a
link on MSDN forums that suggest accessing the Scrollviewer directly
in order to scroll. To me the solution presented there looks very much like a hack, but you can decide for yourself.
Here is the code snippet from the
link above
:
```
```
VirtualizingStackPanel vsp =
  (VirtualizingStackPanel)typeof(ItemsControl).InvokeMember("_itemsHost",
   BindingFlags.Instance | BindingFlags.GetField | BindingFlags.NonPublic, null,
   _listView, null);

double scrollHeight = vsp.ScrollOwner.ScrollableHeight;

// itemIndex_ is index of the item which we want to show in the middle of the view
double offset = scrollHeight * itemIndex_ / _listView.Items.Count;

vsp.SetVerticalOffset(offset);
```
```


q: Now that everyone is talking about MVC, I notice that the business rules are not being addressed. In the old days of the 3-tier architecture, The business rules were in the middle layer. Where do they fall in the new MVC?

[A]
A quote from a Wikipedia
Article
:
MVC is often seen in web applications, where the view is the actual HTML page, and the controller is the code that gathers dynamic data and generates the content within the HTML. Finally, the
model
is represented by the actual content, usually stored in a database or in XML nodes,
and the business rules
that transform that content based on user actions.


q:
I have a C# method which accepts a Predicate<Foo> and returns a list of matching items...

public static List<Foo> FindAll( Predicate<Foo> filter )
{
    ...
}

The filter will often be one of a common set...

public static class FooPredicates
{
    public static readonly Predicate<Foo> IsEligible = ( foo => ...)
    ...
}

...but may be an anonymous delegate.

I'd now like to have this method cache its results in the ASP.NET cache, so repeated calls with the same delegate just return the cached result. For this, I need to create a cache key from the delegate. Will Delegate.GetHashCode() produce sensible results for this purpose? Is there some other member of Delegate that I should look at? Would you do this another way entirely?

[A]
Delegate equality looks at each invocation in the invocation list, testing for equality of method to be invoked, and target of method.
The method is a simple piece of the cache key, but the target of the method (the instance to call it on - assuming an instance method) could be impossible to cache in a serializable way. In particular, for anonymous functions which capture state, it will be an instance of a nested class created to capture that state.
If this is all in memory, just keeping the delegate itself as the hash key will be okay - although it may mean that some objects which clients would expect to be garbage collected hang around. If you need to serialize this to a database, it gets hairier.
Could you make your method accept a cache key (e.g. a string) as well? (That's assuming an in memory cache is inadequate.)


q:
I would like to break a long line of text assigned to the standard Label widget in GWT.
I was experimenting with inline <br /> elements but with no success.

Something like this:

label = "My very very very long<br />long long text"

[A]
You need to use the HTML widget, which extends the standard Label widget, and adds support for interpreting HTML tags.
See the
JavaDoc
.


q:
I'm using the ListView control (ASP.NET 2008) to show a bunch of lines of data, and at the bottom I want some totals. I was initially going to define the header and footer in the LayoutTemplate and get the totals with some local function, i.e. <%#GetTheSum()%>, but it appears that the LayoutTemplate does not process the <%#...%> syntax.

Another thought would be to put a Label in the LayoutTemplate and use FindControl to update it. Not sure if that's possible (will try shortly).

What's the best way to show totals using a ListView?

UPDATE: Solution here.

[A]
Use a literal and set the variable in the code-behind.
```
```
<asp:Literal ID="litTotal" runat="server" />
```
```
code-behind:
```
```
litTotal.Text = GetTheSum();
```
```


q: In a spring configuration, what is the difference between using name vs id?   I'm aware that XML restricts the "id" attribute to be unique in a document and limits the characters for using in the id.   But otherwise when declaring a bean, what is the difference between using the "name" attribute vs the "id" attribute?


q: Are there any performance benefits of using SQL Server 2008 over SQL Server 2005?

[A]
Moving a single database from SQL Server 2005-2008 will not notice a difference really.  However, there are new tools and options available in SQL Server 2008 that you MIGHT be able to leverage to provider better performance later on in your application.
One item that comes to mind is filtered indexes.  Allowing to create an index on a subset of information.


q:
This is the way I read file:

    public static string readFile(string path)
    {
        StringBuilder stringFromFile = new StringBuilder();
        StreamReader SR;
        string S;
        SR = File.OpenText(path);
        S = SR.ReadLine();
        while (S != null)
        {
            stringFromFile.Append(SR.ReadLine());
        }
        SR.Close();
        return stringFromFile.ToString();
    }

The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way?

Solution taken

    public static string readFile(string path)
    {

       return File.ReadAllText(path);

    }

Took less than 1 second... :)

[A]
Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and
certainly
shouldn't take 5 minutes to read 2.5 megs.
Where does the file live? Is it on a flaky network share?
By the way, the only difference between what you're doing and using File.ReadAllText is that you're losing line breaks. Is this deliberate? How long does ReadAllText take?


q:
I find that most of microsoft's new programs are very hard to use.

Microsoft Office 2007 (word especially) I find to be hard to use.
Microsoft IIS 7.0 is a PAIN, I never remember which icon to click on, things are just to cluttered and hard to find.

As a programmer, we have to design according to what people are used too, what exactly is MS telling us to do?

[A]
Well, Microsoft has to balance this. On one side, users scream for new features and change-for-change's sake in a lot of MS software. On the other, lack of backwards compatibility (including subjective UI compatibility) is a deal breaker. Really no way to win there.
That said, I don't think we need to design according to what people are used to; neither does Microsoft. Change will never happen if we just do what has always been done before. IIS is not developed for programmers; it's developed for IT people. And the new interface serves them well. Likewise, Office is designed for office drones, not programmers, and the new Office is very discoverable for that particular group.


q: Is it possible to convert an existing WPF Application to SilverLight automatically/with minimal effort?

[A]
No.  Silverlight runs in its own cut-down version of the CLR.  It also is WPF-like, not WPF.  You'll have to do a fair amount of work to convert it.
Times have changed.  Check out
Portable Class Libraries
, now supported in .NET 4.0.  You can build assemblies that can be used on different supported platforms: WP7, Silverlight WPF and even XBOX applications.


q:
What is the best method for displaying major/minor versions in a C# console application?

The System.Windows.Forms namespace includes a ProductVersion class that can be used to display the name/version information set via the Visual Studio project properties (Assembly Information). As such, here is my current mechanism:

Console.WriteLine("{0} ({1})",
   System.Windows.Forms.Application.ProductName,
   System.Windows.Forms.Application.ProductVersion);

Why is this part of Forms? Is this appropriate for a Console application?

[A]
```
```
Assembly.GetExecutingAssembly().GetName().Version
```
```
Also, you can still use the class, you just have to reference the containing assembly.  It's no biggie.


q:
Some friends and colleagues of mine have a little running contest to find or write the longest class/variable/property/method names possible.  Keep in mind, we try to be good boys and girls and keep the naming intelligible and concise, while still explaining what the thing does via its name.

Sometimes it just doesn't happen though.  Have you run in to this?  I'd just like to see what's out there. (Maybe my friends and I aren't as crazy as we think)

Note: I'm not looking for bad naming. That's already here.  I'm looking for good naming that just got a little long.

[A]
Check out Apple's documentation. They're kings at that. Very descriptive, but sometimes miles long. A couple of examples from the NSString class:
```
```
NSString.completePathInfoString:caseSensitive:matchesToArray:filterType
NSString.stringByAddingPercentEscapesUsingEncoding
```
```
My favourite in the Microsoft world:
```
SetProcessWorkingSetSize
```


q: I need to scale calls into Tomcat and it's been suggested to launch threads internally.  Has anyone needed to do this and, if so, what solutions did they come up with?

[A]
Your question is a bit vague. Tomcat itself already uses a thread pool to service HTTP requests. You can increase the number of threads through Tomcat configuration - look to the Tomcat wiki for info on this.
If you mean that in your code you want to launch threads, then I advise perusing the java.util.concurrent API introduced in Java 5. Also read "Java Concurrency in Practice", which is
the
text on this subject.


q:
In a windows MSVC6.0 compiler, if there is a workspace with one project in it, what files would be in the Header Files  folder  and what files would be in the External Dependencies folder?

I thought those files which are explicitly included (#include <*.h>  are to be in the Header Files folder and thsoe which are in turn included by added header files, will be in External Dependencies folder? But doesnt seem to be case.

So what is the difference between the two?

-AD

[A]
After looking at the structure of header files and #include *.h in the workspace i found following:
1.) Those files which are not explicitly added to the Projects
Header Files
folder, but are nonetheless included using the #include directive, by different header and source files, are added to the project automatically by MSVC under the folder
External Dependencies
But now i have a question, is it better to let MSVC add those header files as
External Dependencies
or is it better to add it explicitly in the
Header Files
folder, or is there no difference in the two?
-AD


q: What is the purpose of the Using block in C#? How is it different from a local variable?

[A]
```
Using
```
calls
```
Dispose()
```
after the
```
using
```
-block is left, even if the code throws an exception.
So you usually use
```
using
```
for classes that require cleaning up after them, like IO.
So, this using block:
```
```
using (MyClass mine = new MyClass())
{
  mine.Action();
}
```
```
would do the same as:
```
```
MyClass mine = new MyClass();
try
{
  mine.Action();
}
finally
{
  if (mine != null)
    mine.Dispose();
}
```
```
Using
```
using
```
is way shorter and easier to read.


q:
I've got a code that lists the running application on a win32 box, and then displays theirs icons.

So far so good, I get the hwnd of the app, then call for GetClassLong(hwnd,GCL_HICONSM),  and everything's fine.

But the case of a java apps is a pain to deal with, as the process answering to my calls is javaw.exe, and not the shiny-pimpy java application, who's got a so beautiful icon...

I gave a shot at GetWindowThreadProcessId also, but alas, it's the PID of javaw that's returned...

There's a way to do this though, as the task manager (alt+tab) displays the good icon.

[A]
Mmm, it can be done, because
Process Viewer
has a Show Applications button which does that (even if the main view shows the Java's icon). Alas this freeware isn't open source, so it won't tell its secret... :-(
Sysinternals' ProcMon doesn't do that, alas.
I will dig a bit more... :-)
[EDIT] Both a MS KB article and a
Code Project
article recommend using WM_QUERYDRAGICON if GCL_HICON fails...


q:
I'm trying to display a loading icon while my iPhone app downloads a network resource, but I can't figure out how to make it show up correctly.

I searched around and found some details on the UIActivityView class, but the available example source code didn't work, and the documentation is kind of terse.

Could someone provide a simple example on how to use this class?

[A]
Assuming you've got a view controller set up, and would like to add a
```
UIActivityIndicator
```
to it, here's how you could do it:
(assume you've got a member variable called
```
indicator
```
, which you can use later to clean up)
For your interface (.h file):
```
```
UIActivityIndicator *indicator;
```
```
For your implementation (.m file):
Start the Animation
```
```
CGRect b = self.view.bounds;
indicator = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle:
                                             UIActivityIndicatorStyleWhite];
//center the indicator in the view
indicator.frame = CGRectMake((b.size.width - 20) / 2, (b.size.height - 20) / 2, 20, 20);
[self.view addSubview: indicator];
[indicator release];
[indicator startAnimating];
```
```
Stop the Animation
```
```
[indicator removeFromSuperview];
indicator = nil;
```
```


q:
I have read the GOLD Homepage ( http://www.devincook.com/goldparser/ ) docs, FAQ and Wikipedia to find out what practical application there could possibly be for GOLD. I was thinking along the lines of having a programming language (easily) available to my systems such as ABAP on SAP or X++ on Axapta - but it doesn't look feasible to me, at least not easily - even if you use GOLD.

The final use of the parsed result produced by GOLD escapes me - what do you do with the result of the parse?

EDIT: A practical example (description) would be great.

[A]
GOLD can be used for any kind of application where you have to apply context-free grammars to input.
elaboration:
Essentially, CFGs apply to all programming languages. So if you wanted to develop a scripting language for your company, you'd need to write a parser- or get a parsing program. Alternatively, if you wanted to have a semi-natural language for input for non-programmers in the company, you could use a parser  to read that input and spit out more "machine-readable" data. Essentially, a context-free grammar allows you to describe far more inputs than a regular expression. The GOLD system apparently makes the parsing problem somewhat easier than lex/yacc(the UNIX standard programs for parsing).


q:
I am building an MS Access application in which all the forms are modal. However, after data change in a form, I want to refresh the parent form of this form with newer data. Is there any way to do it. To elaborate further :

Consider there are two forms, Form A and Form B. Both are modal form. From Form A, I initiate Form B, and now Form B has the user attention. But at the close of form B, I want to refresh the Form A. Is there a way to do it?

[A]
You can repaint and / or requery:
On the close event of form B:
```
```
Forms!FormA.Requery
```
```
Is this what you mean?


q:
My company has been working on a Flex dashboard that displays realtime financial information. It will be deployed over a corporate WAN to perhaps a few dozen users.

This is our first Flex project, and while development has been very pleasant, we're a little concerned about what production issues might come up (users not having the right Flash player installed, long download times,BlazeDS performance, etc).

Our stack is RDBMS/Spring/BlazeDS (remoting and messaging)/Flex.

Does anyone with experience deploying a commercial Flex app have any words of advice?

[A]
Your biggest problems are likely to be:
your users not having the correct version of the flash player
your users having locked-down desktops and either not being able to download the right version of the player or not being allowed to use the player at all
download speeds of the swf if you have a big app
intermittent loss of connection to your back-end due to either bugs in your code or unavailable network connection
restrictive browser policies
None of these are insurmountable, but you are likely to encounter all of them in the first few months.
I am presuming that you have tested your app for performance under reasonable load and will have fixed those scalability issues already :-)
HTH


q:
Our web application renders fast in some IE browsers, slow in others...  It seems to be an HTML rendering problem...  The first 10% of the page displays immediately, the last 90% takes up to 10 seconds, and this is static content.  I've run with firefox/yslow, renders very quickly.  Seems to be isolated to some users/configurations of ie.  Quirks mode does not seem to make a difference.

Is there a tool or application that I can use to help me discover a rendering bottleneck?  Am I doing something egregious in my code?  Could it be a javascript issue?  Any help or suggestions will be much appreciated.  thanks.

[A]
Use Fiddler to look at the times to load images, css, js files, etc.  In other words, is caching a problem?  Javascript can definitely cause issues in different browser versions.  There's lots of optimizations you find in some versions that aren't in others.  Also, make sure your html is well-formed xhtml if possible.  How the page is arranged can also affect life.  If your document tree is deep, it may need to wait to render large sections until it reads all the child nodes.  Another thing to note, certain toolbars and plugins do look ahead loading and can slow down life.   An HTTP Proxy can help you watch what's going on network-wise at least.
Not sure if anything of those ideas might help your exact problem, but they can help life overall.


q: I know Java well. Which caveats and resources will help me cross to the other side (C#) as painlessly as possible.

[A]
Biggest tip: go with the
.NET naming conventions
from the word go. That way you'll constantly be reminded about which language you're in. (Sounds silly, but it really is helpful.) Embrace the idioms of the language as far as possible.
There are various books specifically for folks in your situation - search for "C# for Java" in Amazon and you'll get plenty of hits. It's worth reading
carefully
to make sure you don't assume that things will work the same in C# as in Java. (For instance, in C# instance variable initializers are executed before the base class constructor body; in Java they happen after. Subtle things like this can take a while to learn, and are easy to miss if you're skimming.)
If you're going to be using C# 3, I'd get a book which definitely covers that - everything in C# 3 will be new to you. Gratuitous plug: my own book (
C# in Depth
) covers C# 2 and 3, but assumes you already know C# 1. (In other words, it won't be enough on its own, but you may want it as a "second" book.)


q:
I would like to know if there are general rules for creating an index or not.
How do I choose which fields I should include in this index or when not to include them?

I know its always depends on the environment and the amount of data, but I was wondering if we could make some globally accepted rules about making indexes in Oracle.

[A]
There are some things you should always index:
Primary Keys - these are given an index automatically (unless you specify a suitable existing index for Oracle to use)
Unique Keys - these are given an index automatically (ditto)
Foreign Keys - these are
not
automatically indexed, but you should add one to avoid performance issues when the constraints are checked
After that, look for other columns that are
frequently
used to filter queries: a typical example is people's surnames.


q:
Do moderate or large projects ever not require an architect? I have worked on a number of projects where the development company involved has choosen not to assign an application architect. Either the software is built organically and with little concern for design or the design responsibility falls to senior developers.

The motivations for not having an architect range from cost considerations to believing that the development methodology makes the architectural role unnecessary (this argument could be made for agile development). Some open source projects work on the principle of collective contribution rather than development with architectural leadership.

[A]
I'm going to have to use an analogy here utilizing houses.  Not too long ago (relatively) people could build houses without an architect or architected plans.  They cut down some wood, used learned skills to cut and plane boards and built their houses.  Cathedrals, castles, etc....they had architects and engineers, sure.  But the vast majority of the time it was people using skills passed down to build a house.
These houses did the job but didn't last as long. They might be a bit leaky, they might be hard to improve, etc.  But it's easy to use water to level your foundation and then add wood.
Modern day houses have infrastructure to plug into, codes that have to be met, etc.  We need our housing designs created or approved by an architect before they can be built. The architect makes sure everything's up to snuff and that the house will stand and be habitable.
Applications are no different. We are not living in a world where complex structures can get away without being architected.  Sure I can write a database for my library as a trivial exercise; I can also build bookshelves for my library without getting an architect involved.  But once you get beyond simple structures, you should absolutely make sure somebody is paying attention to the bigger picture -- whether your structure (house or application) is going to do what it needs to do, whether it plays nice with others, and whether it meets the rules set upon its construction.


q:
Anyone know a simple way using Java calendar to subtract X days from a date?

I have not been able to find any function which allows me to directly subtract X days from a date in Java. Can someone point me to the right direction?

[A]
Taken from
the docs here
:
Adds or subtracts the specified amount of time to the given calendar field, based on the calendar's rules. For example, to subtract 5 days from the current time of the calendar, you can achieve it by calling:
```
```
Calendar calendar = Calendar.getInstance(); // this would default to now
calendar.add(Calendar.DAY_OF_MONTH, -5).
```
```


q:
The JPA (Java Persistence API) specification has 2 different ways to specify entity composite keys: @IdClass and @EmbeddedId.

I'm using both annotations on my mapped entities, but it turns out to be a big mess to people who aren't very familiar with JPA.

I want to adopt only one way to specify composite keys. Which one is really the best? Why?

[A]
I consider that
```
@EmbeddedId
```
is probably more verbose because with
```
@IdClass
```
you cannot access the entire primary key object using any field access operator. Using the
```
@EmbeddedId
```
you can do like this:
```
```
@Embeddable class EmployeeId { name, dataOfBirth }
@Entity class Employee {
  @EmbeddedId EmployeeId employeeId;
  ...
}
```
```
This gives a clear notion of the fields that make the composite key because they are all aggregated in a class that is accessed trough a field access operator.
Another difference with
```
@IdClass
```
and
```
@EmbeddedId
```
is when it comes to write HQL :
With
```
@IdClass
```
you write:
```
select e.name from Employee e
```
and with
```
@EmbeddedId
```
you have to write:
```
select e.employeeId.name from Employee e
```
You have to write more text for the same query. Some may argue that this differs from a more natural language like the one promoted by
```
IdClass
```
. But most of the times understanding right from the query that a given field is part of the composite key is of invaluable help.


q:
I have an embedded webserver that has a total of 2 Megs of space on it.  Normally you gzip files for the clients benefit, but this would save us space on the server.  I read that you can just gzip the js file and save it on the server.  I tested that on IIS and I didn't have any luck at all.  What exactly do I need to do on every step of the process to make this work?

This is what I imagine it will be like:

gzip foo.js

change link in html to point to foo.js.gz instead of just .js

Add some kind of header to the response?

Thanks for any help at all.

-fREW

EDIT: My webserver can't do anything on the fly.  It's not Apache or IIS; it's a binary on a ZiLog processor.  I know that you can compress streams; I just heard that you can also compress the files once and leave them compressed.

[A]
Using gzip compression on a webserver usually means compressing the output from it to conserve your bandwidth - not quite what you have in mind.
Look at this description
or
This example


q:
I am trying to create a multi dimensional array using this syntax:

$x[1] = 'parent';
$x[1][] = 'child';

I get the error: [] operator not supported for strings  because it is evaluating the $x[1] as a string as opposed to returning the array so I can append to it.

What is the correct syntax for doing it this way? The overall goal is to create this multidimensional array in an iteration that will append elements to a known index.

The syntax ${$x[1]}[] does not work either.


q:
From Wikipedia, the free encyclopedia: Closure (computer science)

In computer science, a closure is a
  function that is evaluated in an
  environment containing one or more
  bound variables. When called, the
  function can access these variables.
  The explicit use of closures is
  associated with functional programming
  and with languages such as ML and
  Lisp. Constructs such as objects in
  other languages can also be modeled
  with closures.

To use this inside of JavaScript, can someone point me to an example of how this applies?

[A]
Searching for "javascript closures" gave plenty of encouraging-looking links. The top three were these two (the third link was a reformatted version of the second):
Javascript closures
JavaScript closures for dummies
If these didn't help you, please explain why so we're in a better position to actually help. If you didn't search before asking the question, well - please do so next time :)


q:
Is the singleton class in Ruby a class in and of itself? Is it the reason why all objects belong to "class?" The concept is fuzzy, but I believe it has something to do with why I can define a class method at all (class foo; def foo.bar ...).

What is the singleton class in Ruby?

[A]
The most pragmatic/action-oreinted way to think of it (IMHO) is: as an inheritance chain, or method lookup/resolution order.  This picture might help
http://www.klankboomklang.com/2007/11/25/modules-part-i-enter-the-include-class/
This is r 1.9, contrasting builtin and user-defined classes: i'm still digesting this one.
http://d.hatena.ne.jp/sumim/20080111/p1
Also, i htink a confusing use of the term is "Singleton object", which is different concept.  A singleton object comes from  a class which has its constructor/instantiator method overridden so that you can allocate only one of that class.


q:
How can I go about making my routes recognise an optional prefix parameter as follows:

/*lang/controller/id

In that the lang part is optional, and has a default value if it's not specified in the URL:

/en/posts/1   => lang = en
/fr/posts/1   => lang = fr
/posts/1      => lang = en

EDIT

Ideally, I'm looking to do this across many controllers and actions by mapping a namespace:

map.namespace "*lang" do |lang|
  lang.resources :posts
  lang.resources :stories
end

[A]
I'm guessing (no time to test right now) that this might work:
```
```
map.connect ':language/posts/:id', :controller => 'posts', :action => 'show'
map.connect 'posts/:id', :controller => 'posts', :action => 'show'
```
```
OK, tried it - it works, on Rails 2.1.1 at least. So that's good. Can't get the :defaults idea to work, though, which is a shame, because it's DRYer.


q:
As the title states, is there a way to prevent extra elements from showing up in VBA dynamic arrays when they are non-zero based?

For example, when using code similar to the following:

While Cells(ndx, 1).Value <> vbNullString
    ReDim Preserve data(1 To (UBound(data) + 1))
    ndx = ndx + 1
Wend

You have an extra empty array element at the end of processing. While this can be eliminated with the following:

ReDim Preserve data(1 To (UBound(data) - 1))

This doesn't seem like the best way of resolving this problem.

As such, is there a way to prevent that extra element from being created in the first place? Preferably something that doesn't require additional logic inside of the loop.

[A]
Visual Basic arrays are zero-based. This can be changed with the
```
Option Base
```
statement, though.
With your arrays, the extra elements are because you do a
```
UBound() + 1
```
, UBound will give you the correct number already. If the array has 5 Elements, UBound will be 5. But the last index will be 4, so ReDim to UBound will give you an array sized  +1.
As arrays are a pain to use anyway (in VBA, that is) and
```
ReDim Preserve
```
acually is an array copy operation to a new fixed size array, I would recommend you to use Collections wherever you can. They are a lot easier to iterate (
```
For Each ... In ...
```
) and much more efficient at adding, finding and removing elements.
```
```
' creation '
Dim anyValue as Variant
Dim c as New Collection

' and adding values '
c.Add anyValue, strKey

' iteration '
For Each anyValue in c
  Debug.Print anyValue
Next c

' count values '
Debug.Print c.Count

' element deletion '
c.Delete strKey
```
```
(You can use Scripting.Dictionary from VBScript for added comfort, but you need to reference that first.)
You can also have multiple dimensions of Collections by simply placing them inside each other.


q:
I want to do something very simple in C++ but i can't find how.
I want to create a function like a for loop where i will ideally enter a variable for the times the iteration should happen and some functions inside brackets my function will execute. I hope i was clear enough. Thanks...

Example

superFor (1)
{
  //commands to be executed here
  add(1+2);
}

[A]
```
```
void DoSomethingRepeatedly(int numTimesTo Loop)
{
   for(int i=0; i<numTimesToLoop; i++)
   {
       //do whatever;
   }
}
```
```
That it ? That can't be.. too simple.. I must be misunderstanding your question :(
Of course you'd have to check that the value of numTimesToLoop is >= 0.
Edit: I made it a method, just in case.


q:
I've worked with a couple of Visual C++ compilers (VC97, VC2005, VC2008) and I haven't really found a clearcut way of adding external libraries to my builds.  I come from a Java background, and in Java libraries are everything!

I understand from compiling open-source projects on my Linux box that all the source code for the library seems to need to be included, with the exception of those .so files.

Also I've heard of the .lib static libraries and .dll dynamic libraries, but I'm still not entirely sure how to add them to a build and make them work.  How does one go about this?

[A]
Ok.   typically you don't want to load dynamic libraries by hand, but if you do, look into LoadLibrary.
you then have to call other functions to get function pointer addresses and so forth.
Typically how it works, is even .dll files have .lib files for them.. so when they are needed, they just automatically load.
how you specifiy .lib files /static libraries is under Properties/Linker/Input->Additional Dependencies. in the gui.
if you are scripting this.. well. you just specifiy the .lib files on the command line at link time.


q: I use an XML file in App_Data in conjunction with a Repeater on the main page of an intranet application allow me to display messages to users when they logon about application status, maintenance, etc.  To test the functionality, it would be nice to have the file in the App_Data folder under development, but if I do this it copies it over the file on the production server when I publish the application.  Is there anyway I can prevent this from happening short of going to a Web Deployment project (and will that solve my problem)?

[A]
In Visual Studio 2005, I see a checkbox labeled "Include files from the App_Data folder", which defaults to checked. Have you tried publishing with that checkbox unchecked?
EDIT:
Seeing as how that checkbox isn't available for your project, I would look into using the
VS2005 Web Deployment add-on
for visual studio. I haven't used it myself but the features to customize publishing between debug and release mode looks promising.


q: Is there a good way to have a Map<String, ?> get and put ignoring case?

[A]
You need a wrapper class for your String key with a case-insensitive equals() and hashCode() implementation.  Use that instead of the String for the Map's key.
See an example implementation at
http://www.java.happycodings.com/Java_Util_Package/code3.html
I found it in 2 minutes of googling.  Looks sensible to me, though I've never used it.


q:
I’m having an issue where a drop down list in IE 6/7 is behaving as such:

You can see that the drop down width is not wide enough to display the whole text without expanding the overall drop down list.

However in Firefox, there is no issue as it expands the width accordingly. This is the behaviour we want in IE 6/7:

We’ve looked at various ways to utilize the onfocus, onblur, onchange, keyboard and mouse events to attempt to solve the problem but still some issues.

I was wondering if anyone has solved this issue in IE 6/7 without using any toolkits/frameworks (YUI, Ext-JS, jQuery, etc…).

[A] I would recommend making the select wider. Firefox is friendly about it and expands the width of the option so that you can see its value, but that doesn't solve the problem that once you've selected an option, you won't be able to see exactly what you selected as a user unless you make the select wider. So from a user-friendliness viewpoint, I would advise just allowing the browser to size the select based on its contents, or set a width that is wide enough for the value of the widest option's contents.


q:
I'm trying to write some SQL that will delete files of type '.7z' that are older than 7 days.

Here's what I've got that's not working:

DECLARE @DateString CHAR(8)
SET @DateString = CONVERT(CHAR(8), DATEADD(d, -7, GETDATE()), 1)
EXECUTE master.dbo.xp_delete_file 0,
                  N'e:\Database Backups',N'7z', @DateString, 1

I've also tried changing the '1' at the end to a '0'.

This returns 'success', but the files aren't getting deleted.

I'm using SQL Server 2005, Standard, w/SP2.

[A]
Try changing the first parameter from 0 to 1.
Here is a small
summary on
```
xp_delete_file
```
I just found. Sounds a bit like you'd be out of luck with this procedure.


q:
Should a method that implements an interface method be annotated with @Override?

The javadoc of the Override annotation says:

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

I don't think that an interface is technically a superclass. Or is it?

Question Elaboration

[A]
You should use @Override whenever possible.  It prevents simple mistakes from being made.  Example:
```
```
class C {
    @Override
    public boolean equals(SomeClass obj){
        // code ...
    }
}
```
```
This doesn't compile because it doesn't properly override
```
public boolean equals(Object obj)
```
.
The same will go for methods that implement an interface (
1.6 and above only
) or override a Super class's method.


q:
Does anyone know any good tutorial about using NAnt for native code build process instructions?

Is there any other tool for build process automation that is better suitable with native code environment?

We are developing a win32 mobile application and it will be available online for download as a CAB file. The CAB file should include the informations filled by user before the download so the application install process would write some user's information into the device registry.

[A]
We tried a while ago to use NAnt to build a large VC++ (VS2005) project ... it didn't work.
The problem was there is no way of capturing the dependencies outside of Visual Studio.  Ie. which cpp files should be rebuilt when a given header file is modified.
We could create nant tasks that threw all the files at the compiler, and it would rebuild them all every time.
In the end we stuck with a NAnt task that invoked devenv to do the build.  This may have changed in VS2008, but I doubt it ...


q: Which log4j Version is bundled with latest OpenCms 7?

[A]
OpenCms
7.0.5
includes log4j
1.2.14


q:
I have found an interesting issue in windows which allows me to cause the Windows clock (but not the hardware clocks) to run fast - as much as 8 seconds every minute. I am doing some background research to work out how Windows calculates and updates it's internal time (not how it syncs with an NTP servers). Any information anyone has or any documents you can point me to would be greatly appreciated!

Also, if anyone knows how _ftime works please let me know.

[A]
This MSDN article
gives a very brief description of how the system time is handled: "When the system first starts, it sets the system time to a value based on the real-time clock of the computer and then regularly updates the time." Another interesting function is
GetSystemTimeAdjustment
, which has this to say:
A value of TRUE [for lpTimeAdjustmentDisabled] indicates that periodic time adjustment is disabled. At each clock interrupt, the system merely adds the interval between clock interrupts to the time-of-day clock. The system is free, however, to adjust its time-of-day clock using other techniques. Such other techniques may cause the time-of-day clock to noticeably jump when adjustments are made.
Finally, in regard to _ftime, it appears to be implemented using
GetSystemTimeAsFileTime
. So it would wrap directly onto the same built-in time facilities as would be used everywhere else.


q:
Within a stored procedure, another stored procedure is being called within a cursor. For every call, the SQL Management Studio results window is showing a result. The cursor loops over 100 times and at that point the results window gives up with an error. Is there a way I can stop the stored procedure within the cursor from outputting any results?

  WHILE @@FETCH_STATUS = 0
  BEGIN
    EXEC @RC = dbo.NoisyProc
    SELECT @RValue2 = 1 WHERE @@ROWCOUNT = 0
    FETCH NEXT FROM RCursor INTO @RValue1, @RValue2
  END

Thanks!

[A]
Place:
```
```
SET ROWCOUNT OFF
/* the internal SP */
SET ROWCOUNT ON
```
```
wrap that around the internal SP, or you could even do it around the SELECT statement from the originating query, that will prevent results from appearing.


q:
Does anyone know of a Jabber library for Lua?  I've found the 'Lua Messaging Library' for AIM, although I can't find a download for it, it appears to be abandoned.

Something like that for Lua would be helpful.

I'm sorry I didn't state this originally, I meant a 'pure Lua' library.

I'm familiar with Verse, but don't have the option of building my own Lua distribution for this particular application.

[A]
Verse
.
Verse is a Jabber/XMPP library for Lua. It is based on the C version of the strophe library.
One handy feature of verse is that only the core protocol is implemented by default. Extensions to the protocol (either XEPs, or custom-made protocols) can be 'described', and then used by any verse application. It is the developer's intention to include support for as many XEPs as possible with verse, any number of which can be optionally loaded by the application when initialising the library.
Kind Regards


q:
I was recommeded a book called:

Accelerated C++ Practical Programming by Example
by Andrew Koenig and Barbara E. Moo
Addison-Wesley, 2000
ISBN 0-201-70353-X

The basis of this book is that Object Oriented Programming is highly wasteful memory-wise, and that most source-code should not be written this way, rather that you should use all inline function calls and procedural programming.

I mean I know most programming books have about the same shelf life as milk, but if your coding a client/server application (database, server and all) (not a device driver or a video game) is it really worth the hassle of having un-maintainable code just for a speed boost?

Or is it worth it just to make the application run on a client's really old machine?  Or to be able to run more servers on a single box?

[A]
Wow, no.
Modern C++ compilers are excellent.  Massive memory usage is more of a symptom of a poor design or large memory data set.  The overhead needed for C++ classes is minimal and really not a problem these days.
Object oriented programming is a way to write components in such a way that they can logically group actions related to a single concept (ie, all actions for a 'car' or all actions for a 'cat').  That's not to say it can't be misused to write spaghetti objects, but as they say, you can write COBOL in any language.
As a further example, it's quite possible and accepted these days to write for embedded software platforms with C++ and objects.  The slight speed decrease and memory usage increase (if any) is repaid a thousand times over by increased maintainability and code usability.


q:
I have a SQL Server 2000 database with around a couple of hundred tables. There are several SQL user accounts that can access this database but each one has different permissions granted on tables in the DB.

How do I create a script to give me a report of the permissions granted to a particular user. i.e. to generate something like:

Table      SELECT   DELETE   UPDATE    INSERT    ALTER
-----      ------   ------   ------    ------    -----
Invoices   Yes      No       Yes       Yes       No
Orders     Yes      Yes      Yes       Yes       No
Customers  Yes      No       Yes       Yes       No

and so on. It's Friday, my SQL-fu is low today and I have a million other things to do before getting finished here today and if someone had a handy script to do this already then I would be eternally grateful :)


q:
Every class that wants to use java.util.logging generally needs to declare a logger like this:

public class MyClass {
    private static Logger _log = Logger.getLogger(MyClass.class.getName());
}

How do you avoid this MyClass.class.getName() boilerplate code?

[A] You don't need getName() if you're using a 1.2+ version of log4j, getLogger() accepts a Class argument. But as for the rest, there isn't any way around it if you want each class to have a static log member with its own category.


q: Using subversion 1.5 I have branch B which was branched off of branch A. After doing work in both branches I go to merge changes from A into B (using svn merge http://path/to/A in the working directory of B) and get svn: Target path does not exist. What does this mean?

[A]
It means that there was a change in a file in branch A which Subversion tried to merge into branch B, but the file does not exist in branch B, so it has nowhere to merge the change. For example:
Create branch B
Change A/README
Delete B/README
Merge A -> B
Now the change in README cannot be applied in branch B, because the file has been removed there.
EDIT: This will result in a
tree conflict
in Subversion 1.6.


q:
The NUnit documentation doesn't tell me when to use a method with a TestFixtureSetup and when to do the setup in the constructor.

public class MyTest
{
    private MyClass myClass;

    public MyTest()
    {
        myClass = new MyClass();
    }

    [TestFixtureSetUp]
    public void Init()
    {
        myClass = new MyClass();
    }
}

Are there any good/bad practices about the TestFixtureSetup versus default constructor or isn't there any difference?

[A]
Why would you need to use a constructor in your test classes?
I use
```
[SetUp]
```
and
```
[TearDown]
```
marked methods for code to be executed before and after each test, and similarly
```
[TestFixtureSetUp]
```
and
```
[TestFixtureTearDown]
```
marked methods for code to be executed only once before and after all test in the fixture have been run.
I guess you could probably substitute the
```
[TestFixtureSetUp]
```
for a constructor (although I haven't tried), but this only seems to break from the clear convention that the marked methods provide.


q:
How do you automatically start a service after running an install from a Visual Studio Setup Project?

I just figured this one out and thought I would share the answer for the general good.  Answer to follow.  I am open to other and better ways of doing this.

[A]
Add the following class to your project.
```
```
using System.ServiceProcess;

class ServInstaller : ServiceInstaller
{
    protected override void OnCommitted(System.Collections.IDictionary savedState)
    {
        ServiceController sc = new ServiceController("YourServiceNameGoesHere");
        sc.Start();
    }
}
```
```
The Setup Project will pick up the class and run your service after the installer finishes.


q:
I wrote a savefile method to save an object to xml. But I am not sure how to test the method in NUnit. Do I need create a sample file manually and compare the string between the files? Are there any better ways to test the method?

Thanks for your answer.

[A]
Here's what I do -- it works for me but it might not be to your specifications.
In the teardown I make sure I delete any files I might have created as part of the suite.  So yes, make sure the file is a scratch file just for testing
In the test method I delete the file if it exists (it shouldn't as the teardown has already taken care of it), then output the file to XML then assert the file exists.  I then reload the file either into an object graph or into the xml DOM and query the state through as many assertions as you need.
If you can get away with writing to files and your design allows you to write to a generic text writer or xml writer then you could bypass the file save and replace the calls with a string writer instead and just query a string.  Much cleaner but it doesn't test that the actual file persistence is working or not.


q:
It seems

import Queue

Queue.Queue().get(timeout=10)

is keyboard interruptible (ctrl-c) whereas

import Queue

Queue.Queue().get()

is not. I could always create a loop;

import Queue
q = Queue()

while True:
    try:
        q.get(timeout=1000)
    except Queue.Empty:
        pass

but this seems like a strange thing to do.

So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?

[A]
```
Queue
```
objects have this behavior because they lock using
```
Condition
```
objects form the
```
threading
```
module.  So your solution is really the only way to go.
However, if you really want a
```
Queue
```
method that does this, you can monkeypatch the
```
Queue
```
class.  For example:
```
```
def interruptable_get(self):
    while True:
        try:
            return self.get(timeout=1000)
        except Queue.Empty:
            pass
Queue.interruptable_get = interruptable_get
```
```
This would let you say
```
```
q.interruptable_get()
```
```
instead of
```
```
interruptable_get(q)
```
```
although monkeypatching is generally discouraged by the Python community in cases such as these, since a regular function seems just as good.


q: What applications/modules/dlls do I need on the Window CE 5.0 device in order to be able to attach Visual Studio 2005 to process running on the device ?

[A]
In the Debug menu, select Attach to process...
In the dialog that pops up change Transport to Smart Device.
Hit the Browse button and pick the type of device.
It'll pop up a connecting dialog, when it disappears, you get a list of processes on the device.
Pick the one you want to debug and the debugger will start up.
This should work on at least Standard VS2005, as long as you selected Smart device development during install (Express doesn't support smart devices).


q:
Object o = new Long[0]
System.out.println( o.getClass().isArray() )
System.out.println( o.getClass().getName() )
Class ofArray = ???

Running the first 3 lines emits;

true
[Ljava.lang.Long;

How do I get ??? to be type long?   I could parse the string and do a Class.forname(), but thats grotty.   What's the easy way?

[A]
http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Class.html#getComponentType()
:
```
```
public Class<?> getComponentType()
```
```
Returns the
```
Class
```
representing the component type of an array. If this class does not represent an array class this method returns null...


q: I'm trying to find an efficient C++ interval tree implementation (mostly likely based on red black trees) without a viral or restrictive license. Any pointers to a clean lightweight standalone implementation? For the use case I have in mind, the set of intervals is known at the outset (there would be say a million) and I want to be able to quickly obtain a list of intervals that overlap a given interval. Thus the tree once built will not change -- just needs rapid queries.

[A]
The C++ standard library offers red/black trees
```
std::map
```
,
```
std::multimap
```
,
```
std::set
```
and
```
std::multiset
```
.
Really, I can't think of any way to handle this more efficiently than to keep a
```
std::map
```
of iterator pairs, and passing those iterator pairs to
```
upper_bound()
```
and
```
lower_bound()
```
.  You'd want the iterator pairs to be kept in a map themselves so that you could easily zero in on which pairs are likely to be in the interval (if the beginning iterator in the "candidate interval" comes after the end of the given interval you're looking at, then you can skip checking that -- and all later -- iterator pairs).


q:
The test form generated by ASMX is pretty handy for testing operations.  However, there is no apparent way to include SOAP headers.

How can you test your headers without programming a client to use the service?

[A]
Instead of directly accessing the headers, provide an abstraction that your code accesses instead. For example, if you have a header called "Customer", you might provide a context class you can access like so:
string customer = MyContext.Current.Customer;
Now, all you have to do is swap in a mock implementation in your test classes that doesn't require all the plumbing.
Note, however, that testing ASMX outside of a web server isn't exactly ideal since it can miss things like serialization. If you could deploy to a test server and test the deployed copy, you would be better off. If you really care about testing, WCF is a better option since you can self host WCF rather easily in tests.


q:
My current project uses NUnit for unit tests and to drive UATs written with Selenium.  Developers normally run tests using ReSharper's test runner in VS.Net 2003 and our build box kicks them off via NAnt.

We would like to run the UAT tests in parallel so that we can take advantage of Selenium Grid/RCs so that they will be able to run much faster.

Does anyone have any thoughts on how this might be achieved? and/or best practices for testing Selenium tests against multiple browsers environments without writing duplicate tests automatically?

Thank you.

[A]
There hasn't been a lot of work on this subject. I didn't find anything really relevent.
However, your point is well taken. Most machines nowadays have more cores and less powerful cores compared to powerful one core cpu.
So I did find something on a Microsoft blog. The technology is called PUnit and is made especially for testing multi-threaded environment.
It's as close as possible to what you requested that I could find :)
You can visit it the appropriate blog post right there:
http://blogs.microsoft.co.il/blogs/eyal/archive/2008/07/09/punit-parallel-unit-testing-in-making.aspx
Update: Link is not valid anymore. The project on CodePlex has been removed.
Update2: This is on the roadmap for NUnit 2.5.
Reference


q:
With the recent announcement of .NET 4.0 and Visual Studio 2010, it is becoming ever more difficult to keep track of what .NET Framework versions build on what version of the CLR and belong with which version(s) of Visual Studio.

Is there a definitive table that shows these relationships?

[A]
It's hard to find, isn't it? I believe these are the versions (ignoring service packs)
Visual Studio version 6 = last one before
.NET
, released in 1998
Visual Studio 2002 = version 7.1, Rainier, first .NET version retroactively added 2002 to the name, .NET 1.0 -- released Feb 2002
Visual Studio 2003 =     version 7, Everett, .NET 1.1 -- released early 2003.
Visual Studio 2005 =     version 8  Whidbey, .NET 2.0 & 3.0 -- launch was Nov 2005. No longer called Visual Studio .NET
Visual Studio 2008 =     version 9 Orcas, .NET 3.5 -- released 11/19/2007 as 9.0.21022.8
Visual Studio 2010 = version 10 Hawaii
The next version of Visual Studio Team System is Rosario.
How to determine which versions and service pack levels of the Microsoft .NET Framework are installed
will give you more information about build numbers and service packs, but only through .NET 2.0.


q:
I've used lex and yacc (more usually bison) in the past for various projects, usually translators (such as a subset of EDIF streamed into an EDA app). Additionally, I've had to support code based on lex/yacc grammars dating back decades. So I know my way around the tools, though I'm no expert.

I've seen positive comments about Antlr in various fora in the past, and I'm curious as to what I may be missing. So if you've used both, please tell me what's better or more advanced in Antlr. My current constraints are that I work in a C++ shop, and any product we ship will not include Java, so the resulting parsers would have to follow that rule.

[A]
Update/warning: This answer may be out of date!
One major difference is that ANTLR generates an LL(*) parser, whereas YACC and Bison both generate parsers that are LALR.  This is an important distinction for a number of applications, the most obvious being operators:
```
```
expr ::= expr '+' expr
       | expr '-' expr
       | '(' expr ')'
       | NUM ;
```
```
ANTLR is entirely incapable of handling this grammar as-is.  To use ANTLR (or any other LL parser generator), you would need to convert this grammar to something that is not left-recursive.  However, Bison has no problem with grammars of this form.  You would need to declare '+' and '-' as left-associative operators, but that is not strictly required for left recursion.  A better example might be dispatch:
```
```
expr ::= expr '.' ID '(' actuals ')' ;

actuals ::= actuals ',' expr | expr ;
```
```
Notice that both the
```
expr
```
and the
```
actuals
```
rules are left-recursive.  This produces a much more efficient AST when it comes time for code generation because it avoids the need for multiple registers and unnecessary spilling (a left-leaning tree can be collapsed whereas a right-leaning tree cannot).
In terms of personal taste, I think that LALR grammars are a lot easier to construct and debug.  The downside is you have to deal with somewhat cryptic errors like shift-reduce and (the dreaded) reduce-reduce.  These are errors that Bison catches when generating the parser, so it doesn't affect the end-user experience, but it can make the development process a bit more interesting.  ANTLR is generally considered to be easier to use than YACC/Bison for precisely this reason.


q:
I'm trying to find about ALL the possible options that I can set in web.config.
Surprisingly, I can't find this at all. I expected it to be somewhere inside MSDN.

I know I can technically add "anything" to web.config, what I'm looking for is the things that the .NET Framework "as shipped" uses.

In particular, right now I'm interested in the <mailsettings> section.

For example, in many examples I've found, I noticed that they set DeliveryMethod="Network".
I'm really curious what other values this attribute can take.

Is there any document on all the attributes and all their values, and all the effects those have?

[A]
It all starts on
http://msdn.microsoft.com/en-us/library/zeshe0eb(v=vs.100).aspx
:
```
<system.web>
```
```
<system.web.extensions>
```
```
<appSettings>
```
```
<configSections>
```
```
<connectionStrings>
```


q:
My customer is replacing MS Office with OpenOffice in some workstations. My program export a file to Excel using the .xml extension (using open format) and opens it using the current associated program (using ShellExecute)

The problem is that OpenOffice does not register the .xml extension associated with it.

Manually association works fine, but I want to make a .reg or something to easily change the setting.

I'm looking in the registry in a PC with the change already made, but the

"HKEY_CLASSES_ROOT\.xml"

key does not have anything referencing OpenOffice.

Where is the association stored? How can I make a script to do the work?

[A]
The real association is stored in the key that
```
"HKEY_CLASSES_ROOT\.xml"
```
points to.
On my machine, the default value of that key says
```
"xmlfile"
```
, most likely that is the same for yours.
So let's go to
```
"HKEY_CLASSES_ROOT\xmlfile"
```
. There you can see (and change) what command is going to be used to launch that type of file:
```
```
HKEY_CLASSES_ROOT\xmlfile\shell\open\command
```
```
Windows uses this kind of redirection to map multiple file extensions to the same file type, and thus to the same application.
Under
```
"HKEY_CLASSES_ROOT\xmlfile\shell"
```
there are multiple sub-keys that resemble the "verbs" of what you can do to the file. Again, the default value of the
```
"shell"
```
key decides which of these verbs is used if you double click the file. In my case this is
```
"open"
```
.
Conclusion:
With that knowledge, the easiest way to make an association scriptable is to use regedit to export a .reg file containing that change, and apply it to the target computer with a double click or:
```
```
regedit /s new_xml_association.reg
```
```
or (if you are on XP or higher and know what you do) overwrite the current value with:
```
```
reg add "HKEY_CLASSES_ROOT\xmlfile\shell\open\command" /ve /d "path\to\program %1"
```
```
At any rate, a deeper look into
```
reg add/?
```
command is advised. The first solution is safer.


q: I need to change the permissions of a directory to be owned by the Everyone user with all access rights on this directory.  I'm a bit new to the Win32 API, so I'm somewhat lost in the SetSecurity* functions.

[A]
Ok, I figured it out:
```
```
SetSecurityInfo(hDir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, NULL, NULL);
```
```
This will give all permissions to all users for the given directory handle.


q:
MySQL 5.0.45

What is the syntax to alter a table to allow a column to be null, alternately what's wrong with this:

ALTER mytable MODIFY mycolumn varchar(255) null;

I interpreted the manual as  just run the above and it would recreate the column, this time allowing null. The server is telling me I have syntactical errors. I just don't see them.

[A]
You want the following:
```
```
ALTER TABLE mytable MODIFY mycolumn VARCHAR(255);
```
```
Columns are nullable by default.  As long as the column is not declared
```
UNIQUE
```
or
```
NOT NULL
```
, there shouldn't be any problems.


q: I have a django application that I'd like to add some rest interfaces to.  I've seen http://code.google.com/p/django-rest-interface/ but it seems to be pretty simplistic.  For instance it doesn't seem to have a way of enforcing security.  How would I go about limiting what people can view and manipulate through the rest interface?  Normally I'd put this kind of logic in my views.  Is this the right place or should I be moving some more logic down into the model?  Alternatively is there a better library out there or do I need to roll my own?

[A]
Well, from the look of things, there's an
```
authentication
```
parameter to
```
Collection
```
. (see this example:
authentication.py
)
Second, (even if Django doesn't have it yet,) there should probably be a middleware that does CSRF/XSRF form checking. (Oh, there seems to
be one
.) You should also be able to use the
```
login_required
```
and
```
permission_required
```
decorators
in the urls.py.


q:
What I want to do is the following:

read in multiple line input from stdin into variable A

make various operations on A

pipe A without losing delimiter symbols (\n,\r,\t,etc) to another command

The current problem is that, I can't read it in with read command, because it stops reading at newline.

I can read stdin with cat, like this:

my_var=`cat /dev/stdin`

, but then I don't know how to print it. So that the newline, tab, and other delimiters are still there.

My sample script looks like this:

#!/usr/local/bin/bash

A=`cat /dev/stdin`

if [ ${#A} -eq 0 ]; then
        exit 0
else
        cat ${A} | /usr/local/sbin/nextcommand
fi

[A]
This is working for me:
```
```
myvar=`cat`

echo "$myvar"
```
```
The quotes around
```
$myvar
```
are important.


q:
I have G729 encoded audio files. I need to programmatically convert them to WAV PCM (16bit 8kHz mono) in the flow of a tool that is doing other thing too. I have an executable that will do that for me. But spawning that external process every time I convert is too heavy on resources. Especially if I need many of them being done in parallel.
Looking for a .NET library or code that will let me call this inside my process.

[A]
According to Wikipedia, G.729 includes several patents and is licensed by
Sipra
, so you probably won't have much luck finding an appropriate lobrary.  Unless you're decoding a large number of very small files, the cost of spawning a new process shouldn't be that big compared to the cost of doing the decoding, so I'd say use the executable you have.
As far as resources go, yes, spawning processes requires a lot more resources compared to using threads.  This shouldn't really matter, though, so long as you only spawn as many processes as you have cores in your machine.  Spawning more processes just wastes resources and doesn't gain you any extra parallelism.


q:
I need a way to build C++ code from UML diagrams and vice versa.

Should be simple too hopefully. I don't mind paying too much.

[A]
You could try
Sparx Enterprise Architect
but the code quality would be average, not excellent.
I am not aware of any great automatic code generators for C++
Prices start from $135


q: I tried "x = y ** e", but that didn't work.

[A]
use the
```
pow
```
function (it takes
```
float
```
s/
```
double
```
s though).
```
man pow
```
:
```
```
#include <math.h>

   double pow(double x, double y);
   float powf(float x, float y);
   long double powl(long double x, long double y);
```
```
EDIT
: For the special case of positive integer powers of
```
2
```
, you can use bit shifting:
```
(1 << x)
```
will equal
```
2
```
to the power
```
x
```
. There are some potential gotchas with this, but generally, it would be correct.


q:
I have a class library with some extension methods written in C# and an old website written in VB.

I want to call my extension methods from the VB code but they don't appear in intelisense and I get compile errors when I visit the site.

I have got all the required Imports because other classes contained in the same namespaces are appearing fine in Intelisense.

Any suggestions

EDIT: More info to help with some comments.

my implementation looks like this

//C# code compiled as DLL
namespace x.y {
    public static class z {
        public static string q (this string s){
             return s + " " + s;
        }

    }
}

and my usage like this

Imports x.y

'...'
Dim r as string = "greg"
Dim s as string = r.q() ' does not show in intelisense
                        ' and throws error : Compiler Error Message: BC30203: Identifier expected.

[A]
Extension methods are just syntactic sugar for static methods. So
```
```
public static string MyExtMethod(this string s)
```
```
can be called in both VB.NET and C# with
```
```
MyExtMethod("myArgument")
```
```


q:
I've been trying to SSL working on my IW program for the last little while and I keep running up against the 'Could not load SSL Library'. I've followed every piece of advice I could find on the subject, but still no joy. I've tried the suggested DLLs in both the local directory and in system32.

Does anyone have a definitive answer about what OpenSSL DLLs I should be using? And what build of them? Or any other ideas at all?

Indy: updated to the most recent snapshot yesterday
IntraWeb: stock D2007 installed

This is running on a Vista machine, if that makes any difference.

TIA,

Trevor

[A]
You need the OpenSSL dlls (0.9.8i worked for me, but I'm not using Vista), which you can download
here
(as I think you're suggesting, the Indy dlls don't work with IW9, which is the version bundled with D2007).
After installation, copy ssleay32.dll and libeay32.dll from system32 to your application directory.
If it still doesn't work:
is your servercontroller's ssl port set to 443?
does your cert pw match your servercontroller's ssl cert pw?
is servercontroller.sslversion set to sslv23?
have you tried compiling/running the AtoZed demo application for SSL (standalonessl)?
Hope this helps.
EDIT: once you get this working, you'll want to change sslversion to sslv3, and get users to turn off v2.


q:
The general problem:

We have urls coming to our IIS web servers formatted like:

http://www.server.com/page.aspx

We are also seeing that urls like this are coming in:

http://www.server.com//page.aspx

We would like to get rid of that extra path character because when the user agent is Internet Explorer, this is resolving as 2 different pages, and thus, downloading the content twice when it should be resolved from a cache.

I am not sure if this is a problem to be solved with something like a url-rewriting module, or if there is a configuration setting.

[A]
Perhaps you need to enable it?
```
```
DBMS_AQADM.ENABLE_PROPAGATION_SCHEDULE(queue_name => 'Test_Q');
```
```


q: Is there a built-in/custom script available?

[A]
Although its maybe not really programing related you could try
Orca
.


q:
Umm, I guess my questions in the title:

How do I turn on Option Strict / Infer in a VB.NET aspx page without a code behind file?

<%@ Page Language="VB" %>
<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub
</script>

[A]
```
```
<%@ Page Language="VB" Strict="true" %>
```
```


q:
In my ideal world, what I'm looking for would exist as something along the lines of this:

public string UserDefinedField
{
    get { return _userDefinedField; }
    internal set { _userDefinedField = value; }
    set { _userDefinedField = value; ChangedFields.Add(Fields.UserDefinedField); }
}

Where one statement is executed regardless of the access modifier, and another statement is executed if it's called from an external assembly or class.

I'm sure I could code something by using reflection and checking up the current call stack to see if the caller is in the same assembly, but I'm looking to see if there's a more elegant approach than that.

[A]
```
```
public string UserDefinedField
{
    get { return _userDefinedField; }
    set { SetField(value); ChangedFields.Add(Fields.UserDefinedField); }
}

// Call this from internal methods and use the public property for other cases
internal string SetField(string userValue)
{
    _userDefinedField = userValue;
}
```
```
You
could
get the caller information by
examining the calling stack
but that is extremely slow (compared to the above) and I wouldn't recommend it.


q:
When I try to login to this site using my yahoo openid, it takes me to the yahoo site, I click "continue" meaning that i want to send my authentication details to stackoverflow.com and stackoverflow.com gives me the following error underneath the login text field:

Unable to log in with your OpenID provider:

failed to authenticate, returning Failed. Please ensure your identifier is correct and try again.