Question:
I need a function written in Excel VBA that will hash passwords using a standard algorithm such as SHA-1.  Something with a simple interface like:

Public Function CreateHash(Value As String) As String
...
End Function

The function needs to work on an XP workstation with Excel 2003 installed, but otherwise must use no third party components.  It can reference and use DLLs that are available with XP, such as CryptoAPI.

Does anyone know of a sample to achieve this hashing functionality?

Answer:
Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in.
This is based on some VBA code from
http://vb.wikia.com/wiki/SHA-1.bas
, with changes to support passing it a string, and executable from formulas in Excel cells.
```
```
' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function
```
```


Question:
I am working with a Sharepoint document library and I'm trying to locate the source of the document library page. I'm working on the Sharepoint server. I just can't find it, where should it be stored?

Thank you!

Answer:
Your question is not very clear...
Are you refering to the "source" code of the document library pages?
It depends if you have edited them with SharePoint Designer or not. If not they should be located under 12 hive (c:\program files\common files\microsoft shared\web server extensions\12). If any modification were done using SPD2007 the files will be stored in the content database.
...or are you refering to the "source" where the files are stored?
All the files saved in document libraries are stored in the content database as blobs in the AllUserData table.


Question:
I am investigating the design of a work queue processor where the QueueProcessor retrieves a Command Pattern object from the Queue and executes it in a new thread.

I am trying to get my head around a potential Queue lockup scenario where nested Commands may result in a deadlock.

E.G.

A FooCommand object is placed onto the queue which the QueueProcessor then executes in its own thread.

The executing FooCommand places a BarCommand onto the queue.

Assuming that the maximum allowed threads was only 1 thread, the QueueProcessor would be in a deadlocked state since the FooCommand is infinitely waiting for the BarCommand to complete.

How can this situation be managed? Is a queue object the right object for the job? Are there any checks and balances that can be put into place to resolve this issue?

Many thanks. ( application uses C# .NET 3.0 )

Answer:
For simple cases like this an additional monitoring thread that can spin off more threads on demand is helpful.
Basically every N seconds check to see if any jobs have been finished, if not, add another thread.
This won't necessarily handle even more complex deadlock problems, but it will solve this one.
My recommendation for the heavier problem is to restrict waits to newly spawned process, in other words, you can only wait on something you started, that way you never get deadlocks, since cycles are impossible in that situation.


Question:
I've been given the task of laying the groundwork of a SOA for my client. The goal is to open up various processes in an end-client independent way and also to make data available offline e.g. for reps visiting customers.

I do have extensive experience with J2EE (Websphere) and web services but I would appreciate advice on how to build up such an SOA.

Where are the pitfalls? What about security? How finely granulated should services be? etc.

Links to tutorials and book recommendations would also be useful.

Thanks!

Answer:
Pitfalls
Versioning/backwards compatibility: it gets really hard to change a contract once you have loads of clients. I have seen many sites version the APIs by introducing the version in the URL
Granularity
Each service should be reasonly self-contained (don't expect people to do 3 calls before they get what they need)
Platform Independence
Try to give more than one way of accessing your APIs (WS, JSON, REST...)


Question:
I have this RewriteRule that works too well :-)

RewriteRule ^([^/]*)/$ /script.html?id=$1 [L]

The bad thing about this rule is that it also matches physical directories which I don't want.

How can I tell the mod_rewrite to ignore physical directories and apply the above rule only when the directory matched does not exist?

Answer:
Take a look at
RewriteCond
. Put the following before your rule to exempt out directories and files
```
```
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
```
```


Question:
Having a problem getting a TreeView control to display node images. The code below works sometimes but fails to show any image at other times.

private TreeNode AddNodeForCore(TreeNode root, Core c) {
    string key = GetImageKey(c);
    TreeNode t = root.Nodes.Add(c.Name, c.Name, key, key);
    t.Tag = c;
    return t;
}

Note that when it fails, the TreeView fails to show any images for any node. The TreeView does have an ImageList assigned to it, and the image key is definitely in the images collection.

Edit:

My google-fu is weak. Can't believe I didn't find that answer myself.

Answer:
A quick google search found this answer:
http://forums.microsoft.com/MSDN/ShowPost.aspx?siteid=1&PostID=965968
Quote
from that page:
If the Form containing the TreeView is instantiated in the add-in startup function as below, the icons appear!
```
```
public partial class ThisApplication
{
    Form1 frm;

    private void ThisApplication_Startup(object sender, System.EventArgs e)
    {
        frm  = new Form1();
        frm.Show();

    }
```
```
BUT, if instantiated with the class, as below:
```
```
public partial class ThisApplication
{
    Form1 frm = new Form1();

    private void ThisApplication_Startup(object sender, System.EventArgs e)
    {
                    frm.Show();

    }
```
```
Then they do NOT appear.    Furthermore, if "VisualStyles" (new with XP) are disabled, the icons work in both instances.


Question:
I need to change the credentials of an already existing Windows service using C#. I am aware of two different ways of doing this.

ChangeServiceConfig, see ChangeServiceConfig on pinvoke.net

ManagementObject.InvokeMethod using Change as the method name.

Neither seems a very "friendly" way of doing this and I was wondering if I am missing another and better way to do this.

Answer:
Here is one quick and dirty method using the System.Management classes.
```
```
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;

namespace ServiceTest
{
  class Program
  {
    static void Main(string[] args)
    {
      string theServiceName = "My Windows Service";
      string objectPath = string.Format("Win32_Service.Name='{0}'", theServiceName);
      using (ManagementObject mngService = new ManagementObject(new ManagementPath(objectPath)))
      {
        object[] wmiParameters = new object[11];
        wmiParameters[6] = @"domain\username";
        wmiParameters[7] = "password";
        mngService.InvokeMethod("Change", wmiParameters);
      }
    }
  }
}
```
```


Question:
(Not related to versioning the database schema)

Applications that interfaces with databases often have domain objects that are composed with data from many tables. Suppose the application were to support versioning, in the sense of CVS, for these domain objects.

For some arbitry domain object, how would you design a database schema to handle this requirement? Any experience to share?

Answer:
A technique I've used for this in that past has been to have a concept of "generations" in the database, each change increments the current generation number for the database - if you use subversion, think revisions.
Each record has 2 generation numbers associated with it (2 extra columns on the tables) - the generation that the record starts being valid for, and the generation the it stops being valid for. If the data is currently valid, the second number would be NULL or some other generic marker.
So to insert into the database:
increment the generation number
insert the data
tag the lifetime of that data with valid from, and a valid to of NULL
If you're updating some data:
mark all data that's about to be modified as valid to the current generation number
increment the generation number
insert the new data with the current generation number
deleting is just a matter of marking the data as terminating at the current generation.
To get a particular version of the data, find what generation you're after and look for data valid between those generation versions.
Example:
Create a person.
```
```
|Name|D.O.B  |Telephone|From|To  |
|Fred|1 april|555-29384|1   |NULL|
```
```
Update tel no.
```
```
|Name|D.O.B  |Telephone|From|To  |
|Fred|1 april|555-29384|1   |1   |
|Fred|1 april|555-43534|2   |NULL|
```
```
Delete fred:
```
```
|Name|D.O.B  |Telephone|From|To  |
|Fred|1 april|555-29384|1   |1   |
|Fred|1 april|555-43534|2   |2   |
```
```


Question:
I am new to java so excuse my lame questions:)

I am trying to build a web service in Java  NetBeans 6.1 , but I have some troubles with configuration parameters ( like .settings in .net).

What is the right way to save and access such settings in a java web service.

Is there a way to read context parameters from web.xml in a web method?

If no what are the alternatives for storing your configuration variables like pathnames ?

Thank you

Answer:
If you are using servlets, you can configure parameters in web.xml:
```
```
<servlet>
  <servlet-name>jsp</servlet-name>
  <servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
    <init-param>
      <param-name>fork</param-name>
      <param-value>false</param-value>
     </init-param>
</servlet>
```
```
These properties will be passed in a ServletConfig object to your servlet's "init" method.
Another way is to read your system's environment variables with
```
```
System.getProperty(String name);
```
```
But this is not recommended for other than small programs and tests.
There is also the Properties API if you want to use ".properties" files.
http://java.sun.com/javase/6/docs/api/java/util/Properties.html
Finally, I believe looking up configurations with JNDI is pretty common when developing modern web service applications, Netbeans and app containers have pretty good support for that. Google it.


Question:
I'm trying to implement the WMD editor used on StackOverflow to create some basic Wiki-style functionality.  I'm up to the point where it's time to save to the database, but I'm unsure as to what I should be saving.

If I save the produced HTML then I can retrieve and display it correctly, but on re-edit I'm faced with editing HTML, not Markdown.  However, if I save the Markdown I can't see any way of converting this back to HTML to display, and looking at StackOverflow it sends the browser HTML.

I'm guessing that I don't need to save both, so what simple thing am I missing?

Answer:
I would suggest saving the exact entered text to the database, so editing will work with the original markdown or HTML.
When you retrieve the text for display, you parse it on the server side and convert to HTML where necessary
[Edit]
At comment:
You seem to have a way of parsing and converting to HTML already, if I understand your question correctly.  Here you talk about the produced HTML.
If I save the produced HTML then I can retrieve and display it correctly, but on re-edit I'm faced with editing HTML, not Markdown


Question:
I'm trying to handle Winsock_Connect event (Actually I need it in Excel macro) using the following code:

Dim Winsock1 As Winsock 'Object type definition

Sub Init()
    Set Winsock1 = CreateObject("MSWinsock.Winsock") 'Object initialization
    Winsock1.RemoteHost = "MyHost"
    Winsock1.RemotePort = "22"
    Winsock1.Connect

    Do While (Winsock1.State <> sckConnected)
        Sleep 200
    Loop
End Sub

'Callback handler
Private Sub Winsock1_Connect()
    MsgBox "Winsock1::Connect"
End Sub

But it never goes to Winsock1_Connect subroutine although Winsock1.State is "Connected".
I want to use standard MS library because I don't have administrative rights on my PC and I'm not able to register some custom libraries.
Can anybody tell me, where I'm wrong?

Answer:
Are you stuck using MSWinsock?
Here
is a site/tutorial using a custom winsock object.
Also... You need to declare Winsock1
WithEvents
within a "Class" module:
```
```
Private WithEvents Winsock1 As Winsock
```
```
And finally, make sure you reference the winsock ocx control.
Tools -> References -> Browse -> %SYSEM%\MSWINSCK.OCX


Question:
When modelling an architecture in UML component diagrams, how do you show various attributes of connectors simultaneously? Like

business object information flow (A->B, B->A, A<->B)

request/response direction

synchronous/asynchronous behaviour

I am aware of other diagram types like sequence diagrams. However, having this information visible in component diagrams would have value.

What is possible beyond associations (merely showing that components are connected) or "lollipops" (request/response)?

Answer:
You might want to use
sequence diagrams
instead of class (i.e, component) diagrams.
If you want to stick to a static diagram, you may also want to consider adding << sterotypes>> to various connectors, or even use
association classes
.
If possible, you can use connectors from sequence diagrams to connect classifiers in component diagrams (e.g., synchronous/asynchronous message-passing arrows).


Question:
I know this is not directly a programming question, but people on stackoverflow seems to be able to answer any question.

I have a server running Centos 5.2 64 bit.  Pretty powerful dual core 2 server with 4GB memory.  It mostly serves static files, flash and pictures.  When I use lighttpd it easily serves over 80 MB/sec, but when I test with nginx it drops down to less than 20 MB/sec.

My setup is pretty straight forward, uses the default setup file, and I have added the following

user  lighttpd;
worker_processes  8;
worker_rlimit_nofile 206011;
#worker_rlimit_nofile 110240;

error_log   /var/log/nginx/error.log;
#error_log  /var/log/nginx/error.log  notice;
#error_log  /var/log/nginx/error.log  info;

pid        /var/run/nginx.pid;

events {
    worker_connections  4096;
}

http {
....

keepalive_timeout  2;
....
}

And I thought nginx was supposed to be at least as powerful, so I must be not doing something.

Answer:
Perhaps lighttpd is using some kind of caching?  There's a great article
here
that describes how to set up memcached with nginx for a reported 400% performance boost.
The nginx doc on the memcached module is
here
.


Question:
Specifically I have a PHP command-line script that at a certain point requires input from the user. I would like to be able to execute an external editor (such as vi), and wait for the editor to finish execution before resuming the script.

My basic idea was to use a temporary file to do the editing in, and to retrieve the contents of the file afterwards. Something along the lines of:

$filename = '/tmp/script_' . time() . '.tmp';

get_user_input ($filename);

$input = file_get_contents ($filename);
unlink ($filename);

I suspect that this isn't possible from a PHP command-line script, however I'm hoping that there's some sort of shell scripting trick that can be employed to achieve the same effect.

Suggestions for how this can be achieved in other scripting languages are also more than welcome.

Answer:
```
```
system('vi');
```
```
http://www.php.net/system


Question:
We have a 3D viewer that uses OpenGL, but our clients sometimes complain about it "not working". We suspect that most of these issues stem from them trying to use, what is in effect a modern 3d realtime game, on a businiss laptop computer.

How can we, in the windows msi installer we use, check for support for openGL?

And as a side note, if you can answer "List of OpenGL supported graphic cards?", that would also be greate. Strange that google doesnt help here..

Answer:
OpenGL is part of Windows since Windows NT or Win95. It's unlikely that you'll ever find a windows system where OpenGL is not pre-installed (e.g. Windows 3.1)
However, your application may need a more recent version of OpenGL than the default OpenGL 1.1 that comes with very old versions of windows. You can check that from your program. I don't know of any way how to find that from msi.
Note that the OpenGL gets updated via the graphic drivers, not by installing a service pack or so.
Regarding OpenGL enabled graphic cards: All have OpenGL. Even if the customer uses a ISA ET4000 graphic card from the stone ages he at least has OpenGL 1.1 via software-rendering.


Question:
I am having my web application deployed on Tomcat5.5 and I use it in integration with eclipse 3.2.Each time I close the eclipse and restart it, I need to republish the application even when it hasn't been modified.

Is there a way to avoid this or any step I am missing ?

Answer: Do eclipse 3.3 or 3.4, or later versions of WTP behave the same way for you?


Question:
I have an email subject of the form:

=?utf-8?B?T3.....?=

The body of the email is utf-8 base64 encoded - and has decoded fine.
I am current using Perl's Email::MIME module to decode the email.

What is the meaning of the =?utf-8 delimiter and how do I extract information from this string?

Answer:
The
```
encoded-word
```
tokens (as per
RFC 2047
) can occur in values of some headers. They are parsed as follows:
```
```
=?<charset>?<encoding>?<data>?=
```
```
Charset is UTF-8 in this case, the encoding is
```
B
```
which means base64 (the other option is
```
Q
```
which means Quoted Printable).
To read it, first decode the base64, then treat it as UTF-8 characters.
Also read the various Internet Mail RFCs for more detail, mainly
RFC 2047
.
Since you are using Perl,
Encode::MIME::Header
could be of use:
SYNOPSIS
```
```
use Encode qw/encode decode/;
$utf8   = decode('MIME-Header', $header);
$header = encode('MIME-Header', $utf8);
```
```
ABSTRACT
This module implements RFC 2047 Mime
  Header Encoding. There are 3 variant
  encoding names; MIME-Header, MIME-B
  and MIME-Q. The difference is
  described below
```
```
decode()          encode()
MIME-Header   Both B and Q      =?UTF-8?B?....?=
MIME-B        B only; Q croaks  =?UTF-8?B?....?=
MIME-Q        Q only; B croaks  =?UTF-8?Q?....?=
```
```


Question:
What's the fastest way to count the number of keys/properties of an object? Is it possible to do this without iterating over the object?  I.e., without doing:

var count = 0;
for (k in myobj) if (myobj.hasOwnProperty(k)) ++count;

(Firefox did provide a magic __count__ property, but this was removed somewhere around version 4.)

Answer:
If you are actually running into a performance problem I would suggest wrapping the calls that add/remove properties to/from the object with a function that also increments/decrements an appropriately named (size?) property.
You only need to calculate the initial number of properties once and move on from there. If there isn't an actual performance problem, don't bother. Just wrap that bit of code in a function
```
getNumberOfProperties(object)
```
and be done with it.


Question:
Problem. I need a way to find Starteam server time through Starteam Java SDK 8.0. Version of server is 8.0.172 so method Server.getCurrentTime() is not available since it was added only in server version 9.0.

Motivation. My application needs to use views at specific dates. So if there's some difference in system time between client (where the app is running) and server then obtained views are not accurate. In the worst case the client's requested date is in the future for server so the operation results in exception.

Answer:
```
<stab_in_the_dark>
```
I'm not familiar with that SDK but from looking at the API if the server is in a known timezone why not create and an OLEDate object whose date is going to be the client's time rolled appropriately according to the server's timezone?
```
</stab_in_the_dark>
```


Question:
Is there any python module for rendering a HTML page with javascript and get back a DOM object?

I want to parse a page which generates almost all of its content using javascript.

Answer:
The big complication here is emulating the full browser environment outside of a browser. You can use stand alone javascript interpreters like Rhino and SpiderMonkey to run javascript code but they don't provide a complete browser like environment to full render a web page.
If I needed to solve a problem like this I would first look at how the javascript is rendering the page, it's quite possible it's fetching data via AJAX and using that to render the page. I could then use python libraries like simplejson and httplib2 to directly fetch the data and use that, negating the need to access the DOM object. However, that's only one possible situation, I don't know the exact problem you are solving.
Other options include the selenium one mentioned by Łukasz, some kind of webkit embedded craziness, some kind of IE win32 scripting craziness or, finally, a pyxpcom based solution (with added craziness). All these have the drawback of requiring pretty much a fully running web browser for python to play with, which might not be an option depending on your environment.


Question:
I need to determine which version of GTK+ is installed on Ubuntu

Man does not seem to help

Answer:
You can use this command:
```
```
$ dpkg -s libgtk2.0-0|grep '^Version'
```
```


Question:
How is the salt generated in HashProvider in Microsoft Enterprise Library when we set SaltEnabled?

Is it random to new machines? Is it some magic number?

(I know what is a salt, the question is what's the actual value of a/the salt in Enterprise Library HashProvider)

Answer:
Edit:
See Microsoft.Practices.EnterpriseLibrary.Security.Cryptography.HashAlgorithmProvider for an example implementation. Hashing steps are:
If SaltEnabled, generate random bytes for the salt length using RNGCryptoServiceProvider.
Append the salt to the plaintext.
Hash the salted plaintext.
Then (this is the important step), append the salt again to the
hash
.
To compare against hashed text, you must use:
```
```
public bool CompareHash(byte[] plaintext, byte[] hashedtext)
```
```
versus rehashing and comparing. If you rehash, a new random salt is generated and you're lost.
CompareHash does the following:
Pulls the non-hashed salt off the hashtext. Remember, it was appended at step 4 above.
Uses that salt to compute a hash for the plaintext.
Compares the new hash with the hashedtext minus salt. If they're the same - true, else false.
Original:
"if salt is enabled on a HashProvider, the provider will generate a random sequence of bytes, that will be added to the hash. If you compare a hashed value with a unhashed value, the salt will be extracted from the hashed value and used to hash the unhashed value, prior to comparison."
and
"As for decoding as hash-value. this cannot be done. after creating a hash there should be no way to reverse this into the original value.
However, what you can do is compare an unhashed-value with a hashed-value by putting it through the same algorithm and comparing the output."
From
http://www.codeplex.com/entlib/Thread/View.aspx?ThreadId=10284


Question: I am designing a page to Add/Edit users - I used a repeater control and a table to display users. In users view the individual columns of the table row have labels to display a record values and when users click on edit button, the labels are hidden and text boxes are displayed for users to edit values - The problem is - as soon as the text boxes are visible, the table size increases - the row height and cells size becomes large. Is there a way to display the text boxes so that they take the same size as the labels

Answer:
I'd use JS+CSS... You'll have to get your hands dirty for this one though. Visual Studio isn't going to help you much.
Here's how I'd do it:
Get the
```
<td>
```
clientWidth and clientHeight.
Set
the
```
<td>
```
's width and height to those px values (so they're no longer relative)
Swap the text for the input
In your CSS, make sure the input has no padding/margin/border and set width:100%, line-height:1em, and height:1em
When you switch back, make sure you un-set the
```
<td>
```
width and height so they return to automatic values.
You'll need to tweak this all slightly. I'm sure you'll have to play around with the padding on the
```
<td>
```
and perhaps set overflow:hidden but you should be able to do what you want.


Question:
Assume the following class:

public class MyEnum: IEnumerator
{
    private List<SomeObject> _myList = new List<SomeObject>();
...
}

It is necessary to implement the IEnumerator methods in MyEnum.
But is it possible to 'delegate' or redirect the implementation for IEnumerator directly to _myList without needing to implement the IEnumerator methods?

Answer:
Not unless you derive from List<T>.
```
```
public class MyEnum : List<SomeObject>, IEnumerable<SomeObject>{}
```
```


Question:
the company I work for want to use a "hosted payment form" to charge our customers. A question came up on how we can populate the "payment form" automatically with information from one of our other system. We have no control over the hosed payment form, and we have to use IE. Is this possible at all? And if so, how can this be done?

If something is unclear, please let me know...

Answer:
Unless your payment gateway allows you to pass through data in a set API (which lots do!), you'd need to take control (and responsibility) for your payment form.
I say responsibility because you would have to prove to your merchant account provider that everything is secure. This will probably incur some security testing fees too.
So check with your merchant gateway first. Lots of systems have the means to accept data from your site and their tech support will be able to give you a straight answer immediately. Otherwise you'd have to switch it over so you process all the data yourself which, just for making things easier, isn't worth it IMO.


Question:
This is probably explained more easily with an example. I'm trying to find a way of turning a relative URL, e.g. "/Foo.aspx" or "~/Foo.aspx" into a full URL, e.g. http://localhost/Foo.aspx. That way when I deploy to test or stage, where the domain under which the site runs is different, I will get http://test/Foo.aspx and http://stage/Foo.aspx.

Any ideas?

Answer:
Have a play with this (modified
from here
)
```
```
public string ConvertRelativeUrlToAbsoluteUrl(string relativeUrl) {
    return string.Format("http{0}://{1}{2}",
        (Request.IsSecureConnection) ? "s" : "",
        Request.Url.Host,
        Page.ResolveUrl(relativeUrl)
    );
}
```
```


Question:
Say you want to generate a matched list of identifiers and strings

enum
{
NAME_ONE,
NAME_TWO,
NAME_THREE
};

myFunction(NAME_ONE, "NAME_ONE");
myFunction(NAME_TWO, "NAME_TWO");
myFunction(NAME_THREE, "NAME_THREE");

..without repeating yourself, and without auto-generating the code, using C/C++ macros

Initial guess:

You could add an #include file containing

myDefine(NAME_ONE)
myDefine(NAME_TWO)
myDefine(NAME_THREE)

Then use it twice like:

#define myDefine(a) a,
enum {
#include "definitions"
}
#undef myDefine

#define myDefine(a) myFunc(a, "a");
#include "definitions"
#undef myDefine

but #define doesn't let you put parameters within a string?

Answer:
For your second #define, you need to use the # preprocessor operator, like this:
```
```
#define myDefine(a) myFunc(a, #a);
```
```
That converts the argument to a string.


Question:
We have a SQUID reverse proxy and a MOSS 2007 portal. All sites are using NTLM.

We cannot get it working with SQUID as a reverse proxy.

Any ideas where to start?

Answer:
Can you switch to Kerberos instead of NTLM?
You're encountering the "Double-Hop Issue", whereby NTLM authentication cannot traverse proxies or servers.
This is outlined at this location:
http://blogs.msdn.com/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx
And over here:
http://support.microsoft.com/default.aspx?scid=kb;en-us;329986
Double-Hop Issue
  The double-hop issue is when the ASPX page tries to use resources that are located on a server that is different from the IIS server. In our case, the first "hop" is from the web browser client to the IIS ASPX page; the second hop is to the AD. The AD requires a primary token. Therefore, the IIS server must know the password for the client to pass a primary token to the AD. If the IIS server has a secondary token, the NTAUTHORITY\ANONYMOUS account credentials are used. This account is not a domain account and has very limited access to the AD.
The double-hop using a secondary token occurs, for example, when the browser client is authenticated to the IIS ASPX page by using NTLM authentication. In this example, the IIS server has a hashed version of the password as a result of using NTLM. If IIS turns around and passes the credentials to the AD, IIS is passing a hashed password. The AD cannot verify the password and, instead, authenticates by using the NTAUTHORITY\ANONYMOUS LOGON.
On the other hand, if your browser client is authenticated to the IIS ASPX page by using Basic authentication, the IIS server has the client password and can make a primary token to pass to the AD. The AD can verify the password and does authenticate as the domain user.
  For more information, click the following article number to view the article in the Microsoft Knowledge Base:
  264921 (
http://support.microsoft.com/kb/264921/
) How IIS authenticates browser clients
If switching to Kerberos is not an option, have you investigated the Squid NTLM project?
http://devel.squid-cache.org/ntlm/


Question:
I'm calling a non-.NET dll from my project using P/Invoke, meaning that the .dll must always be present in the .exe's directory.

Is there any way to tell Visual Studio of this dependency, so that it will automatically copy the .dll to the output directory when compiling, and will automatically include the .dll in the setup? Or do I have to do this manually?

Answer:
You can simply add the .DLL to your project.
Select the
```
Properties
```
pane for that file and set
```
Build Action
```
to
```
Content
```
and
```
Copy to Output Directory
```
to
```
Copy if newer
```
.


Question:
I'm wanting a method called same_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings.

same_url?({:controller => :foo, :action => :bar}, "http://www.example.com/foo/bar") # => true

The Rails Framework helper current_page? seems like a good starting point but I'd like to pass in an arbitrary number of URLs.

As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like:

same_url?(projects_path(:page => 2), "projects?page=3", :excluding => :page) # => true

Answer:
Is this the sort of thing you're after?
```
```
def same_url?(one, two)
  url_for(one) == url_for(two)
end
```
```


Question:
This is kind of hard to explain, I hope my English is sufficient:

I have a class "A" which should maintain a list of objects of class "B" (like a private List). A consumer of class "A" should be able to add items to the list. After the items are added to the list, the consumer should not be able to modify them again, left alone that he should not be able to temper with the list itself (add or remove items). But he should be able to enumerate the items in the list and get their values. Is there a pattern for it? How would you do that?

If the question is not clear enough, please let me know.

Answer:
EDIT:
Added support for edition contexts. Caller can only add elements inside an edition context. You can aditionally enforce that only one edition context can be created for the lifetime of the instance.
Using encapsulation you can define any set of policies to access the inner private member. The following example is a basic implementation of your requirements:
```
```
namespace ConsoleApplication2
{
    using System;
    using System.Collections.Generic;
    using System.Collections;

    class B
    {
    }

    interface IEditable
    {
        void StartEdit();
        void StopEdit();
    }

    class EditContext<T> : IDisposable where T : IEditable
    {
        private T parent;

        public EditContext(T parent)
        {
            parent.StartEdit();
            this.parent = parent;
        }

        public void Dispose()
        {
            this.parent.StopEdit();
        }
    }

    class A : IEnumerable<B>, IEditable
    {
        private List<B> _myList = new List<B>();
        private bool editable;

        public void Add(B o)
        {
            if (!editable)
            {
                throw new NotSupportedException();
            }
            _myList.Add(o);
        }

        public EditContext<A> ForEdition()
        {
            return new EditContext<A>(this);
        }

        public IEnumerator<B> GetEnumerator()
        {
            return _myList.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public void StartEdit()
        {
            this.editable = true;
        }

        public void StopEdit()
        {
            this.editable = false;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();
            using (EditContext<A> edit = a.ForEdition())
            {
                a.Add(new B());
                a.Add(new B());
            }

            foreach (B o in a)
            {
                Console.WriteLine(o.GetType().ToString());
            }

            a.Add(new B());

            Console.ReadLine();
        }
    }
}
```
```


Question:
We've been using Scrum on a few projects now with varying success and I now have a query relating to documentation.

In Scrum, you obviously have the product backlog ("The application begins by bringing up the last document the user was working with.") and the sprint task backlog ("Implement forgot password screen").  However, in all the examples I have seen, these two items are fairly high level in terms of detail (being designed on fit on a post-it note).

So, where does the detail sit?  Let's say the client has some very specific requirements for a stock management screen, or has a complex API that needs to be integrated with on the back end, where is this documented, how and who captures this information?  Is it seperate to the backlog but populated on a just-in-time basis or some other way?

Answer:
My understanding is that specific requirements such as this are handled by the product owner. They will liase with the client during Sprint Planning 2 and update the tasks with specfic requirements as needed - hence why the Product Owner is a optional attendee of the Sprint Planning 2 meeting. This gives you a hybrid of Just-in-Time and Sprint Planning 2 population of the specifics. Anything that isn't satisfied by the time you come to work on the task will be an impediment and should be dealt with a the daily scrum, by the product owner.
As the development is Agile when using Scrum you shouldn't find too much of an issues getting requirements just in time.


Question:
I write a lot of dynamically generated content (developing under PHP) and I use jQuery to add extra flexibility and functionality to my projects.

Thing is that it's rather hard to add JavaScript in an unobtrusive manner. Here's an example:

You have to generate a random number of div elements each with different functionality triggered onClick. I can use the onclick attribute on my div elements to call a JS function with a parameter but that is just a bad solution. Also I could generate some jQuery code along with each div in my PHP for loop, but then again this won't be entirely unobtrusive.

So what's the solution in situations like this?

Answer:
You need to add something to the divs that defines what type of behaviour they have, then use jQuery to select those divs and add the behaviour. One option is to use the class attribute, although arguably this should be used for presentation rather than behaviour. An alternative would be the rel attribute, but I usually find that you also want to specify different CSS for each behaviour, so class is probably ok in this instance.
So for instance, lets assume you want odd and even behaviour:
```
```

...

...

...

...

```
```
Then in jQuery:
```
```
$(document).load(function() {
$('.odd').click(function(el) {
// do stuff
});
$('.even').click(function(el) {
// dostuff
});
});
```
```
jQuery has a very powerful selector engine that can find based on any CSS based selector, and also support some XPath and its own selectors. Get to know them!
http://docs.jquery.com/Selectors


Question:
Debugging some finance-related SQL code found a strange issue with numeric(24,8) mathematics precision.

Running the following query on your MSSQL you would get A + B * C expression result to be 0.123457

SELECT A,
       B,
       C,
       A + B * C
FROM
(
SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A,
       CAST(0 AS NUMERIC(24,8)) AS B,
       CAST(500 AS NUMERIC(24,8)) AS C
) T

So we have lost 2 significant symbols. Trying to get this fixed in different ways i got that conversion of the intermediate multiplication result (which is Zero!) to numeric (24,8) would work fine.

And finally a have a solution. But still I hace a question - why MSSQL behaves in this way and which type conversions actually occured in my sample?

Answer:
Just as addition of the float type is inaccurate, multiplication of the decimal types can be inaccurate (or cause inaccuracy) if you exceed the precision. See
Data Type Conversion
and
decimal and numeric
.
Since you multiplied
```
NUMERIC(24,8)
```
and
```
NUMERIC(24,8)
```
, and SQL Server will only check the type not the content, it probably will try to save the potential 16 non-decimal digits (24 - 8) when it can't save all 48 digits of precision (max is 38). Combine two of them, you get 32 non-decimal digits, which leaves you with only 6  decimal digits (38 - 32).
Thus the original query
```
```
SELECT A, B, C, A + B * C
FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A,
  CAST(0 AS NUMERIC(24,8)) AS B,
  CAST(500 AS NUMERIC(24,8)) AS C ) T
```
```
reduces to
```
```
SELECT A, B, C, A + D
FROM ( SELECT CAST(0.12345678 AS NUMERIC(24,8)) AS A,
  CAST(0 AS NUMERIC(24,8)) AS B,
  CAST(500 AS NUMERIC(24,8)) AS C,
  CAST(0 AS NUMERIC(38,6)) AS D ) T
```
```
Again, between
```
NUMERIC(24,8)
```
and
```
NUMERIC(38,6)
```
, SQL Server will try to save the potential 32 digits of non-decimals, so
```
A + D
```
reduces to
```
```
SELECT CAST(0.12345678 AS NUMERIC(38,6))
```
```
which gives you
```
0.123457
```
after rounding.


Question:
I would like to change the database files location of MySQL administrator to another drive of my computer.  (I run Windows XP SP2 and MySQL Administrator 1.2.8.)

--Under the startup variable --> General Parameters --> I changed Data directory: from  C:/Program Files/MySQL/MySQL Server 5.0/data to D:/....., but after I stopped the service and restarted it, the following error appeared:

Could not re-connect to the MySQL Server.
Server could not be started.

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

Has anyone else had this problem?

Answer:
Normally it works like this:
shut down MySQL
change the
```
[mysqld]
```
and
```
[mysqld_safe]
```
```
datadir
```
variable in the MySQL configuration
change the
```
basedir
```
variable in the same section.
move the location over
restart MySQL
If that doesn't work I have no idea.  On linux you can try to move the socket to a new location too, but that shouldn't affect windows.  Alternatively you can use a symbolic link on *nix what most people do I guess.


Question: What are the ways to eliminate the use of switch in code?

Answer:
Everybody loves HUGE
```
if else
```
blocks. So easy to read! I am curious as to why you would want to remove switch statements, though. If you need a switch statement, you probably need a switch statement. Seriously though, I'd say it depends on what the code's doing. If all the switch is doing is calling functions (say) you could pass function pointers. Whether it's a
better
solution is debatable.
Language is an important factor here also, I think.


Question:
I am implementing a design that uses custom styled submit-buttons. They are quite simply light grey buttons with a slightly darker outer border:

input.button {
    background: #eee;
    border: 1px solid #ccc;
}

This looks just right in Firefox, Safari and Opera. The problem is with Internet Explorer, both 6 and 7.

Since the form is the first one on the page, it's counted as the main form - and thus active from the get go. The first submit button in the active form receives a solid black border in IE, to mark it as the main action.

If I turn off borders, then the black extra border in IE goes away too. I am looking for a way to keep my normal borders, but remove the outline.

Answer:
Right, well here's an ugly fix for you to weigh up... Stick the button in a
```
<span>
```
, nuke the border on the button and give the border to the span instead.
IE is a bit iffy about form element margins so this might not work precisely. Perhaps giving the span the same background as the button might help in that respect.
```
```
span.button {
    background: #eee;
    border: 1px solid #ccc;
}

span.button input {
    background: #eee;
    border:0;
}
```
```
and
```
```
<input type="button" name="..." value="Button"/>
```
```


Question: I want to execute a certain batch file and redirect its console output to a text control in visual c++ or redirect the console output at the same time the logs/echo are showing.

Answer:
Basically, you have to make the run process to write to a pipe, and to read the output of this pipe.
[EDIT] I know how SciTE does that (you can take a look at the source: win32/SciTEWin.cxx, ExecuteOne function), I searched a slightly more generic way, found
How to spawn console processes with redirected standard handles
from Microsoft itself.
If you seach
CreatePipe PeekNamedPipe CreateProcess
keyword, for example, you might find other examples.


Question:
I am running following PHP code to interact with a MS Access database.

$odbc_con = new COM("ADODB.Connection");
$constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";";
$odbc_con -> open($constr);

$rs_select = $odbc_con -> execute ("SELECT * FROM Main");

Using ($rs_select -> RecordCount) gives -1 though the query is returning non-zero records.

(a) What can be the reason?
(b) Is there any way out?

I have also tried using count($rs_select -> GetRows()). This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.

Answer:
Doesn't Access have its own COUNT operator? eg:
```
```
$rs_select = $odbc_con -> execute ("SELECT COUNT(*) FROM Main");
```
```


Question:
I'm look for a GIS/Mapping tool that will give me easy SERVER-SIDE access to route information (specifically, trip time and distance) in an ASP.NET web application.

From what I can tell, Google and Yahoo maps do everything client-side in javascript, but neither provide services to retrieve just the route information. I'm interested in both free and paid products. Also, if you have experience with a product I like to hear about what you think (complexity of API, runtime performance, likes, dislikes, etc.)

Answer:
We've had success with using the web services from Map24 (
http://developer.navteq.com/site/global/zones/ms/index.jsp
) to do some GIS-y type things. They have a web service for doing routing (
http://developer.navteq.com/site/global/zones/ms/map24webservices/map24routingservice.jsp
) which I had a quick play with last year.
There's a bit of a learning curve wih their APIs but once you get past it their stuff is quite powerful and performs really well.
Phil


Question:
I could swear I've seen the function (or method) that takes a list, like this [3, 7, 19] and makes it into iterable list of tuples, like so: [(0,3), (1,7), (2,19)] to use it instead of:

for i in range(len(name_of_list)):
    name_of_list[i] = something

but I can't remember the name and googling "iterate list" gets nothing.

Answer:
```
```
>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
...     print i, val
...
0 3
1 4
2 5
3 6
>>>
```
```


Question: On the safari browser, the standard <asp:Menu> doesn't render well at all. How can this be fixed?

Answer:
You can use ControlAdapters to alter the rendering of server controls.
Here's an example:
http://www.pluralsight.com/community/blogs/fritz/archive/2007/03/27/46598.aspx
Though, in my opinion it might be equal amount of work to abandon the menu control for a pure css one (available on many sites).


Question:
Running VS2003/05 under Vista makes the former screw up the display at least 50% of the time - you start debugging, VS kicks in and you see the windows/docking panes screwed up, not refreshing, etc... I've contacted Microsoft about this, but they weren't much help, I was wondering if someone knows any fixes?

I'm running VS with visual styles turned off under Vista, so that it doesn't hang when you try to do a "find in files".

All the latest updates/service packs are installed.

Answer:
For Visual Studio 2005 , install the
Microsoft® Visual Studio® 2005  Service Pack 1
and the
Visual Studio 2005 Service Pack 1 Update for Windows Vista
Take a look at the
Visual Studio .NET 2003 on Windows Vista Issue List
and see if you find something there.
And see if that help things.


Question: I want to replace a single file inside a msi. How to do it?

Answer:
You need to extract the CAB file stream from your msi using
MsiDB.exe
(supplied with the
Windows Installer SDK
). Run it from the
command line with the -x option
and specify the name of the cab file - this is listed in the Media table in the msi database.
Alternatively you can skip this part if you specify the "Package Files as:" option in the VSI options to "Compresses in Cabinet Files" to have the cab file left out of the msi when it's built (it will be created in the same directory as the msi).
Once extracted you can change the specified file in the cab folder - its name has been mangled so you need to find out what msi name for the file is in the file table and then rename your new file to that.
Once done you can pop it back in with the
MsiDB utility using the -a option
.
Before you add with -a you need to use
msidb -k
to
remove the cab from the MSI
.


Question:
I have a requirement to be be able to embed scanned tiff images into some SSRS reports.

When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning :

Warning    2   [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType.   c:\SSRSStuff\TestReport.rdl 0   0

and instead of an image I get the little red x.

Has anybody overcome this issue?

Answer:
Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you
can
use.
```
```
Response.ContentType = "image/png";
Response.Clear();
using (Bitmap bmp = new Bitmap(tifFilepath))
  bmp.Save(Response.OutputStream, ImageFormat.Png);
Response.End();
```
```


Question:
I have an old server with a defunct evaluation version of SQL 2000 on it (from 2006), and two databases which were sitting on it.

For some unknown reason, the LDF log files are missing. Presumed deleted.

I have the mdf files (and in one case an ndf file too) for the databases which used to exist on that server, and I am trying to get them up and running on another SQL 2000 box I have sitting around.

sp_attach_db complains that the logfile is missing, and will not attach the database. Attempts to fool it by using a logfile from a database with the same name failed miserably. sp_attach_single_file_db will not work either. The mdf files have obviously not been cleanly detached.

How do I get the databases attached and readable?

Answer:
I found this answer, which worked with my SQL 2000 machines:
How to attach a database with a non-cleanly detached MDF file.
Step 1:
Make a new database with same name, and which uses the same files as the old one on the new server.
Step 2:
Stop SQL server, and move your mdf files (and any ndf files you have) over the top of the new ones you just created. Delete any log files.
Step 3:
Start SQL and run this to put the DB in emergency mode.
```
```
sp_configure 'allow updates', 1
go
reconfigure with override
GO
update sysdatabases set status = 32768 where name = 'TestDB'
go
sp_configure 'allow updates', 0
go
reconfigure with override
GO
```
```
Step 4:
Restart SQL server and observe that the DB is successfully in emergency mode.
Step 5:
Run this undocumented dbcc option to rebuild the log file (in the correct place)
```
```
DBCC REBUILD_LOG(TestDB,'D:\SQL_Log\TestDB_Log.LDF')
```
```
Step 6:
You might need to reset the status. Even if you don't, it won't do any harm to do so.
```
```
exec sp_resetstatus TestDB
```
```
Step 7:
Stop and start SQL to see your newly restored database.


Question: I'm using Visual Studio 2008 and the built-in installation tools for a C# client application. How can I use this installer to install a font on the client machine (if it's not already there)?

Answer:
Take a look at this article.
http://www.atakala.com/Browser/Item.aspx?user_id=amos&dict_id=83
The most important call is the
AddFontResource
Win32 API call altough the described sequence of operations must be respected for you to have a working font setup in the system.
http://msdn.microsoft.com/en-us/library/ms534231(VS.85).aspx
The AddFontResource function adds the
  font resource from the specified file
  to the system font table. The font can
  subsequently be used for text output
  by any application.


Question:
It is mentioned on the Systems Development Life Cycle page on Wikipedia:

To manage this, a number of system development life cycle (SDLC) models have been created: waterfall, fountain, spiral, build and fix, rapid prototyping, incremental, and synchronize and stabilize.

I found a few things on Google, but I felt that they were vague and they just didn't click for me. Perhaps an explanation from someone here might be more clear.

Answer:
Waterfall is a model that enforces control and avoids parallelism; every requirement for a task has to be fulfilled before starting the task. Fountain says that a new task can be started before all requirements are met, because not all requirements are necessary at the start of the task.
Think of this: Super Mario Game,
Waterfall: first, design everything, then get hardware done (Hardware Team), then create some test sprites, then code the engine, then create artwork, then music and finish.
Fountain: while the hardware team is doing its job, artwork starts conceptual work, and coding starts some prototyping on preexisting hw. When artists and hw finishes, coders integrate these onto their code and continue 'til finishing the game...


Question:
Is it possible to pass a function/callback from javascript to a java applet?

For example i have an applet with a button that when pressed it will call the passed js callback

function onCommand() {
  alert('Button pressed from applet');
}
applet.onCommand(onCommand);

Answer:
You can use
JSObject
to call back into javascript from Java.
From that page:
```
```
import netscape.javascript.*;
import java.applet.*;
import java.awt.*;
class MyApplet extends Applet {
     public void init() {
         JSObject win = JSObject.getWindow(this);
         JSObject doc = (JSObject) win.getMember("document");
         JSObject loc = (JSObject) doc.getMember("location");

         String s = (String) loc.getMember("href");  // document.location.href
         win.call("f", null);                      // Call f() in HTML page
     }
}
```
```


Question:
(Oracle) I have to return all records from last 12 months. How to do that in PL/SQL?

EDIT: Sorry, I forgot to explain, I do have a column of DATA type

Answer:
```
```
SELECT *
FROM   table
WHERE  date_column > SYSDATE - 365
```
```


Question: Looking for one that is fast enough and still graceful with memory. The image is a 24bpp  System.Drawing.Bitmap.

Answer:
If you need an exact number, then you are going to have to loop over all of the pixels.  Probably storing the color and a count in a hash is the best way to go because of the sparseness of the colors.
Using the Color.ToArgb() in the hash instead of the color object would probably be a good idea too.
Also, if speed is a major concern, you don't want to use a function like GetPixel(x, y) -- instead try to process chunks at a time (row a time).  If you can, get a pointer to the beginning of the image memory and do it unsafe.


Question:
I'm just reading up on SOA and the service registry / UDDI get mentioned regularly. It sounds nice but how is used in reality?

Is the registry meant to decouple a logical service from its' physical implementation (port, url etc)?

Is the registry meant to be browsed by a human looking for an interesting service to play with?

Would it be 'wrong' to hard-wire an
application
    to the services it uses?

Answer:
A service registry stores and publishes information about all available services, mainly their interface description and their current URI (ip, port, whatever). This way the application can simply ask the registry for the needed service and will get the details of a fitting service implementation, and can connect.
UDDI is not the only way to get a registry for you services. But remember that UDDI is intended for webservices only, so it's only usefull if your SOA consists only of webservices.
1) Correct.
2) No, it's not really meant for human eyes. Sure, there are tools to browse the directory, but they are mainly for looking if the registry got the services you need etc. The real usage happens directly between your application/service and the registry.
3) That depends on what you want to accomplish. If you want to build a SOA it think it would be 'wrong' because this contradicts the loose coupling paradigm of SOA.
If this is your only service, the only application that uses it and it's likely that the service won't change it's URI there's definitely no problem in hard-wiring it - but then there's propably no need to separate this service :)


Question:
I have an application that depends on gpsd and ntpd to accurately set the system time on a linux machine.

gpsd is fed NMEA + PPS

The application is punping ~25MB per second over the network and I think the loading on the system is causing jitter in the time somehow. (loaded PCI express bus causing irregular interrupt latency)

I have another machine that is not loaded at all that I could setup to read the GPS and act as an NTP server for the loaded machine. (the loaded machine would be getting startum 1 ???)

How accurate can I expect the time to be from a stratum 0 NTP server on the same subnet on Ethernet?

I hope this is not too off topic, I am sure sometime someone else will be happy the answer is documented here. ;-)

Answer:
Best info I could find on
NTP accuracy
, seems to point at 1-2 ms in a LAN setting:
NTP v4 with kernel mods to support it, is capable of much better than 1ms accuracy, possibly as good as 1ns.  According to [Dave Mills] article, NTP v3 is accurate to 1-2ms in a LAN and 10s of ms in WAN nets.
http://www.cis.udel.edu/~mills/ntp.html
Other articles suggest that with an accurate time source, such as a GPS time source, NTP is accurate to 50us, but the links on the Linux kernel support say that accuracy of a few ms are possible.
http://www.atomic-clock.galleon.eu.com/support/ntp-time-server-accuracy.html
Another article says that it is dependent on the predictability of network delays (i.e. a low jitter network).
http://www.postel.org/pipermail/end2end-interest/2003-April/002925.html


Question:
I have drawn an image in the device context using python and I want to move it smoothly/animate either vertically or horizontally.

What algorithm should I use? Where can I get info for this kind of tasks in python?

Answer:
Once an object is drawn in a device context it stays there. If you want to move it you need to redraw it.
You can keep a background that's fixed and only redraw the movable elements each time they move. Basically that's how it's done.
To move an object smoothly over a line you have to do something like this (I don't have a program ready, so can only give you an idea):
choose the start and end position: point A(x1, y1) and B(x2, y2)
choose in how much time the object should change position from A to B (say 10 seconds).
use a timer set to a certain interval (say 2 seconds)
calculate the delta X and Y that the object should change for each timer interval. In this case dx = (x2-x1)*2/10 and dy = (y2-y1)*2/10
in the timer callback increment the current object position with dx and dy and redraw the image
That would be the algorithm.
I suggest that you also take a look to
PyGame
. Maybe you can use that and it also has some tutorials.


Question:
I'm translating a library written in C++ to C#, and the keyword 'union' exists once. In a struct.

What's the correct way of translating it into C#? And what does it do? It looks something like this;

struct Foo {
    float bar;

    union {
        int killroy;
        float fubar;
    } as;
}

Answer:
You can use explicit field layouts for that:
```
```
[StructLayout(LayoutKind.Explicit)]
public struct SampleUnion
{
    [FieldOffset(0)] public float bar;
    [FieldOffset(4)] public int killroy;
    [FieldOffset(4)] public float fubar;
}
```
```
Untested.  The idea is that two variables have the same position in your struct.  You can of course only use one of them.
More informations about unions in
struct tutorial


Question: Almost every Python web framework has a simple server that runs a wsgi application and automatically reloads the imported modules every time the source gets changed. I know I can look at the code and see how it's done, but that may take some time and I'm asking just out of curiosity. Does anyone have any idea how this is implemented?

Answer:
As the author of one of the reloader mechanisms (the one in werkzeug) I can tell you that it doesn't work.  What all the reloaders do is forking one time and restarting the child process if a monitor thread notices that one module changed on the file system.
Inline
```
reload()
```
ing doesn't work because references to the reloaded module are not updated.


Question: In a destructor, is there a way to determine if an exception is currently being processed?

Answer:
You can use std::uncaught_exception(), but it might not do what you think it does: see
GoTW#47
for more information.


Question:
Here's a question to expose my lack of experience: I have a method DoSomething() which throws an exception if it doesn't manage to do it cleanly. If it fails, I try the less accurate method DoSomethingApproximately() several times in the hope that it will find a sufficiently good solution; if this also fails I finally call DoSomethingInaccurateButGuaranteedToWork(). All three are methods belonging to this object.

Two questions: first, is this (admittedly ugly) pattern acceptable, or is there a more elegant way?

Second, what is the best way to keep track of how many times I have called DoSomethingApproximately(), given that it is likely to throw an exception? I am currently keeping a variable iNoOfAttempts in the object, and nesting try blocks... this is horrible and I am ashamed.

Answer:
Return an error code instead of throwing an exception.
If the ways those methods fail do throw exceptions, catch them all in the same method and take appropriate action, like increasing a counter and returning an error code.
```
```
bool result = DoSomething();
   while (!result && tries < MAX_TRIES) {
       result = DoSomethingApproximately(); //This will increment tries
       if (tries > THRESHOLD) {
           result = DoSomethingThatAlwaysWorks();
       }
   }
```
```


Question:
I have two tables, Users and DoctorVisit

User
- UserID
- Name

DoctorsVisit
- UserID
- Weight
- Date

The doctorVisit table contains all the visits a particular user did to the doctor.
The user's weight is recorded per visit.

Query:  Sum up all the Users weight, using the last doctor's visit's numbers. (then divide by number of users to get the average weight)

Note: some users may have not visited the doctor at all, while others may have visited many times.

I need the average weight of all users, but using the latest weight.

Update

I want the average weight across all users.

Answer:
This should get you the average weight per user if they have visited:
```
```
select user.name, temp.AvgWeight
from user left outer join (select userid, avg(weight)
            from doctorsvisit
            group by userid) temp
    on user.userid = temp.userid
```
```


Question:
I'm developing a C# assembly which is to be called via COM from a Delphi 7 (iow, native win32, not .net) application.

So far, it seems to work. I've exported a TLB file, imported that into my Delphi project, and I can create my C# object and call its functions.

So that's great, but soon I'm going to really want to use Visual Studio to debug the C# code while it's running. Set breakpoints, step through code, all that stuff.

I've tried breaking in the Delphi code after the COM object is created, then looking for a process for VS to attach to, but I can't find one.

Is there a way to set VS2008 up to do this? I'd prefer to just be able to hit f5 and have VS start the Delphi executable, wait for the C# code to be called, and then attach itself to it.. But I could live with manually attaching to a process, I suppose.

Just please don't tell me I have to make do with MessageBox.Show etc.

Answer:
Place the following in the method you wish to debug:
```
```
#if DEBUG
    if (!System.Diagnostics.Debugger.IsAttached)
        Debugger.Launch();
#endif
```
```
When you want to debug, build a debug version and use that in your application.  When this code runs, a dialog pops up asking if you want to attach a debugger.


Question:
I use the right button>Refactor>Encapsultate field to have my accessor every time. The problem is when I create new class, I can have more than 10 attributes and it's long to do 1 by 1 every accessor. Is there a faster way to create them?

Thank you for your time.

Answer:
Looks like the refactoring built into studio only supports a single field at a time for the Encapsulate Field refactoring.  Refactor Pro! (
http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/
) or Resharper (
http://www.jetbrains.com/resharper/index.html
)  both have support for encapsulating multiple fields.
You may be able to get fancy and put together a macro that would allow you to select multiple fields and then encapsulate each one, but VS macros are not my ball of wax.


Question:
we are using git-svn to manage branches of an SVN repo. We are facing the following problem: after a number of commits by user X in the branch, user Y would like to use git-svn to merge the changes in branch to trunk. The problem we're seeing is that the commit messages for all the individual merge operations look as if they were made by user Y, whereas the actual change in branch was made by user X.

Is there a way to indicate to git-svn that when merging, use the original commit message/author for a given change rather than the person doing the merge?

Answer:
The git-svn man page recommends that you
don't use merge
. ""It is recommended that you run git-svn fetch and rebase (not pull or merge)"". Having said that, you can do what you like :-)
There are 2 issues here. First is that svn only stores the
commiter
, not the author of a patch as git does. So when Y commits the merges to trunk, svn only records her name, even though the patches were authored by X. This is an
amazing
feature of git, stunningly simple yet vital for open source projects were attributing changes to the author can avoid legal problems down the road.
Secondly, git doesn't seem to use the relatively new svn merge features. This may be a temporary thing, as git is actively developed and new features are added all the time. But for now, it doesn't use them.
I've just tried with git 1.6.0.2 and it "loses" information compared to doing the same operation with svn merge. In svn 1.5, a new feature was added to the logging and annotation methods, so that svn log -g on the trunk would output something like this for a merge:
```
```
------------------------------------------------------------------------
r5 | Y | 2008-09-24 15:17:12 +0200 (Wed, 24 Sep 2008) | 1 line

Merged release-1.0 into trunk
------------------------------------------------------------------------
r4 | X | 2008-09-24 15:16:13 +0200 (Wed, 24 Sep 2008) | 1 line
Merged via: r5

Return 1
------------------------------------------------------------------------
r3 | X | 2008-09-24 15:15:48 +0200 (Wed, 24 Sep 2008) | 2 lines
Merged via: r5

Create a branch
```
```
Here, Y commits r5, which incorporates the changes from X on the branch into the trunk. The format of the log is not really that great, but it comes into its own on svn blame -g:
```
```
2          Y int main()
       2          Y {
G      4          X   return 1;
       2          Y }
```
```
Here assuming Y only commits to trunk, we can see that one line was editted by X (on the branch) and merged.
So, if you are using svn 1.5.2, you are possibly better of merging with the real svn client for now. Although you would lose merge info in git, it is usually clever enough not to complain.
Update: I've just tried this with git 1.7.1 to see if there has been any advances in the interim. The bad news is that merge within git still does not populate the svn:mergeinfo values, so
```
git merge
```
followed by
```
git svn dcommit
```
will not set svn:mergeinfo and you will lose merge information if the Subversion repository is the canonical source, which it probably is. The good news is that
```
git svn clone
```
does read in svn:mergeinfo properties to construct a better merge history, so if you use
```
svn merge
```
correctly (it requires merging full branches) then the git clone will look correct to git users.


Question: The question is pretty self-explanatory. I'm looking for a PostgreSQL equivalent to the SQLite datetime function.

Answer:
```
```
postgres=# select to_char(now(),'YYYY-mm-dd HH:MM:ss');
       to_char
---------------------
 2008-09-24 02:09:20
(1 row)

postgres=# select to_char(now(),'YYYY-mm-dd HH24:MM:ss');
       to_char
---------------------
 2008-09-24 14:09:20
(1 row)
```
```


Question: What I'm looking for is a simple timer queue possibly with an external timing source and a poll method (in this way it will be multi-platform). Each enqueued message could be an object implementing a simple interface with a virtual onTimer() member function.

Answer:
There is a nice article in CodeProject,
here
, that describes the various timers available in Windows, and has chapters titled "Queue timers" and "Make your own timer".
For platform independence, you'd have to make implementations for the different platforms inside
```
#ifdef -- #endif
```
pairs. I can see nothing less ugly than that.


Question:
When writing j2me applications for cellphones, using System.out.println() prints on the console if using an emulator. However, when the code is deployed on a cellphone, where does the console output go?

If it is impossible to see this in the untethered cellphone, is there a way to see it if the cellphone is still connected to the deploying PC [via USB] ?

Answer:
I found
this question
with answers on j2me logging. Maybe one can try this if nothing else works. A simple way to access
```
System.out.println()
```
would be nice though.


Question: I need to compress portions of our application's network traffic for performance.  I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.

Answer:
You can use
Deflater
/
Inflater
which is built into the JDK.  There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use.
Edit:
Reading further comments it looks like the network taffic is HTTP.  Depending on the server, it probably has support for compression (especially with deflate/gzip).  The problem then becomes on the client.  If the client is a browser it probably already supports it.  If your client is a webservices client or an
http client
check the documentation for that package to see if it is supported.
It looks like jakarta-commons httpclient may require you to manually do the compression.  To enable this on the client side you will need to do something like
```
```
.addRequestHeader("Accept-Encoding","gzip,deflate");
```
```


Question: Could anyone recommend to me a good online guide to PowerPoint VBA? Also, does anyone has advice on how to record a macro in PowerPoint?

Answer:
To record a powerpoint macro:
In the menu bar, click on Tools
Mouse over Macro >  and the submenu will be displayed
Click the Record button - a new toolbar will be displayed
Do your thing
Click the stop button on the new macro toolbar
Click on Tools->Macro->Macros.  Find the macro you just recorded and click the Edit button.  That will show you what was recorded.  Make your modifications and click the triangular run button (or push F5) to run your code.
As far as an online guide, I usually think of a question and use
Google
or ask a question here on StackOverflow.com.  I've been able to answer most of my questions that way, I haven't found a particular main resource for all things Powerpoint VBA.
Also, you can find answers that can help you by looking into VBA articles for other MS Office products - a lot of things that are not Powerpoint-specific (general VBA) will be the same as for the other products.


Question: Why is it not a good idea to use SOAP for communicating with the front end? For example, a web browser using JavaScript.

Answer:
Because SOAP reinvents a lot of the HTTP wheel in its quest for protocol-independence. What's the point if you
know
you're going to serve the response over HTTP anyway (since your client is a web browser)?
UPDATE: I second gizmo's (implied) suggestion of JSON.


Question: In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?

Answer:
For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.
```
```
function copyIntoClipboard(text) {

    var flashId = 'flashId-HKxmj5';

    /* Replace this with your clipboard.swf location */
    var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';

    if(!document.getElementById(flashId)) {
        var div = document.createElement('div');
        div.id = flashId;
        document.body.appendChild(div);
    }
    document.getElementById(flashId).innerHTML = '';
    var content = '<embed src="' +
        clipboardSWF +
        '" FlashVars="clipboard=' + encodeURIComponent(text) +
        '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashId).innerHTML = content;
}
```
```
The only disadvantage is that this requires Flash to be enabled.
The source is currently dead:
http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/
(and so is its
Google cache
)


Question:
We have a production machine and are trying to slowly introduce some 3.0 and up features on our web application. 3.5 is installed but I would like to upgrade to SP1, I would just like to know if it requires a restart of the machine in the end so I can schedule some down time.

Thanks!

EDIT: so it did require the restart, thanks guys for the answer...but the hosting company didn't give us the rights to do so...LOL

Answer:
He he.  I installed it on about 4 machines...two required a restart, two did not.  The configuration was similar between them, so there was no obvious way to determine why some needed a restart and others didn't.  The best theory I have currently is that the ones which needed restarts tended to be the ones which were more active (they were all running ASP.Net sites), so it is possible that the framework bits had not yet been loaded by IIS for the ones which did not need a restart.
To be safe, plan on restarting and schedule the update accordingly.


Question:
In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?

i.e.

dim fooArr() as foo;
gv1.datasource =  fooArr;
gv1.databind();

On Row Select

Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand

        If e.CommandName = "Select" Then
            'get and use foo(index)
        End If
    End Sub

Answer:
in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, you should be able to do something along these lines
```
```
dim x as object = foo(e.row.selectedIndex)
```
```
The other alternative is to find a way to databind the index to the commandArgument attribute of the button.


Question:
I was wondering if there was an easy way in SQL to convert an integer to its binary representation and then store it as a varchar.

For example 5 would be converted to "101" and stored as a varchar.

Answer:
Following could be coded into a function.  You would need to trim off leading zeros to meet requirements of your question.
```
```
declare @intvalue int
set @intvalue=5

declare @vsresult varchar(64)
declare @inti int
select @inti = 64, @vsresult = ''
while @inti>0
  begin
    select @vsresult=convert(char(1), @intvalue % 2)+@vsresult
    select @intvalue = convert(int, (@intvalue / 2)), @inti=@inti-1
  end
select @vsresult
```
```


Question:
Does anyone know a good online resource for example of R code?

The programs do not have to be written for illustrative purposes, I am really just looking for some places where a bunch of R code has been written to give me a sense of the syntax and capabilities of the language?

Edit: I have read the basic documentation on the main site, but was wondering if there was some code samples or even programs that show how R is used by different people.

Answer:
Why not look at
www.r-project.org
under documentation and read at least the introduction?  The language is sufficiently different from what you're used to that just looking at code samples won't be enough for you to pick it up. (At least, not beyond basic calculator-like functionality.)
If you want to look a bit deeper, you might want to look at
CRAN
: an online collection of R modules with source code:
cran.r-project.org


Question:
i was wondering how you deal with permalinks on international sites. By permalink i mean some link which is unique and human readable.

E.g. for english phrases its no problem e.g. /product/some-title/

but what do you do if the product title is in e.g chinese language??
how do you deal with this problem?

i am implementing an international site and one requirement is to have human readable URLs.
Thanks for every comment

Answer:
If memory serves, you're only able to use English letters in URLs. There's a discussion to change that, but I'm fairly positive that it's not been implemented yet.
that said, you'd need to have a look up table where you assign translations of products/titles into whatever word that they'll be in the other language.  For example:
foo.com/cat will need a translation look up for "cat" "gato" "neko" etc.
Then your HTTP module which is parsing those human reading objects into an exact url will know which page to serve based upon the translations.


Question:
This is an exercise for the CS guys to shine with the theory.

Imagine you have 2 containers with elements. Folders, URLs, Files, Strings, it really doesn't matter.

What is AN algorithm to calculate the added and the removed?

Notice: If there are many ways to solve this problem, please post one per answer so it can be analysed and voted up.

Edit: All the answers solve the matter with 4 containers. Is it possible to use only the initial 2?

Answer:
I have not done this in a while but I believe the algorithm goes like this...
```
```
sort left-list and right-list
adds = {}
deletes = {}
get first right-item from right-list
get first left-item from left-list
while (either list has items)
  if left-item < right-item or right-list is empty
    add left-item to deletes
    get new left-item from left-list
  else if left-item > right-item or left-list is empty
    add right-item to adds
    get new right-item from right-list
  else
    get new right-item from right-list
    get new left-item from left-list
```
```
In regards to right-list's relation to left-list,
deletes
contains items removed and
adds
now contains new items.


Question:
How do I check if an index exists on a table field in MySQL?

I've needed to Google this multiple times, so I'm sharing my Q/A.

Answer:
Use
```
SHOW INDEX
```
like so:
```
```
SHOW INDEX FROM [tablename]
```
```
Docs:
https://dev.mysql.com/doc/refman/5.0/en/show-index.html


Question:
Can you explain STA and MTA in your own words?

Also, what are apartment threads and do they pertain only to COM? If so, why?

Answer:
Each EXE which hosts COM or OLE controls defines it's apartment state.  The apartment state is by default STA (and for most programs should be STA).
STA
- All OLE controls by necessity must live in a STA.  STA means that your COM-object must be always manipulated on the UI thread and cannot be passed to other threads (much like any UI element in MFC).  However, your program can still have many threads.
MTA
- You can manipulate the COM object on any thread in your program.


Question:
I have a constructor like as follows:

public Agent(){

    this.name = "John";
    this.id = 9;
    this.setTopWorldAgent(this, "Top_World_Agent", true);

}

I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?

Answer:
```
this
```
is not null, that much is sure. It's been allocated.
That said, there's no need to pass
```
this
```
into the method, it's automatically available in all instance methods. If the method's static, you may want refactor it into an instance method.


Question: This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.

Answer:
```
foreach
```
does
not
require
```
IEnumerable
```
, contrary to popular belief. All it requires is a method
```
GetEnumerator
```
that returns any object that has the method
```
MoveNext
```
and the get-property
```
Current
```
with the appropriate signatures.
/EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:
```
```
class EnumerableWrapper {
    private readonly TheObjectType obj;

    public EnumerableWrapper(TheObjectType obj) {
        this.obj = obj;
    }

    public IEnumerator<YourType> GetEnumerator() {
        return obj.TheMethodReturningTheIEnumerator();
    }
}

// Called like this:

foreach (var xyz in new EnumerableWrapper(yourObj))
    …;
```
```
/EDIT: The following method, proposed by several people, does
not
work if the method returns an
```
IEnumerator
```
:
```
```
foreach (var yz in yourObj.MethodA())
    …;
```
```


Question:
Is there a side effect in doing this:

C code:

struct foo {
      int k;
};

int ret_foo(const struct foo* f){
    return f.k;
}

C++ code:

class bar : public foo {

   int my_bar() {
       return ret_foo( (foo)this );
   }

};

There's an extern "C" around the C++ code and each code is inside its own compilation unit.

Is this portable across compilers?

Answer:
Wow, that's evil.
Is this portable across compilers?
Most definitely not. Consider the following:
```
```
foo* x = new bar();
delete x;
```
```
In order for this to work, foo's destructor must be virtual which it clearly isn't. As long as you don't use
```
new
```
and as long as the derived objectd don't have custom destructors, though, you could be lucky.
/EDIT: On the other hand, if the code is only used as in the question, inheritance has no advantage over composition. Just follow the advice given by m_pGladiator.


Question:
I need to install amp on a windows2003 production server. I'd like, if possible, an integrated install/management tool so I don't have to install/integrate the components of amp separately. Those that I've found are 'development' servers. Are there any packages out there that install amp in a production ready (locked down state)?

I'm aware of LAMP... Windows, since we have IIS apps already and we've paid for this box, is a requirement. I'll take care of all the other hangups. I just want a simple way to install, integrate, and manage AMP.

Answer:
There doesn't appear to be any all-in one packages that are up to date and 'designed' for production. You just can't trust the default installs to be secure on whats out there.
I ended up just doing this manually. It wasn't painful though. Each component's install procedure was documented reasonably well. Took me about 3.5hrs. A nice side effect of the involved setup was that it gave me a much better understanding of each component's dependencies and the ways in which they touch. In hind sight I should have done it manually from the start.
Note: make sure you read the comments below each component's documentation pages. Some contain valuable corrections to the install process.


Question:
I first got an error usign the code below, explaining that "DataGridLinkButton' must be placed inside a form tag with runat=server."

Now I've tried setting AllowSorting to false, as well as removing the sort expression from each column, with the same error.  Then I tried creating a new, plain, DataGrid, with the same data source, but now I get a blank page and FF doesn't recognise the content type properly any more.  Please help.

Response.Clear();
base.Response.Buffer = true;
base.Response.ContentType = "application/vnd.ms-excel";
base.Response.AddHeader("Content-Disposition", "attachment;filename=file.xls");
base.Response.Charset = "";
this.EnableViewState = false;
StringWriter writer = new StringWriter();
HtmlTextWriter writer2 = new HtmlTextWriter(writer);
this.lblExport.RenderControl(writer2);
base.Response.Write(writer.ToString());

Answer:
Add the following empty method to your code. That should fix it.
```
```
public override void VerifyRenderingInServerForm(Control control)
    {
    }
```
```


Question:
I have a class that defines the names of various constants, e.g.

class Constants {
    public static final String ATTR_CURRENT_USER = "current.user";
}

I would like to use these constants within a JSP without using Scriptlet code such as:

<%@ page import="com.example.Constants" %>
<%= Constants.ATTR_CURRENT_USER %>

There appears to be a tag in the Apache unstandard taglib that provides this functionality. However, I cannot find any way to download this taglib. I'm beginning to wonder if it's been deprecated and the functionality has been moved to another (Apache) tag library?

Does anyone know where I can get this library, or if it's not available, if there's some other way I can access constants in a JSP without using scriptlet code?

Cheers,
Don

Answer:
Why do you want to print the value of the constant on the JSP? Surely you are defining them so that in the JSP you can extract objects from the session and request before you present them?
```
<%@ page import="com.example.Constants" %>
<%@ page import="com.example.model.User" %>
<%
User user = (User) session.getAttribute(Constants.ATTR_CURRENT_USER);
%>

<h1>Welcome <%=user.getFirstName()%></h1>
```


Question:
Outlook saves its client-side rule definitions in a binary blob in a hidden message in the Inbox folder of the default store for a profile. The hidden message is named "Outlook Rules Organizer" with a message class IPM.RuleOrganizer. The binary blob is saved in property 0x6802. The same binary blob is written to the exported RWZ file when you manually export the rules through the Rules and Alerts Wizard.

Has anyone deciphered the layout of this binary blob?

Answer:
Why do you want to print the value of the constant on the JSP? Surely you are defining them so that in the JSP you can extract objects from the session and request before you present them?
```
<%@ page import="com.example.Constants" %>
<%@ page import="com.example.model.User" %>
<%
User user = (User) session.getAttribute(Constants.ATTR_CURRENT_USER);
%>

<h1>Welcome <%=user.getFirstName()%></h1>
```


Question:
different programming languages have different features or lack certain features. Design patterns are a way to work around those shortcomings. I have seen the books and lists about design patterns in static, object oriented languages (Java, C++), but also the Videos about design patterns in Python.

I'm interested in to see some common design patterns in other languages like Forth, Icon, Lisp etc. A short description how they look like and why are they needed in a language would be nice. Maybe a short comparision to another language that solves this problem without a design pattern.

Answer:
In Lisp, instead of design patterns you are using:
lambda and closure (anonymous functions and capture environments)
higher order functions (functions dealing with functions)
macros (syntax extesnions)
different evaluation strategies (lazy evaluation, backtracking)
first class functions, classes, namespaces, modules, etc.
dynamic environment (e.g. replace functions at any time)
etc.
I don't really know what a design pattern means in this context. If a design pattern is a recipe which one should follow to solve certain kinds of problems, then it is a lack of feature in the programming language or the environment. Computers can handle repetitive tasks pretty well, so design patterns must be implemented and just called with the actual parameters.


Question:
In Visual Studio, we've all had "baadf00d", have seen seen "CC" and "CD" when inspecting variables in the debugger in C++ during run-time.

From what I understand, "CC" is in DEBUG mode only to indicate when a memory has been new() or alloc() and unitilialized.  While "CD" represents delete'd or free'd memory.  I've only seen "baadf00d" in RELEASE build (but I may be wrong).

Once in a while, we get into a situation of tacking memory leaks, buffer overflows, etc and these kind of information comes in handy.

Would somebody be kind enough to point out when and in what modes the memory are set to recognizable byte patterns for debugging purpose?

Answer:
This link has more information:
https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values
```
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory
* 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
* 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
* 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
* 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
* 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory
* 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory
* 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory
* 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
* 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory
* 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
```


Question:
I was asked a question in C last night and I did not know the answer since I have not used C much since college so I thought maybe I could find the answer here instead of just forgetting about it.

If a person has a define such as:

#define count 1

Can that person find the variable name count using the 1 that is inside it?

I did not think so since I thought the count would point to the 1 but do not see how the 1 could point back to count.

Answer:
What do you mean by "finding"?
The line
```
```
#define count 1
```
```
defines a symbol "count" that has value 1.
The first step of the compilation process (called preprocessing) will replace every occurence of the symbol count with 1 so that if you have:
```
```
if (x > count) ...
```
```
it will be replaced by:
```
```
if (x > 1) ...
```
```
If you get this, you may see why "finding count" is meaningless.


Question:
Is there a way when creating web services to specify the types to use? Specifically, I want to be able to use the same type on both the client and server to reduce duplication of code.

Over simplified example:

    public class Name
    {
        public string FirstName {get; set;}
        public string Surname { get; set; }

        public override string ToString()
        {
            return string.Concat(FirstName, " ", Surname);
        }
    }

I don't want to have recode pieces of functionality in my class. The other thing is that any code that exists that manipulates this class won't work client side as the client side class that is generated would be a different type.

Answer:
If you want to have a type or structure shared between your web service and your client, add a public struct to your web service project like so:
```
```
public struct Whatever
{
    public string A;
    public int B;
}
```
```
then add a method to your web service that has this struct as its return type:
```
```
[WebMethod]
public Whatever GiveMeWhatever()
{
    Whatever what = new Whatever();
    what.A = "A";
    what.B = 42;
    return what;
}
```
```
After you update your client's web reference, you'll be able to create structs of type Whatever in your client application like so:
```
```
Webreference.Whatever what = new Webreference.Whatever();
what.A = "that works?";
what.B = -1; // FILENOTFOUND
```
```
This technique lets you maintain the definition of any structures you need to pass back and forth in one place (the web service project).


Question: What are the naming conventions that you use while coding?

Answer:
Here's a list of
general naming conventions
from MSDN.
I tend to just go-with-the-flow, however.  Whatever standards are currently in place, it's usually easiest to just go with them and maybe slowly shift it over time. It's not really practical to just come into a project with your own idea of "standards" and try to implement them.
It doesn't REALLY matter what standards are used, imo -- just that there are some and people know what they are.


Question:
I have Excel add-in which I add so many class modules that it is now very bulky. I want to convert it into a type library or a COM package so that I can re-use it for the other apps in the MS Office suite.

I ported the add-in to Visual Studio as a class library project but Excel Automation doesn't recognize the classes in the compiled .dll file. Intuitively I think I would need a manifest, an interface or the something like that in my code.

What do I need to know in order to expose a class's methods and properties for use in OLE Automation?

Answer:
Here's a list of
general naming conventions
from MSDN.
I tend to just go-with-the-flow, however.  Whatever standards are currently in place, it's usually easiest to just go with them and maybe slowly shift it over time. It's not really practical to just come into a project with your own idea of "standards" and try to implement them.
It doesn't REALLY matter what standards are used, imo -- just that there are some and people know what they are.


Question:
I need to be able to change the users' password through a web page (in a controlled environment).
So, for that, I'm using this code:

<?php
$output = shell_exec("sudo -u dummy passwd testUser testUserPassword");
$output2 = shell_exec("dummyPassword");
echo $output;
echo $output2;
echo "done";
?>

My problem is that this script is not changing the password for the user "testUser".
What am I doing wrong?

Thanks

Answer:
I'm not familiar enough with PHP to tell you how to fix it, but your problem is that the two
```
shell_exec
```
commands are entirely separate. It appears as though you're trying to use the second command to pipe input to the first one, but that's not possible. The first command shouldn't return until after that process has executed, when you run the second one it will attempt to run the program
```
dummyPassword
```
, which we can probably expect to fail.


Question: Is anyone aware of a reasonably well documented example of simulated annealing in Visual Basic that I can examine and adapt?

Answer:
This project looks pretty well documented:
http://www.codeproject.com/KB/recipes/simulatedAnnealingTSP.aspx
. It's C# but contains only one important source file (TravellingSalesmanProblem.cs) so it's pretty easy to run it through a converter. Maybe:
http://labs.developerfusion.co.uk/convert/csharp-to-vb.aspx
?
MSDN magazine also had an interesting article on
neural networks
. As I understand simulated annealing, you can add it to other function estimation methods (like neural nets). So you could add simulated annealing to the MSDN VB code by shrinking the Momentum over time. The network starts 'hot' by backpropagating error with a large Momentum and slowly 'cools' by shrinking the Momentum and thus reducing the effect of output error in backpropagation.
Cheers.