q:
How do people approach mocking out TcpClient (or things like TcpClient)?

I have a service that takes in a TcpClient.  Should I wrap that in something else more mockable?  How should I approach this?

[A]
When coming to mock classes that are not test friendly (i.e. sealed/not implementing any interface/methods are not virtual), you would probably want to use the
Adapter
design pattern.
In this pattern you add a wrapping class that implements an interface. You should then mock the interface, and make sure all your code uses that interface instead of the unfriendly concrete class. It would look something like this:
```
```
public interface ITcpClient
{
   Stream GetStream();
   // Anything you need here
}
public class TcpClientAdapter: ITcpClient
{
   private TcpClient wrappedClient;
   public TcpClientAdapter(TcpClient client)
   {
    wrappedClient = client;
   }

   public Stream GetStream()
   {
     return wrappedClient.GetStream();
   }
}
```
```


q:
I'm trying to use Exchange Web Services to update a calendar item.  I'm creating an ItemChangeType, and then an ItemIdType.  I have a unique ID to use for ItemIdType.Id, but I have nothing to use for the ChangeKey.  When I leave it out, I get an ErrorChangeKeyRequiredForWriteOperations.  But when i try to just put something in there, I get an ErrorInvalidChangeKey.

What can I use for this to get it to work?

I'm also trying to determine what is the best implementation of BaseItemIdType to use for ItemChangeType.Item.  So far, I'm using ItemIdType, and I'm guessing that's correct, but I haven't been able to find any particularly helpful documentation on this.

[A]
If you have the ItemIdType.Id property you should also have access to the Changekey, it's also a property of ItemIdType:
```
ItemIdType.ChangeKey
```
Like the Id property it's a string, so you can grab it when you grab the Id.
Regards
Jesper Hauge

s: huggingface

c: devops

d: intermediate


q: What do you insert into Python source code to have it break into pdb (when execution gets to that spot)?

[A]
```
```
import pdb; pdb.set_trace()
```
```
See
Python: Coding in the Debugger for Beginners
for this and more helpful hints.


q:
I have a website in which I provide tool-tips for certain things using a hidden <span> tag and JavaScript to track various mouse events. It works excellently. This site somewhat caters towards people with vision issues, so I try to make things degrade as well as possible if there is no JavaScript or CSS and generally I would say that it is successful in this regard.

So my question is, is it possible for these <span> to only exist if CSS is being used? I have thought about writing out the tool-tips in JavaScript on document load. But I was wondering if there is a better solution.

[A]
Perhaps you need to re-think the way you are providing tooltips.  Could the content be contained in the title attribute of a semantically appropriate element?
EDIT: If you provide more info, someone might be able to suggest more of a solution.  What sorts of elements are the tooltips popping up on?  Images?  Would the abbreviation tags be appropriate?
Quick Solution I just came up with:
```
<span>
```
has access to the
core attributes
, which include title, so you could include the tooltip text in the title, and use a javascript library like jQuery to display tooltips for all spans with a title.


q:
I'm wondering if there are any architectural frameworks out there to create desktop or standalone applications, in Java or C# for instance. It seems that there are tons of them available for web applications but I can't find many good resources on frameworks or architectural best-practices for desktop development.

Ideally I would like to know if there is any source code available of desktop applications that would be considered to have a good architecture or are built with a certain framework.

[A]
You can use some of the same approaches in client development that you use in web development, such as Model View Presenter. The System.Windows.Forms namespace has everything you need to build a client application in C#, with the rest of the .NET Framework available to provide the services you need (such as IO and remoting).
As far as source code for solid architectures in desktop apps, look at the code for
Paint.NET
and
SharpDevelop
. Both have very different approaches that will be interesting to you.
Sorry for the .NET slant of this reply. It's what I know best. :)


q:
With our next major release we are looking to globalize our ASP.Net application and I was asked to think of a way to keep track of what code has been already worked on in this effort.

My thought was to use a custom Attribute and place it on all classes that have been "fixed".

What do you think?

Does anyone have a better idea?

[A]
Using an attribute to determine which classes have been globalized would then require a tool to process the code and determine which classes have and haven't been "processed", it seems like it's getting a bit complicated.
A more traditional project tracking process would probably be better - and wouldn't "pollute" your code with attributes/other markup that have no functional meaning beyond the end of the globalisation project. How about having a defect raised for each class that requires work, and tracking it that way?


q:
I am currently defining regular expressions in order to capture parameters in a URL, as described in the tutorial. How do I access parameters from the URL as part the HttpRequest object?

My HttpRequest.GET currently returns an empty QueryDict object.

I'd like to learn how to do this without a library, so I can get to know Django better.

[A]
When a URL is like
```
domain/search/?q=haha
```
, you would use
```
request.GET.get('q', '')
```
.
```
q
```
is the parameter you want, and
```
''
```
is the default value if
```
q
```
isn't found.
However, if you are instead just configuring your
```
URLconf
```
**, then your captures from the
```
regex
```
are passed to the function as arguments (or named arguments).
Such as:
```
```
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
```
```
Then in your
```
views.py
```
you would have
```
```
def profile_page(request, username):
    # Rest of the method
```
```


q:
I've got a C# program that's supposed to play audio files.  I've figured out how to play any sound file for which Windows has a codec by using DirectShow, but now I want to properly fill in the file type filter box on the Open dialog.  I'd like to automatically list any file format for which Windows has a codec.  If some random user installs a codec for an obscure format, its associated extension(s) and file type description(s) need to show up in the list.

Any ideas?

[A]
If I remember correctly, a codec does not know which file types, i.e. file extensions, it supports, since a codec takes some stream as input and not actually a file. So if what you want is to display the file extensions of the supported audio file formats, you'll most likely be out of luck unless you have a extensive list of file extensions and associated codecs, but even then you'll get problems with container formats and all that.
For example, my Windows Media Player happily plays m4b files, but does not know anything about them. I had to manually associate it with the file type.


q:
I have a form in HTML where our users fill in the data and then print it.  The data isn't saved anywhere.  These forms come from outside our company and are built as html pages to resemble the original as closely as possible and then stuffed away and forgotten in a folder on the intranet.  Normally another developer does them, but I have to do a few while he's out.  Looking through his code, all his forms have a bunch of server-side code to take the inputs and re-write the page with only the contents.  It seems like there should be a better way.

I want to just style the text inputs using a media selector so that when it prints you can see the text, but nothing of the box surrounding it.  Any thoughts?

[A]
```
```
<input type="text" style="border: 0; background-color: #fff;" />
```
```
Where #fff is your background color..


q:
In the database I have a field named 'body' that has an XML in it. The
method I created in the model looks like this:

def self.get_personal_data_module(person_id)
    person_module = find_by_person_id(person_id)
    item_module = Hpricot(person_module.body)
    personal_info = Array.new
    personal_info = {:studies => (item_module/"studies").inner_html,
                            :birth_place => (item_module/"birth_place").inner_html,
                            :marrital_status => (item_module/"marrital_status").inner_html}
    return personal_info
end

I want the function to return an object instead of an array. So I can
use Module.studies instead of Model[:studies].

[A]
This is relatively simple; you're getting an Array because the code is building one. If you wanted to return an object, you'd do something like this:
```
```
class PersonalData
  attr_accessor :studies
  attr_accessor :birth_place
  attr_accessor :marital_status

  def initialize(studies,birth_place,marital_status)
    @studies = studies
    @birth_place = birth_place
    @marital_status = marital_status
  end
end
```
```
And your translation code would look like:
```
```
def self.get_personal_data_module(person_id)
  person_module = find_by_person_id(person_id)
  item_module = Hpricot(person_module.body)
  personal_info = PersonalData.new((item_module/"studies").inner_html,
                                   (item_module/"birth_place").inner_html,
                                   (item_module/"marital_status").innner_html)
  return personal_info
end
```
```


q: This is an almost-duplicate of Send file using POST from a Python script, but I'd like to add a caveat: I need something that properly handles the encoding of fields and attached files. The solutions I've been able to find blow up when you throw unicode strings containing non-ascii characters into the mix. Also, most of the solutions don't base64-encode data to keep things 7-bit clean.

[A]
Best thing I can think of is to encode it yourself.  How about this subroutine?
```
```
from urllib2 import Request, urlopen
from binascii import b2a_base64

def b64open(url, postdata):
  req = Request(url, b2a_base64(postdata), headers={'Content-Transfer-Encoding': 'base64'})
  return urlopen(req)

conn = b64open("http://www.whatever.com/script.cgi", u"Liberté Égalité Fraternité")
# returns a file-like object
```
```
(Okay, so this code just sends POST-data.  But you apparently want multipart-encoded data, as if you clicked an "Upload File" button, right?  Well, it's a pretty straightforward combination of what I have here and the answers from the question you linked.)


q:
Using Restlet I needed to serve some simple static content in the same context as my web service. I've configured the component with a Directory, but in testing, I've found it will only serve 'index.html', everything else results in a 404.

router.attach("/", new Directory(context, new Reference(baseRef, "./content"));

So... http://service and http://service/index.html both work,

but http://service/other.html gives me a 404

Can anyone shed some light on this? I want any file within the ./content directory to be available.

PS: I eventually plan to use a reverse proxy and serve all static content off another web server, but for now I need this to work as is.


q: How do you remove the jagged edges from a wide button in internet explorer?  For example:

[A]
As a workaround, you can remove the blank spaces on each end of the button, which has the effect of decreasing the jagged edges. This is accomplished with the following css and a bit of jQuery:
```
```
input.button {
   padding: 0 .25em;
   width: 0; /* for IE only */
   overflow: visible;
}

input.button[class] { /* IE ignores [class] */
    width: auto;
}
```
```
```
```
$(function(){
    $('input[type=button]').addClass('button');
});
```
```
The jQuery is for adding the button class. A more in depth write up can be found
here
.


q: I've used asp.net profiles (using the AspNetSqlProfileProvider) for holding small bits of information about my users. I started to wonder how it would handle a robust profile for a large number of users. Does anyone have experience using this on a large website with large numbers of simultaneous users? What are the performance implications? How about maintenance?


q:
In C, is it possible to forward the invocation of a variadic function? As in,

int my_printf(char *fmt, ...) {
    fprintf(stderr, "Calling printf with fmt %s", fmt);
    return SOMEHOW_INVOKE_LIBC_PRINTF;
}

Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.

[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function without modifying that function's definition.]

[A]
Use vfprintf:
```
```
int my_printf(char *fmt, ...) {
    va_list va;
    int ret;

    va_start(va, fmt);
    ret = vfprintf(stderr, fmt, va);
    va_end(va);
    return ret;
}
```
```


q: In C# code can you catch a native exception thrown from deep in some unmanaged library? If so do you need to do anything differently to catch it or does a standard try...catch get it?

[A]
If you use a
```
```
try
{

}
catch(Exception ex)
{

}
```
```
it will catch ALL exceptions, depending on how you call the external libraries you might get a com related exception that encapsulates the error but it will catch the error.


q: If I have an instance of a System.Timers.Timer that has a long interval - say 1 minute, how can I find out if it is started without waiting for the Tick?

[A]
```
System.Timer.Timer.Enabled
```
should work, when you call "Start" it sets Enabled to TRUE, "Stop" sets it to FALSE.


q: Where can I test HTML 5 functionality today - is there any test build of any rendering engines which would allow testing, or is it to early? I'm aware that much of the spec hasn't been finalised, but some has, and it would be good to try it out!

[A]
Ones that are built using a recent webkit build, and Presto.
Safari 3.1 for webkit
Opera for Presto.
I'm pretty sure firefox will start supporting html5 partially in 3.1
All support is extremely partial. Check
here for information on what is supported.


q:
I have a website laid out in tables. (a long mortgage form)

in each table cell is one HTML object. (text box, radio buttons, etc)

What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?

[A]
Possibly:
```
```

<input type="..." onfocus="getParent(this,'td').style.backgroundColor='#400';" onblur="getParent(this,'td').style.backgroundColor='';">

```
```


q:
I'm trying to do this

SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` NOT IN ('Do not get this one'|'or this one');

But it doesn't seem to work.

How do I get all the values, except for a select few, without doing this:

SELECT `Name`,`Value` FROM `Constants`
WHERE `Name` != 'Do not get this one'
AND `Name` != 'or this one'

The first one works with int values, but doesn't work with varchar, is there a syntax like the first one, that performs like the second query?

[A]
It's
```
IN('foo', 'bar')
```
, with a comma, not a pipe.


q: I'm trying to create a new Excel file using jxl, but am having a hard time finding examples in their API documentation and online.

[A]
Not sure if you need to stick with JXL, but the best library for handling Excel files is
Apache's POI HSSF
.
I think there are plenty of examples on the website I provided, but if you need further assistence, let me know. I may have a few examples laying around.
Just out of curiosity, POI stands for Poor Obfuscation Interface and HSSF is Horrible SpreadSheet Format. You see how much Apache loves Microsoft Office formats :-)


q:
Do you use any of these technologies? Which ones are current and hence sensible to include in a site?

Documentation on any seems to be relatively sparse, and usage of any of them limited, as search engines get better, are they even relevant any more?

[A]
I use microformats whenever I can.  Usually it just makes sense anyway, as frequently when I have an address block, I may want to style some elements differently then other elements, and that makes it super easy.  It's not like microformats are that hard to figure out.
There has been a couple of instances where, because I was using a microformat, I was able to re-use the markup of a certain portion of a site somewhere else (as an include), and not have to change the markup, only the styling.
Finally, ever since I really stated exploring microformats, I got better at writing semantic markup and better at naming CSS classes.


q: It seems like Sql Reporting Services Server logs information in several places including web server logs and logging tables in the database. Where are all the locations SSRS logs to, and what type of errors are logged in each place?

[A]
As far as I know SSRS logs to the Event Log, the filesystem and its own database.
The database is typically the most easily available one. You just login to the ReportServer database and execute
```
```
select * from executionlog
```
```
This only logs the executions though. If you want more information you can go to the Trace Log files, which are usually available at (location may of course vary):
```
```
C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\LogFiles
```
```
These are quite verbose and not really fun to look through. But they do log a lot of stuff.
If you're searching for an error you can go to the Windows Application Log (Under Administrative Tools in your control panel)
Edit
Found a nice link:
https://learn.microsoft.com/en-us/sql/reporting-services/report-server/reporting-services-log-files-and-sources


q: I would like to write some data to a file in Ruby. What is the best way to do that?

[A]
```
```
filey = File.new("/path/to/the/file", APPEND)
filey.puts "stuff to write"
```
```


q: I'm working on a qnx device, and I want to be able to ssh into it.  Does anyone have a primer on getting something like openSSH up and running?

[A]
Open Source Applications for QNX
provides ported open source
  tools/applications including their
  complete sources and/or ready to use
  binaries for QNX, like XFree86,
  Lesstif, DDD, VNC, Nedit and cluster
  middleware like PVM.
I have no idea what that means, but I hope it gives you something to start with.


q:
Let me first say that being able to take 17 million records from a flat file, pushing to a DB on a remote box and having it take 7 minutes is amazing. SSIS truly is fantastic. But now that I have that data up there, how do I remove duplicates?

Better yet, I want to take the flat file, remove the duplicates from the flat file and put them back into another flat file.

I am thinking about a:

Data Flow Task

File source (with an associated file connection)

A for loop container

A script container that contains some logic to tell if another row exists

Thak you, and everyone on this site is incredibly knowledgeable.

Update: I have found this link, might help in answering this question

[A]
I would suggest using SSIS to copy the records to a temporary table, then create a task that uses Select Distinct or Rank depending on your situation to select the duplicates which would funnel them to a flat file and delete them from the temporary table.  The last step would be to copy the records from the temporary table into the destination table.
Determining a duplicate is something SQL is good at but a flat file is not as well suited for.  In the case you proposed, the script container would load a row and then would have to compare it against 17 million records, then load the next row and repeat...The performance might not be all that great.


q:
I have a file that lists filenames, each on it's own line, and I want to test if each exists in a particular directory. For example, some sample lines of the file might be

mshta.dll
foobar.dll
somethingelse.dll

The directory I'm interested in is X:\Windows\System32\, so I want to see if the following files exist:

X:\Windows\System32\mshta.dll
X:\Windows\System32\foobar.dll
X:\Windows\System32\somethingelse.dll

How can I do this using the Windows command prompt? Also (out of curiosity) how would I do this using bash or another Unix shell?

[A]
In Windows:
```
```
type file.txt >NUL 2>NUL
if ERRORLEVEL 1 then echo "file doesn't exist"
```
```
(This may not be the best way to do it; it is a way I know of; see also
http://blogs.msdn.com/oldnewthing/archive/2008/09/26/8965755.aspx
)
In Bash:
```
```
if ( test -e file.txt ); then echo "file exists"; fi
```
```


q:
My company is heavily invested in the MS BI Stack (SQL Server Reporting Services, -Analysis Services and -Integration Services), but I want to have a look at what the seemingly most talked about open-source alternative Pentaho is like.

I've installed a version, and I got it up and running quite painlessly. So that's good. But I haven't really the time to start using it for actual work to get a thorough understanding of the package.

Have any of you got any insights into what are the pros and cons of Pentaho vs MS BI, or any links to such comparisons?

Much appreciated!

[A]
I can't offer any input on the MS BI Stack but at the most recent
Barcamp Orlando
, the folks from Pentaho were there and spoke about their products and it was an extremely impressive demo.
The fact that it's an Open Source project that you can extend yourself as well as a paid package for really good service leaves you with a lot of options.  They demonstrated some paid work they did for a client and they definitely wow'd the crowd.
I also had a chance to chat a little bit with a developer working on the data warehousing side of things for Pentaho and he was extremely sharp and was very open to suggestions and had no problems answering any questions.
So as far as a company goes, Pentaho really impressed me with both their work and how friendly and approachable all of their developers were.


q: I'd like to get at least one JRE/JDK level on my Windows machine where I have the JRE/JDK source that matches the exact level of the JRE/JDK. My purpose is to be able to go into the system classes while debugging. Any suggestions about how to do this? Thanks in advance.

[A] The source code is included in the JDK 1.5+ installer. Just make sure that the option is not unchecked while installing.


q:
I am creating a Windows Forms control derived from UserControl to be embedded in a WPF app. I have generally followed the procedures given in this link.

public ref class CTiledImgViewControl : public UserControl
{
...

virtual void OnPaint( PaintEventArgs^ e ) override;

...
};

And in my CPP file:

void CTiledImgViewControl::OnPaint( PaintEventArgs^ e )
{
    UserControl::OnPaint(e);
    // do something interesting...
}

Everything compiles and runs, however the OnPaint method is never getting called.

Any ideas of things to look for? I've done a lot with C++, but am pretty new to WinForms and WPF, so it could well be something obvious...

[A]
The
```
OnPaint
```
won't normally get called in a
```
UserControl
```
unless you set the appropriate style when it is constructed using the
```
SetStyle
```
method. You need to set the
```
UserPaint
```
style to true for the
```
OnPaint
```
to get called.
```
```
SetStyle(ControlStyles::UserPaint, true);
```
```
Update
I recently encountered this issue myself and went digging for an answer. I wanted to perform some calculations during a paint (to leverage the unique handling of paint messages) but I wasn't always getting a call to
```
OnPaint
```
.
After digging around with Reflector, I discovered that
```
OnPaint
```
is only called if the clipping rectangle of the corresponding
```
WM_PAINT
```
message is not empty. My
```
UserControl
```
instance had a child control that filled its entire client region and therefore, clipped it all. This meant that the clipping rectangle was empty and so no
```
OnPaint
```
call.
I worked around this by overriding
```
WndProc
```
and adding a handler for
```
WM_PAINT
```
directly as I couldn't find another way to achieve what I wanted.


q:
Anyone know a good Regex expression to drop in the ValidationExpression to be sure that my users are only entering ASCII characters?

<asp:RegularExpressionValidator id="myRegex" runat="server" ControlToValidate="txtName" ValidationExpression="???" ErrorMessage="Non-ASCII Characters" Display="Dynamic" />

[A]
If you want to map the possible 0x00 - 0xff ASCII values you can use this regular expression (.NET).
```
```
^([\x00-\xff]*)$
```
```


q:
How can an object be loaded via Hibernate based on a field value of a member object? For example, suppose the following classes existed, with a one-to-one relationship between bar and foo:

Foo {
    Long id;
}

Bar {
    Long id;
    Foo aMember;
}

How could one use Hibernate Criteria to load Bar if you only had the id of Foo?

The first thing that leapt into my head was to load the Foo object and set that as a Criterion to load the Bar object, but that seems wasteful. Is there an effective way to do this with Criteria, or is HQL the way this should be handled?

[A]
You can absolutely use Criteria in an efficient manner to accomplish this:
```
```
session.createCriteria(Bar.class).
        createAlias("aMember", "a").
        add(Restrictions.eq("a.id", fooId));
```
```
ought to do the trick.


q:
I'm used to doing basic password protection for Apache w/ the following method in Apache config files:

AuthType Basic

  AuthName "By Invitation Only"

  AuthUserFile /path/to/.htpasswd

  Require valid-user

However, I've been asked to put some protection on a subdirectory of a site running ColdFusion on top of IIS6, and I'm unfamiliar with how to do this.  How is this done?  What should I look out for?  I just need to password protect an administrative subdirectory, so I don't need a full user login system - just something that limits who can access the section of the site.

[A] You can go into IIS 6 and the properties for your website's folder you want to protect. Click directory security tab and uncheck allow anonymous. Then you need to choose an authntication type. If its over SSL you can use basic, otherwise use another type. But since you mention basic, this may suffice regardless. Keep in mind basic auth will send password in plain text. Thsi will ask for a windows login in order to access that folder. You can create a limited wondows account for this purpose, reagrdless if its on the domain or local.One more thing, wether you use an existing account or create a new account make sure this folder has at least read permission to the folder and its sub folders.


q:
What is the best way to replace all '&lt' with &lt; in a given database column? Basically perform s/&lt[^;]/&lt;/gi

Notes:

must work in MS SQL Server 2000

Must be repeatable (and not end up with &lt;;;;;;;;;;)

[A]
Some hacking required but we can do this with
LIKE
,
PATINDEX
,
LEFT
AND
RIGHT
and good old string concatenation.
```
```
create table test
(
    id int identity(1, 1) not null,
    val varchar(25) not null
)

insert into test values ('< <- ok, &lt <- nok')

while 1 = 1
begin
    update test
        set val = left(val, patindex('%&lt[^;]%', val) - 1) +
                      '<' +
                      right(val, len(val) - patindex('%&lt[^;]%', val) - 2)
    from test
    where val like '%&lt[^;]%'

    IF @@ROWCOUNT = 0 BREAK
end

select * from test
```
```
Better is that this is SQL Server version agnostic and should work just fine.


q: In my ActionScript3 class, can I have a property with a getter and setter?

[A]
Ok, well you can just use the basic getter/setter syntax for any property of your AS3 class.  For example
```
```
package {

    public class PropEG {

        private var _prop:String;

        public function get prop():String {
            return _prop;
        }

        public function set prop(value:String):void {
            _prop = value;
        }
    }
}
```
```


q: How can I create an Excel spreadsheet with C# without requiring Excel to be installed on the machine that's running the code?

[A]
You actually might want to check out the interop classes available in C# (e.g.
```
Microsoft.Office.Interop.Excel
```
. You say no OLE (which this isn't), but the interop classes are very easy to use. Check out the
C# Documentation here
(Interop for Excel starts on page 1072 of the C# PDF).
You might be impressed if you haven't tried them.
Please be warned of Microsoft's
stance
on this:
Microsoft does not currently recommend, and does not support,
  Automation of Microsoft Office applications from any unattended,
  non-interactive client application or component (including ASP,
  ASP.NET, DCOM, and NT Services), because Office may exhibit unstable
  behavior and/or deadlock when Office is run in this environment.


q:
sqlite> DELETE FROM mails WHERE (`id` = 71);
SQL error: database is locked

How do I unlock the database so this will work?

[A] the SQLite db files are just files, so the first step would be to make sure it isn't read-only.  The other thing to do is to make sure that you don't have some sort of GUI SQLite DB viewer with the DB open.  You could have the DB open in another shell, or your code may have the DB open.  Typically you would see this if a different thread, or application such as SQLite Database Browser has the DB open for writing.


q:
When I load script/console, sometimes I want to play with the output of a controller or a view helper method.

Are there ways to:

simulate a request?

call methods from a controller instance on said request?

test helper methods, either via said controller instance or another way?

[A]
Here's one way to do this through the console:
```
```
>> foo = ActionView::Base.new
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>

>> foo.extend YourHelperModule
=> #<ActionView::Base:0x2aaab0ac2af8 @assigns_added=nil, @assigns={}, @helpers=#<ActionView::Base::ProxyModule:0x2aaab0ac2a58>, @controller=nil, @view_paths=[]>

>> foo.your_helper_method(args)
=> "<html>created by your helper</html>"
```
```
Creating a new instance of
```
ActionView::Base
```
gives you access to the normal view methods that your helper likely uses.  Then extending
```
YourHelperModule
```
mixes its methods into your object letting you view their return values.


q:
I'm trying to figure out the best way to determine whether I'm in the last iteration of a loop over a map in order to do something like the following:

for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
    bool last_iteration;
    // do something for all iterations
    if (!last_iteration) {
        // do something for all but the last iteration
    }
}

There seem to be several ways of doing this: random access iterators, the distance function, etc. What's the canonical method?

Edit: no random access iterators for maps!

[A]
This seems like the simplest:
```
```
bool last_iteration = iter == (--someMap.end());
```
```


q:
In .NET, under which circumstances should I use GC.SuppressFinalize()?

What advantage(s) does using this method give me?

[A]
That method must be called on the
```
Dispose
```
method of objects that implements the
```
IDisposable
```
, in this way the GC wouldn't call the finalizer another time if someones calls the
```
Dispose
```
method.
See:
GC.SuppressFinalize(Object) Method - Microsoft Docs


q:
Having this route:

map.foo 'foo/*path', :controller => 'foo', :action => 'index'

I have the following results for the link_to call

link_to "Foo", :controller => 'foo', :path => 'bar/baz'
# <a href="/foo/bar%2Fbaz">Foo</a>

Calling url_for or foo_url directly, even with :escape => false, give me the same url:

foo_url(:path => 'bar/baz', :escape => false, :only_path => true)
# /foo/bar%2Fbaz

I want the resulting url to be: /foo/bar/baz

Is there a way around this without patching rails?

[A]
Instead of passing path a string, give it an array.
```
```
link_to "Foo", :controller => 'foo', :path => %w(bar baz)
# Foo
```
```
If you didn't have the route in your routes file, this same link_to would instead create this:
```
```
# Foo
```
```
The only place I could find this documented is in
this ticket
.


q:
I have two tables that are joined together.

A has many B

Normally you would do:

select * from a,b where b.a_id = a.id

To get all of the records from a that has a record in b.

How do I get just the records in a that does not have anything in b?

[A]
```
```
select * from a where id not in (select a_id from b)
```
```
Or like some other people on this thread says:
```
```
select a.* from a
left outer join b on a.id = b.a_id
where b.a_id is null
```
```


q:
Which one should I use?

catch (_com_error e)

or

catch (_com_error& e)

[A]
The second.  Here is my attempt at quoting Sutter
"Throw by value, catch by reference"
Learn to
```
catch
```
properly: Throw exceptions by value (not pointer) and
  catch them by reference (usually to
```
const
```
). This is the combination
  that meshes best with exception semantics. When rethrowing the same
  exception, prefer just
```
throw;
```
to
```
throw e;
```
.
Here's the full
Item 73. Throw by value, catch by reference.
The reason to avoid catching exceptions by value is that it implicitly makes a copy of the exception. If the exception is of a subclass, then information about it will be lost.
```
```
try { throw MyException ("error") }
catch (Exception e) {
    /* Implies: Exception e (MyException ("error")) */
    /* e is an instance of Exception, but not MyException */
}
```
```
Catching by reference avoids this issue by not copying the exception.
```
```
try { throw MyException ("error") }
catch (Exception& e) {
    /* Implies: Exception &e = MyException ("error"); */
    /* e is an instance of MyException */
}
```
```


q:
I encountered the following ddl in a pl/sql script this morning:

create index genuser.idx$$_0bdd0011
...

My initial thought was that the index name was generated by a tool...but I'm also not a pl/sql superstar so I could very well be incorrect. Does the double dollar sign have any special significance in this statement?

[A]
No special meaning or significance.
```
```
SQL> create table t (col number)
  2  /

Table created.

SQL> create index idx$$_0bdd0011 on t(col)
  2  /

Index created.
```
```
Note: CREATE INDEX is a DDL statement which is usually executed in a SQL script, not in PL/SQL.


q:
I have a bunch of tasks in a MySQL database, and one of the fields is "deadline date". Not every task has to have to a deadline date.

I'd like to use SQL to sort the tasks by deadline date, but put the ones without a deadline date in the back of the result set. As it is now, the null dates show up first, then the rest are sorted by deadline date earliest to latest.

Any ideas on how to do this with SQL alone? (I can do it with PHP if needed, but an SQL-only solution would be great.)

Thanks!

[A]
```
```
SELECT foo, bar, due_date FROM tablename
ORDER BY CASE ISNULL(due_date, 0)
WHEN 0 THEN 1 ELSE 0 END, due_date
```
```
So you have 2 order by clauses. The first puts all non-nulls in front, then sorts by due date after that


q: If I have two dates (ex. '8/18/2008' and '9/26/2008'), what is the best way to get the number of days between these two dates?

[A]
If you have two date objects, you can just subtract them, which computes a
```
timedelta
```
object.
```
```
from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
```
```
The relevant section of the docs:
https://docs.python.org/library/datetime.html
.
See
this answer
for another example.


q:
I need to get the actual local network IP address of the computer (e.g. 192.168.0.220) from my program using C# and .NET 3.5. I can't just use 127.0.0.1 in this case.

How can I accomplish this?

[A]
In
How to get IP addresses in .NET with a host name
by John Spano, it says to add the
```
System.Net
```
namespace, and use the following code:
```
```
//To get the local IP address
string sHostName = Dns.GetHostName ();
IPHostEntry ipE = Dns.GetHostByName (sHostName);
IPAddress [] IpA = ipE.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
    Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
}
```
```


q:
It seems that I've never got this to work in the past. Currently, I KNOW it doesn't work.

But we start up our Java process:

-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=6002
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

I can telnet to the port, and "something is there" (that is, if I don't start the process, nothing answers, but if I do, it does), but I can not get JConsole to work filling in the IP and port.

Seems like it should be so simple, but no errors, no noise, no nothing. Just doesn't work.

Anyone know the hot tip for this?

[A]
Are you running on Linux? Perhaps the management agent is binding to localhost:
http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1


q:
movie id tt0438097 can be found at http://www.imdb.com/title/tt0438097/

What's the url for its poster image?

[A]
The URL is a random string as far as I can tell.
It can still be easily retrieved. It is the only
```
img
```
inside the anchor named
```
poster
```
.
So, if you are reading the source, simply search for
```
<a name="poster"
```
and it will be the text following the first
```
src="
```
from there.
However, you will need to keep the screen scraping code updated because that will probably change.
You should also be aware that the images are copyrighted, so be careful to only use the image under a good "fair use" rationale.


q: Is it possible to use system.currency. It says system.currency is inaccessible due to its protection level. what is the alternative of currency.

[A]
You have to use
Decimal
data type..
The decimal keyword indicates a 128-bit data type. Compared to floating-point types, the decimal type has more precision and a smaller range, which makes it appropriate for financial and monetary calculations.


q:
I'm looking for a cross-browser method - I know IE has something (I've already forgotten what), and the way to do it in Mozilla may have to do with a focusNode thing I found, that seems related to getting text selections.

Methods involving jQuery or another common JS library are fine by me.

Thanks!

[A]
OK then, so use jQuery.
There is no current, available way to just ask this. You need to track the focus events when they happen, so this sample (thanks to Karl Rudd
here
) does that across all elements. This is for inputs but you can adjust the selector to fit your needs, even across the entire DOM.
```
```
var currentFocus = null;
$(':input').focus( function() {
    currentFocus = this;
}).blur( function() {

    currentFocus = null;
});
```
```


q:
How can I add an instance variable to a defined class at runtime, and later get and set its value from outside of the class?

I'm looking for a metaprogramming solution that allows me to modify the class instance at runtime instead of modifying the source code that originally defined the class.  A few of the solutions explain how to declare instance variables in the class definitions, but that is not what I am asking about.

[A]
Ruby provides methods for this,
```
instance_variable_get
```
and
```
instance_variable_set
```
. (
docs
)
You can create and assign a new instance variables like this:
```
```
>> foo = Object.new
=> #<Object:0x2aaaaaacc400>

>> foo.instance_variable_set(:@bar, "baz")
=> "baz"

>> foo.inspect
=> #<Object:0x2aaaaaacc400 @bar=\"baz\">
```
```


q: What are my options?  I tried MonoDevelop over a year ago but it was extremely buggy.  Is the latest version a stable development environment?

[A]
Is the latest version stable a stable development environment?
Probably ... it hit 1.0 this past spring.


q: Does anyone know any good tool that I can use to perform stress tests on a video streaming server? I need to test how well my server handles 5,000+ connections.

[A] start downloading 5000+ files of the same type with different connections.  Don't really need to play them, because essentially the client video player, flash, windows media player, etc. will just be doing a download.  So if you server can handle 5000+ downloads you will be fine.  My bet is your bandwidth gives out before you server.


q:
I have a function pointer defined by:

typedef void (*EventFunction)(int nEvent);

Is there a way to handle that function with a specific instance of a C++ object?

class A
{
private:
    EventFunction handler;

public:
    void SetEvent(EventFunction func) { handler = func; }

    void EventOne() { handler(1); }
};

class B
{
private:
    A a;
public:
    B() { a.SetEvent(EventFromA); }  // What do I do here?

    void EventFromA(int nEvent) { // do stuff }
};

Edit: Orion pointed out the options that Boost offers such as:

boost::function<int (int)> f;
X x;
f = std::bind1st(
      std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)

Unfortunately Boost is not an option for me.  Is there some sort of "currying" function that can be written in C++ that will do this kind of wrapping of a pointer to a member function in to a normal function pointer?

[A]
Unfortunately, the EventFunction type cannot point to a function of B, because it is not the correct type. You could make it the correct type, but that probably isn't really the solution you want:
```
typedef void (*B::EventFunction)(int nEvent);
```
... and then everything works once you call the callback with an obhect of B. But you probably want to be able to call functions outside of B, in other classes that do other things. That is sort of the point of a callback. But now this type points to something definitely in B. More attractive solutions are:
Make B a base class, then override a virtual function for each other class that might be called. A then stores a pointer to B instead of a function pointer. Much cleaner.
If you don't want to bind the function to a specific class type, even a base class (and I wouldn't blame you), then I suggest you make the function that gets called a static function: "
```
static void EventFrom A(int nEvent);
```
". Then you can call it directly, without an object of B. But you probably want it to call a specific instance of B (unless B is a singleton).
So if you want to be able to call a specific instance of B, but be able to call non-B's, too, then you need to pass something else to your callback function so that the callback function can call the right object. Make your function a static, as above, and add a void* parameter which you will make a pointer to B.
In practice you see two solutions to this problem: ad hoc systems where you pass a void* and the event, and hierarchies with virtual functions in a base class, like windowing systems


q: I have a web service API. Some calls return objects containing text fields with information provided by the user. From both a design and a security standpoint, what are the downsides to returning null in those fields when no information has been provided? Is there a clear advantage to always returning an empty string instead, other then simplifying the API by not requiring the client code to check for nulls?

[A]
I don't think there's a security issue involved with returning null vs. returning an empty string.
There's not any real downside to returning null for those fields for which there is no information - that's kind of what nulls are meant to indicate.
You can simplify your client code by using
```
```
string.IsNullOrEmpty()
```
```
(assuming this is .NET)


q: In .NET, what is the difference between String.Empty and "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?

[A]
In .NET prior to version 2.0,
```
""
```
creates an object while
```
string.Empty
```
creates no object
ref
, which makes
```
string.Empty
```
more efficient.
In version 2.0 and later of .NET, all occurrences of
```
""
```
refer to the same string literal, which means
```
""
```
is equivalent to
```
.Empty
```
, but still not as fast as
```
.Length == 0
```
.
```
.Length == 0
```
is the fastest option, but
```
.Empty
```
makes for slightly cleaner code.
See the
.NET specification for more information
.


q:
I am converting an excel sheet formula to java but I can't understand how excel manages to take the following: 0.22
Applies a formula: =TEXT(R5/14, "h:mm")
and somehow arrives at: 0.22

Again if I provide: 2.8
it arrives at 4.48
Can someone please explain to me how it does this. I have read a little regarding decimal and I understand the conversion but this hasn't yet helped to explain the above.

[A]
Yeah it is a bit goofy.  Take the /14 out and that helps.  Basically 1=1 day so R5 is expressed in 14ths of a day.  You could probably do
```
```
int msInADay= 86400000;
Time value = new Time(R5/14 * msInADay);
```
```
but it is untested.


q:
I came from Java, and now I am working more with Ruby.

One language feature I am not familiar with is the module. I am wondering what exactly is a module and when do you use one, and why use a module over a class?

[A]
Basically, the module cannot be instantiated. When a class includes a module, a proxy superclass is generated that provides access to all the module methods as well as the class methods.
A module can be included by multiple classes. Modules cannot be inherited, but this "mixin" model provides a useful type of "multiple inheritrance". OO purists will disagree with that statement, but don't let purity get in the way of getting the job done.
(This answer originally linked to
```
http://www.rubycentral.com/pickaxe/classes.html
```
, but that link and its domain are no longer active.)


q: It is unclear to me from the MSDN documentation if I should provide a deep or a shallow clone when implementing ICloneable. What is the preferred option?

[A]
Clones are deep by default, thats the naming convention
and copy constructors can be shallow if they want, for performance reasons.
Edit: This naming convention goes beyond boundaries, its the same for .Net, Java, C++, Javascript, etc... the actual source is beyond my knowledge but its part of the standard Object Oriented lexicon, just like objects, and classes. Thus MSDN doesn't specify implementation because its a given by the word itself (of course lots of newcomers to OO languages don't know this, and they SHOULD specify it, but then again their documentation is quite frugal anyways)


q:
I'm looking for a cross-browser method of detecting that a client web browser is scrolled all the way to the bottom (or top) of the screen.

Really, the top is fairly easy, as

    scrY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop

is zero if you're at the top.  The problem is that scrY seems to return the top of the scroll bar, and not the bottom, so instead of getting something equivalent to the height of the document (in pixels) I what is presumably the height of the document less the size of the scroll bar.

Is there an easy, cross-browser way to find out if the user has scrolled down to the bottom of the document/window?  Most specifically, I understand general scroll bar manipulation (setting it, moving it, etc.) but how can I get the delta of the bottom of the scrollbar's position relative to the bottom of the window/document.

[A]
http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
http://www.sitepoint.com/article/preserve-page-scroll-position/
http://codepunk.hardwar.org.uk/ajs02.htm
In order to ensure that an element is visible, you can use the
.scrollIntoView method


q: I need to get the fully expanded hostname of the host that my Ruby script is running on.  In Perl I've used Sys::Hostname::Long with good results.  Google seems to suggest I should use Socket.hostname in ruby, but that's returning just the nodename, not the full hostname.

[A]
This seems to work:
```
```
hostname = Socket.gethostbyname(Socket.gethostname).first
```
```


q:
About a year ago, I picked up Scott Ambler's Refactoring Databases: Evolutionary Database Design. I was won over to the idea that just as you can develop your code with TDD, you probably should be covering your databases with unit tests (at least) or even writing database tests before you make a change to the schema so you do database work in a TDD style as well.

I really like the idea, and I have been doing this (OK, sometimes I do it) by hand for a while now, just writing regular unit tests that happen to connect to the database and check its structure against a given schema file. But I haven't found any good database change management tool-kits that might help automate this process. Does anyone know any?

[A]
I only know of two unit testing frameworks:
DBUnit
TSQLUnit
As for change management, these are some recommended tools:
Redgate SQL Compare
ApexSQL
Toad
Although I am not sure if this is really what you're looking for.


q:
I'm a huge fan of bzr and I'm glad they're working on tortoise for it, but currently it's WAY too slow to be useful.  The icons are almost always incorrect and when I load a directory in explorer with a lot of branches it locks up my entire system for anywhere from 10 seconds to 2 minutes.  I look forward to trying it again in the future, but for now I'd like to disable it.

Unfortunately I don't see it in add/remove programs and I can't find a way to disable it in the bazaar config directory.  When I right click the icon in the task panel (by the clock) and choose "Exit Program" it just restarts moments later.  I don't see it in the Services panel either.  Is there any way to disable it?

I'm running Windows XP on the system in question.

[A]
According to the
TortoiseBZR readme
, you can disable it by running
```
```
python tortoise-bzr.py --unregister
```
```
from the install folder.  Not sure where it's installed by default, but it looks like that might be in your Python site-packages folder.


q: How do you detect if Socket#close() has been called on a socket on the remote side?

[A]
The
```
isConnected
```
method won't help, it will return
```
true
```
even if the remote side has closed the socket. Try this:
```
```
public class MyServer {
    public static final int PORT = 12345;
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
        Socket s = ss.accept();
        Thread.sleep(5000);
        ss.close();
        s.close();
    }
}

public class MyClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
        System.out.println(" connected: " + s.isConnected());
        Thread.sleep(10000);
        System.out.println(" connected: " + s.isConnected());
    }
}
```
```
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an
```
IOException
```
(broken pipe) will be thrown) on the associated Input/OutputStreams.


q: In PHP5, is the __destruct() method guaranteed to be called for each object instance? Can exceptions in the program prevent this from happening?

[A]
The destructor will be called when the all references are freed, or when the script terminates.  I assume this means when the script terminates properly.  I would say that critical exceptions would not guarantee the destructor to be called.
The
PHP documentation
is a little bit thin, but it does say that Exceptions in the destructor will cause issues.


q:
I'm looking for a tool that will, in bulk, add a license header to some source files, some of which already have the header.  Is there a tool out there that will insert a header, if it is not already present?

Edit: I am intentionally not marking an answer to this question, since answers are basically all environment-specific and subjective

[A]
Python 2 solution, modify for your own need
Features:
handles UTF headers (important for most IDEs)
recursively updates all files in target directory passing given mask (modify the .endswith parameter for the filemask of your language (.c, .java, ..etc)
ability to overwrite previous copyright text (provide old copyright parameter to do this)
optionally omits directories given in the
```
excludedir
```
array
```
```
# updates the copyright information for all .cs files
# usage: call recursive_traversal, with the following parameters
# parent directory, old copyright text content, new copyright text content

import os

excludedir = ["..\\Lib"]

def update_source(filename, oldcopyright, copyright):
    utfstr = chr(0xef)+chr(0xbb)+chr(0xbf)
    fdata = file(filename,"r+").read()
    isUTF = False
    if (fdata.startswith(utfstr)):
        isUTF = True
        fdata = fdata[3:]
    if (oldcopyright != None):
        if (fdata.startswith(oldcopyright)):
            fdata = fdata[len(oldcopyright):]
    if not (fdata.startswith(copyright)):
        print "updating "+filename
        fdata = copyright + fdata
        if (isUTF):
            file(filename,"w").write(utfstr+fdata)
        else:
            file(filename,"w").write(fdata)

def recursive_traversal(dir,  oldcopyright, copyright):
    global excludedir
    fns = os.listdir(dir)
    print "listing "+dir
    for fn in fns:
        fullfn = os.path.join(dir,fn)
        if (fullfn in excludedir):
            continue
        if (os.path.isdir(fullfn)):
            recursive_traversal(fullfn, oldcopyright, copyright)
        else:
            if (fullfn.endswith(".cs")):
                update_source(fullfn, oldcopyright, copyright)

oldcright = file("oldcr.txt","r+").read()
cright = file("copyrightText.txt","r+").read()
recursive_traversal("..", oldcright, cright)
exit()
```
```


q:
  <my:DataGridTemplateColumn
            CanUserResize="False"
            Width="150"
            Header="{Binding MeetingName, Source={StaticResource LocStrings}}"
            SortMemberPath="MeetingName">
  </my:DataGridTemplateColumn>

I have the above column in a Silverlight grid control. But it is giving me a XamlParser error because of how I am trying to set the Header property. Has anyone done this before? I want to do this for multiple languages.

Also my syntax for the binding to a resouce is correct because I tried it in a lable outside of the grid.

[A]
You can't Bind to Header because it's not a FrameworkElement.  You can make the text dynamic by modifying the Header Template like this:
```
```
xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
xmlns:dataprimitives="clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data"

<data:DataGridTemplateColumn>
   <data:DataGridTemplateColumn.HeaderStyle>
       <Style TargetType="dataprimitives:DataGridColumnHeader">
          <Setter Property="Template">
             <Setter.Value>
                <ControlTemplate>
                  <TextBlock Text="{Binding MeetingName, Source={StaticResource LocStrings}}" />
               </ControlTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </data:DataGridTemplateColumn.HeaderStyle>
</data:DataGridTemplateColumn>
```
```


q:
I've been trying to submit a form with the FormPanel using the Action class Ext defaults to. However, I'd like it to consider the response as a script, not JSON-encoded.

Has anyone had any experience on this?

[A]
The best plan would be to create a custom action by extending
```
Ext.form.Action
```
.
You can then
```
eval
```
the
```
response
```
object or the
```
result
```
object in the
```
success
```
callback of your custom action.
Your custom action can be called from
```
Ext.form.BasicForm
```
in the usual way.


q:
The link over here lists ([http://www.yoda.arachsys.com/csharp/singleton.html][1]) some singleton patterns in C#. The article also describes the obvious that a singleton is not meant to accept parameters which “as otherwise a second request for an instance but with a different parameter could be problematic”. This means that any parameters you need to get the class working should be induced as a property.

I am curious to know if there are any parameterized singleton design patterns out there. Accepting values as a property does not enforce anything to the consumer.

[A]
Based on your question, it seems you may be looking at an Abstract Factory pattern (creates an instance of several families of classes) that keeps an internal list/dictionary of classes that have already been instantiated, thus mimicking the singleton pattern functionality.
You would then use this factory class to request an object based on parameters you've passed in, and if it exists in its internal list it gets returned, and if not, a new instance is created and then added to the list and returned.


q:
Is it possible for a web server to know which type of device request has been received from?

For example, can a create a website which shows different contents if request came from a computer (Firefox) and something different if it came from iPhone?

[A]
Check the
```
User-Agent
```
in the Request Header
For full details on HTTP headers, see the specifications at
http://www.w3.org/Protocols/
.


q:
Does Microsoft force an update down to all of its users of windows-update?  Is it for legal reasons?

EDIT(aku):

Question was reformulated. if you want to know which version of Windows comes with .NET see this topic:

https://stackoverflow.com/questions/71390/which-operating-systems-come-with-net

[A]
Yes, Windows Vista shipped with .NET Framework 3.0. I'm sure future versions of Windows will ship with whichever is the most recent version of the framework.
Scott Hanselman recently blogged about the status of .NET 3.5 on Windows Update:
http://www.hanselman.com/blog/UpdateOnNETFramework35SP1AndWindowsUpdate.aspx


q:
We have an old project written using Managed C++ syntax. I would like to propose to the team a reasonably pain-free (I don't mind some level of human interaction, I think I'm realistic in my expectations that we'll still have to do some work by hand) method of updating the existing code to C++/CLI syntax so that we can also add XML documentation (the project is a library into other projects and having documentation would be immensely useful).

So, are there any good tools out there to help with this? Or is it just a case of switching to the new C++/CLI syntax compiler and fixing errors as we go?

[A]
Microsoft has a
tool
that will help a little.
Visual c++ blog post about it.
Here are a couple other resources I found useful when I made our switch
C++/CLI Migration Primer
Managed Extensions for C++ Syntax Upgrade Checklist
The Microsoft tool is just a start. there were many files that it could not convert.


q:
Does it matter to developers that the current, and newer versions of .Net don't support windows 2000?

It scares me to think that several of my clients still use Windows 2000 and although I may decide to stop supporting Windows 2000 one day, I don't like that Microsoft is pushing it on people's products.

Could anyone see Microsoft doing this with XP in the future to spur sales of Vista and later?

Just to clarify, this is not a bashing of MS in any way, I love MS, but it is a genuine concern that I would like opinions on.

In contrast I can't see C++0x implementors saying "it won't work on windows 2000"

I'm really trying to convince myself that I should be switching to .Net but this is one of my concerns.

[A]
Supporting older operating systems costs money. It's not necessarily a push to spur sales of new systems so much as avoiding the cost of trying to make things work on old systems that they've already ceased supporting. Just as Windows 2000 support has ended, so will Windows XP support, and Vista support, and Windows 7 support, etc etc. Continuing to support the .NET framework on operating systems that are no longer supported in any other way does not seem prudent.
EDIT: To address the notion that since the CLR is the same for .NET 2.0 and the newer framework versions, the restriction was artificial. Although it is still working on the same CLR, that doesn't mean that all the support they've added will effectively work on Windows 2000. There are performance and hardware considerations to be made and I think considering the age of Windows 2000 and some of the more intensive features added to 3.0 and 3.5 frameworks, it was a reasonable decision to abandon WIndows 2k.
Whenever we as developers consider supporting a particular user-base, there has to be a consideration of the resources needed to add that additional user-base over the benefits of supporting them. Testing, bug fixing, and support costs have to be factored in. As Windows 2000 is no longer given any security updates, they would need to resurrect an update mechanism just for .NET updates. I suspect that the benefits do not outweigh the costs in this scenario. It therefore makes sense to me that Microsoft should artificially prevent newer frameworks from running on Windows 2000 as they are then saving themselves these additional costs.


q: just curious to know which CPU architectures support compare and swap atomic primitives?

[A]
Sparc v9 has a cas instruction. The SPARC v9
architecture manual
discusses the use of the CAS instruction in Annex J, look specifically at examples J.11 and J.12.
I believe the name of the instruction is actually "casa", because it can access either the current address space or an alternate. "cas" is an assembler macro which accesses the current ASI.
There is also an article on
developers.sun.com
discussing the various atomic instructions which Sparc processors have implemented over the years, including cas.


q:
Given a database field named "widget_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget_ids... how would you make an update statement with SQL that would say:
"if the widget_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"

Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL?

[A]
Updates are kind of like if-thens themselves, and there is also if-then support of some sort in most SQL implementations. A simple solution might be:
```
```
update <tablename>
  set widget_id = widget_id + "somenumber/"
  where row_id = X
    and widget_id not like "%/somenumber/%"
    and widget_id not like "somenumber/%";
```
```


q:
I'd like to document what high-level (i.e. C++ not inline assembler ) functions or macros are available for Compare And Swap (CAS) atomic primitives...

E.g., WIN32 on x86 has a family of functions _InterlockedCompareExchange in the <_intrin.h> header.

[A]
I'll let others list the various platform-specific APIs, but for future reference in C++09 you'll get the
```
```
atomic_compare_exchange()
```
```
operation in the new "Atomic operations library".


q:
Since Unicode lacks a series of zero width sorting characters, I need to determine equivalent characters that will allow me to force a certain order on a list that is automatically sorted by character values. Unfortunately the list items are not in an alphabetical order, nor is it acceptable to prefix them with visible characters to ensure the result of the sort matches the wanted outcome.

What Unicode characters can be thrown in front of regular Latin alphabet text, and will not appear, but still allow me to "spike" the sort in the way I require?

(BTW this is being done with Drupal 5 with a user profile list field. Don't bother suggesting changing that to a vocabulary/category.)

[A]
Personally, I just prefer to use a primary/secondary sort key. It's less kludgy, and easy to implement in a typical sql query (ORDER BY column_a,column_b).
Edited to add
: In Php, you could use
```
usort(array, comparisonFunction)
```
with a custom comparison function to add additional logic for sorting, if you can't use SQL to do the trick.
However, if you only have one column to work with and that's unfixable, just prefix with a certain number of unlikely characters like underscores for sorting, then strip them just before you display them. (using regexp substitution or similar).
Unicode-based hacks will depend heavily on what fonts are used, what locale's collation/sorting order you're using, and may produce undesirable side effects on clients you don't have control over (different browsers, different oses, different client locales). Most "unprintable" characters yield the "unknown character" when displayed on systems without support for them, which usually looks like an empty square. There are some zero-width characters used for languages like Arabic, but they shouldn't affect sorting except in applications with very perverse Unicode support.


q: This isn't as malicious as it sounds, I want to get the current size of their windows, not look at what is in them.  The purpose is to figure out that if every other window is fullscreen then I should start up like that too.  Or if all the other processes are only 800x600 despite there being a huge resolution then that is probably what the user wants.  Why make them waste time and energy resizing my window to match all the others they have?  I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.

[A]
Check out the
```
win32gui
```
module
in the Windows extensions for Python. It may provide some of the functionality you're looking for.


q:
In many languages, assignments are legal in conditions. I never understood the reason behind this. Why would you write:

if (var1 = var2) {
  ...
}

instead of:

var1 = var2;
if (var1) {
  ...
}

?

[A]
It can be useful if you're calling a function that returns either data to work on or a flag to indicate an error (or that you're done).
Something like:
```
```
while ((c = getchar()) != EOF) {
    // process the character
}

// end of file reached...
```
```
Personally it's an idiom I'm not hugely fond of, but sometimes the alternative is uglier.


q: I have renamed some excel files on my web server and after renaming the users cannot download those files. What could be the problem. They are all excel files.

[A]
Some possibilities I can think of:
Make sure the extension on the files is still .xls (that's how it associates the mime type)
Check the file protections on the files in case it, or the ownership got changed when you renamed them
Make sure Excel didn't open them on the webserver (if a windows web server) as it will keep them locked until the EXCEL.EXE process is killed.
Might be one of those ...


q:
I have a form where i have used Infragistics windows grid control to display the data.
In this, i have placed a button on one of the cell. I want to set its visibility either True or False based on the row condition.
I have handled the InitializeRow event of UltraWinGrid control and able to disable the button. But i am unable to set the button's visible to False.

[A]
```
```
UltraGridRow row = ...

row.Cells[buttonCellIndex].Hidden = true;
```
```
(I'm using the
```
UltraGrid
```
in Infragistics NetAdvantage for Windows Forms 2008 Vol. 2 CLR 2.0.)


q: What is the best way to free resources (in this case unlock the ReadWriteLock) when leaving the scope ? How to cover all possible ways (return, break, exceptions etc)?

[A]
A try/finally block is the closest thing that you can get to this behaviour:
```
```
Lock l = new Lock();
l.lock();  // Call the lock before calling try.
try {
    // Do some processing.
    // All code must go in here including break, return etc.
    return something;
} finally {
    l.unlock();
}
```
```


q: Emacs puts backup files named foo~ everywhere and I don't like having to remember to delete them.  Also, if I edit a file that has a hard link somewhere else in the file system, the hard link points to the backup when I'm done editing, and that's confusing and awful.  How can I either eliminate these backup files, or have them go somewhere other than the same directory?

[A]
If you've ever been saved by an Emacs backup file, you
probably want more of them, not less of them.  It is annoying
that they go in the same directory as the file you're editing,
but that is easy to change.  You can make all backup files go
into a directory by putting something like the following in your
```
.emacs
```
.
```
```
(setq backup-directory-alist `(("." . "~/.saves")))
```
```
There are a number of arcane details associated with how Emacs
might create your backup files.  Should it rename the original
and write out the edited buffer?  What if the original is linked?
In general, the safest but slowest bet is to always make backups
by copying.
```
```
(setq backup-by-copying t)
```
```
If that's too slow for some reason you might also have a look at
```
backup-by-copying-when-linked
```
.
Since your backups are all in their own place now, you might want
more of them, rather than less of them.  Have a look at the Emacs
documentation for these variables (with
```
C-h v
```
).
```
```
(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)
```
```
Finally, if you absolutely must have no backup files:
```
```
(setq make-backup-files nil)
```
```
It makes me sick to think of it though.


q: The Project's Web section (under project properties in VS2008) has a list of debuggers: ASP.NET, Native Code, SQL Server. What is Native Code?

[A]
Native code is machine code executed directly by the CPU. This is in contrast to .NET bytecode, which is interpreted by the .NET virtual machine.
A nice MSDN hit:
Debugging Native Code


q:
I am looking to store 2D arrays of 900x100 elements in a database.  Efficient recall and comparison of the arrays is important.  I could use a table with a schema like [A, x, y, A(x,y)] such that a single array would compromise 90,000 records.  This seems like an ~ok~ table design to store the array, and would provide for efficient recall of single elements, but inefficient recall of a whole array and would make for very inefficient array comparisons.

Should I leave the table design this way and build and compare my arrays in code?  Or is there a better way to structure the table such that I can get efficient array comparisons using database only operations?

thanks

[A]
900 x 100 elements is actually very small (even if the elements are massive 1K things that'd only be 90 MB).  Can't you just compare in memory when needed and store on disk in some serialized format?
It doesn't make sense to store 2D arrays in the database, especially if it is immutable data.


q:
In PHP 5, what is the difference between using self and $this?

When is each appropriate?

[A]
According to
Static Keyword
, there isn't any
```
$self
```
. There is only
```
$this
```
, for referring to the current instance of the class (the object), and
```
self
```
, which can be used to refer to static members of a class. The difference between an object instance and a class comes into play here.


q:
What is currying?

How can currying be done in C++?

Please Explain binders in STL container?

[A]
In short, currying takes a function
```
f(x, y)
```
and given a fixed
```
Y
```
, gives a new function
```
g(x)
```
where
```
```
g(x) == f(x, Y)
```
```
This new function may be called in situations where only one argument is supplied, and passes the call on to the original
```
f
```
function with the fixed
```
Y
```
argument.
The binders in the STL allow you to do this for C++ functions. For example:
```
```
#include <functional>
#include <iostream>
#include <vector>

using namespace std;

// declare a binary function object
class adder: public binary_function<int, int, int> {
public:
    int operator()(int x, int y) const
    {
        return x + y;
    }
};

int main()
{
    // initialise some sample data
    vector<int> a, b;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);

    // here we declare a function object f and try it out
    adder f;
    cout << "f(2, 3) = " << f(2, 3) << endl;

    // transform() expects a function with one argument, so we use
    // bind2nd to make a new function based on f, that takes one
    // argument and adds 5 to it
    transform(a.begin(), a.end(), back_inserter(b), bind2nd(f, 5));

    // output b to see what we got
    cout << "b = [" << endl;
    for (vector<int>::iterator i = b.begin(); i != b.end(); ++i) {
        cout << "  " << *i << endl;
    }
    cout << "]" << endl;

    return 0;
}
```
```


q:
I've got a php script. Most of the time the script returns html, which is working fine, but on one occasion (parameter ?Format=XML) the script returns XML instead of HTML.

Is there any way to change the returned mime type of the php output on the fly from text/html to text/xml or application/xml?

[A]
```
```
header('Content-type: application/xml');
```
```
More information available at the PHP documentation for
```
header()
```


q: I have a RDK-IDM from Luminary Micro. This board has a 32-bit ARM® Cortex™-M3 core. Has anybody tried to run a .NET Micro Framework application on such a device?

[A]
It seems that the LM3S6918 (The chip on the RDK-IDM) has only 256KB Flash and 64Kb SRAM but .NET Micro Framework requires 256KB RAM and 512K Flash/ROM!
Read more
here


q: .Net 3.5 doesn't support tuples. Too bad, But not sure whether the future version of .net will support tuples or not?

[A]
```
```
#region tuples

    public class Tuple<T>
    {
        public Tuple(T first)
        {
            First = first;
        }

        public T First { get; set; }
    }

    public class Tuple<T, T2> : Tuple<T>
    {
        public Tuple(T first, T2 second)
            : base(first)
        {
            Second = second;
        }

        public T2 Second { get; set; }
    }

    public class Tuple<T, T2, T3> : Tuple<T, T2>
    {
        public Tuple(T first, T2 second, T3 third)
            : base(first, second)
        {
            Third = third;
        }

        public T3 Third { get; set; }
    }

    public class Tuple<T, T2, T3, T4> : Tuple<T, T2, T3>
    {
        public Tuple(T first, T2 second, T3 third, T4 fourth)
            : base(first, second, third)
        {
            Fourth = fourth;
        }

        public T4 Fourth { get; set; }
    }

    #endregion
```
```
And to make declarations prettier:
```
```
public static class Tuple
{
    //Allows Tuple.New(1, "2") instead of new Tuple<int, string>(1, "2")
    public static Tuple<T1, T2> New<T1, T2>(T1 t1, T2 t2)
    {
        return new Tuple<T1, T2>(t1, t2);
    }
    //etc...
}
```
```


q:
Any time I try to publish my Portal project on a Websphere Portal 6.1 Server, I get the following error message:

Portal project publishing is not supported on WebSphere Portal v6.1 Server

Is that really true or have I done something wrong?

I'm trying to deploy a portal project, with the underlying goal of publishing a new theme.

Unfortunately, any time I try to deploy, I get the error message listed above from the IDE and no errors in the console.

The RAD version is 7.0.0.7.

[A]
Not sure this will help, but:
Limitation: Although the WebSphere
  Portal installer contains an advanced
  option to install an empty portal,
  Portal Designer relies on
  administration portlets for setting
  access control; therefore, publishing
  a portal project to an empty portal is
  not supported.
Are you trying to deploy a portlet or an entire portal project? What version of RAD are you using? Any other information in the error log? (Both within RAD & on WP server) Is the error message posted verbatim?


q:
I have a submission table that is very simple: userId, submissionGuid

I want to select the username (simple inner join to get it) of all the users who have more than 10 submissions in the table.

I would do this with embedded queries and a group by to count submissions... but is there a better way of doing it (without embedded queries)?

Thanks!

[A]
```
```
select userId, count(*)
from   submissions
having count(*) > 10
group by userId
```
```


q:
I want to be able to compare an image taken from a webcam to an image stored on my computer.

The library doesn't need to be one hundred percent accurate as it won't be used in anything mission critical (e.g. police investigation), I just want something OK I can work with.

I have tried a demonstration project for Image Recognition from CodeProject, and it only works with small images / doesn't work at all when I compare an exact same image 120x90 pixels (this is not classified as OK :P ).

Has there been any success with image recognition before?

If so, would you be able to provide a link to a library I could use in either C# or VB.NET?

[A]
You could try this:
http://code.google.com/p/aforge/
It includes a comparison analysis that will give you a score. There are many other great imaging features of all types included as well.
```
```
// The class also can be used to get similarity level between two image of the same size, which can be useful to get information about how different/similar are images:
// Create template matching algorithm's instance

// Use zero similarity to make sure algorithm will provide anything
ExhaustiveTemplateMatching tm = new ExhaustiveTemplateMatching(0);

// Compare two images
TemplateMatch[] matchings = tm.ProcessImage( image1, image2 );

// Check similarity level
if (matchings[0].Similarity > 0.95)
{
    // Do something with quite similar images
}
```
```


q: I want to learn MVC "architecture pattern" but I don't want to jump into a framework like Rails or Django just yet.  I want to understand the concept first and write some simple code in my currently familiar environment, which happens to be PHP/HTML/CSS/MySQL.  I don't necessarily need a tutorial that is based on PHP, as I do understand a lot of different languages. And I don't want to have to install any frameworks or APIs or libraries.  I just want to learn how to think in MVC and apply it to my projects. Any suggestions?

[A]
Almost every framework does MVC differently, so you might end up getting even more confused. The general principles of MVC are very simple: "Model is state; view reacts to model; controller reacts to view; controller changes model". The model, view and controller are concepts - they are whatever you feel them to be. Classes, bunches of classes, instances of classes with XML configuration files, you name it.
I actually think that about covers the basic principles. Without a framework, you'd not get much further. What matters is how a particular framework defines model, view and controller and their interactions.


q: How can I set points on a 24h period spreaded by the Gaussian distributions? For example to have the peak at 10 o'clock?

[A]
If you have trouble generating gaussian distributed random points look up
http://en.wikipedia.org/wiki/Box-Muller_transform
Else please clarify your question.


q:
I am trying to use Lucene Java 2.3.2 to implement search on a catalog of products. Apart from the regular fields for a product, there is field called 'Category'. A product can fall in multiple categories. Currently, I use FilteredQuery to search for the same search term with every Category to get the number of results per category.

This results in 20-30 internal search calls per query to display the results. This is slowing down the search considerably. Is there a faster way of achieving the same result using Lucene?

[A]
You may want to consider looking through all the documents that match categories using a
TermDocs iterator
.
This example code goes through each "Category" term, and then counts the number of documents that match that term.
```
```
public static void countDocumentsInCategories(IndexReader reader) throws IOException {
    TermEnum terms = null;
    TermDocs td = null;

    try {
        terms = reader.terms(new Term("Category", ""));
        td = reader.termDocs();
        do {
            Term currentTerm = terms.term();

            if (!currentTerm.field().equals("Category")) {
                break;
            }

            int numDocs = 0;
            td.seek(terms);
            while (td.next()) {
                numDocs++;
            }

            System.out.println(currentTerm.field() + " : " + currentTerm.text() + " --> " + numDocs);
        } while (terms.next());
    } finally {
        if (td != null) td.close();
        if (terms != null) terms.close();
    }
}
```
```
This code should run reasonably fast even for large indexes.
Here is some code that tests that method:
```
```
public static void main(String[] args) throws Exception {
    RAMDirectory store = new RAMDirectory();

    IndexWriter w = new IndexWriter(store, new StandardAnalyzer());
    addDocument(w, 1, "Apple", "fruit", "computer");
    addDocument(w, 2, "Orange", "fruit", "colour");
    addDocument(w, 3, "Dell", "computer");
    addDocument(w, 4, "Cumquat", "fruit");
    w.close();

    IndexReader r = IndexReader.open(store);
    countDocumentsInCategories(r);
    r.close();
}

private static void addDocument(IndexWriter w, int id, String name, String... categories) throws IOException {
    Document d = new Document();
    d.add(new Field("ID", String.valueOf(id), Field.Store.YES, Field.Index.UN_TOKENIZED));
    d.add(new Field("Name", name, Field.Store.NO, Field.Index.UN_TOKENIZED));

    for (String category : categories) {
        d.add(new Field("Category", category, Field.Store.NO, Field.Index.UN_TOKENIZED));
    }

    w.addDocument(d);
}
```
```


q:
I don't need a Link but rather only the href= part of the ActionLink.

But if I call Html.ActionLink(...) I get a  back.
Is there a way to just return the URL of the Action while not getting the ?

[A]
Edit: in response to commment, now including parameters:
```
```
<% =Html.BuildUrlFromExpression<YourController>(c => c.YourAction(parameter)) %>
```
```


q: Has anyone used the noweb literate programming tool on a large Java project, where several source code files must be generated in different subdirectories? How did you manage this with noweb? Are there any resources and/or best practices out there?

[A]
Literate Programming works its best if the generated intermediate code can point back to the original source file to allow debugging, and analyzing compiler errors.  This usually means pre processor support, which Java doesn't support.
Additionally Literate Programming is really not necessary for Java, as the original need for a strict sequential order - which was what prompted Knuth to write a tool to put snippets together in the appropriate sequence - is not present.    The final benefit of literate programming, namely being able to write prose about the code, is also available as Javadoc which allow you to put everything in as comments.
To me, there is no benefit in literate programming for Java, and only troubles (just imagine getting IDE support).
Any particular reason you are considering it?


q:
What type of authentication would you suggest for the service that is:

implemented as WCF and exposed via
varios enpoints (including XML-RPC)

has to be consumed easily by various cross-platform clients

Why?

Options that I'm aware of are:

Forms-based authentication for IIS-hosted WCF (easy to implement, but has horrible cross-platform support, plus it is not REST)

Sending plain-text username/pwd with every call (easy to use on any platform, but totally unsecure)

Using ticket-based authentication, when username&pwd are used to create a ticket that is valid for some time and is passed with every request (can be consumed by any client easily, but the API model is bound to this type of security)

Thanks for your time!


q: I have read in some of the ClickOnce posts that ClickOnce does not allow you to create a desktop icon for you application. Is there any way around this?

[A]
The desktop icon can be a shortcut to the
```
.application
```
file. Install this as one of the first things your application does.


q:
I'm working on a Java library and would like to remove some functions from it. My reasons for this is public API and design cleanup. Some objects have setters, but should be immutable, some functionality has been implemented better/cleaner in different methods, etc.

I have marked these methods 'deprecated', and would like to remove them eventually. At the moment I'm thinking about removing these after few sprints (two week development cycles).

Are there any 'best practices' about removing redundant public code?

/JaanusSiim

[A]
Use
@deprecated
tag. Read the
Deprecation of APIs
document for more info.
After everyone using the code tells you they have cleaned up on their side, start removing the deprecated code and wait and see if someone complains - then tell them to fix their own code...


q:
Here's the problem:

split=re.compile('\\W*')

This regular expression works fine when dealing with regular words, but there are occasions where I need the expression to include words like k&amp;auml;ytt&amp;auml;j&aml;auml;.

What should I add to the regex to include the & and ; characters?

[A]
You probably want to take the problem reverse, i.e. finding all the character without the spaces:
```
```
[^ \t\n]*
```
```
Or you want to add the extra characters:
```
```
[a-zA-Z0-9&;]*
```
```
In case you want to match HTML entities, you should try something like:
```
```
(\w+|&\w+;)*
```
```


q: Can someone point me in the right direction? I wish to distribute a WCF peer to peer cloud over the internet. So far I've seen examples of how it works on the same subnet. I wish to push it a little further.

[A]
I believe you'll need to look into using
IPV6 Teredo Tunneling
for crossing NAT and firewalls, so maybe check out this on
WCF transports
from MSDN.
Also, take a look at the
PRNP series
Kevn Hoffman did this year.


q: Say if I had a table of books in a MySQL database and I wanted to search the 'title' field for keywords (input by the user in a search field); what's the best way of doing this in PHP? Is the MySQL LIKE command the most efficient way to search?

[A]
Yes, the most efficient way usually is searching in the database. To do that you have three alternatives:
LIKE, ILIKE
to match exact substrings
RLIKE
to match POSIX regexes
FULLTEXT
indexes to match another three different kinds of search aimed at natural language processing
So it depends on what will you be actually searching for to decide what would the best be. For book titles I'd offer a LIKE search for exact substring match, useful when people know the book they're looking for and also a FULLTEXT search to help find titles similar to a word or phrase. I'd give them different names on the interface of course, probably something like exact for the substring search and similar for the fulltext search.
An example about fulltext:
http://www.onlamp.com/pub/a/onlamp/2003/06/26/fulltext.html


q:
I have a Delphi DLL with a function defined as:

function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;

I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:

[DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int SubmitJobStringList(string[] tStringList, ref int jobno);

But when I call it I get a memory access violation exception.

Anyone know how to pass to a tStringList correctly from C#?

[A]
You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely.
Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.


q:
I am about to set up a subversion server to be accessed via svn+ssh. I was wondering, where the default repository location is (on a unix box).

Do you put it in

/opt/svn

or

/home/svn

or

/usr/subversion

or even

/svn

or somewhere else?

I am looking for the place, most people put it. Is there a convention?

EDIT:

It is absolutely possible to "hide" the actual repository location from the user. For example (in my case) by wrapping the svnserve executable in a way that it is called like:

svnserve -r /var/svn/repos

[A]
I typically place the repositories somewhere under
```
/var
```
, usually in
```
/var/lib/svn
```
- I'm trying to follow the
Filesystem Hierarchy Standard
which has this to say about the
purpose of /var
:
```
/var
```
is specified here in order to make it possible to mount
```
/usr
```
read-only. Everything that once went into
```
/usr
```
that is written to during system operation (as opposed to installation and software maintenance) must be in
```
/var
```
.


q:
Why isn't this project maintained anymore?  I love this app, however not updating it seems like a crime against all .Net developers. There are several items that I would love to add to it given the chance of a future release.

Can anyone share something I don't know?

[A]
http://nunit.org
shows that the latest release is 2.4.8, released on July 21, 2008. It looks like it's still an active project to me.


q:
I'm looking for a decent sort implementation for arrays in VBA. A Quicksort would be preferred. Or any other sort algorithm other than bubble or merge would suffice.

Please note that this is to work with MS Project 2003, so should avoid any of the Excel native functions and anything .net related.

[A]
Take a look
here
:
Edit:
The referenced source (allexperts.com) has since closed, but here are the relevant
author
comments:
There are many algorithms available on the web for sorting.  The most versatile and usually the quickest is the
Quicksort algorithm
.  Below is a function for it.
Call it simply by passing an array of values (string or numeric; it doesn't matter) with the
Lower Array Boundary
(usually
```
0
```
) and the
Upper Array Boundary
(i.e.
```
UBound(myArray)
```
.)
Example
:
```
Call QuickSort(myArray, 0, UBound(myArray))
```
When it's done,
```
myArray
```
will be sorted and you can do what you want with it.
(Source:
archive.org
)
```
```
Public Sub QuickSort(vArray As Variant, inLow As Long, inHi As Long)
  Dim pivot   As Variant
  Dim tmpSwap As Variant
  Dim tmpLow  As Long
  Dim tmpHi   As Long

  tmpLow = inLow
  tmpHi = inHi

  pivot = vArray((inLow + inHi) \ 2)

  While (tmpLow <= tmpHi)
     While (vArray(tmpLow) < pivot And tmpLow < inHi)
        tmpLow = tmpLow + 1
     Wend

     While (pivot < vArray(tmpHi) And tmpHi > inLow)
        tmpHi = tmpHi - 1
     Wend

     If (tmpLow <= tmpHi) Then
        tmpSwap = vArray(tmpLow)
        vArray(tmpLow) = vArray(tmpHi)
        vArray(tmpHi) = tmpSwap
        tmpLow = tmpLow + 1
        tmpHi = tmpHi - 1
     End If
  Wend

  If (inLow < tmpHi) Then QuickSort vArray, inLow, tmpHi
  If (tmpLow < inHi) Then QuickSort vArray, tmpLow, inHi
End Sub
```
```
Note that this only works with
single-dimensional
(aka "normal"?) arrays.  (There's a working multi-dimensional array QuickSort
here
.)


q:
I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.

The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.

Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?

Edit:

Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.

I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.

Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:

wscript sendmail.vbs

[A]
I think that you'll have to install some ActiveX or other component what could be invoked from WScript, such as:
http://www.activexperts.com/ActivEmail/
and:
http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp
Otherwise, you'll have to write the entire SMTP logic (if possible, not sure) in WScript all on your own.


q: How to unit test WCF services? Any 3rd Party tools available?

[A]
What exactly do you want to test? Connectivity or service methods?
Cool thing about WCF is that you can just define interfaces (err, contracts) and test them as regular code. Then you can assume that they will work via any connection type supported by WCF.
Connectivity can be tested by hosting your service directly in UT or on development web-server.
As for tools, you there are tons of unit testing frameworks: NUnit, built-in tests in Visual Studio, xUnit, etc, etc.
You can download "
Visual Studio 2008 and .NET Framework 3.5 Training Kit
" and "
.NET Framework 3.5 Enhancements Training Kit
" if I recall correctly there were samples for WCF unit tests


q:
I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.

I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ?

[A]
Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance.
Aside note:
Remember that by keeping a read-only collection you are only preventing modifications to the collection itself. Each collection element is still changeable.
```
```
class Test {
    public Test(final int a, final int b) {
        this.a = a;
        this.b = b;
    }

    public int a;
    public int b;
}

public class Main {

    public static void main(String[] args) throws Exception {
        List<Test> values = new ArrayList<Test>(2);
        values.add(new Test(1, 2));
        values.add(new Test(3, 4));

        List<Test> readOnly = Collections.unmodifiableList(values);
        for (Test t : readOnly) {
            t.a = 5;
        }

        for (Test t : values) {
            System.out.println(t.a);
        }
    }

}
```
```
This outputs:
```
```
5
5
```
```
Important considerations from @WMR answser.
It depends on if the threads that are
  reading your collection are started
  before or after you're filling it. If
  they're started before you fill it,
  you have no guarantees (without
  synchronizing), that these threads
  will ever see the updated values.
The reason for this is the Java Memory
  Model, if you wanna know more read the
  section "Visibility" at this link:
http://gee.cs.oswego.edu/dl/cpj/jmm.html
And even if the threads are started
  after you fill your collection, you
  might have to synchronize because your
  collection implementation could change
  its internal state even on read
  operations (thanks
Michael
  Bar-Sinai
,
  I didn't know such collections
  existed).
Another very interesting read on the
  topic of concurrency which covers
  topics like publishing of objects,
  visibility, etc. in much more detail
  is Brian Goetz's book
Java
  Concurrency in
  Practice
.


q: Does anyone have tools or experience with code coverage for PL/SQL. I believe this is possible using DBMS_PROFILER?

[A]
Not sure if this is quite what you're after, but in 10g onwards there's a tool to do static PL/SQL code analysis.
Info here...
http://www.psoug.org/reference/plsql_warnings.html
Note that it can be enabled at either session or database level.
In my experience it's thrown up quite a few false negatives so far.


q:
I am actually new to this forum and I kept trying for a few days to find an easy way to copy an entire LDAP subtree to another tree. Since I couldn't find anything useful, i thought of dropping a question here as well. Does anybody know how to do this programatically ?

For normal operations like add, remove, search, I've been using Spring LDAP.

Thanks a lot !

[A]
I actually don't know Spring LDAP but if your LDAP interface does not provide any high level abstraction for moving/renaming or copying an entire subtree you have to move/rename or copy all subtree nodes recursively. The LDAP API does not provide such an option directly.
The following is pseudo-code:
```
```
function copySubtree(oldDn, newDn)
{
    copyNode(oldDn, newDn); // the new node will be created here
    if (nodeHasChildren(oldDn) {
        foreach (nodeGetChildren(oldDn) as childDn) {
            childRdn=getRdn(childDn); // we have to get the 'local' part, the so called RDN
            newChildDn=childRdn + ',' + newDn; // the new DN will be the old RDN concatenated with the new parent's DN
            copySubtree(childDn, newChildDn); // call this function recursively
        }
    }
}
```
```


q: Is there a way to print all methods of an object in JavaScript?

[A]
From
here
:
Example 1: This example writes out all the properties of the "navigator" object, plus their values:
```
```
for (var myprop in navigator){
 document.write(myprop+": "+navigator[myprop]+"<br>")
}
```
```
Just replace 'navigator' with whatever object you are interested in and you should be good to go.
As mentioned by Anthony in the comments section - This returns all attributes not just methods as the question asked for.
Oops!  That'll teach me to try and answer a question in a language I don't know.  Still, I think the code is useful - just not what was required.


q:
I have a stored procedure that looks like:

CREATE PROCEDURE dbo.usp_TestFilter
  @AdditionalFilter BIT = 1
AS
  SELECT *
  FROM dbo.SomeTable T
  WHERE
    T.Column1 IS NOT NULL
    AND CASE WHEN @AdditionalFilter = 1 THEN
      T.Column2 IS NOT NULL

Needless to say, this doesn't work. How can I activate the additional where clause that checks for the @AdditionalFilter parameter? Thanks for any help.

[A]
```
```
CREATE PROCEDURE dbo.usp_TestFilter
  @AdditionalFilter BIT = 1
AS
  SELECT *
  FROM dbo.SomeTable T
  WHERE
    T.Column1 IS NOT NULL
    AND (NOT @AdditionalFilter OR T.Column2 IS NOT NULL)
```
```