q:
I'm trying to modify my GreaseMonkey script from firing on window.onload to window.DOMContentLoaded, but this event never fires.

I'm using FireFox 2.0.0.16 / GreaseMonkey 0.8.20080609

This is the full script that I'm trying to modify, changing:

window.addEventListener ("load", doStuff, false);

to

window.addEventListener ("DOMContentLoaded", doStuff, false);

[A]
So I googled
greasemonkey dom ready
and the
first result
seemed to say that the greasemonkey script is actually running at "DOM ready" so you just need to remove the onload call and run the script straight away.
I removed the
```
window.addEventListener ("load", function() {
```
and
```
}, false);
```
wrapping and it worked perfectly. It's
much
more responsive this way, the page appears straight away with your script applied to it and all the unseen questions highlighted, no flicker at all. And there was much rejoicing.... yea.


q:
Let me use the following example to explain my question:

public string ExampleFunction(string Variable) {
    return something;
}

string WhatIsMyName = "Hello World";
string Hello = ExampleFunction(WhatIsMyName);

When I pass the variable WhatIsMyName to the ExampleFunction, I want to be able to get a string of the original variable's name. Perhaps something like:

Variable.OriginalName.ToString() // == "WhatIsMyName"

Is there any way to do this?

[A]
No.
I don't think so.
The variable name that you use is for your convenience and readability. The compiler doesn't need it & just chucks it out if I'm not mistaken.
If it helps, you could define a new class called
```
NamedParameter
```
with attributes
```
Name
```
and
```
Param
```
. You then pass this object around as parameters.

s: huggingface

c: devops

d: intermediate


q:
Using C++ (and Qt), I need to process a big amount of 3D coordinates.

Specifically, when I receive a 3D coordinate (made of 3 doubles), I need to check in a list if this coordinate has already been processed.
If not, then I process it and add it to the list (or container).

The amount of coordinates can become very big, so I need to store the processed coordinates in a container which will ensure that checking if a 3D coordinate is already contained in the container is fast.

I was thinking of using a map of a map of a map, storing the x coordinate, then the y coordinate then the z coordinate, but this makes it quite tedious to use, so I'm actually hoping there is a much better way to do it that I cannot think of.

[A]
Well, it depends on what's most important... if a tripple map is too tedious to use, then is implementing other data structures not worth the effort?
If you want to get around the uglyness of the tripple map solution, just wrap it up in another container class with an access function with three parameter, and hide all the messing around with maps internally in that.
If you're more worried about the runtime performance of this thing, storing the coordinates in an
Octree
might be a good idea.
Also worth mentioning is that doing these sorts of things with floats or doubles you should be very careful about precision -- if (0, 0, 0.01) the same coordinate as (0, 0, 0.01000001)? If it is, you'll need to look at the comparison functions you use, regardless of the data structure. That also depends on the source of your coordinates I guess.


q:
How can I construct a MSBuild ItemGroup to exclude .svn directories and all files within (recursively). I've got:

<ItemGroup>
     <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*" Exclude=".svn" />
</ItemGroup>

At the moment, but this does not exclude anything!

[A]
Thanks for your help, managed to sort it as follows:
```
```
<ItemGroup>
     <LibraryFiles Include="$(LibrariesReleaseDir)\**\*.*"
                   Exclude="$(LibrariesReleaseDir)\**\.svn\**" />
</ItemGroup>
```
```
Turns out the pattern matching basically runs on files, so you have to exclude everything BELOW the
```
.svn
```
directories (
```
.svn\\**
```
) for MSBuild to exclude the
```
.svn
```
directory itself.


q:
We have hundreds of websites which were developed in asp, .net and java and we are paying lot of money for an external agency to do a penetration testing for our sites to check for security loopholes.
Are there any (good) software (paid or free) to do this?

or.. are there any technical articles which can help me develop this tool?

[A] I've heard good things about SpiDynamics WebInspect as far as paid solutions go, as well as Nikto (for a free solution) and other open source tools. Nessus is an excellent tool for infrastructure in case you need to check that layer as well. You can pick up a live cd with several tools on it called Nubuntu (Auditor, Helix, or any other security based distribution works too) and then Google up some tutorials for the specific tool. Always, always make sure to scan from the local network though. You run the risk of having yourself blocked by the data center if you scan a box from the WAN without authorization. Lesson learned the hard way. ;)


q:
How do I find out which sound files the user has configured in the control panel?

Example: I want to play the sound for "Device connected".

Which API can be used to query the control panel sound settings?

I see that there are some custom entries made by third party programs in the control panel dialog, so there has to be a way for these programs to communicate with the global sound settings.

Edit: Thank you. I did not know that PlaySound also just played appropriate sound file when specifying the name of the registry entry.

To play the "Device Conntected" sound:

::PlaySound( TEXT("DeviceConnect"), NULL, SND_ALIAS|SND_ASYNC );

[A]
```
PlaySound
```
is the API.
Also see
Play System Sounds
.


q:
I have a query that is dynamically built after looking up a field list and table name.  I execute this dynamic query inside a stored proc.  The query is built without a where clause when the two proc parameters are zero, and built with a where clause when not.

When I execute the proc with
    SET FMTONLY ON
    exec [cpExportRecordType_ListByExportAgentID] null, null
It returns no column information.  I have just now replaced building the query without a where clause to just executing the same query directly, and now I get column information.  I would love to know what causes this, anyone?

[A]
Perhaps it is related to the fact that the passed parameters are NULL,
check how your query is build perhaps it behaves in different way then expected when you pass NULL.
Does you proc returns expected results when you call:
    SET FMTONLY OFF exec [cpExportRecordType_ListByExportAgentID] null, null
?
Other possibility:
I understand that you build your query dynamically by getting results from calling another queries to get the column names.
Perhaps the query that would normally give you the column names returns no data but only column information (SET FMTONLY ON) so you do not have data to build you dynamic query.


q:
I'm a Java-developer toying with Ruby, and loving it. I have understood that because of Ruby's metaprogramming facilities my unit-tests become much cleaner and I don't need nasty mocking frameworks. I have a class which needs the File class's services and in my test I don't want to touch my real filesystem. In Java I would use some virtual file system for easier "seams" to pass fake-objects in but in Ruby that's obviously overkill. What I come up seems already really nice compared to the Java-world. In my class under test I have an optional constructor parameter:

def initialize(file_class=File)

When I need to open files within my class, I can then do this:

@file_class.open(filename)

And the call goes to either the real File-class, or in case of my unit-test, it goes to a fake-class which doesn't touch the filesystem. I know there must be a better way to do this with metaprogramming?

[A]
Mocha (
http://mocha.rubyforge.org/
) is a very good mocking library for ruby.  Depending on what you're actually wanting to test (i.e. if you want to just fake out the File.new call to avoid the file system dependency or if you want to verify that the correct arguments are passed into File.new) you could do something like this:
```
```
require 'mocha'

mock_file_obj = mock("My Mock File") do
  stubs(:some_instance_method).returns("foo")
end

File.stubs(:new).with(is_a(String)).returns(mock_file_obj)
```
```


q:
I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE.

What are the steps to create such an executable?

[A]
Single Assembly Deployment of Managed and Unmanaged Code
Sunday, February 4, 2007
.NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs.
So here´s what I came up with for a solution:
I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources.
Then I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think.
```
```
namespace MyLib
{
    public class MyClass
    {
        static MyClass()
        {
            ResourceExtractor.ExtractResourceToFile("MyLib.ManagedService.dll", "managedservice.dll");
            ResourceExtractor.ExtractResourceToFile("MyLib.UnmanagedService.dll", "unmanagedservice.dll");
        }

        ...
```
```
In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code.
The code to extract the DLLs into files of their own is simple:
```
```
public static class ResourceExtractor
{
    public static void ExtractResourceToFile(string resourceName, string filename)
    {
        if (!System.IO.File.Exists(filename))
            using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create))
                {
                    byte[] b = new byte[s.Length];
                    s.Read(b, 0, b.Length);
                    fs.Write(b, 0, b.Length);
                }
    }
}
```
```
Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource.
For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g.
```
```
[DllImport("unmanagedservice.dll")] public extern static int Add(int a, int b);
```
```
That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient.
Enjoy!
http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx


q: Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking?

[A]
The CLR likes to optimize instructions, so when you access a field in code it might not always access the current value of the field (it might be from the stack, etc). Marking a field as
```
volatile
```
ensures that the current value of the field is accessed by the instruction. This is useful when the value can be modified (in a non-locking scenario) by a concurrent thread in your program or some other code running in the operating system.
You obviously lose some optimization, but it does keep the code more simple.


q: I'd like to add the HttpOnly flag to JSF/richfaces cookies, especially the session cookie, to up the level of security on my web app. Any ideas?

[A]
Something like:
```
```
response.setHeader("Set-Cookie", "yourcookiename=yourcookievalue; HTTPOnly");
```
```
might work in a Java environment. I am not aware of a JSF-specific way to achieve this... sorry
This seems to be not an easy task in Java.


q:
here is what a I'm doing:

object ReturnMatch(System.Type type)
{
    foreach(object obj in myObjects)
    {
        if (obj == type)
        {
            return obj;
        }
    }
}

However, if obj is a subclass of type, it will not match. But I would like the function to return the same way as if I was using the operator is.

I tried the following, but it won't compile:

if (obj is type) // won't compile in C# 2.0

The best solution I came up with was:

if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type))

Isn't there a way to use operator is to make the code cleaner?

[A]
Perhaps
```
```
type.IsAssignableFrom(obj.GetType())
```
```


q:
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:

result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness")
# result is None`

After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:

regex = ".*(a_regex_of_pure_awesomeness)"

into

regex = "a_regex_of_pure_awesomeness"

Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.

[A]
Are you using the
```
re.match()
```
or
```
re.search()
```
method? My understanding is that
```
re.match()
```
assumes a "
```
^
```
" at the beginning of your expression and will only search at the beginning of the text, while
```
re.search()
```
acts more like the Perl regular expressions and will only match the beginning of the text if you include a "
```
^
```
" at the beginning of your expression. Hope that helps.


q:
Is it possible in a large GWT project, load some portion of JavaScript lazy, on the fly?
   Like overlays.

PS: Iframes is not a solution.

[A]
I think this is what you are looking for.
```
```
<body onload="onloadHandler();">
<script type="text/javascript">
function onloadHandler() {
    if (document.createElement && document.getElementsByTagName) {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = './test.js';
        var heads = document.getElementsByTagName('head');
        if (heads && heads[0]) {
            heads[0].appendChild(script);
        }
    }
}
function iAmReady(theName) {
   if ('undefined' != typeof window[theName]) {
       window[theName]();
   }
}
function test() {
   // stuff to do when test.js loads
}
</script>
```
```
-- test.js
```
```
iAmReady('test');
```
```
Tested and working in Firefox 2, Safari 3.1.2 for Windows, IE 6 and Opera 9.52. I assume up-level versions of those should work as well.
Note that the loading is asynchronous. If you attempt to use a function or variable in the loaded file immediately after calling
```
appendChild()
```
it will most likely fail, that is why I have included a call-back in the loaded script file that forces an initialization function to run when the script is done loading.
You could also just call an internal function at the bottom of the loaded script to do something once it has loaded.


q:
What does the volatile keyword do? In C++ what problem does it solve?

In my case, I have never knowingly needed it.

[A]
```
volatile
```
is needed when developing embedded systems or device drivers, where you need to read or write a memory-mapped hardware device. The contents of a particular device register could change at any time, so you need the
```
volatile
```
keyword to ensure that such accesses aren't optimised away by the compiler.


q:
I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.

Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.


q: What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API?

[A]
If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models:
```
```
class Foo(models.Model):
    name = models.CharField(max_length=255)

class FizzBuzz(models.Model):
    bleh = models.CharField(max_length=255)

class Bar(models.Model):
    foo = models.ForeignKey(Foo)
    fizzbuzz = models.ForeignKey(FizzBuzz)
```
```
You can do something like:
```
```
Fizzbuzz.objects.filter(bar__foo__name = "Adrian")
```
```


q:
Can you use CMFCVisualManager with a dialog based application to change the applications appearance? If so how is it done?

The idea is to change the shape, colour etc. of controls such as push buttons using the MFC Feature Pack released with MSVC 2008.

[A]
No, can't be done, at least not if you're talking about the Feature Pack version. Version 10 of the BCGSoft libraries do have this functionality, see for example:
http://www.bcgsoft.com/bcgcontrolbarpro-versions.htm
and
http://www.bcgsoft.com/images/SkinnedBuiltInDlgs.jpg
. The MFC feature pack is more or less the previous version of the BCGSoft libraries, MS bought a license from them.


q:
I have a non-.Net executable file that is included in my .net assembly as an embedded resource.  Is there a way to run this executable that does not involve writing it out to disk and launching it?

This is .Net 2.0.

[A]
You can load a .NET assembly from a byte array using an overload of
Assembly.Load
.
However, there are implications for the security model that need to be considered which make things more complex.  See the discussion
here
, and also this
thread
.
If your embedded executable is not .NET then I think you will have to write it out to disk  first.


q:
I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, not a source code file -- but embed that file in the executable file like a resource.

(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)

Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)

[A]
Use macros. Technically that file would be
source code
file but it wouldn't look like this.
Example:
```
```
//queries.incl - SQL queries
Q(SELECT * FROM Users)
Q(INSERT [a] INTO Accounts)

//source.cpp
#define Q(query) #query,
char * queries[] = {
#include "queries.incl"
};
#undef Q
```
```
Later on you could do all sorts of other processing on that file by the same file, say you'd want to have array and a hash map of them, you could redefine Q to do another job and be done with it.


q:
Has anyone written an 'UnFormat' routine for Delphi?

What I'm imagining is the inverse of SysUtils.Format and looks something like this

UnFormat('a number %n and another %n',[float1, float2]);

So you could unpack a string into a series of variables using format strings.

I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.

[A]
This is called scanf in C, I've made a Delphi look-a-like for this :
```
```
function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer;
var
  InputOffset: Integer;
  FormatOffset: Integer;
  InputChar: Char;
  FormatChar: Char;

  function _GetInputChar: Char;
  begin
    if InputOffset <= Length(Input) then
    begin
      Result := Input[InputOffset];
      Inc(InputOffset);
    end
    else
      Result := #0;
  end;

  function _PeekFormatChar: Char;
  begin
    if FormatOffset <= Length(Format) then
      Result := Format[FormatOffset]
    else
      Result := #0;
  end;

  function _GetFormatChar: Char;
  begin
    Result := _PeekFormatChar;
    if Result <> #0 then
      Inc(FormatOffset);
  end;

  function _ScanInputString(const Arg: Pointer = nil): string;
  var
    EndChar: Char;
  begin
    Result := '';
    EndChar := _PeekFormatChar;
    InputChar := _GetInputChar;
    while (InputChar > ' ')
      and (InputChar <> EndChar) do
    begin
      Result := Result + InputChar;
      InputChar := _GetInputChar;
    end;

    if InputChar <> #0 then
      Dec(InputOffset);

    if Assigned(Arg) then
      PString(Arg)^ := Result;
  end;

  function _ScanInputInteger(const Arg: Pointer): Boolean;
  var
    Value: string;
  begin
    Value := _ScanInputString;
    Result := TryStrToInt(Value, {out} PInteger(Arg)^);
  end;

  procedure _Raise;
  begin
    raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]);
  end;

begin
  Result := 0;
  InputOffset := 1;
  FormatOffset := 1;
  FormatChar := _GetFormatChar;
  while FormatChar <> #0 do
  begin
    if FormatChar <> '%' then
    begin
      InputChar := _GetInputChar;
      if (InputChar = #0)
      or (FormatChar <> InputChar) then
        Exit;
    end
    else
    begin
      FormatChar := _GetFormatChar;
      case FormatChar of
        '%':
          if _GetInputChar <> '%' then
            Exit;
        's':
          begin
            _ScanInputString(Args[Result]);
            Inc(Result);
          end;
        'd', 'u':
          begin
            if not _ScanInputInteger(Args[Result]) then
              Exit;

            Inc(Result);
          end;
      else
        _Raise;
      end;
    end;

    FormatChar := _GetFormatChar;
  end;
end;
```
```


q:
I have a svn repository, R, that depends on a library, l, in another repository.

The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.

I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.

If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.

[A]
I suggest using a script wrapper for svn co.
```
```
#!/bin/sh
svn co path://server/R svn-R
git clone path://server/l git-l
```
```
Or similar.


q: Is there an easy way to capitalize the first letter of a string and lower the rest of it?  Is there a built in method or do I need to make my own?

[A]
```
TextInfo.ToTitleCase()
```
capitalizes the first character in each token of a string.
If there is no need to maintain Acronym Uppercasing, then you should include
```
ToLower()
```
.
```
```
string s = "JOHN DOE";
s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower());
// Produces "John Doe"
```
```
If CurrentCulture is unavailable, use:
```
```
string s = "JOHN DOE";
s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower());
```
```
See the
MSDN Link
for a detailed description.


q:
Imagine this directory structure:

app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py

I'm coding mod1, and I need to import something from mod2. How should I do it?

I tried from ..sub2 import mod2 but I'm getting an "Attempted relative import in non-package".

I googled around but found only "sys.path manipulation" hacks. Isn't there a clean way?

Edit: all my __init__.py's are currently empty

Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (sub1, subX, etc.).

Edit3: The behaviour I'm looking for is the same as described in PEP 366 (thanks John B)

[A]
Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From
PEP 328
:
Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.
In Python 2.6, they're adding the ability to reference modules relative to the main module.
PEP 366
describes the change.
Update
: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.


q: How can I redirect the response to an IFrame?

[A] . . . not totally sure what your trying to do, but you normally control the source of an iframe through javascript


q: Are there any programs or IDEs that support refactoring for Ruby or RoR?

[A] I believe net-beans and eclipse both support some refactoring within their 'ruby-mode' - also the emacs code browser (ECB)  and the various ruby support tools (e.g. rinari) for emacs have some support.


q: I have been researching asynchronous messaging, and I like the way it elegantly deals with some problems within certain domains and how it makes domain concepts more explicit. But is it a viable pattern for general domain-driven development (at least in the service/application/controller layer), or is the design overhead such that it should be restricted to SOA-based scenarios, like remote services and distributed processing?

[A]
Great question :). The main problem with asynchronous messaging is that when folks use procedural or object oriented languages, working in an asynchronous or event based manner is often quite tricky and complex and hard for the programmer to read & understand. Business logic is often way simpler if its built in a kinda synchronous manner - invoking methods and getting results immediately etc :).
My rule of thumb is generally to try use simpler synchronous programming models at the micro level for business logic; then use asynchrony and SEDA at the macro level.
For example submitting a purchase order might just write a message to a message queue; but the processing of the purchase order might require 10 different steps all being asynchronous and parallel in a high performance distributed system with many concurrent processes & threads processing individual steps in parallel. So the macro level wiring is based on a SEDA kind of approach - but at the micro level the code for the individual 10 steps could be written mostly in a synchronous programming style.


q: If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?

[A]
A Lambda expression can contain complex statements, so you can do the following:
```
```
Func<IEnumerator, object> f = ie => { ie.MoveNext(); return ie.Current; };
```
```


q:
Using Django's built in models, how would one create a triple-join between three models.

For example:

Users, Roles, and Events are the models.

Users have many Roles, and Roles many Users.  (ManyToMany)

Events have many Users, and Users many Events. (ManyToMany)

But for any given Event, any User may have only one Role.

How can this be represented in the model?

[A]
I'd recommend just creating an entirely separate model for this.
```
```
class Assignment(Model):
    user = ForeignKey(User)
    role = ForeignKey(Role)
    event = ForeignKey(Event)
```
```
This lets you do all the usual model stuff, such as
```
```
user.assignment_set.filter(role__name="Chaperon")
role.assignment_set.filter(event__name="Silly Walkathon")
```
```
The only thing left is to enforce your one-role-per-user-per-event restriction.  You can do this in the Assignment class by either overriding the save method (
http://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods
) or using signals (
http://docs.djangoproject.com/en/dev/topics/signals/
)


q:
I am trying to program a small server+client in Javascript on Firefox, using XPCOM.

To get the HTTP message in Javascript, I am using the nsIScriptableInputStream interface.
This f**ing component through the read() method randomly cut the message and I cannot make it reliable.

Is anybody know a solution to get reliably the information? (I already tried a binary stream, same failure.)

J.

[A]
If you control the protocol (that is, both the client and server) I would highly recommend using Javascript/JSON for your server-to-client messages.  The client can open a stream either via dynamically adding a <script> tag to the DOM.  The server can then send a stream of Javascript commands like:
```
```
receiveMsg({type:"text", content:"this is my message"});
```
```
Then the client just needs to define a receiveMsg function. This allows you to rely on fast browser code to parse the message and determine where the end of each message is, at which point it will call your handler for you.
Even if you're working with an existing HTTP protocol and can't use JSON, is there some reason you can't use XMLHttpRequest?  I would expect it to be more stable than some poorly documented Firefox-specific XPCOM interface.
--Chouser


q:
This is from an example accompanying the agsXMPP .Net assembly.  I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message.  I guess what I'm looking for is an understanding of why delegate(0) accomplishes this, in the kind of simple terms I can understand.

xmpp.OnLogin += delegate(object o) {
    xmpp.Send(new Message(new Jid(JID_RECEIVER),
    MessageType.chat,
    "Hello, how are you?"));
};

[A] That is creating an anonymous function.  This feature was introduced in C# 2.0


q:
I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.

I have an array (in Ruby) that I need to sort by multiple conditions.  I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions.  However, in this case I need the first condition to sort ascending and the second to sort descending.  For example:

ordered_list = [[1, 2], [1, 1], [2, 1]]

Any suggestions?

Edit:  Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here).  So for a simple example it's more like:

ordered_list = [[1, "b"], [1, "a"], [2, "a"]]


q:
I need to run a stored procedure from a C# application.

I use the following code to do so:

Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();

From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).

How can I customize these return codes?

H.

[A]
If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line.  Look at
```
SqlConnection
```
and
```
SqlCommand
```
in the
```
System.Data.SqlClient
```
namespace.
Once you are calling the stored procedure via
```
SqlCommand
```
you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.


q:
I'm working with a fairly simple database, from a Java application.  We're trying to insert about 200k of text at a time, using the standard JDBC mysql adapter.  We intermittently get a com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column error.

The column type is longtext, and database collation is UTF-8.  The error shows up using both MyISAM and InnoDB table engines.  Max packet size has been set ot 1 GB on both client and server sides, so that shouldn't be causing a problem, either.

[A]
Well you can make it ignore the error by doing an INSERT IGNORE which will just truncate the data and insert it anyway. (from
http://dev.mysql.com/doc/refman/5.0/en/insert.html
)
If you use the IGNORE keyword, errors
  that occur while executing the INSERT
  statement are treated as warnings
  instead. For example, without IGNORE,
  a row that duplicates an existing
  UNIQUE index or PRIMARY KEY value in
  the table causes a duplicate-key error
  and the statement is aborted. With
  IGNORE, the row still is not inserted,
  but no error is issued. Data
  conversions that would trigger errors
  abort the statement if IGNORE is not
  specified. With IGNORE, invalid values
  are adjusted to the closest values and
  inserted; warnings are produced but
  the statement does not abort.


q:
For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.

This is a readonly textbox used only for display.  It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check  for overflow (if so, how to tell if the text fits?)

Not having any luck with various combinations of WordWrap and Scrollbars settings.  I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.

@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.

@André Neves, good point, and I would go that way if it was user-editable.  I agree that consistency is the cardinal rule for UI intuitiveness.

[A]
I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal bar always shows as long as it's enabled and
```
WordWrap == false
```
.
I think you're not going to get exactly what you want here. However, I believe that users would like better Windows' default behavior than the one you're trying to force. If I were using your app, I probably would be bothered if my textbox real-estate suddenly shrinked just because it needs to accomodate an unexpected scrollbar because I gave it too much text!
Perhaps it would be a good idea just to let your application follow Windows' look and feel.


q:
I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array new thus:

STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize];

Later on however the memory is freed using a delete call:

delete pStruct;

Will this mix of array new[] and non-array delete cause a memory leak or would it depend on the compiler?  Would I be better off changing this code to use malloc and free instead?

[A]
Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.
Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)
Better would be to do it correctly, as this will also correctly call any constructors and deconstructors
```
```
STRUCT* pStruct = new STRUCT;
...
delete pStruct;
```
```


q: Are there any utilities or browser plugins that let you easily switch the version of the Flash player that is being used?

[A]
Found the following:
http://www.google.be/search?q=firefox%20switch%20flash%20version
http://www.sephiroth.it/weblog/archives/2006/10/flash_switcher_for_firefox.php
(seems nice)
http://www.communitymx.com/content/article.cfm?page=2&cid=6FBA7
(seems nicely integrated as well)
https://addons.mozilla.org/nl/firefox/addon/5044
(from mozilla.org, must be good :p)


q:
I want to use a specific foreign language font for a Blackberry application.  How is such a font created and loaded onto the Blackberry device?

For example: ਪੰਜਾਬੀ

[A]
A quick google search shows that the same thing has been asked at
blackberry forums
.
The solution they came up with is a class for loading the font from a
fnt file
.
There are
programs available
to import and edit fnt files.


q: I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.

[A] Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function.  A delegate can do a lot more than just anonymous functions: things like events, asynchronous calls, and multiple method chains.


q: If a user saves the password on the login form, ff3 is putting the saved password in the change password dialoge on the profile page, even though its not the same input name as the login. how can I prevent this?

[A]
Try using autocomplete="off" as an attribute of the text box. I've used it in the past to stop credit card details being stored by the browser but i dont know if it works with passwords. e.g.
```
print("<input type="text" name="cc" autocomplete="off" />");
```


q:
Looking for a way to read the unique ID / serial# of a USB thumb drive;
please note that

- I am looking for the value of the manufacturer, not the one Windows allocates for it.

- I need to support multiple OS (Windows, Unix, Mac), thus needs to be a Java solution

The idea is to be able to distinguish between different USB thumb drives.

[A]
I've never tried using it (it's been on my todo list for a good few months now), but there is the "marge" project on java.net:
http://marge.java.net/
This should let you connect to bluetooth devices (although I don't think it is 100% feature complete, there is demo code on there), and then the ClientDevice class has a "getBluetoothAddress" method which I
believe
should be unique to that device
http://marge.java.net/javadoc/v06/marge-core/net/java/dev/marge/entity/ClientDevice.html
As I say though, I've never tried it...


q: What is the difference between Introspection and Reflection in .NET

[A]
They're two parts of the same whole.
Introspection refers to the ability of a class to look 'inside' itself and see, for example, what parameters a method takes, what the names of its members are, etc.
Reflection is the specific name for how .NET implements introspection.  Other languages may call it something different (C++ calls its limited introspection RTTI, for run-time type information).


q:
Is there an easy way to convert a string from csv format into a string[] or list?

I can guarantee that there are no commas in the data.


q:
Does a caching-nameserver usually cache the negative DNS response SERVFAIL?

EDIT:
To clarify the question, I can see the caching nameserver caching negative responses NXDOMAIN, NODATA. But it does not do this for SERVFAIL responses. Is this intentional?

[A] One of the timeout fields in the SOA is a "negative timeout". It is usually set to a short time, such as 30 or 60 seconds. So, yes, but for a shorter time than a "positive" response.


q: What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?

[A]
How about this:
```
```
master.sys.fn_varbintohexstr(@binvalue)
```
```


q: We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?

[A]
No, it isn't true, you can encode XML to any Writer in Java using something similar to:
```
```
char[] ch;
AttributesImpl atts = new AttributesImpl();
Writer writer = new StringWriter();
StreamResult streamResult = new StreamResult(writer);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();

// SAX2.0 ContentHandler
TransformerHandler transformerHandler = tf.newTransformerHandler();

Transformer serializer = transformerHandler.getTransformer();

serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
// serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");

transformerHandler.setResult(streamResult);

transformerHandler.startDocument();

atts.clear();
// atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes");
// atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
// atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd");
transformerHandler.startElement("", "", "node_list", atts);

// displayName element
if (displayName != null) {
    transformerHandler.startElement("", "", "display_name", null);
    ch = displayName.toCharArray();
    transformerHandler.characters(ch, 0, ch.length);
    transformerHandler.endElement("", "", "display_name");
}

// nodes element
transformerHandler.startElement("", "", "nodes", null);

atts.clear();
atts.addAttribute("", "", "node_type", "CDATA", "sometype");
transformerHandler.startElement("", "", "node", atts);

ch = node.getValue().toCharArray();
transformerHandler.startElement("", "", "value", null);
transformerHandler.characters(ch, 0, ch.length);
transformerHandler.endElement("", "", "value");

transformerHandler.endElement("", "", "node");

transformerHandler.endElement("", "", "nodes");

transformerHandler.endElement("", "", "node_list");

transformerHandler.endDocument();

String xml = writer.toString();
```
```


q:
When I'm initializing a dialog, I'd like to select one of the radio buttons on the form.  I don't see a way to associate a Control variable using the Class Wizard, like you would typically do with CButtons, CComboBoxes, etc...

Further, it doesn't like a CRadioButton class even exists.

How can I select one of the several radio buttons?

[A]
Radio buttons and check buttons are just buttons.  Use a
```
CButton
```
control and use
```
GetCheck
```
/
```
SetCheck
```
.


q:
I am getting some errors thrown in my code when I open a Windows Forms form in Visual Studio's designer. I would like to branch in my code and perform a different initialization if the form is being opened by designer than if it is being run for real.

How can I determine at run-time if the code is being executed as part of designer opening the form?

[A]
```
```
System.Diagnostics.Debugger.IsAttached
```
```


q:
In a silverlight application, I want to access the page the silverlight .xap file from an HTTP subdomain, but have the web services access a different subdomain for sensitive information over HTTPS.

I set up clientaccesspolicy.xml at the root of the subdomain and it lets the silverlight app access its services over http, but not over https.  It gives the cross domain access error that it would give normally without a clientaccesspolicy in place.

I know that browsers themselves have a lot of restrictions about mixing http and https.  Am I trying to do something that is not allowed?

[A]
Check out:
http://silverlight.net/forums/t/12741.aspx
You can either make https calls to the
  same domain or http cross-domain
  calls, but not https cross-domain
  calls.
This is described in
http://msdn2.microsoft.com/en-us/library/cc189008(VS.95).aspx
(see "If not HTTPS" in the matrix)
  By JohnSpurlock


q: I'm developing a client/server app that will communicate via rest. Some custom request data will be stored in the header of the request. Both the server sending the request and the receiving server have an SSL certificate - will the headers be encrypted, or just the content?

[A]
SSL encrypts the entire communications path from the client to the server and back, so yes - the headers will be encrypted.
By the way, if you develop networked applications and care about data security, the least you should do is read a book like Practical Cryptography, by Niels Ferguson and Bruce Schneier, and probably further reading that's more focused on web application security would be a good idea. If I may make an observation - and please, I don't mean that as a personal criticism - your question indicates a fundamental lack of understanding of very basic web security technologies, and that's never a good sign.
Also, it's never a bad idea to confirm that data which is assumed to be encrypted is indeed encrypted. You can use a network analyzer to monitor traffic on the wire and watch out for anything sensitive being sent in the clear. I've used Wireshark to do this before - the results can be surprising, sometimes.


q:
I have an List and I'd like to wrap it into an IQueryable.

Is this possible?

[A]
```
```
List<int> list = new List<int>() { 1, 2, 3, 4, };
IQueryable<int> query = list.AsQueryable();
```
```
If you don't see the
```
AsQueryable()
```
method, add a using statement for
```
System.Linq
```
.


q: If you have a JSF <h:commandLink> (which uses the onclick event of an <a> to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed?

[A]
```
```
<h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}">
    <h:outputText value="#{msgs.deleteText}" />
</h:commandLink>
<script type="text/javascript">
if (document.getElementById) {
    var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />');
    if (commandLink && commandLink.onclick) {
        var commandLinkOnclick = commandLink.onclick;
        commandLink.onclick = function() {
            var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?');
            if (result) {
                return commandLinkOnclick();
            }
            return false;
        }
    }
}
</script>
```
```
Other Javascript actions (like validating form input etc) could be performed by replacing the call to
```
confirm()
```
with a call to another function.


q:
I have a string that is like below.

,liger, unicorn, snipe

in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?

Thanks.

There's been a lot of back and forth about the StartTrim function.  As several have pointed out, the StartTrim doesn't affect the primary variable.  However, given the construction of the data vs the question, I'm torn as to which answer to accept.  True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data.  So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.


q: How can I start an interactive console for Perl, similar to the irb command for Ruby or python for Python?

[A]
```
perl -d
```
is your friend:
```
```
% perl -de 0
```
```


q:
The following will cause infinite recursion on the == operator overload method

    Foo foo1 = null;
    Foo foo2 = new Foo();
    Assert.IsFalse(foo1 == foo2);

    public static bool operator ==(Foo foo1, Foo foo2) {
        if (foo1 == null) return foo2 == null;
        return foo1.Equals(foo2);
    }

How do I check for nulls?

[A]
Cast to object in the overload method:
```
```
public static bool operator ==(Foo foo1, Foo foo2) {
    if ((object) foo1 == null) return (object) foo2 == null;
    return foo1.Equals(foo2);
}
```
```


q:
I have a dropdownlist with the autopostback set to true. I want the
user to confirm if they really want to change the value,
which on post back fires a server side event (selectedindexchanged).

I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm
result and the value in the list does not revert back if cancel
selected.

When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ).

Any leads will be helpful.

Thanks!

[A]
Make sure your event is wired:
```
```
dropDown.SelectedIndexChanged += new EventHandler(dropDown_SelectedIndexChanged);
```
```
You can also apply a client-side attribute to return the confirmation. Set the index accordingly if cancelled.
```
```
dropDown.Attributes.Add("onchange", "javascript: return confirm('confirmation msg')");
```
```


q: I've heard people referring to this table and was not sure what it was about.

[A]
I think this wikipedia article may help clarify.
http://en.wikipedia.org/wiki/DUAL_table
The DUAL table is a special one-row
  table present by default in all Oracle
  database installations. It is suitable
  for use in selecting a pseudocolumn
  such as SYSDATE or USER The table has
  a single VARCHAR2(1) column called
  DUMMY that has a value of "X"


q:
I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells.  The cells may contain text, numbers or be blank.  I am not very familiar / comfortable working with the concept of 'Range'.  Therefore, any sample codes would be greatly appreciated.  (I did try to google it, but the code snippets I found didn't quite do what I needed)

Thank you.

[A]
In Excel VBA, this function will give you the content of any cell in any worksheet.
```
```
Function getCellContent(Byref ws As Worksheet, ByVal rowindex As Integer, ByVal colindex As Integer) as String
    getCellContent = CStr(ws.Cells(rowindex, colindex))
End Function
```
```
So if you want to check the value of cells, just put the function in a loop, give it the reference to the worksheet you want and the row index and column index of the cell. Row index and column index both start from 1, meaning that cell A1 will be ws.Cells(1,1) and so on.


q: How do I tell Subversion (svn) to treat a file as a binary file?

[A]
For example:
```
```
svn propset svn:mime-type image/png foo.png
```
```


q: Has anyone run into issues serializing components into a file and reading them back, specifically in the area where the component vendor upgrades the VCL components.  For example a file serialized with DelphiX and then years later read back with delphiY.  Do the serialization formats change and if so what can be done to prevent errors reading in the componets when upgrading.

[A]
Formats will defintely change, as vendors will add features to their components. Serialization simply loops over all published properties and saves them to a stream. When they are read back, each of the properties that is read from the stream will be set back to the component. If the property does not exist anymore, you have a problem. I don't think you can do anything about that besides some basic exception handling.
Best way to guarantee compatibility is to do your own serialization.


q: I would like to write small console based applications on Windows Mobile.  What console applications might I use?

[A]
There is no command prompt style console on Windows Mobile.  If you're really after a command prompt, check out www.pocketdos.com for a high level of dos application compatibility.
If you're more interested in writing small applications for Windows Mobile, C# or VB.Net are your best choices.
On small mobile devices like this, command prompts are significantly harder for users to interact with compared to GUI based applications.


q:
I'm looking into clustering points on a map (latitude/longitude). Are there any recommendations as to a suitable algorithm that is fast and scalable?

More specifically, I have a series of latitude/longitude coordinates and a map viewport. I'm trying to cluster the points that are close together in order to remove clutter.

I already have a solution to the problem (see here), only I am wondering if there is any formal algorithm that solves the problem efficiently.

[A]
Google Maps Hacks
has a hack,
"Hack 69. Cluster Markers at High Zoom Levels"
, on that.
Also, see
Wikipedia on clustering algorithms
.


q: How can I combine multiple PDFs into one PDF without a 3rd party component?

[A]
AFAIK C# has no built-in support for handling PDF so what you are asking can not be done without using a 3rd party component or a COTS library.
Regarding libraries there is a myriad of possibilities. Just to point a few:
http://csharp-source.net/open-source/pdf-libraries
http://www.codeproject.com/KB/graphics/giospdfnetlibrary.aspx
http://www.pdftron.com/net/index.html


q:
In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.

The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?

Thanks

[A]
It should be something like:
```
ifconfig eth0 192.168.0.42 up
```
Replace eth0 by the network interface of your network card, obviously adapt the ip address to your needs and the up is only necessary once, but doesn't hurt if you run it each time.


q:
In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content.

This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(

Is there any workaround for this problem?
How can I use CSS to set different widths for dropbox and the dropdownlist?

[A]
You can add a style directly to the select element:
```
<select name="foo" style="width: 200px">
```
So this select item will be 200 pixels wide.
Alternatively you can apply a class or id to the element and reference it in a stylesheet


q:
In JavaScript, what is the best way to determine if a date provided falls within a valid range?

An example of this might be checking to see if the user input requestedDate is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.

[A]
So if i understand currenctly, you need to look if one date is bigger than the other.
```
```
function ValidRange(date1,date2)
{
   return date2.getTime() > date1.getTime();
}
```
```
You then need to parse the strings you are getting from the UI, with Date.parse, like this:
```
```
ValidRange(Date.parse('10-10-2008'),Date.parse('11-11-2008'));
```
```
Does that help?


q: I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?

[A]
An explicit cursor is one you declare, like:
```
```
CURSOR my_cursor IS
  SELECT table_name FROM USER_TABLES
```
```
An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).


q:
How can I specify the filename when dumping data into the response stream?

Right now I'm doing the following:

byte[] data= GetFoo();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.BinaryWrite(data);
Response.End();

With the code above, I get "foo.aspx.pdf" as the filename to save.  I seem to remember being able to add a header to the response to specify the filename to save.

[A]
```
```
Response.AppendHeader("Content-Disposition", "attachment; filename=foo.pdf");
```
```


q: I'm looking for real world best practices, how other people might have implemented solutions with complex domains.

[A]
This is what
MSDN
has to say about IEqualityComparer (non-generic):
This interface allows the implementation of customized equality comparison for collections. That is, you can create your own definition of equality, and specify that this definition be used with a collection type that accepts the
```
IEqualityComparer
```
interface. In the .NET Framework, constructors of the
```
Hashtable
```
,
```
NameValueCollection
```
, and
```
OrderedDictionary
```
collection types accept this interface.
This interface supports only equality comparisons. Customization of comparisons for sorting and ordering is provided by the
```
IComparer
```
interface.
It looks like the generic version of this interface performs the same function but is used for
```
Dictionary<(Of <(TKey, TValue>)>)
```
collections.
As far as best practices around using this interface for your own purposes.  I would say that the best practice would be to use it when you are deriving or implementing a class that has similar functionality to the above mentioned .NET framework collections and where you want to add the same capability to your own collections.  This will ensure that you are consistent with how the .NET framework uses the interface.
In other words support the use of this interface if you are developing a custom collection and you want to allow your consumers to control equality which is used in a number of LINQ and collection related methods (eg. Sort).


q:
Is there a way to use sql-server like analytic functions in Hibernate?

Something like

select foo from Foo foo where f.x = max(f.x) over (partition by f.y)

[A]
You are after a native SQL query.
If you are using JPA the syntax is:
```
```
Query q = em.createNativeQuery("select foo.* from Foo foo " +
                               "where f.x = max(f.x) over " +
                               "(partition by f.y)", Foo.class);
```
```
If you need to return multiple types, take a look at the
SQLResultSetMapping
annotation.
If you're using the the Hibernate API directly:
```
```
Query q = session.createSQLQuery("select {foo.*} from Foo foo " +
                                 "where f.x = max(f.x) over "+
                                 "(partition by f.y)");
q.addEntity("foo", Foo.class);
```
```
See
10.4.4. Queries in native SQL
in the Hibernate documentation for more details.
In both APIs you can pass in parameters as normal using setParameter.


q:
When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report.

It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas?


q:
I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc.  Normally you could use callable() for this, but I don't want to include classes.  The best I've come up with so far is:

isinstance(obj, (types.BuiltinFunctionType, types.FunctionType, types.MethodType))

Is there a more future-proof way to do this check?

Edit: I misspoke before when I said: "Normally you could use callable() for this, but I don't want to disqualify classes."  I actually do want to disqualify classes.  I want to match only functions, not classes.

[A]
```
```
if hasattr(obj, '__call__'): pass
```
```
This also fits in better with Python's "duck typing" philosophy, because you don't really care
what
it is, so long as you can call it.
It's worth noting that
```
callable()
```
is being removed from Python and is not present in 3.0.


q: It seems obvious that some people have been able to figure out how to access the iPhone camera through the SDK (Spore Origins, for example). How can this be done?

[A]
You need to use the
```
UIImagePickerController
```
class, basically:
```
```
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = pickerDelegate
picker.sourceType = UIImagePickerControllerSourceTypeCamera
```
```
The
```
pickerDelegate
```
object above needs to implement the following method:
```
```
- (void)imagePickerController:(UIImagePickerController *)picker
           didFinishPickingMediaWithInfo:(NSDictionary *)info
```
```
The dictionary
```
info
```
will contain entries for the original, and the edited image, keyed with
```
UIImagePickerControllerOriginalImage
```
and
```
UIImagePickerControllerEditedImage
```
respectively. (see
https://developer.apple.com/documentation/uikit/uiimagepickercontrollerdelegate
and
https://developer.apple.com/documentation/uikit/uiimagepickercontrollerinfokey
for more details)


q:
I have a Windows XP SP2 virtual machine which can be accessed via VNC. It's also running Deep Freeze so there should be no problem in forcing it to reboot. I am looking for a way to force the operating system to reboot instead of shutting down or completely remove the ability to shut down the machine using software applications (such as the usual way from the start menu, the shutdown program or other custom programs).

Thank you,
Tom

[A]
Try this:
```
shutdown /r /t 1 /f
```
Alex


q: How do you convert between hexadecimal numbers and decimal numbers in C#?

[A]
```
```
String stringrep = myintvar.ToString("X");

int num = int.Parse("FF", System.Globalization.NumberStyles.HexNumber);
```
```


q:
I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES
  (SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1);

I tried but get a syntax error message.

What would you do if you want to do this?

[A]
Remove
```
VALUES
```
from your SQL.


q:
I have been playing with this for a while, but the closest I have gotten is a button that opens the Paste Special dialog box and requires another couple of mouse clicks to paste the contents of the clipboard as unformatted text.

So often I am doing a copy-paste from a web site into a document where I don't want the additional baggage of the HTML formatting, it would be nice to be able to do this with a shortcut key or a toolbar button.

[A]
Make the button call the macro:
```
```
public sub PasteSpecialUnformatted()
  selection.pastespecial datatype:=wdpastetext
end sub
```
```


q:
Is there a way to restart the Rails app (e.g. when you've changed a plugin/config file) while Mongrel is running. Or alternatively quickly restart Mongrel. Mongrel gives these hints that you can but how do you do it?

** Signals ready.  TERM => stop.  USR2 => restart.  INT => stop (no restart).

** Rails signals registered.  HUP => reload (without restart).  It might not work well.

[A]
For example,
```
```
killall -USR2 mongrel_rails
```
```


q:
On a JSTL/JSP page, I have a java.util.Date object from my application. I need to find the day after the day specified by that object. I can use <jsp:scriptlet> to drop into Java and use java.util.Calendar to do the necessary calculations, but this feels clumsy and inelegant to me.

Is there some way to use JSP or JSTL tags to achieve this end without having to switch into full-on Java, or is the latter the only way to accomplish this?

[A]
While this does not answer your initial question, you could perhaps eliminate the hassle of going through java.util.Calendar by doing this:
```
```
// Date d given
d.setTime(d.getTime()+86400000);
```
```


q:
I have an ext combobox which uses a store to suggest values to a user as they type.

An example of which can be found here: combobox example

Is there a way of making it so the suggested text list is rendered to an element in the DOM. Please note I do not mean the "applyTo" config option, as this would render the whole control, including the textbox to the DOM element.

[A]
So clarify, you want the selected text to render somewhere besides directly below the text input. Correct?
ComboBox is just a composite of
Ext.DataView
, a text input, and an optional trigger button. There isn't an official option for what you want and hacking it to make it do what you want would be really painful. So, the easiest course of action (other than finding and using some other library with a component that does exactly what you want) is to build your own with the components above:
Create a text box. You can use an
Ext.form.TextField
if you want, and observe the keyup event.
Create a DataView bound to your store, rendering to whatever DOM element you want. Depending on what you want, listen to the 'selectionchange' event and take whatever action you need to in response to the selection. e.g., setValue on an Ext.form.Hidden (or plain HTML input type="hidden" element).
In your keyup event listener, call the store's filter method (see
doc
), passing the field name and the value from the text field. e.g., store.filter('name',new RegEx(value+'.*'))
It's a little more work, but it's a lot shorter than writing your own component from scratch or hacking the ComboBox to behave like you want.


q: I am working on a large C++ project in Visual Studio 2008, and there are a lot of files with unnecessary #include directives. Sometimes the #includes are just artifacts and everything will compile fine with them removed, and in other cases classes could be forward declared and the #include could be moved to the .cpp file.  Are there any good tools for detecting both of these cases?

[A]
While it won't reveal unneeded include files, Visual studio has a setting
```
/showIncludes
```
(right click on a
```
.cpp
```
file,
```
Properties->C/C++->Advanced
```
) that will output a tree of all included files at compile time.  This can help in identifying files that shouldn't need to be included.
You can also take a look at the pimpl idiom to let you get away with fewer header file dependencies to make it easier to see the cruft that you can remove.


q:
I need to convert a value which is in a DateTime variable into a varchar variable formatted as yyyy-mm-dd format (without time part).

How do I do that?

[A]
Try the following:
```
```
CONVERT(varchar(10), [MyDateTimecolumn], 20)
```
```
For a full date time and not just date do:
```
```
CONVERT(varchar(23), [MyDateTimecolumn], 121)
```
```
See this page for convert styles:
http://msdn.microsoft.com/en-us/library/ms187928.aspx
OR
SQL Server CONVERT() Function


q:
I am trying to use the import random statement in python, but it doesn't appear to have any methods in it to use.

Am I missing something?

[A]
I think you need to give some more information.  It's not really possible to answer why it's not working based on the information in the question.  The basic documentation for random is at:
https://docs.python.org/library/random.html
You might check there.


q:
What is the easiest way to manage the authorized_keys file for openssh across a large number of hosts? If I need to add or revoke a new key to an account on 10 hosts say, I must login and add the public key manually, or through a clumsy shell script, which is time consuming.

Ideally there would be a central database linking keys to accounts@machines with some sort of grouping support (IE, add this key to username X on all servers in the web category). There's fork of SSH with ldap support, but I'd rather use the mainline SSH packages.

[A]
I've always done this by maintaining a "master" tree of the different servers' keys, and using rsync to update the remote machines. This lets you edit things in one location, push the changes out efficiently, and keeps things "up to date" -- everyone edits the master files, no one edits the files on random hosts.
You may want to look at projects which are made for running commands across groups of machines, such as Func at
https://fedorahosted.org/func
or other server configuration management packages.


q:
I have a .ico file that is embedded as a resource (build action set to resource).  I am trying to create a NotifyIcon.  How can I reference my icon?

notifyIcon = new NotifyIcon();
notifyIcon.Icon = ??     // my icon file is called MyIcon.ico and is embedded

[A]
Your icon file should be added to one of your project assemblies and its Build Action should be set to Resource. After adding a reference to the assembly, you can create a NotifyIcon like this:
```
```
System.Windows.Forms.NotifyIcon icon = new System.Windows.Forms.NotifyIcon();
Stream iconStream = Application.GetResourceStream( new Uri( "pack://application:,,,/YourReferencedAssembly;component/YourPossibleSubFolder/YourResourceFile.ico" )).Stream;
icon.Icon = new System.Drawing.Icon( iconStream );
```
```


q:
I have a function that takes, amongst others, a parameter declared as int privateCount.  When I want to call ToString() on this param, ReSharper greys it out and marks it as a redundant call.  So, curious as I am, I remove the ToString(), and the code still builds!

How can a C# compiler allow this, where str is a string?

str += privateCount + ...

[A]
The + operator for string is overloaded to call String.Concat passing in the left and right side of the expression. Thus:
```
```
string x = "123" + 45;
```
```
Gets compiled to:
```
```
String.Concat("123", 45);
```
```
Since String.Concat takes in two objects, the right hand side (45) is boxed and then ToString() is called on it.
Note that this "overloading" is not via operator overloading in the language (aka it's not a method named op_Addition) but is handled by the compiler.


q:
I'm developing a website on an XP virtual machine and have an SMTP virtual server set up in IIS -- it delivers mail just fine. What I would like is to confirm that any emails the site sends are only going to a specific domain.

The XP firewall seems to only involve incoming connections, I can't block outgoing TCP on port 25. And I haven't been able to configure the SMTP server to filter by delivery address.

With this setup, is there any easy way to filter outgoing email by destination address?

[A]
I think the easiest way would be to add a check to your mail sending code on the website (there's got to be some class which is in charge of sending the mails out).
You could include a check which is only active when the code is compiled in debug mode (using compiler directives). Thus, when you are developing and building the site in debug mode, this code checks if the outgoing messages are valid (specific domain) or not. If they are it lets them go, else it doesn't send the mail.


q: I would like to use the 7-Zip DLLs from Delphi but have not been able to find decent documentation or examples.  Does anyone know how to use the 7-Zip DLLs from Delphi?

[A]
As of release 1.102 the
JEDI Code Library
has support for
7-Zip
built into the
JclCompression
unit. Haven't used it myself yet, though.


q:
Does anyone have details in setting up Qt4 in Visual Studio 2008? Links to other resources would be appreciated as well.

I already know that the commercial version of Qt has applications to this end. I also realize that I'll probably need to compile from source as the installer for the open source does not support Visual Studio and installs Cygwin.


q:
In Team Foundation Server, I know that you can use the Annotate feature to see who last edited each line in a particular file (equivalent to "Blame" in CVS). What I'd like to do is akin to running Annotate on every file in a project, and get a summary report of all the developers who have edited a file in the project, and how many lines of code they currently "own" in that project.

Aside from systematically running Annotate of each file, I can't see a way to do this. Any ideas that would make this process faster?

PS - I'm doing to this to see how much of a consultant's code still remains in a particular (rather large) project, not to keep tabs on my developers, in case you're worried about my motivation :)

[A]
It's easy enough to use the "tf.exe history" command recursively across a directory of files in TFS. This will tell you who changed what files.
However what you're after is a little bit more than this - you want to know if the latest versions of any files have lines written by a particular user.
The Team Foundation Power Tools ship with a command-line version of annotate called "tfpt.exe annotate". This has a /noprompt option to direct the output to the console, but it only outputs the changeset id - not the user name.
You could also use the TFS VersionControl object model to write a tool that does exactly what you need.


q: I am interested in writing static code analyzer for vb.net to see if it conforms to my company standard coding guidelines. Please advise from where i have to start.

[A]
Rather than write your own static code analyzer, I recommend you use
FxCop
: and instead, write custom FxCop rules for your needs. It'll save you a lot of time.
http://www.binarycoder.net/fxcop/


q:
I'm maintaining the Perl Beginners' Site and used a modified template from Open Source Web Designs. Now, the problem is that I still have an undesired artifact: a gray line on the left side of the main frame, to the left of the navigation menu. Here's an image highlighting the undesired effect.

How can I fix the CSS to remedy this problem?

[A]
It's the
```
background-image
```
on the body showing through. Quick fix (edit style.css or add elsewhere):
```
```
#page-container
{
   background-color: white;
}
```
```


q:
I have a table inside a div. I want the table to occupy the entire width of the div tag.

In the CSS, I've set the width of the table to 100%.  Unfortunately, when the div has some margin on it, the table ends up wider than the div it's in.

I need to support IE6 and IE7 (as this is an internal app), although I'd obviously like a fully cross-browser solution if possible!

I'm using the following DOCTYPE...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Edit: Unfortunately I can't hard-code the width as I'm dynamically generating the HTML and it includes nesting the divs recursively inside each other (with left margin on each div, this creates a nice 'nested' effect).

[A]
The following works for me in Firefox and IE7... a guideline, though is: if you set width on an element, don't set margin or padding on the same element. This holds true
especially
if you're mixing units -- say, mixing percents and pixels.
```
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Test</title>

      This is the outer div

        This is the inner div

            Here is my td

```
```
See
here
for an example.


q:
Every project I compile with Delphi 7, in which I do not compile with run-time packages, gives a linker error: "Too many resources". Even a blank application gives this error.

In other words: Delphi died on me.

[A]
What happens when you try to build it from the command line?
(i.e., \Program Files\Borland\Delphi7\Bin\dcc32.exe)
Also, have you build any custom .RES files for this project?  If not, try deleting the default .RES that Delphi created for you, and let it get re-created by the project.
You can also force an update to the .RES file by changing something trivial, like the version #, saving your project, then changing it back again.
Sorry these are not answers... but hopefully we will find the issue with a little poking around.


q:
example:

public static void DoSomething<K,V>(IDictionary<K,V> items) {
   items.Keys.Each(key => {
      if (items[key] **is IEnumerable<?>**) { /* do something */ }
      else { /* do something else */ }
}

Can this be done without using reflection? How do I say IEnumerable in C#? Should I just use IEnumerable since IEnumerable<> implements IEnumerable?

[A]
```
```
if (typeof(IEnumerable).IsAssignableFrom(typeof(V))) {
```
```


q:
Can't understand why the following takes place:

String date = "06-04-2007 07:05";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm");
Date myDate = fmt.parse(date);

System.out.println(myDate);  //Mon Jun 04 07:05:00 EDT 2007
long timestamp = myDate.getTime();
System.out.println(timestamp); //1180955100000 -- where are the milliseconds?

// on the other hand...

myDate = new Date();
System.out.println(myDate);  //Tue Sep 16 13:02:44 EDT 2008
timestamp = myDate.getTime();
System.out.println(timestamp); //1221584564703 -- why, oh, why?

[A]
What milliseconds? You are providing only minutes information in the first example, whereas your second example grabs current date from the system with milliseconds, what is it you're looking for?
```
```
String date = "06-04-2007 07:05:00.999";
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss.S");
Date myDate = fmt.parse(date);

System.out.println(myDate);
long timestamp = myDate.getTime();
System.out.println(timestamp);
```
```


q: I need to check CPU and memory usage for the server in java, anyone know how it could be done?

[A]
If you are using Tomcat, check out
Psi Probe
, which lets you monitor internal and external memory consumption as well as a host of other areas.


q: I have a QMainWindow in a Qt application. When I close it I want it to store its current restore size (the size of the window when it is not maximized). This works well when I close the window in restore mode (that is, not maximized). But if I close the window if it is maximized, then next time i start the application and restore the application (because it starts in maximized mode), then it does not remember the size it should restore to. Is there a way to do this?

[A]
I've encountered this problem as well.
What you can do: in addition to the window's size, save whether it's maximized or not (
```
QWidget::isMaximized()
```
).
Then next time you start the application, first set the size (
```
QWidget::resize()
```
) and then maximize it if appropriate (
```
QWidget::showMaximized()
```
). When it's restored, it should return to the correct size.


q:
Is it possible to listen for a certain hotkey (e.g:Ctrl-I) and then perform a specific action? My application is written in C, will only run on Linux, and it doesn't have a GUI. Are there any libraries that help with this kind of task?

EDIT: as an example, amarok has global shortcuts, so for example if you map a combination of keys to an action (let's say Ctrl-+, Ctrl and +) you could execute that action when you press the keys. If I would map Ctrl-+ to the volume increase action, each time I press ctrl-+ the volume should increase by a certain amount.

Thanks

[A]
How global do your hotkeys need to be?  Is it enough for them to be global for a X session?  In that case you should be able to open an Xlib connection and listen for the events you need.
Ordinarily keyboard events in X are delivered to the window that currently has the focus, and propagated up the hierarchy until they are handled.  Clearly this is not what we want.  We need to process the event before any other window can get to it.  We need to call
XGrabKey
on the root window with the keycode and  modifiers of our hotkey to accomplish this.
I found a good example
here
.


q:
I am looking for a tool which will take an XML instance document and output a corresponding XSD schema.

I certainly recognize that the generated XSD schema will be limited when compared to creating a schema by hand (it probably won't handle optional or repeating elements, or data constraints), but it could at least serve as a quick starting point.

[A]
the
Microsoft XSD inference tool
is a good, free solution. Many XML editing tools, such as XmlSpy (mentioned by @Garth Gilmour) or OxygenXML Editor also have that feature. They're rather expensive, though. BizTalk Server also has an XSD inferring tool as well.
edit: I just discovered the .net
XmlSchemaInference
class, so if you're using .net you should consider that


q:
I need to rearrange some content in various directories but it's a bit of a pain. In order to debug the application I'm working on (a ruby app) I need to move my gems into my gem folder one at a time (long story; nutshell: one is broken and I can't figure out which one).

So I need to do something like:

sudo mv backup/gem/foo gem/
sudo mv backup/doc/foo doc/
sudo mv backup/specification/foo.gemspec specification/

replacing "foo" each time. How can I author a simple shell script to let me do something like: gemMove("foo") and it fill in the blanks for me?

[A]
Put the following into a file named
```
gemmove
```
:
```
```
#!/bin/bash

if [ "x$1" == x ]; then
  echo "Must have an arg"
  exit 1
fi

for d in gem doc specification ; do
  mv "backup/$d/$1" "$d"
done
```
```
then do
```
```
chmod a+x gemmove
```
```
and then call
```
sudo /path/to/gemmove foo
```
to move the foo gem from the backup dirs into the real ones


q:
Flex has built in drag-n-drop for list controls, and allows you to override this. But they don't cover this in examples. The built-in functionality automatically drags the list-item, if you want to override this you find the handlers are being set up on the list itself.
What I specifically want to do, is my TileList shows small thumbnails of items I can drag onto a large Canvas. As I drag an item from the list, the drag proxy should be a different image.

So, I followed the technique suggested and it only works if I explicitly set the width/height on the proxy Image. Why?

[A]
It's not obvious until you've tried it =) I struggled with the same thing just a few weeks ago. This was my solution:
The list:
```
```
<List>
  <mouseDown>onListMouseDown(event)</mouseDown>
</Tree>
```
```
The mouse down handler:
```
```
private function onMouseDown( event : MouseEvent ) : void {
  var list : List = List(event.currentTarget);

  // the data of the clicked row, change the name of the class to your own
  var item : MyDataType = MyDataType(list.selectedItem);

  var source : DragSource = new DragSource();

  // MyAwsomeDragFormat is the key that you will retrieve the data by in the
  // component that handles the drop
  source.addData(item, "MyAwsomeDragFormat");

  // this is the component that will be shown as the drag proxy image
  var dragView : UIComponent = new Image();

  // set the source of the image to a bigger version here
  dragView.source = getABiggerImage(item);

  // get hold of the renderer of the clicked row, to use as the drag initiator
  var rowRenderer : UIComponent = UIComponent(list.indexToItemRenderer(list.selectedIndex));

  DragManager.doDrag(
    rowRenderer,
    source,
    event,
    dragView
  );
}
```
```
That will start the drag when the user clicks an item in the list. Notice that I don't set
```
dragEnabled
```
and the other drag-related properties on the list since I handle all that myself.
It can be useful to add this to the beginning of the event handler:
```
```
if ( event.target is ScrollThumb || event.target is Button ) {
  return;
}
```
```
Just to short circuit if the user clicks somewhere in the scrollbar. It's not very elegant but it does the job.


q: I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.

[A]
At the moment, XBAPs do not work in Google Chrome.  I've gotten it to run once, somehow, but every time there after I've received an error that the browser cannot locate xpcom.dll.  Apparently this error occurs for more than just XBAP applications.  From what I've read users will have to wait for a fix seeing as Chrome is still in beta.
Update:
Looks like it's not going to be fixed:
http://code.google.com/p/chromium/issues/detail?id=4051


q:
In a VB6 application, I have a Dictionary whose keys are Strings and values are instances of a custom class.  If I call RemoveAll() on the Dictionary, will it first free the custom objects?  Or do I explicitly need to do this myself?

Dim d as Scripting.Dictionary

d("a") = New clsCustom
d("b") = New clsCustom

' Are these two lines necessary?
Set d("a") = Nothing
Set d("b") = Nothing

d.RemoveAll

[A]
Yes, all objects in the
```
Dictionary
```
will be released after a call to
```
RemoveAll()
```
.  From a performance (as in speed) standpoint I would say those lines setting the variables to
```
Nothing
```
are unnecessary, because the code has to first look them up based on the key names whereas
```
RemoveAll()
```
will enumerate and release everything in one loop.


q:
I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.

Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.

I need to write the values out to a fixed length data file.

[A]
Aside from limiting the columns selected to reduce bandwidth and memory:
```
```
DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
```
```


q: Google custom search code is provided as a form tag. However, Asp.net only allows a single form tag on a page. What is the best way to implement their code so you can include it on an aspx page (say as part of a Masterpage or navigation element).

[A]
You can have multiple form tags on an ASP.NET page. The limitation is on server-side (runat="server") form tags.
You can implement two form tags (or more) as long as only one has the runat="server" attribute and one is not contained in the other. Example:
```
```
<body>
<form action="http://www.google.com/cse" id="cse-search-box"> ... </form>
<form runat="server" id="aspNetform"> ... </form>
<body>
```
```


q:
How to you find the URL that represents the documentation of a .NET framework method on the MSDN website?

For example, I want to embed the URL for the .NET framework method into some comments in some code.  The normal "mangled" URL that one gets searching MSDN isn't very friendly looking: http://msdn.microsoft.com/library/xd12z8ts.aspx.  Using a Google search URL isn't all that pretty looking either.

What I really want a URL that can be embedded in comments that is plain and easy to read.  For example,

// blah blah blah.  See http://<....>/System.Byte.ToString for more information

[A]
A lot of the time you can merely append the lowercase namespace reference to the domain:
```
```
http://msdn.microsoft.com/en-us/library/system.windows.application_events.aspx
```
```
Moreover, for say the .Net 2.0 version (or any specific version) you can add "(VS.80)":
```
```
http://msdn.microsoft.com/en-us/library/system.windows.forms.button(VS.80).aspx
```
```
Other versions:
.Net 1.1 -> (VS.71)
.Net 2.0 -> (VS.80)
.Net 3.0 -> (VS.85)
.Net 3.5 -> (VS.90)
Try it for a method (Control.IsInputChar) like so:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isinputchar.aspx


q: If you have a statically allocated array, the Visual Studio debugger can easily display all of the array elements.  However, if you have an array allocated dynamically and pointed to by a pointer, it will only display the first element of the array when you click the + to expand it.  Is there an easy way to tell the debugger, show me this data as an array of type Foo and size X?

[A]
Yes, simple.
say you have
```
```
char *a = new char[10];
```
```
writing in the debugger:
```
```
a,10
```
```
would show you the content as if it were an array.


q:
Is it possible to reach the individual columns of table2 using HQL with a configuration like this?

<hibernate-mapping>
  <class table="table1">
    <set name="table2" table="table2" lazy="true" cascade="all">
      <key column="result_id"/>
      <many-to-many column="group_id"/>
    </set>
  </class>
</hibernate-mapping>

[A]
They're just properties of table1's table2 property.
```
```
select t1.table2.property1, t1.table2.property2, ... from table1 as t1
```
```
You might have to join, like so
```
```
select t2.property1, t2.property2, ...
    from table1 as t1
    inner join t1.table2 as t2
```
```
Here's the relevant part of the
hibernate doc
.


q:
When you're doing a usual gdb session on an executable file on the same computer, you can give the run command and it will start the program over again.

When you're running gdb on an embedded system, as with the command target localhost:3210, how do you start the program over again without quitting and restarting your gdb session?

[A]
Unfortunately, I don't know of a way to restart the application and still maintain your session.  A workaround is to set the PC back to the entry point of your program.  You can do this by either calling:
```
jump
function
```
or
```
set $pc=
address
```
.
If you munged the arguments to
```
main
```
you may need set them up again.
Edit:
There are a couple of caveats with the above method that could cause problems.
If you are in a multi-threaded program jumping to main will jump the current thread to main, all other threads remain.  If the current thread held a lock...then you have some problems.
Memory leaks, if you program flow allocates some stuff during initialization then you just leaked a bunch of memory with the jump.
Open files will still remain open.  If you mmap some files or an address, the call will most likely fail.
So, using jump isn't the same thing as restarting the program.


q: In how many languages is Null not equal to anything not even Null?

[A]
Oracle is this way.
```
```
SELECT * FROM dual WHERE NULL=null;  --no rows returned
```
```


q:
Does anyone know of a good open source plugin for database querying and exploring within Eclipse?

The active Database Exploring plugin within Eclipse is really geared around being associated with a Java project. While I am just trying to run ad-hoc queries and explore the schema. I am effectively looking for a just a common, quick querying tool without the overhead of having to create a code project. I have found a couple open source database plugins for Eclipse but these have not seen active development in over a year.

Any suggestions?


q:
The problem is simple, but I'm struggling a bit already.

Server server = new Server(8080);
Context context = new Context(server, "/", Context.NO_SESSIONS);
context.addServlet(MainPageView.class, "/");
context.addServlet(UserView.class, "/signup");
server.start();

That's a pretty standard piece of code that you can find anywhere in Jetty world. I have an application that embeds Jetty as a servlet engine and has some servlets.

Instantiation of some of these servlets requires heavy work on startup. Say – reading additional config files, connecting to the database, etc. How can I make the servlet engine instantiate all servlets eagerly, so that I can do all the hard work upfront and not on the first user request?

[A]
Use the
```
Context.addServlet
```
overload that takes a
```
ServletHolder
```
.
```
ServletHolder
```
is a class that accepts either a Class or a Servlet instance.
```
```
Servlet myServlet = new MyServlet();
ServletHolder holder = new ServletHolder(myServlet);
context.addServlet(holder, "/");
```
```
This assumes Jetty 6.  I think it will work for Jetty 7 as well.


q: What method do I call to get the name of a class?

[A]
It's not a method, it's a field.  The field is called
```
__name__
```
.
```
class.__name__
```
will give the name of the class as a string.
```
object.__class__.__name__
```
will give the name of the class of an object.


q: As part of the Nant copy task, I would like to change the properties of the files in the target location. For instance make the files "read-write" from "read-only". How would I do this?

[A]
Use the <
attrib
> task. For example, to make the file "test.txt" read/write, you would use
```
```
<attrib file="test.txt" readonly="false"/>
```
```


q: I have just started reading DDD. I am unable to completely grasp the concept of Entity vs Value objects.. Can someone please explain the problems (maintainability, performance.. etc) a system could face when a Value object is designed as a Entity object? Example would be great...

[A]
Reduced to the essential distinction, identity matters for entities, but does not matter for value objects. For example, someone's Name is a value object. A Customer entity might be composed of a customer Name (value object), List<Order> OrderHistory (List of entities), and perhaps a default Address (typically a value object). The Customer Entity would have an ID, and each order would have an ID, but a Name should not; generally, within the object model anyway, the identity of an Address probably does not matter.
Value objects can typically be represented as immutable objects; changing one property of a value object essentially destroys the old object and creates a new one, because you're not as concerned with identity as with content. Properly, the Equals instance method on Name would return "true" as long as the object's properties are identical to the properties of another instance.
However, changing some attribute of an entity like Customer doesn't destroy the customer; a Customer entity is typically mutable. The identity remains the same (at least once the object has been persisted).
You probably create value objects without realizing it; anytime you are representing some aspect of an Entity by creating a fine-grained class, you've got a value object. For example, a class IPAddress, which has some constraints on valid values but is composed of simpler datatypes, would be a value object. An EmailAddress could be a string, or it could be a value object with its own set of behaviors.
It's quite possible that even items that have an identity in your database don't have an identity in your object model. But the simplest case is a composite of some attributes that make sense together. You probably don't want to have Customer.FirstName, Customer.LastName, Customer.MiddleInitial and Customer.Title when you can compose those together as Customer.Name; they'll probably be multiple fields in your database by the time you think about persistence, but your object model doesn't care.


q:
Does anyone know of some good resources related to setting up heirarchical user account systems? I'm currently setting one up and am struggling with some of the more complex logic (especially with determining permissions). I was hoping I might be able to find some resources to help me along.

Some Background:
I'm building a user account system for a web CMS that allows for a nested group hierarchy. Each group can be allowed/denied access to read, write, add, and delete (either explicitly for that group, or implicitly by one of its parents). As if that weren't complicated enough, the system also allows for users to be members of multiple groups. -- This is where I'm stuck. I've got everything set up, but I'm struggling with the actual logic for determining pemissions for a  given user.

[A]
Look at the permissions in the
Andrew File System
.  It allows users to create and administer groups of their own, while selectively assigning admin rights and ACLs.  You might find that many of the pesky details are already worked out for you in their model.
Edit:
here's a better link to AFS documentation:
http://www.cs.cmu.edu/~help/afs/index.html
Here's the section on groups:
http://www.cs.cmu.edu/~help/afs/afs_groups.html


q:
I am serving all content through apache with Content-Encoding: zip but that compresses on the fly.  A good amount of my content is static files on the disk.  I want to gzip the files beforehand rather than compressing them every time they are requested.

This is something that, I believe, mod_gzip did in Apache 1.x automatically, but just having the file with .gz next to it.  That's no longer the case with mod_deflate.

[A]
This functionality was misplaced in mod_gzip anyway. In Apache 2.x,
you do that with content negotiation
. Specifically, you need to enable
```
MultiViews
```
with the
```
Options
```
directive
and you need to specify your encoding types with the
```
AddEncoding
```
directive
.


q:
I am pulling a long timestamp from a database, but want to present it as a Date using Tags only, no embedded java in the JSP.

 I've created my own tag to do this because I was unable to get the parseDate and formatDate tags to work, but that's not to say they don't work.

Any advice?

Thanks.

[A]
The parseDate and formatDate tags work, but they work with Date objects.
You can call new java.util.Date(longvalue) to get a date object, then pass that to the standard tag.
somewhere other than the jsp create your date object.
```
```
long longvalue = ...;//from database.
java.util.Date dateValue = new java.util.Date(longvalue);
request.setAttribute("dateValue", dateValue);
```
```
put it on the request and then you can access it in your tag like this.
```
```
<fmt:formatDate value="${dateValue}" pattern="MM/dd/yyyy HH:mm"/>
```
```


q:
I'm trying to have the same KDE Konsole experience within Mac OS X.

Here's my (overly complicated?) setup:

I have Control and Command swapped at the System Preferences level.  (Can't live without this)

Parallels lets you, at the Parallels application level, also reverse Control and Command.  So I can undo the System Preferences setting (and get the setup I want within virtual Linux)

I want this same per-application-opt-out for the Mac OS X Terminal app.  Is it possible?

[A]
You can
simply ssh into the Linux/Unix system
and run X11 programs direct to your Mac screen:
```
ssh -X user@host_or_ipaddress
```
, login, and just run the X11 programs you want (e.g.
```
emacs&
```
) and the X11 apps will appear on the Mac display.
Pros:
X11 windows work just like any other window, including Exposé goodness, etc...
No need to work only inside the Parallels console window
Same solution works with any Linux/Unix system, remote or virtual
ssh connection is secure even over the internet
Tech info:
"ssh -X" turns on X11 forwarding for the ssh connection, i.e. the X11 display connection is tunneled through ssh securely
"ssh -X" also handles X11 authentication tunneling
```
X11.app
```
is automagically started on OSX by
```
launchd
```
when needed
X11 can connect to displays over the network, which is one of the few cool things about it ;-)


q:
I have a JSP page that contains a scriplet where I instantiate an object.  I would like to pass that object to the JSP tag without using any cache.

For example I would like to accomplish this:

<%@ taglib prefix="wf" uri="JspCustomTag" %>

<%
 Object myObject = new Object();
%>

<wf:my-tag obj=myObject />

I'm trying to avoid directly interacting with any of the caches (page, session, servletcontext), I would rather have my tag handle that.

[A]
Use expression language:
```
<wf:my-tag obj="${myObject}" />
```


q: or "How do I answer questions on SO in Firefox using gVim inside the textboxes?"

[A]
One way to do this is to use the
vimperator
extension - of course, that does a
lot
more than what you're looking for.