Question:
I'm trying to port an old library (that doesn't use namespaces as far as I can tell) to modern compilers. One of my targets can't tell the difference between System::TObject and ::TObject (without a namespace). System::TObject is native to the compiler.

I've tried a using directive, i.e. using ::TObject;

But that doesn't do it.

The obvious solution is to wrap all the original library in a namespace and then calling it by name- that should avoid the ambiguity. But is that the wisest solution? Is there any other solution? Adding a namespace would require changing a bunch of files and I don't know if it would have unwanted repercussions later.

Answer:
If you have the source to the library, maybe include a header file at the top of each source where that header file has only:
```
```
#define TObject TMadeUpNameObject
```
```


Question:
I need to store the user's password in my iphone app.

When posting an app to the app store, I have to tell Apple if there's encryption in the app for export purposes.

I don't want my app to be restricted to US only, but I also don't want to store or send passwords over the net in clear text.

So basically the question is, can I encrypt passwords in a way that will not get my app restricted?

Answer:
First, if the user name and password are encrypted and decrypted on the phone, then the decryption key is obviously also on the phone and pretty much worthless. I wouldn't worry about storing user names and passwords encrypted on the phone.
For secure communication, you should use SSL which is probably in a library that is already on the phone. If you use a library that is part of the phone OS, I don't think that means your app "contains encryption".
Of course, I am not a lawyer. Who knows - the law might consider "pig latin" a valid encryption technology.


Question:
I'm trying to convert some code that worked great in VB, but I can't figure out what objects to use in .Net.

    Dim oXMLHttp As XMLHTTP
    oXMLHttp = New XMLHTTP
    oXMLHttp.open "POST", "https://www.server.com/path", False
    oXMLHttp.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    oXMLHttp.send requestString

Basically, I want to send an XML file to a server, then store the response that it returns.  Can anyone point me in the right direction on this?

Answer:
See the following for a sample which does this:
http://www.codeproject.com/KB/dotnet/NET_Interact_j2EE.aspx
I have put the sample below. Sorry, I know it's big, but you never know how long links like this will stay valid.
NOTE: the first version of the question didn't say in C# .NET - it just said "in .NET". (perhaps it was tagged C# and I didn't see it) Converting from VB.NET to C# is pretty easy (though unnecessary).
'This class is representing the same functionality of xmlHTTP object in MSXML.XMLHTTP.
```
```
Imports System.Net
Imports System.Web.HttpUtility

Public Class XMLHTTP
'Makes an internet connection to specified URL
   Public Overridable Sub open(ByVal bstrMethod As String, _
     ByVal bstrUrl As String, Optional ByVal varAsync As _
     Object = False, Optional ByVal bstrUser _
     As Object = "", Optional ByVal bstrPassword As Object = "")
       Try
           strUrl = bstrUrl
           strMethod = bstrMethod

           'Checking if proxy configuration
           'is required...(blnIsProxy value
           'from config file)
           If blnIsProxy Then
           'Set the proxy object
               proxyObject = WebProxy.GetDefaultProxy()

               'Finding if proxy exists and if so set
               'the proxy configuration parameters...
               If Not (IsNothing(proxyObject.Address)) Then
                   uriAddress = proxyObject.Address
                   If Not (IsNothing(uriAddress)) Then
                       _ProxyName = uriAddress.Host
                       _ProxyPort = uriAddress.Port
                   End If
                   UpdateProxy()
               End If
               urlWebRequest.Proxy = proxyObject
           End If

           'Make the webRequest...
           urlWebRequest = System.Net.HttpWebRequest.Create(strUrl)
           urlWebRequest.Method = strMethod

           If (strMethod = "POST") Then
               setRequestHeader("Content-Type", _
                   "application/x-www-form-urlencoded")
           End If

           'Add the cookie values of jessionid of weblogic
           'and PH-Session value of webseal
           'for retaining the same session
           urlWebRequest.Headers.Add("Cookie", str_g_cookieval)

       Catch exp As Exception
           SetErrStatusText("Error opening method level url connection")
       End Try
   End Sub
   'Sends the request with post parameters...
   Public Overridable Sub Send(Optional ByVal objBody As Object = "")
       Try
           Dim rspResult As System.Net.HttpWebResponse
           Dim strmRequestStream As System.IO.Stream
           Dim strmReceiveStream As System.IO.Stream
           Dim encode As System.Text.Encoding
           Dim sr As System.IO.StreamReader
           Dim bytBytes() As Byte
           Dim UrlEncoded As New System.Text.StringBuilder
           Dim reserved() As Char = {ChrW(63), ChrW(61), ChrW(38)}
           urlWebRequest.Expect = Nothing
           If (strMethod = "POST") Then
               If objBody <> Nothing Then
                   Dim intICounter As Integer = 0
                   Dim intJCounter As Integer = 0
                   While intICounter < objBody.Length
                     intJCounter = _
                       objBody.IndexOfAny(reserved, intICounter)
                     If intJCounter = -1 Then
UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _
                                                    objBody.Length - intICounter)))
                       Exit While
                     End If
UrlEncoded.Append(System.Web.HttpUtility.UrlEncode(objBody.Substring(intICounter, _
                                                        intJCounter - intICounter)))
                     UrlEncoded.Append(objBody.Substring(intJCounter, 1))
                     intICounter = intJCounter + 1
                   End While

                   bytBytes = _
                     System.Text.Encoding.UTF8.GetBytes(UrlEncoded.ToString())
                   urlWebRequest.ContentLength = bytBytes.Length
                   strmRequestStream = urlWebRequest.GetRequestStream
                   strmRequestStream.Write(bytBytes, 0, bytBytes.Length)
                   strmRequestStream.Close()
                Else
                    urlWebRequest.ContentLength = 0
               End If
           End If
           rspResult = urlWebRequest.GetResponse()
           strmReceiveStream = rspResult.GetResponseStream()
           encode = System.Text.Encoding.GetEncoding("utf-8")
           sr = New System.IO.StreamReader(strmReceiveStream, encode)

           Dim read(256) As Char
           Dim count As Integer = sr.Read(read, 0, 256)
           Do While count > 0
               Dim str As String = New String(read, 0, count)
               strResponseText = strResponseText & str
               count = sr.Read(read, 0, 256)
           Loop
       Catch exp As Exception
           SetErrStatusText("Error while sending parameters")
           WritetoLog(exp.ToString)
       End Try
   End Sub
   'Setting header values...
   Public Overridable Sub setRequestHeader(ByVal bstrHeader _
                         As String, ByVal bstrValue As String)
       Select Case bstrHeader
            Case "Referer"
                urlWebRequest.Referer = bstrValue
            Case "User-Agent"
                urlWebRequest.UserAgent = bstrValue
            Case "Content-Type"
                urlWebRequest.ContentType = bstrValue
            Case Else
                urlWebRequest.Headers(bstrHeader) = bstrValue
       End Select
   End Sub

   Private Function UpdateProxy()
       Try
           If Not (IsNothing(uriAddress)) Then
               If ((Not IsNothing(_ProxyName)) And _
                 (_ProxyName.Length > 0) And (_ProxyPort > 0)) Then
                   proxyObject = New WebProxy(_ProxyName, _ProxyPort)
                   Dim strByPass() As String = Split(strByPassList, "|")
                   If strByPass.Length > 0 Then
                       proxyObject.BypassList = strByPass
                   End If
                   proxyObject.BypassProxyOnLocal = True
                   If blnNetworkCredentials Then
                       If strDomain <> "" Then
                           proxyObject.Credentials = New _
                             NetworkCredential(strUserName, _
                             strPwd, strDomain)
                       Else
                            proxyObject.Credentials = New _
                              NetworkCredential(strUserName, _
                              strPwd)
                       End If
                   End If
               End If
           End If
       Catch exp As Exception
           SetErrStatusText("Error while updating proxy configurations")
           WritetoLog(exp.ToString)
       End Try
   End Function
   'Property for setting the Responsetext
   Public Overridable ReadOnly Property ResponseText() As String
       Get
           ResponseText = strResponseText
       End Get
   End Property

   Private urlWebRequest As System.Net.HttpWebRequest
   Private urlWebResponse As System.Net.HttpWebResponse
   Private strResponseText As String
   Private strUrl As String
   Private strMethod As String
   Private proxyObject As WebProxy
   Private intCount As Integer
   Private uriAddress As Uri
   Private _ProxyName As String
   Private _ProxyPort As Integer
End Class
```
```


Question: Have a n-tire web application and search often times out after 30 secs.  How to detect the root cause of the problem?

Answer:
A simple solution:
Encode the image as a
jpeg
and look for a substantial change in
filesize
.
I've implemented something similar with video thumbnails, and had a lot of success and scalability.


Question:
I'm making a simple 2D game for the iPhone. It's based on CrashLanding. so it's basically a background texture and a few rectangular textures moving around.

I have this bizarre little graphics problem:  some of the small 2d items (can assume just rectangles) moving around get this little flashing black bar on top of them (the background texture is almost completely white so the little bar is noticable).

The textures I'm using are small (~1Kb) pngs.

Has anyone else run into this? Is this a common openGL issue?

BTW this happens on both the simulator and the actual device.

Answer:
Do you have a thing like that little black bar in your textures?
I've encountered similar problems when I have done something wrong. Here's a small check-list:
Have you have mipmapped your texture or not, and check what parameters does it have.
glTexParameters. (WRAP_S, WRAP_T, MAG_FILTER, MIN_FILTER...)
texture's dimensions. (If there's non-power-of-two -textures allowed, it may cause graphic glitches, depending about how you load your textures)
Are you are drawing that flashing bar on top of your rectangles?
Whether there's something that's causing the black bar, in your texture.
Alignment of the animation frames.
Blending and alpha-blending.
If something in the list is vague for you, it's good exercise to read about them.
I also do a good guess: I believe you aren't wrapping your textures in any direction, and that the animation frames are a bit misaligned, so that your application has a bit wrong texture coordinates/height in the quad you are drawing.
I hope my advices make sense. I have only experience with the usual opengl, not the OpenGL ES that's graphics pipelines have been pruned to make it more compact, cleaner and more elegant.


Question:
I want to put Apache 2.2.9 in front of a Weblogic 9.2 server on Windows XP. What does it take to do that ?

I probably need mod_proxy on the apache side ?

As far as Weblogic and apache are concerned, is there something similar to mod_jk ?

I would like this setup so that I can introduce some filtering later on. But for now, the goal is to allow other computers to access weblogic appserver so that Apache forwards all requests coming to it (at a certain URL) to Weblogic.

I have done this several times earlier BUT have forgotten how I did it.

Thanks for any pointers,

I guess http://e-docs.bea.com/wls/docs81/plugins/apache.html answers most of the basic fundas. Will update the forum if I have more inputs.

Answer:
We used the WebLogic plugin to load balance and front our applicatiosn, using virtual hosts and locations.
For example:
ServerName www.domain.com
WebLogicCluster 10.20.30.41:7002,10.20.30.42:7002
    SetHandler weblogic-handler
This config will balance requests to
http://www.domain.com/PathToApplication
to 10.20.30.41:7002 and 10.20.30.42:7002.


Question:
I've studied C programming in college some years ago and have developed some medium applications back then (nothing serious). Now I have to develop some more 'advanced' C applications (involving POSIX threads and RPC), but right now I'm a little rusty even with the basics.

Can anyone recommend me good online C reference manuals? This may help me get in tune faster.

Answer:
C standard library reference (both C89 and C99)
C89 library reference guide
GNU C tutorial
(more than just a tutorial, quite a useful reference)
I got these all from a previous similar question on SO.  I would like to credit the original posters, but unfortunately cannot seem to find that question.


Question: If I have no connection to internet, does that mean I can't start IDLE (which comes with python 3.0)?

Answer:
IDLE displays a warning message about firewall programs because it connects to the interpreter over the loopback interface, but that interface is always "connected" and doesn't require you to be on the Internet.
If IDLE isn't working for you with Python 3.0, you might consult
Python issue3628
.


Question:
I need to generate random numbers in the range 1 - 10000 continuously with out duplication.
Any recommendations?

Description: we are building a new version for our application, which maintains records in Sqlite DB. in the last version of our application, we did not had unique key for each record. But now with new upgraded version, we need to support the import facility from the last version's DB. So what we do is, we read each and every record from the old DB and generate a random number for the unique key and store it in new DB. Here we many need to import up to 10000 records continuously.

Answer:
Well, eventually you'll either have to stop generating them, or you're going to star duplicating them.
On a computer your options are pretty limited to Pseudo Random Number Generators (PRNGs), and given your constraint that they never repeat then a PRNG is your best option - real random data will occasionally duplicate a number.
In your case, I'd consider using a large PRNG (32 bit or larger) to shuffle your 10,000 numbers, and then send the numbers out in the shuffled order.
Once they're used up you can shuffle again - since the PRNG is so large you'll be able to go through the 10k numbers many times before duplicating a sequence.
Give us more information about what your doing and we may come up with a better answer.
-Adam


Question: I know it's a long shot, but is there some package or means to insert emoticons into a LaTeX document?

Answer:
Unicode's "miscellaneous symbols" include 3 simple emoticons:
```
0x2639
```
-
```
0x263B
```
. You can possibly use
```
0x2686
```
-
```
0x2689
```
as well.
For more variation you are going to need to use images and include them somehow.
I am curious as to the circumstances which lead to this question :)


Question:
I am trying to set my DOS environment variable in Ruby, and have it persist after the script exits. For example, if I want a ruby script set_abc_env.rb to set environment variable 'ABC' to 'blah', I expect to run the following:

C:> echo %ABC%
C:> set_abc_env.rb
C:> echo %ABC% blah

How do I do this?

Answer:
You can access environment variables via Ruby ENV object:
```
```
i = ENV['ABC']; # nil
ENV['ABC'] = '123';
i = ENV['ABC']; # '123'
```
```
Bad news is, as MSDN
says
, a process can never directly change the environment variables of another process that is not a child of that process. So when script exits, you lose all changes it did.
Good news is what Microsoft Windows stores environment variables in the registry and it's possible to
propagate
environment variables to the system. This is a way to modify user environment variables:
```
```
require 'win32/registry.rb'

Win32::Registry::HKEY_CURRENT_USER.open('Environment', Win32::Registry::KEY_WRITE) do |reg|
  reg['ABC'] = '123'
end
```
```
The documentation also says you should log off and log back on or broadcast a WM_SETTINGCHANGE message to make changes seen to applications. This is how broadcasting can be done in Ruby:
```
```
require 'Win32API'

SendMessageTimeout = Win32API.new('user32', 'SendMessageTimeout', 'LLLPLLP', 'L')
HWND_BROADCAST = 0xffff
WM_SETTINGCHANGE = 0x001A
SMTO_ABORTIFHUNG = 2
result = 0
SendMessageTimeout.call(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 'Environment', SMTO_ABORTIFHUNG, 5000, result)
```
```


Question:
I need to do a lot of searches of certain patterns in source files while the user is changing them, so I need to do regexp matching that is efficient in time and memory. The pattern repeats itself so should be compiled once, but I need to be able to retrieve subparts (rather than just confirm a match)

I'm considering using java.util.regexp or the Jakarta perl5util (if it still exists, been a few years since I used it), or perhaps the Eclipse search engine though I doubt that ti's smarter.

Is there any significant performance difference between the two?

Answer:
I am not sure there is a huge performance gap in term of the different regexp java engines.
But there sure is a performance issue when constructing a regexp (and that is, if the data is large enough, as
noted by Jeff Atwood
)
The only thing you should avoid is
catastrophic backtracking
, better avoided when using
atomic grouping
.
So, by default I would use the java.utils.regexp engine, unless you have specific perl-compliant sources of regexp you need to reuse in your program.
Then I would carefully construct the regexp I intend to use.
But in term of choosing one engine or another... as it
has been
said
in
many
other questions
...:
"make it work, make it fast - in that order"
beware of "premature optimization".


Question:
I have found no way of dumping the stack on all threads in .NET. Neither a signal to be send to the process nor programatic access to all the threads. I can only get access to the current thread via Thread.CurrentThread.

Any tricks ?

Answer:
There is a variety of handy classes in the System.Diagnostics that can help you with debugging and gathering various tracking information, i.e. StackTrace.
There is a wonky Process class that can be used to get the number of executing threads but very few details. Use the following Snippet:
```
```
Using  System.Diagnostics;

var threads = Process.GetCurrentProcess().Threads;
```
```
Okay after looking a little bit more it appears the easiest way to capture all the current stacks is through a mini dump and a tool like
SOS
or if you are running vista
this
.
Good luck.


Question:
I have a multi-table query, similar to this (simplified version)

SELECT columns, count(table2.rev_id) As rev_count, sum(table2.rev_rating) As sum_rev_rating
FROM table1
LEFT JOIN table2
ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0 AND rev_status = 1
GROUP BY dom_url
ORDER BY sum_rev_rating/rev_count DESC

The problem is in the ORDER BY clause. This causes a MySQL error to show, which is as follows:

Reference 'sum_ rev_ rating' not supported (reference to group function)

Answer:
my mysql is rusty; you might try
```
```
SELECT columns, count(table2.rev_id) As rev_count,
    sum(table2.rev_rating) As sum_rev_rating,
    sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio
FROM table1
    LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
WHERE dom_lastreview != 0
AND rev_status = 1
GROUP BY dom_url
ORDER BY rev_Ratio DESC
```
```
or
```
```
SELECT * from (
    SELECT columns, count(table2.rev_id) As rev_count,
        sum(table2.rev_rating) As sum_rev_rating
    FROM table1
        LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
    WHERE dom_lastreview != 0
    AND rev_status = 1
    GROUP BY dom_url
) X
ORDER BY X.sum_rev_rating/X.rev_count DESC
```
```
or
```
```
SELECT * from (
    SELECT columns, count(table2.rev_id) As rev_count,
        sum(table2.rev_rating) As sum_rev_rating,
        sum(table2.rev_rating)/count(table2.rev_id) as rev_ratio
    FROM table1
        LEFT JOIN table2ON table1.dom_id = table2.rev_domain_from
    WHERE dom_lastreview != 0
    AND rev_status = 1
    GROUP BY dom_url
) X
ORDER BY rev_Ratio DESC
```
```


Question:
I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.

I have looked for this myself but have been unable to find information on the syntax and how to use it. Does anyone know where the documentation for the syntax is?

EDIT: The attribute filters allow you to select based on patterns of an attribute value.

Answer:
James Padolsey created a
wonderful filter
that allows regex to be used for selection.
Say you have the following
```
div
```
:
```
```
<div class="asdf">
```
```
Padolsey's
```
:regex
```
filter can select it like so:
```
```
$("div:regex(class, .*sd.*)")
```
```
Also, check the
official documentation on selectors
.
UPDATE:
```
:
```
syntax Deprecation JQuery 3.0
Since
```
jQuery.expr[':']
```
used in Padolsey's implementation is already deprecated and will render a syntax error in the latest version of jQuery, here is his code adapted to jQuery 3+ syntax:
```
```
jQuery.expr.pseudos.regex = jQuery.expr.createPseudo(function (expression) {
    return function (elem) {
        var matchParams = expression.split(','),
            validLabels = /^(data|css):/,
            attr = {
                method: matchParams[0].match(validLabels) ?
                    matchParams[0].split(':')[0] : 'attr',
                property: matchParams.shift().replace(validLabels, '')
            },
            regexFlags = 'ig',
            regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g, ''), regexFlags);
        return regex.test(jQuery(elem)[attr.method](attr.property));
    }
});
```
```


Question:
I just got a dedicated server from a hosting company, and for some reason, it didn't have IIS installed.
It did have .Net 2.0, though.

So I installed IIS, but now my ASP.net websites won't work.
I just get a 404, no event log entries, nothing...

I noticed in the redistributable package information that:
"To access the features of ASP.NET, IIS with the latest security updates must be installed prior to installing the .NET Framework"

I also can't uninstall .Net, it just won't let me...

Is there a way to reinstall .Net 2.0, or somehow do whatever it is it does to IIS to make it work?

Thanks!
Daniel

Answer:
run from the command line
```
```
aspnet_regiis -i
```
```
You may have to navigate to the folder it was installed.
Mine and the default is
```
```
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727
```
```


Question: How can I find out the decorated name that will be asigned to each method name ? I'm trying to find out what the decorated name is , so that I may export it , in a DLL .

Answer:
This question is pretty similar:
Exporting DLL C++ Class , question about .def file
. The quick summary is that you probably want to use
```
__declspec(dllexport)
```
to let the compiler do the work of exporting your methods for you.
Microsoft changes the way they do function name mangling (or "decorated names" as they call them) with every compiler version, so you would probably run into future maintenance troubles if you try to manually export the mangled names. If you google for "msvc decorated names" there are some links that might help, but no guarantees.


Question:
This may not be strictly programming related but more OS-structure related.

Running Vista 32 bit on a brand new laptop with 3GB of memory, Running idle the system consumes about 40% of its memory. Other then the fact that this is outrageous on its own right, the OS should be able to fit all of the processes nicely into memory and not need to swap to disk EVER.

Yet looking at the task manager I see processes having page faults all the time. Not many but still. for instance explorer.exe has one every second approximately.

Why is that? Why does the OS feel the need to swap out pages although it has plenty of physical memory?

Answer:
A page fault doesn't necessarily mean that something was paged to disk. A modern OS has many levels of state that a page might be in, for example Windows will probably distinguish between a page of memory that is being actively used, and a page of memory that hasn't been touched in a while and could be paged to disk if needed. (This makes the pager's job easier, because it only has to look at the second kind of page to find out which ones it can page.) Now, how does a page get from the second state back to the first one? The kernel sets a bit on that page indicating that if anything accesses it, then the page will be marked as "active" and moved back to the first state. This results in a page fault.
Other things that might cause a page fault are things like memory mapped files. An application requests that a file be mapped to memory, that is it just
appears
in memory whenever the app wants to read from it. Obviously it would be tremendously expensive to load the whole file into memory all at once, so the kernel just marks the memory space with the "please page fault if this is ever accessed" bit, and reads from the disk if the app ever touches that page.
The real situation is a lot more complex than the above, but that should give you a general idea of what might be going on.


Question:
In Scala, is it possible to get the string representation of a type at runtime?  I am trying to do something along these lines:

def printTheNameOfThisType[T]() = {
  println(T.toString)
}

Answer:
Note: this answer is out of date!
Please see answer using TypeTag for Scala 2.10 and above
May I recommend #Scala on freenode
```
```
10:48 <seet_> http://stackoverflow.com/questions/190368/getting-the-string-representation-of-a-type-at-runtime-in-scala <-- isnt this posible?
10:48 <seet_> possible
10:48 <lambdabot> Title: Getting the string representation of a type at runtime in Scala - Stack Overflow,
                  http://tinyurl.com/53242l
10:49 <mapreduce> Types aren't objects.
10:49 <mapreduce> or values
10:49 <mapreduce> println(classOf[T]) should give you something, but probably not what you want.
```
```
Description of classOf


Question:
An interesting issue came up recently.  We came across some code that is using hashCode() as a salt source for MD5 encryption but this raises the question: will hashCode() return the same value for the same object on different VMs, different JDK versions and operating systems?  Even if its not guaranteed, has it changed at any point up til now?

EDIT: I really mean String.hashCode() rather than the more general Object.hashCode(), which of course can be overridden.

Answer:
No. From
http://tecfa.unige.ch/guides/java/langspec-1.0/javalang.doc1.html
:
The general contract of hashCode is as
  follows:
Whenever it is invoked on the same object more than once during an
  execution of a Java application,
  hashCode must consistently return the
  same integer. The integer may be
  positive, negative, or zero. This
  integer does not, however, have to
  remain consistent from one Java
  application to another, or from one
  execution of an application to another
  execution of the same application.
  [...]


Question:
I am trying to store more than 1 data item at a single index in my linked-list.  All of the examples in my textbook seem to illustrate adding only 1 piece of data per index.  I'm assuming it is possible to add more?

For example, using the Collections API to store an integer I would do the following:

LinkedList <Integer>linky = new LinkedList<Integer>();
int num1 = 2, num2 = 22, num3 = 25, num4 = 1337;
linky.add(num1);

How would I go about adding num2, num3, and num4 to the same first index in the list?  Thanks guys.

Answer:
Use a structure.
For example:
```
```
private struct Node
{
    int Num1;
    int Num2;
    int Num3;
}
```
```
...
```
```
LinkedList<Node> list = new LnkedList<Node>();

Node n = new Node();
n.Num1 = 10;
n.Num2 = 100;
n.Num3 = 1000;
list.Add(n);
```
```
Note; I assume this is in C#; correct me if I'm wrong and I will fix the code ;)
If you have not gone over OOP yet in your book - then I would recommend giving it a try; it will help you solve problems like this.


Question:
How do I manipulate images at the pixel level in C#?

I need to be able to read/modify each bitmap pixel RGB values separately.

A code sample would be appreciated.

Answer:
If you want speed, then
LockBits
.
See here for a good walkthrough by Bob Powell
. If you just want to edit a few, then
GetPixel
/
SetPixel
should do what you want.


Question:
How do you use the CSS content property to add HTML entities?

Using something like this just prints &nbsp; to the screen instead of the non-breaking space:

.breadcrumbs a:before {
  content: '&nbsp;';
}

Answer:
Use the hex code for a non-breaking space. Something like this:
```
```
.breadcrumbs a:before {
  content: '>\00a0';
}
```
```


Question: How can I get Emacs style key bindings in Visual Studio?   Is it available in Settings? Do I need a Plug-in?

Answer:
A quick Live search for "visual studio emacs" gave
this page
.  I'm not sure how thorough it is though (having never used emacs myself).


Question: Is there a PHP function to find out the name of the caller function in a given function?

Answer:
```
debug_backtrace()
```
supplies details of parameters, function/method calls in the current call stack.


Question:
My motivation for trying out git-svn is the effortless merging and branching. Then I noticed that man git-svn(1) says:

Running git-merge or git-pull is NOT recommended on a branch you plan
  to dcommit from. Subversion does not represent merges in any
  reasonable or useful fashion; so users using Subversion cannot see any
  merges you've made. Furthermore, if you merge or pull from a git
  branch that is a mirror of an SVN branch, dcommit may commit to the
  wrong branch.

Does this mean I cannot create a local branch from svn/trunk (or a branch), hack away, merge back into svn/trunk, then dcommit? I understand that svn users will see the same mess that merges in svn pre 1.5.x have always been, but are there any other drawbacks? That last sentence worries me, too. Do people routinely do these kinds of things?

Answer:
Creating local branches is definitely possible with git-svn. As long as you're just using local branches for yourself, and not trying to use git to merge between upstream svn branches, you should be fine.
I have a "master" branch that I use to track the svn server. This is the only branch that I dcommit from. If I'm doing some work, I create a topic branch and work away on it. When I want to commit it, I do the following:
Commit everything to the topic branch
git svn rebase
(resolve any conflicts between your work and svn)
git checkout master
git svn rebase
(this makes the next step a fast-forward merge, see Aaron's comments below)
git merge topic_branch
resolve any merge conflicts
(there shouldn't be any at this point)
git svn dcommit
I also have another situation where I need to maintain some local changes (for debugging) that should never be pushed up to svn. For that, I have the above master branch but also a branch called "work" where I normally do work. Topic branches are branched off work. When I want to commit work there, I checkout master and use cherry-pick to pick the commits from the work branch that I want to commit to svn. This is because I want to avoid committing the three local change commits. Then, I dcommit from the master branch and rebase everything.
It is worthwhile running
```
git svn dcommit -n
```
first to make sure that you are about to commit exactly what you intend to commit. Unlike git, rewriting history in svn is hard!
I feel that there must be a better way to merge the change on a topic branch while skipping those local change commits than using cherry-pick, so if anybody has any ideas they would be welcome.


Question:
Up until recently, I've been storing multiple values into different hashes with the same keys as follows:

%boss = (
    "Allan"  => "George",
    "Bob"    => "George",
    "George" => "lisa" );

%status = (
    "Allan"  => "Contractor",
    "Bob"    => "Part-time",
    "George" => "Full-time" );

and then I can reference $boss("Bob") and $status("Bob") but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.

Is there a better way for storing multiple values in a hash?  I could store the values as

        "Bob" => "George:Part-time"

and then disassemble the strings with split, but there must be a more elegant way.

Answer:
This is the standard way, as per
perldoc perldsc
.
```
```
~> more test.pl
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
           "Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );

print $chums{"Allan"}{"Boss"}."\n";
print $chums{"Bob"}{"Boss"}."\n";
print $chums{"Bob"}{"Status"}."\n";
$chums{"Bob"}{"Wife"} = "Pam";
print $chums{"Bob"}{"Wife"}."\n";

~> perl test.pl
George
Peter
Part-time
Pam
```
```


Question:
I am trying to figure out how to add a custom control to the iPhone MoviePlayer.
For an example of what I am trying to do see the following image.

I am trying to add something like the controls on the right and left of the basic movie controls.

I had done this in the Open SDK by adding a subclass to the playerview, but now in the official SDK and Apple moving to MPMoviePlayerController I am not sure how to do it.

Also with my old 1.x firmware way it required me to capture touch events and hide/show the control myself. I am hoping there is a way that would do this with the standard controls, but if not, that is fine.

Thanks in advance.

Answer:
This sample application
that Apple provides should help. From the description:
Demonstrates how to use the Media
  Player Framework to play a movie
  full-screen. The sample contains code
  to configure the movie background
  color, playback controls and scaling
  mode via the built-in Settings
  application. Also shows how to draw
  custom overlay controls on top of the
  movie during playback.


Question:
I've been working on a project in Delphi 7 where I wanted to have forms inherit components from other forms. I was able to get this working, but came across the following issues (and I'm going to post the solutions to hopefully help others in the future):

In the .pas file of a form, I would change the form to inherit from some other form, but it wouldn't get the components from the ancestor form.

For certain descendant forms, I would get the following error message when opening the form at design time: "Error creating form: Ancestor for 'TAncestorForm' not found." I would have to first manually open the ancestor form, and then I could open the descendant form.

Answer:
First, for those who don't know how to inherit a form visually, you create the ancestor form as usual. Then go to File > New > Other. Select the tab with the name of the current project, and choose the form you want to inherit from. If you want to inherit from a form that's not part of the current project, open that form, right click it, and choose Add to Repository. Then you will be able to go to File > New > Other and select that form from the appropriate tab.
Given that, I came across issues because some of the descendant forms were already created, so I couldn't follow the process above. Also, I made some changes to forms from the standard code Delphi creates. I was able to resolve all issues with visual form inheritance using the following guidelines:
The .pas file of the descendant form must have the form's class inherit from the correct ancestor class, e.g.:
```
type TMyForm = class(TAncestorForm)
```
The first line in the .dfm of the descendant form must have the word
```
inherited
```
instead of
```
object
```
, e.g.:
```
inherited MyForm: TMyForm
```
EDIT: After double checking, the following is NOT required:
The .pas file of the ancestor form must have the standard global variable that Delphi creates, e.g.:
```
var AncestorForm: TAncestorForm;
```
The
```
uses
```
section of the .dpr file of the project must have that same global variable as a comment after the unit's file name, e.g.:
```
unAncestor in 'unAncestor.pas' {AncestorForm}
```
Notes/Tips:
Both the ancestor form and the descendant form are allowed to be non-auto created if you want (Set in Project > Options > Forms > Auto-create forms).
To revert a property on a descendant form to the ancestor form's value, right click on the property in the Object Inspector, and choose Revert to inherited.
To revert all property values of a component to the ancestor's values, right click the component and choose Revert to inherited.


Question:
I'm not sure how familiar people are with the hobbit monitoring system - http://hobbitmon.sourceforge.net/ - but I've got a tricky question.

I've got a custom test, which returns two NCV values. One value normally returns ~300 milliseconds, the other one returns 500 000 euro. Obviously, these two values don't graph very well together. :)

Question is, can hobbit display two graphs for this one test? If so, how do I do it?

Thanks.

Answer:
When accessed individually, I suspect that having a query that returns IQueryable would work - however, I expect that when this is part of a larger Expression, the expression interpreter will complain (which seems like what you are describing).
However, I suspect that you might be able to break it down a bit. Try adding (to customer):
```
```
public static Expression<Func<Customer, bool>> HasActiveContract
    {
        get { return cust => cust.Contracts.Count() == 1; }
    }
```
```
Then you should be able to use:
```
```
var filtered = db.Customers.Where(Customer.HasActiveContract);
```
```
Obviously it is hard to run it (from here) to see what TSQL it comes up with, but I'd be surprised if that does roundtrips; I would expect that to do the COUNT() in the TSQL. As a topmost query, you should also be able to wrap this:
```
```
public IQueryable<Customer> CustomersWithActiveContract
    {
        get { return Customers.Where(Customer.HasActiveContract); }
    }
```
```
Does any of that work?


Question:
When using threads I sometimes visualise them as weaving together 3 or more dimensional interconnections between Objects in a Spatial context.  This isn't a general use case scenario, but for what I do it is a useful way to think about it.

Are there any APIs which you use which aid threading?

Have you used threads in a manner which doesn't conceptualise as thread being a process?

Answer:
Are there any APIs which you use which aid threading?
You mean appart from
```
java.util.concurrent
```
?
FunctionalJava
got some constructs which aid in concurrent programming, as described in a multipart tutorial that starts
here
.
Have you used threads in a manner which doesn't conceptualise as thread being a process?
Yes, to the extent that threads doesn't conceptualise at all. Take an asynchronous task-runner for instance. It uses threads under the covers but I don't see them and I don't care about them. They are fully managed by the task-runner.
Under the covers, it is all just threads, but when we stop caring about the individual thread and just think about them as a number of slots where you can somehow put code in and have it run for a period of time, then that is when we start to reach for a higher level of abstraction.
Agents/Actors is a common way to do this. An Actor is like a thread that has a lump of state, and then you can send it some code and say "do this to your state when you have time" or something along those lines.


Question:
Ruby has a wealth of conditional constructs, including if/unless, while/until etc.

The while block from C:

while (condition) {
    ...
}

can be directly translated to Ruby:

while condition
    ...
end

However, I can't seem to find a built-in equivalent in Ruby for a C-like do ... while block in which the block contents are executed at least once:

do {
    ...
} while (condition);

Any suggestions?

Answer:
...The best I could come up with is the
```
loop
```
construct with a
```
break
```
at the end:
```
```
loop do
    ...
    break unless condition
end
```
```


Question:
I'm creating some text boxes on my form programmatically which I need to reference later using FindControl.

I've put the FindControl instruction in the page load method after the code which creates them but get an error:

Object reference not set to an instance of an object.

I assume this is because the textbox controls are not created until later in the lifecycle and therefore cannot be referenced from within Page_Load.

Can someone advise where in my code-behind I would need to place the FindControl instruction so that it can find these programmatically created text boxes?

Answer:
If you create textboxes programmatically you can use directly that to manipulate them. No need for FindControl (which would also be slower)
```
```
TextBox txt = new TextBox();
...
txt.Text = "Text";
```
```
If you need access in different methods you can just make txt a private variable of the class.
If you really need to use FindControl - are the textboxes added in the page (added to the Controls list of the page) when you call the function?


Question:
I have a Rails app that I need to deploy. Here are the facts:

The app was developed on Windows and requires Windows binary gems

The app is to be deployed onto an Open Solaris shared server (Joyent)

I do not have permissions to install gems on the server

For the non-binary gems, I can simply do a rake gems:unpack locally and then upload; this works just fine.

So my question is, how do I get the binary gems I need onto my production server?

Answer:
The binary gems are the real problem. For all other gems you can use the
```
vendor/gems
```
directory (only possible with Rails 2.1+).


Question:
Delphi 2009 has changed its string type to use 2 bytes to represent a character, which allows support for unicode char sets.  Now when you get sizeof(string) you get length(String) * sizeof(char) .  Sizeof(char) currently being 2.

What I am interested in is whether anyone knows of a way which on a character by character basis it is possible to find out if it would fit in a single byte, eg find out if a char is ascii or Unicode.

What I'm primarily interested in knowing, is before my string goes to a database (oracle, Documentum) how many bytes the string will use up.

We need to be able to enforce limits before hand and ideally (as we have a large installed base) without having to change the database. If a string field allows 12 bytes, in delphi 2009 a string of length 7 would always show as using 14 bytes even though once it got to the db it would only use 7 if ascii or 14 if double byte, or somewhere in between if a mixture.

Answer:
You could check the value of the character:
```
```
if ord(c) < 128 then
    // is an ascii character
```
```


Question: I wonder if there is any good guideline for system administrators to calculate the resources needed to host an ASP.NET website? I want to do some estimates on the processing power needed so I know what kind of VPS/Cloud I need to get.

Answer:
Load testing will be your best solution.
Applications differ in how they scale depending on a large number of variables including types of problem solving, approach to solution and other factors.
100 concurrent users consuming 10% CPU does not mean 500 concurrent at 50%, it could be 20% or it could be 100%.
Your bottleneck could be processor or memory or network bandwidth.
Without actually placing the load on your application, any estimation will be merely a guess and will quite likely be proven incorrect.


Question:
I am writing a drop-in replacement for a legacy application in Java.  One of the requirements is that the ini files that the older application used have to be read as-is into the new Java Application.  The format of this ini files is the common windows style, with header sections and key=value pairs, using # as the character for commenting.

I tried using the Properties class from Java, but of course that won't work if there is name clashes between different headers.

So the question is, what would be the easiest way to read in this INI file and access the keys?

Answer:
The library I've used is
ini4j
.  It is lightweight and parses the ini files with ease.  Also it uses no esoteric dependencies to 10,000 other jar files, as one of the design goals was to use only the standard Java API
This is an example on how the library is used:
```
```
Ini ini = new Ini(new File(filename));
java.util.prefs.Preferences prefs = new IniPreferences(ini);
System.out.println("grumpy/homePage: " + prefs.node("grumpy").get("homePage", null));
```
```


Question:
We are trying to build a High-Volume Orders Record System.
There are three primary tables:
1. Orders
2. OrderDetails
3. OrderShipment

The Shipment table contains n record per order and any record shipment entry can be changed before the Customer accepts th order, after which it is frozen. (A business requirement)

Although this may not happen in real world scenarios...
during our load tests, we are getting System.Data.Linq.ChangeConflictException exceptions.
Wrapping up the submit inside a transacion is not helping either.
Can't we force LINQ to get a lock on the row for the entire duration of the update operation?

Is there any other way to get over this?

Answer:
If you are having genuine issues with concurrent updates on the same data, then you might consider performing the entire operation in a transaction - i.e. getting the data
and
committing it. As long as you treat the get/update/commit as a short-lived, atomic operation (i.e. you don't pause for user-input in the middle) it should be OK.
In particular, with a serializable isolation level, nobody can update data that you have a read lock on (i.e. anything you have queried). The only problem is that this might lead to deadlock scenarios if different queries are reading data in different orders. AFAIK, there is no way to get LINQ-to-SQL to issue the (UPDLOCK) hint, which is a shame.
Either a TransactionScope or a SqlTransaction would do, as long as they are set as serializable isolation (which is the default for TransactionScope).


Question:
How can I read the colors of an image with python using google app engine?

Example: I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.

Answer:
The
Images API
does not (currently) contain pixel-level functions. To quote the overview document:
Note: In order to use the Images API in your local environment you must first download and install PIL, the Python Imaging Library. PIL is not available on App Engine; it is only used as a stub for the Images API in your local environment. Only the transforms provided in the images API are available on App Engine.
The community has been asking for full
PIL
support for some time, but it looks like we'll have to wait.


Question:
I'm working with dRuby and basicly I'm calling a remote method that returns me an object.

In the clientside I have this code:

handle_error(response) if response.is_a?(Error)

where response is the DRbObject. (I've developed this code before using dRuby and I'm returning an Error object if something went wrong). The problem is that now

response.is_a?(Error)

comes back with "false" because the object is actually a DRbObject.
Any idea on how I can check the class of my application object?

Thanks!
Roberto

Answer:
Although I'm not sure how DRb manages the remote objects, I'd expect it to modify #kind_of?   to keep the class hierarchy on the remote object, so you could do:
```
```
response.kind_of?(Error)
```
```
If this doesn't work you can always ask it if it responds to an specific method and go from there
```
```
response.respond_to?(some_method_on_your_errors)
```
```


Question: How do you build and use dynamic sql in a MySQL stored procedure?

Answer:
I don't believe MySQL supports dynamic sql.  You can do "prepared" statements which is similar, but different.
Here is an example:
```
```
mysql> PREPARE stmt FROM
    -> 'select count(*)
    -> from information_schema.schemata
    -> where schema_name = ? or schema_name = ?'
;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> EXECUTE stmt
    -> USING @schema1,@schema2
+----------+
| count(*) |
+----------+
|        2 |
+----------+
1 row in set (0.00 sec)
mysql> DEALLOCATE PREPARE stmt;
```
```
The prepared statements are often used to see an execution plan for a given query.  Since they are executed with the
execute
command and the
sql
can be assigned to a variable you can approximate the some of the same behavior as dynamic sql.
Here is a good
link
about this:
Don't forget to deallocate the
```
stmt
```
using the last line!
Good Luck!


Question:
I've so far dabbled in Flash doing 1-man shows for quite some time, but have never done any big projects with it, where actually source management and code-reuse was truly necessary. However I'm considering Flash for a new project, but this time around it's won't be a 1-man show, that's when it struck me that I had no experience of how one is supposed to do that with flash.

What are some good tips or resources that could help us figure out a good workflow?

Answer:
Good communication
Don't work in .fla's. 100% of the code in .as files
UML (at least discussed)
Different tasks for everybody
Comments in commits to code repository
"Manage your code so that anybody can at any time take over your job"
Consider
the bus factor
With junior developers it's also good to go through basic stuff such as package structures etc, just so that everybody is on the same page.
I think it's also good if somebody is kind of like a technical manager of the project, overseeing what the developers are doing. It may also be one of the developers but i think it's important to have one person who knows what everybody else is doing.


Question:
I want to create an NSOpenPanel that can select any kind of file, so I do this

NSOpenPanel*    panel = [NSOpenPanel openPanel];

if([panel runModalForTypes:nil] == NSOKButton) {
    // process files here
}

which lets me select all files except symbolic links.

They're simply not selectable and the obvious setResolvesAliases

does nothing.

What gives?

Update 1: I did some more testing and found that this strangeness

is present in Leopard (10.5.5) but not in Tiger (10.4.8).

Update 2: The code above can select mac aliases (persistent path

 data that lives in the resource fork) but not symlinks (files created with ln -s).

Answer:
I cannot reproduce this. I just tried it and it works just fine. If symlink points to a directory, it shows the directory content when I select the symlink and if the symlink points to a file, I can select it as well.
Of course if the symlink points to a directory, you can only select it if choosing directories is allowed
```
```
NSOpenPanel * panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:YES];
if ([panel runModalForTypes:nil] == NSOKButton) {
    NSLog(@"%@", [panel filenames]);
}
```
```


Question:
For a new project with Flash I was looking for something along the lines of standard libraries for basic programming needs, along the lines of Python or Ruby standard libraries. But the only thing I found was a dead project on Sourceforge.

Thus is there no standard library for flash? Does everyone reinvent the wheel each time?

Answer:
The basic libraries are
built into flash
. Then on top of that there is
flex
, which gives you an entire RIA framework. Then there are 3rd party frameworks for
3d
,
physics engines
, various design patterns (
MVC
,
IoC
etc) to name just a few.
So no, you do not not to reinvent the wheel every time.


Question:
I am responsible for the User Interface of an application written completely in Visual C++  using MFC and some third-part controls. I would like to use C# (WinForms or even better WPF) to improve the application look&feel.

I would like some advices about how to do it. Links, articles, examples...

Right now the user interface is isolated in a single project and I don't want to compile the whole module with CLR. So how do I have to manage that from the architectural point of view?

I have already looked at the Internet for the subject and read MSDN information. I would like more detailed information...is it convinient? pros/cons? have you used this approach successfully in a "big" application?
I don't want to compile the whole ui project with CLR...can I just have all the .NET code in a isolated project and call it from the ui project? what's the best way to do it?

Thanks in advance.

Answer:
The basic libraries are
built into flash
. Then on top of that there is
flex
, which gives you an entire RIA framework. Then there are 3rd party frameworks for
3d
,
physics engines
, various design patterns (
MVC
,
IoC
etc) to name just a few.
So no, you do not not to reinvent the wheel every time.


Question:
I'm hoping to find out what tools folks use to synchronize data between databases. I'm looking for a JDBC solution that can be used as a command-line tool.

There used to be a tool called Sync4J that used the SyncML framework but this seems to have fallen by the wayside.

Answer:
I have heard that the Data Replication Service provided by Db4O is really good. It allows you to use Hibernate to back onto a RDBMS - I don't think it supports JDBC tho (
http://www.db4o.com/about/productinformation/drs/Default.aspx?AspxAutoDetectCookieSupport=1
)
There is an open source project called Daffodil, but I haven't investigated it at all. (
https://daffodilreplicator.dev.java.net/
)
The one I am currently considering using is called SymmetricDS (
http://symmetricds.sourceforge.net/
)
There are others, they each do it slightly differently. Some use triggers, some poll, some use intercepting JDBC drivers. You need to decide what technical limitations you are under to determine which one you really want to use.
Wikipedia provides a nice overview of different techniques (
http://en.wikipedia.org/wiki/Multi-master_replication
) and also provides a link to another alternative DBReplicator (
http://dbreplicator.org/
).


Question:
See code:

var file1 = "50.xsl";
var file2 = "30.doc";
getFileExtension(file1); //returns xsl
getFileExtension(file2); //returns doc

function getFileExtension(filename) {
    /*TODO*/
}

Answer:
```
```
return filename.replace(/\.([a-zA-Z0-9]+)$/, "$1");
```
```
edit: Strangely (or maybe it's not) the
```
$1
```
in the second argument of the replace method doesn't seem to work... Sorry.


Question:
I have a few combo-boxes and  double spin boxes on my Qt Dialog. Now I need a "ResetToDefault" item on a menu that comes up when you right click on the widget (spin box or combo box).

How do i get it. Is there some way I can have a custom menu that comes up on right click or Is there a way i can add items to the menu that comes on right click.

Answer:
First, for Qt4, the simplest way is to create an action to reset the data, and add it the the widget using the
```
addAction
```
method (or use the designer). Then, set the
```
contextMenuPolicy
```
attribute to
```
Qt::ActionsContextMenu
```
. The context menu will appear and the action will be triggered.
Code example:
```
```
QAction *reset_act = new QAction("Reset to default");
mywidget->addAction(reset_act);
mywidget->setContextMenuPolicy(Qt::ActionsContextMenu);
// here connect the 'triggered' signal to some slot
```
```
For Qt3, you might have to intercept the context menu event, and thus inherit the QSpinBox and others. Or maybe you can intercept the context menu event from the main window, detect if it occurred above the widget supposed to have a context menu (using the
```
QWidget::childAt
```
method) and show it there. But you'll have to test.


Question: When you tap a row in a UITableView, the row is highlighted and selected. Is it possible to disable this so tapping a row does nothing?

Answer:
All you have to do is set the selection style on the
```
UITableViewCell
```
instance using either:
Objective-C:
```
```
cell.selectionStyle = UITableViewCellSelectionStyleNone;
```
```
or
```
```
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
```
```
Swift 2:
```
```
cell.selectionStyle = UITableViewCellSelectionStyle.None
```
```
Swift 3 and 4.x:
```
```
cell.selectionStyle = .none
```
```
Further, make sure you either don't implement
```
-tableView:didSelectRowAtIndexPath:
```
in your table view delegate or explicitly exclude the cells you want to have no action if you do implement it.
More info here
and
here


Question:
I have a DataGridView which shows the content of a DataTable.

I want to set the backcolor of a row based on the value of a cell in this row.

Note that the cell in question is in a column which is not displayed in the DataGridView (Visible=False).

Answer:
If you handle the RowDataBound event you can check the value of the data and modify the attributes of the cell or apply a different style in that event handler.
```
```
protected void Page_Load(object sender, EventArgs e)
{
    GridView g1 = new GridView();
    g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}

void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        // Check the Value
        if(e.Row.Cells[1].Text = someValue)
        {
            e.Row.Cells[1].CssClass = "colorCellRed";
        }

    }
}
```
```
That should give you what you are looking for.  Let me know if you need it in VB rather than C#.
Good Luck!


Question:
When I type 'from' (in a LINQ query) after importing System.Linq namespace, it is understood as a keyword. How does this magic happen?

Is 'from' a extension method on some type?

Answer:
"from" is a language keyword (just like "if" or "foreach").
You don't even need to import System.Linq to use "from", but you need to use 3.5 framework.


Question:
I'm trying to dynamically hide certain DIV's when a print (or print preview) occurs from the browser.

I can easily differentiate statically by having two style sheets, one for normal and one for print media:

But I need to go one step further and hide some elements dynamically when the print style sheet becomes active during a print based upon certain criteria

One way to easily solve it would be to handle a DOM event for handling print / printview, then I could just use jQuery to change the display:none on the classes that need to be hidden, but I can't find a DOM print event!!

Anyone know what the solution is?

Answer:
There's an
onbeforeprint
event in IE. It doesn't appear to be supported by other major browsers. (I tested Firefox 3.0.3 and Safari 3.1.2.)


Question:
dir(re.compile(pattern))

does not return pattern as one of the lists's elements. Namely it returns:

['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']

According to the manual, it is supposed to contain

the object's attributes' names, the
  names of its class's attributes, and
  recursively of the attributes of its
  class's base classes.

It says also that

The list is not necessarily complete.

Is there a way to get the complete list? I always assumed that dir returns a complete list but apparently it does not...

Also: is there a way to list only attributes? Or only methods?

Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)

Answer:
For the
complete
list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the
```
getattr
```
built-in function. As the user can reimplement
```
__getattr__
```
, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The
```
dir
```
function returns the keys in the
```
__dict__
```
attribute, i.e. all the attributes accessible if the
```
__getattr__
```
method is not reimplemented.
For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the
```
inspect
```
module determine the class methods, methods or functions.


Question:
How do I set the initial width of a QDockWidget?

I have implemented the sizeHint function but what next?

Answer:
If you want it to have the same width as the same last time the program was running, you should look into settings. The Qt 4.4 documentation has an example on how to use settings
here
.
This is how I have done it:
```
```
void Applicotion::readSettings() {
  QSettings settings("Company Name", "Application Name");
  settings.beginGroup("LibraryDock");
  libraryDock->setFloating(settings.value("docked").toBool());
  libraryDock->resize(settings.value("size", QSize(1, 1)).toSize());
  libraryDock->move(settings.value("pos", QPoint(200, 200)).toPoint());
  addDockWidget((Qt::DockWidgetArea)settings.value("dockarea", Qt::RightDockWidgetArea).toInt(), libraryDock);
  settings.endGroup();
}

void Applicotion::writeSettings() {
  QSettings settings("Company Name", "Application Name");
  settings.beginGroup("LibraryDock");
  settings.setValue("dockarea", dockWidgetArea(libraryDock));
  settings.setValue("docked", libraryDock->isFloating());
  settings.setValue("size", libraryDock->size());
  settings.setValue("pos", libraryDock->pos());
  settings.endGroup();
```
```
}


Question:
In deploying to a new (Solaris 9) environment recently, one of the steps was to copy a set of files and directories to their new location and then to apply the group UID bit (using "chmod -R g+s") to all files in the directory tree giving a mode of -rwxr-s--- to everything. The result was that none of our shell scripts would execute unless they were individually opened and re-saved. I should add that we had earlier set g+s on the target parent folder prior to copying files; this had set the initial mode on all the new directories to drwxr-s--- but the files had a mode of -rwxr-x---

Having eventually discovered which step caused the problem, we were able to cut out that step and proceed.

I would like, however, to understand what the "s" bit means when applied to directories and files, in the hope that this will explain why we had the problem in the first place.

Answer:
For executable files, this means that when the file is executed, it is executed as the group that owns the file, not the group of the user executing the file.
This is useful if you want users to be able to assume the permissions of a particular group just for running one command.
However, it is also a security risk as it is allowing users to elevate their permissions. You have to know that the scripts with this bit set aren't going to do anything that would let users abuse these extra permissions.


Question:
Could someone please explain to me how the current python webframworks fit together?

The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).

Answer:
There are more to it ofcourse.
Here's a comprehensive list and details!
Web Frameworks for Python
Extract from above link:
Popular Full-Stack Frameworks
A web application may use a
  combination of a base HTTP application
  server, a storage mechanism such as a
  database, a template engine, a request
  dispatcher, an authentication module
  and an AJAX toolkit. These can be
  individual components or be provided
  together in a high-level framework.
These are the most popular high-level
  frameworks. Many of them include
  components listed on the WebComponents
  page.
Django
(1.0 Released 2008-09-03) a
  high-level Python Web framework that
  encourages rapid development and
  clean, pragmatic design
Pylons
(0.9.6.2 Released 2008-05-28) a
  lightweight Web framework emphasizing
  flexibility and rapid development. It
  combines the very best ideas from the
  worlds of Ruby, Python and Perl,
  providing a structured but extremely
  flexible Python Web framework. It's
  also one of the first projects to
  leverage the emerging WSGI standard,
  which allows extensive re-use and
  flexibility but only if you need it.
  Out of the box, Pylons aims to make
  Web development fast, flexible and
  easy. Pylons is built on top of Paste
  (see below).
TurboGears
(1.0.4.4 Released
  2008-03-07) the rapid Web development
  megaframework you've been looking for.
  Combines
CherryPy
, Kid, SQLObject and
MochiKit
. After reviewing the website
  check out:
QuickStart Manual
web2py
(currently version 1.43)
  Everything in one package with no
  dependencies. Development, deployment,
  debugging, testing, database
  administration and maintenance of
  applications can be done via the
  provided web interface. web2py has no
  configuration files, requires no
  installation, can run off a USB drive.
  web2py uses Python for the Model, the
  Views and the Controllers, has a
  built-in ticketing system to manage
  errors, an internationalization
  engine, works with MySQL, PostgreSQL,
  SQLite , Oracle, MSSQL and the Google
  App Engine via an ORM abstraction
  layer. web2py includes libraries to
  handle HTML/XML, RSS, ATOM, CSV, RTF,
  JSON, AJAX, XMLRPC, WIKI markup.
  Production ready, capable of
  upload/download of very large files,
  and always backward compatible.
Grok
(0.13 Released 2008-06-23) is
  built on the existing Zope 3
  libraries, but aims to provide an
  easier learning curve and a more agile
  development experience. It does this
  by placing an emphasis on convention
  over configuration and DRY (Don't
  Repeat Yourself).
Zope
(2.10.4 Released 2007-07-04,
  3.3.1 Released 2007-01-14, Zope 3.4.0c1 Released 2008-01-31) Being the grandaddy of Python web frameworks,
  Zope has grown into a family of
  frameworks over the years. Zope 1 was
  released in 1999. Zope 2 is both a web
  framework and a general purpose
  application server, today it is
  primarily used by
  ContentManagementSystems. Zope 3 is
  both a standalone framework and a
  collection of related libraries, which
  are also included with newer releases
  of Zope 2. All of the Zope frameworks
  include the ZODB, an object database
  for Python.


Question: I'm getting ready to start a new project and I've been researching the entity framework. My question is what is the best strategy for validating the entities? Other projects I've worked on have used attributes for most of the validation, but obviously this is not possible in the entity framework. Is the only way to do this by handling the partial methods in the property setters? All advice is much appreciated.

Answer:
I have not actually used the Entity framework before but a quick search indicates that you have several options.
1) Validate at another layer in your application
Always an option, I just thought I would throw it out there explicitly.
2) Hook into the OnChanged events of the Entity then perform validation
Likely brittle and would become confusing/slow after if you have many different properties things that can change for each entity.
3) Implement partial methods to validate property changes
According to
this
post and
this
walkthrough there are partial methods available for validation. This seems like your best option as it is not very intrusive and you can selectively implement the validation you want.
I hope that helps. Good luck.


Question: I am currently using NUnit and testing a class library. Up until now, I have used a list of constants at the top of the test class to hold some static test variables. Is this the best way to do this, or is there a more fluent way to handle it?

Answer:
By "static test variables" do you actually mean constants (whether genuine constant, immutable instances or just ones you don't change)? I use those frequently, and just put them at the top of the test class.
If there are several related test classes, it can be handy to separate out common values into a different class though. (It
could
act as your base class, but I'm not terribly fond of using inheritance just to get access to things more easily. Java static imports are handy there...)


Question:
I have a table in SQL server that has the normal tree structure of Item_ID, Item_ParentID.
Suppose I want to iterate and get all CHILDREN of a particular Item_ID (at any level).

Recursion seems an intuitive candidate for this problem and I can write an SQL Server function to do this.

Will this affect performance if my table has many many records?
How do I avoid recursion and simply query the table? Please any suggestions?

Answer:
Perhaps some more detail is in order.
If you have a master-detail relationship as you describe, then won't a simple JOIN get what you need?
As in:
```
```
SELECT
  SOME_FIELDS
FROM
  MASTER_TABLE MT
 ,CHILD_TABLE CT
WHERE CT.PARENT_ID = MT.ITEM_ID
```
```


Question:
By default, copying from the command prompt will prompt you to overwrite files that already exist in the target location.

You can add "/Y" to say "Yes to all" replacements.

But how can you say "No to all" ?

In other words, I want to copy everything from one directory that does not already exist in the target.

The closest thing I see is the XCOPY argument to only copy things after a specific mod-datetime.

Answer:
I expect
xxcopy
has an
option
for that.
Bingo:
http://www.xxcopy.com/xxcopy27.htm#tag_231
```
```
2.3   By comparison with the file in destination

    The switches in this group select files based on the
    comparison between the files in the source and those in
    the destination.  They are often used for periodic backup
    and directory synchronization purposes. These switches
    were originally created as variations of directory backup.
    They are also convenient for selecting files for deletion.

2.3.1  by Presence/Absence

    The /BB and /U switches are the two switches which select
    files by the pure presence or absence as the criteria.
    Other switches in the this group (Group 2.3) are also
    affected by the file in the destination, but for a
    particular characteristics for comparison's sake.

    /BB  Selects files that are present in source but not in destination.
    /U   Selects files that are present in both source and destination.
```
```
-Adam


Question:
I'm experimenting with Latent Dirichlet Allocation for topic disambiguation and assignment, and I'm looking for advice.

Which program is the "best", where best is some combination of easiest to use, best prior estimation, fast

How do I incorporate my intuitions about topicality.  Let's say I think I know that some items in the corpus are really in the same category, like all articles by the same author.  Can I add that into the analysis?

Any unexpected pitfalls or tips I should know before embarking?

I'd prefer is there are R or Python front ends for whatever program, but I expect (and accept) that I'll be dealing with C.

Answer:
In addition to the
usual
sources
, it seems like the most active area talking about this is on the
topics-models listserv
.  From my initial survey, the easiest package to understand is the
LDA Matlab package
.
This is not lightweight stuff at all, so I'm not surprised it's hard to find good resources on it.


Question:
I have the following code fragment that starts a Google Earth process using a hardcoded path:

var process =
    new Process
        {
            StartInfo =
                {
                    //TODO: Get location of google earth executable from registry
                    FileName = @"C:\Program Files\Google\Google Earth\googleearth.exe",
                    Arguments = "\"" + kmlPath + "\""
                }
        };
process.Start();

I want to programmatically fetch the installation location of googleearth.exe from somewhere (most likely the registry).

Answer:
From the example given you can gauge that I'm actually trying to pass a KML file to Google Earth. Because of this, the simplest way of resolving this problem is relying on the file association of KML with Google Earth and using the following as a replacement for the entire example:
```
```
Process.Start(kmlPath);
```
```
This was found by reviewing the answers to
this
question.


Question:
We've recently completed phase 1 of a ASP.Net website in English and French. We went with using resource files to store language specific strings, but because the site used ASP.Net AJAX and javascript heavily we rigged up a solution to pass the right files through the ASP.Net pipeline where we could catch "tokens" and replace them with the appropriate text pulled from the resource files.

This is the second project I've been involved in that had these kinds of challenges, the first one stored the text strings in a database, and instead of ASP.Net AJAX, it used the AJAX tools that come with the Prototype library and put all Javascript into aspx files so that the tokens could be replaced on the way out.

What I'm wondering is, has anyone else encountered a similar scenario? What approach did you take? What lessons were learned? How did you deal with things like internationalized date formats?

Answer:
In my main project (a RAD framework using PHP with gettext for translations) we're doing already alot of prepare operations on javascript files like merging and minifying them. Within this preperations we parse for gettext-markers and replace them with the language specific text.
The result get save as javascript file and normal included into the html.
```
```
<script scr="var/scripts/en_GB-76909c49e9222ec2bb2f45e0a3c8baef80deb665.js"></script>
```
```
The filename contains Locale and a hash value for caching.
Date and money values get always converted from system format to Locale format on output and visa versa for input.


Question: How would you manually trigger additional team builds from a team build? For example, when we were in CC.Net other builds would trigger if certain builds were successful. The second  build could either be projects that use this component or additional, long running test libraries for the same component.

Answer:
One way you could do it is you could an an AfterEndToEndIteration target to your TFSBuild.proj file that would runs the TfsBuild.exe command line to start you other builds.  I'm thinking something like this (though I haven't tested it)
```
```
<Target Name="AfterEndToEndIteration">

    <GetBuildProperties TeamFoundationServerUrl="$(TeamFoundationServerUrl)"
                        BuildUri="$(BuildUri)"
                        Condition=" '$(IsDesktopBuild)' != 'true' ">
      <Output TaskParameter="Status" PropertyName="Status" />
    </GetBuildProperties>

    <Exec Condition=" '$(Status)'=='Succeeded' "
          Command="TfsBuild.exe start /server:$(TeamFoundationServerUrl) /buildDefinition:"Your Build Definition To Run"" />

  </Target>
```
```


Question: I want to force the current execution line to a specific line in the same function, possibly skipping intermediate lines. All my old school debuggers had this feature, but I can't find it in eclipse. Is there a way to do it without changing code?

Answer:
"Run to line" appears to need the program to be running and in a paused state to use.  The other option is to set a breakpoint for that line when running in debug-mode.
Double-click far-left vertical bar in the source pane on the same line to add a breakpoint; or,
Select the line and go to Run > Toggle Breakpoint.
At least, this is in Eclipse 3.3.2.


Question:
If you launch Emacs using the -nw flag to force a console session (rather than an X session if you have X windows running), how do you get to the menu?

There are some items held in the menus that are infrequently-enough used on my part that I don't recall the escape or control sequence to do them.

Answer:
```
```
M-x menu-bar-mode
```
```


Question:
I am working through a book which gives examples of Ranges being converted to equivalent arrays using their "to_a" methods

When i run the code in irb I get the following warning

 warning: default `to_a' will be obsolete

What is the the correct alternative to using to_a?

are there alternate ways to populate an array with a Range?

Answer:
This works for me in irb:
```
```
irb> (1..4).to_a
=> [1, 2, 3, 4]
```
```
I notice that:
```
```
irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
        from (irb):1
```
```
So perhaps you are missing the parentheses?
(I am running Ruby 1.8.6 patchlevel 114)


Question:
I have a DataGridView bound to a DataView. The grid can be sorted by the user on any column.

I add a row to the grid by calling NewRow on the DataView's underlying DataTable, then adding it to the DataTable's Rows collection. How can I select the newly-added row in the grid?

I tried doing it by creating a BindingManagerBase object bound to the BindingContext of the DataView, then setting BindingManagerBase.Position = BindingManagerBase.Count. This works if the grid is not sorted, since the new row gets added to the bottom of the grid. However, if the sort order is such that the row is not added to the bottom, this does not work.

How can I reliably set the selected row of the grid to the new row?

Answer:
Assuming you have some sort of unique identifier in your data source you could iterate over your collection of rows and compare, as such:
```
```
Dim myRecentItemID As Integer = 3

For Each row As GridViewRow In gvIndividuals.Rows
    Dim drv As DataRowView = DirectCast(row.DataItem, DataRowView)
    If CInt(drv("ItemID")) = myRecentItemID Then
        gvIndividuals.EditIndex = row.RowIndex
    End If
Next
```
```
Hope this helps!


Question:
Is there a succinct way to retrieve a random record from a sql server table?

I would like to randomize my unit test data, so am looking for a simple way to select a random id from a table.  In English, the select would be "Select one id from the table where the id is a random number between the lowest id in the table and the highest id in the table."

I can't figure out a way to do it without have to run the query, test for a null value, then re-run if null.

Ideas?

Answer:
Is there a succinct way to retrieve a random record from a sql server table?
Yes
```
```
SELECT TOP 1 * FROM table ORDER BY NEWID()
```
```
Explanation
A
```
NEWID()
```
is generated for each row and the table is then sorted by it. The first record is returned (i.e. the record with the "lowest" GUID).
Notes
GUIDs are generated as pseudo-random numbers since version four:
The version 4 UUID is meant for generating UUIDs from truly-random or
  pseudo-random numbers.
The algorithm is as follows:
Set the two most significant bits (bits 6 and 7) of the
  clock_seq_hi_and_reserved to zero and one, respectively.
Set the four most significant bits (bits 12 through 15) of the
  time_hi_and_version field to the 4-bit version number from
  Section 4.1.3.
Set all the other bits to randomly (or pseudo-randomly) chosen
  values.
—
A Universally Unique IDentifier (UUID) URN Namespace - RFC 4122
The alternative
```
SELECT TOP 1 * FROM table ORDER BY RAND()
```
will not work as one would think.
```
RAND()
```
returns one single value per query, thus all rows will share the same value.
While GUID values are pseudo-random, you will need a better PRNG for the more demanding applications.
Typical performance is less than 10 seconds for around 1,000,000 rows — of course depending on the system. Note that it's impossible to hit an index, thus performance will be relatively limited.


Question:
I am trying to rename all the files present in a Windows directory using FOR command as follows at the command prompt:

for %1 in (*.*) do ren %1 test%1

E.g. This renames a file enc1.ctl to testenc1.ctl enc2.ctl  to testenc2.ctl

Thats not what i want. What i want is
enc1.ctl renamed to test1.ctl   enc2.ctl renamed to test2.ctl

How do i do that?

@Akelunuk:
Thanks, that w kind of works but i have files names as

h263_enc_random_pixels_1.ctl , h263_enc_random_pixels_2.ctl which i want to rename to

test1.ctl and test2.ctl respectively

Then how?

Answer:
If you know the number of files, (say 10), you can use
```
```
for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl
```
```


Question:
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.

I'd like to do the equivalent of:

iconv -t utf-8 $file > converted/$file # this is shell code

Thanks!

Answer:
You can use the
codecs module
, like this:
```
```
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)
```
```
EDIT
: added
```
BLOCKSIZE
```
parameter to control file chunk size.


Question:
Trying to debug an issue with a server and my only log file is a 20GB log file (with no timestamps even! Why do people use System.out.println() as logging? In production?!)

Using grep, I've found an area of the file that I'd like to take a look at, line 347340107.

Other than doing something like

head -<$LINENUM + 10> filename | tail -20

... which would require head to read through the first 347 million lines of the log file, is there a quick and easy command that would dump lines 347340100 - 347340200 (for example) to the console?

update I totally forgot that grep can print the context around a match ... this works well. Thanks!

Answer:
with GNU-grep you could just say
```
grep --context=10 ...
```


Question:
I can reset FPU's CTRL registers with this:

http://support.microsoft.com/kb/326219

But how can I save current registers, and restore them later?

It's from .net code..

What I'm doing, is from Delphi calling an .net dll as an COM module. Checking the Ctrl registers in delphi yield one value, checking with controlfp in the .net code gives another value.
What I need, is in essential is to do this:

_controlfp(_CW_DEFAULT, 0xfffff);

So my floatingpoint calculations in the .net code does not crash, but I want to restore the Ctrl registers when returning.

Maybe I don't? Maybe Delphi is resetting them when needed?
I blogged about this problem here.

Answer:
Same function you use to change them:
```
_controlfp()
```
. If you pass in a mask of 0, the current value won't be altered, but it
will
be returned - save it, and use a second call to
```
_controlfp()
```
to restore it later.


Question:
Our situation is as follows, but I'm curious about this problem in any situation.

We have a framework consisting of 4 projects:

beans

util

framework

web

We also have modules that need a version and depend on a version of beans and util.

Finally we have a customer project that consists of a specific version of the core projects and one or more modules.

Is there a standard way to version these projects?

What seems simple to me is becoming really complicated as we try to deliver releases to QA and then manage our ongoing development with the maintenance of the release (release = tag and possible branch).

I kind of prefer the following:

1.2.0 - major and minor versions + release.

1.2.1 - next release

1.2.0_01 - bug fix in 1.2.0 release (branch)

etc.

Any ideas?

Answer:
There are no standard version number systems. Common themes are to have a major, minor and build number, and occasionally a point number as well (1.2.2.1 for example, for version 1.2 point release 2 build 1). The meaning of the version numbers is highly flexible. A frequent choice is to have backwards compatibility between minor versions or point releases though.
Releases are probably best done by labeling a set of source controlled files as long as your source control allows this. Recreating a release is then as simple as syncing to the label and building, which is very useful :)


Question:
I'm about to inherit a rather large Java enterprise project that has a large amount of third party dependencies. There is at least seventy JARs included and some of them would seem to be unused e.g. spring.jar which I know isn't used.

It seems that over the years as various developers have touched upon the code base they have all tried out new project-of-the-month type libraries.

How does one go about getting rid of these? Within reason of course, as clearly some dependencies are helpful to not have to re-invent the wheel.

I'm obviously interested in java based projects but I'm welcome to answers across languages that people think will be helpful.

Answer:
Personally, I think you have to start by assessing the scale of the problem.  It's going to be fairly painful, but I'd make a list of the dependencies and work out exactly which parts of the project use which ones.
Then I'd work out exactly what features of each you're actually making use of (in many cases, you'll end up having a massive third party library which you're using a tiny part of).
Once you have this information, you'll at least know what you're dealing with.
My next step would be to look at all of the dependencies that you only use to a small extent.  Checking around might uncover things that you could use from other libraries that would eliminate the lesser used libraries.
I'd also have a look around to see if there's anything small that you could just re-write and include in your own code-base.
Finally, I'd have a look around at the vendors of your dependencies and their competitors to see if the latest versions contain more functionality that will allow you to eliminate a few others.
Then you're just left wondering whether it's better to be highly dependent on a few vendors, or less dependent on a lot of vendors!!  ;o)


Question:
How do I change the Read-only file attribute for each file in a folder using c#?

Thanks

Answer:
```
```
foreach (string fileName in System.IO.Directory.GetFiles(path))
{
    System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);

    fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;
    // or
    fileInfo.IsReadOnly = true;
}
```
```


Question:
I have around 25 worksheets in my workbook (Excel spreadsheet).
Is there a way I can protect all the 25 worksheets in single click ? or this feature is not available and I will have to write a VBA code to accomplish this. I need very often to protect all sheets and unprotect all sheets and doing individually is time consuming

Answer:
I don't believe there's a way to do it without using VBA.  If you are interested in a VBA solution, here is the code:
```
```
Dim ws as Worksheet
Dim pwd as String

pwd = "" ' Put your password here
For Each ws In Worksheets
    ws.Protect Password:=pwd
Next ws
```
```
Unprotecting is virtually the same:
```
```
Dim ws as Worksheet
Dim pwd as String

pwd = "" ' Put your password here
For Each ws In Worksheets
    ws.Unprotect Password:=pwd
Next ws
```
```


Question:
I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).

So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class?

Illustating with an example:

class A : object - Class A created.

class B : object - Class B created.

class A : B - this again is supported. What happens to the earlier association to object.

We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then

class A : B

class C : B

class A : C - I must be able to access class B's methods in A. Which is not the case?

Can anyone please explain?

Answer:
You're confusing mutliple inheritance with an inheritance tree.  You can inherit from something other than Object.  It's just that Object is sitting way up there at the top of your tree.  And someone can inherit your class, but because Object is still up there at the top that class will also inherit from object.  Your "Multi-level" inheritance is not multiple inheritance.
Multiple inheritance is when you inherit from two different trees, and .Net actually does support this after a fashion via interfaces.


Question:
Is it possible to change the language of system messages from PostgreSQL?

In MSSQL for instance this is possible with the SQL statement SET LANGUAGE.

Answer:
```
```
SET lc_messages TO 'en_US.UTF-8';
```
```
More info on requirements and limitations
here
.


Question:
I'm trying to build a similar 'slider' as demoed here http://ui.jquery.com/repository/real-world/product-slider/ but I'm trying to use interior divs inside of the list items (<li>).  it seems as if this demo breaks if you're not using an image or block element (<p>,<div>,etc.)

Anyone have any quick solutions to this?  I basically want to use text and possibly images inside of a <div> instead of using images.

I did find jCarousel which seems as if it works, but I was looking for something a little more lightweight?  Any ideas?

Answer:
I think I
sort of
have a working example of what you're trying to do, but there are a couple issues.
Using the example you posted as a base, you can replace the HTML markup of the LI's in a UL to be DIV's in a container DIV. For example:
```
```

Some text!

Some text!

Some text!

            ...

```
```
Then you modify the jQuery code in the page to target that container DIV instead of the UL:
```
```
window.onload = function () {
        var container = $('div.sliderGallery');
        var divThatGetsCropped = $('div.div-that-gets-cropped', container);
        var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth();
        $('.slider', container).slider({
            minValue: 0,
            maxValue: itemsWidth,
            handle: '.handle',
            stop: function (event, ui) {
                divThatGetsCropped.animate({'left' : ui.value * -1}, 500);
            },
            slide: function (event, ui) {
                divThatGetsCropped.css('left', ui.value * -1);
            }
        });
    };
```
```
Then you have some non-trivial CSS changes to make...  The original example relied on the LI's being styled to display: inline, inside of a container with overflow hidden. It's going to be a headache to try to get everything to show up correctly if you just style these "text-and-images-chunk" DIV's to be displayed inline. You probably want to float them all.
BUT
, floated elements won't play very nicely with the container "div-that-gets-cropped" DIV because of the way it's being "revealed" by the "sliderGallery" DIV (at least that's what I'm experiencing in Firefox 3.03). I got around this by setting a really big width for the "div-that-gets-cropped" DIV (10000 px):
```
```
.sliderGallery div.div-that-gets-cropped {
          position: absolute;
          list-style: none;
          overflow: none;
      white-space: nowrap;
      padding: 0;
          margin: 0;
          width: 10000px;
        }

        .sliderGallery div.div-that-gets-cropped div.text-and-images-chunk {
      float: left;
      margin-right: 24px;
        }
```
```
And you'll have to tweak the "left" values for .slider-lbl1, .slider-lbl2 to match up whatever the widths end up being (this might be tricky if the size of your text ends up changing the width of the "text-and-images-chunk" elements).
The one issue I noticed is that when you have the images in a block-level element, there isn't a good way to get them to "hug" the bottom, as they do in the example using inline. You might be able to get this working by playing around with the positioning of the elements (I couldn't), but hopefully this won't be a big deal in your specific usage.
All of that said, jCarousel seems like it's
intended for exactly what you're doing
, even if it does add a little code bulk.


Question:
I want to display the results of a searchquery in a website with a title and a short description. The short description should be a small part of the page which holds the searchterm. What i want to do is:
1 strip tags in page
2 find first position of seachterm
3 from that position, going back find the beginning (if there is one) of that sentence.
4 Start at the found position in step 3 and display ie 200 characters from there

I need some help with step 3. I think i need an regex that finds the first capital or dot...

Answer:
The way I would do it is, I would parse the page...
Skip over all the things starting with '<'
When you encounter a "." or [A-Z], start putting it into a buffer till you find another "."
If the buffered string has the search keyword, thats your string! Else. start buffering at the "." you encountered and repeat.
EDIT: As James Curran pointed out, this strategy would fail in some cases... So heres the solution:
What you can do, is to start X number of characters from start of page (after tags)
and then search for your keyword, buffering 2 previous words. When you find it,
do something like this:
{X} ... {prev-2}  {next-2}
Example:
This planet has - or rather had - a problem, which was this: most of the people living on it were unhappy for pretty much of the time. Many solutions were suggested for this problem, but most of these were largely concerned with the movement of small green pieces of paper, which was odd because on the whole it wasn't the small green pieces of paper that were unhappy.
Search Keyword: "suggested"
Result:
This planet has - or rather had - a problem ... Many solutions were
suggested
for this problem...


Question:
I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this.

Dialog.Edit1.Text := MyObject.Username;
Dialog.Edit2.Text := MyObject.Password;
// ... many more of the same

if (Dialog.ShowModal = mrOk)
begin
  MyObject.Username := Dialog.Edit1.Text;
  MyObject.Password := Dialog.Edit2.Text;
  // ... again, many more of the same
end;

I also often need similar code for marshalling objects to/from xml/ini-files/whatever.

Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?

Answer:
Delphi at least have 'With', though it doesn't solve the problem completely.
```
```
if (Dialog.ShowModal = mrOk)
begin
  with MyObject do
  begin
    Username := Dialog.Edit1.Text;
    Password := Dialog.Edit2.Text;
    // ... again, many more of the same
  end;
end;
```
```
And builder AFAIK has nothing alike.


Question:
I found this:

http://www.evolt.org/failover-database-connection-with-php-mysql

and similar examples. But is there a better way?

I am thinking along the lines of the Automatic Failover Client in the MS SQL Native Client.

Answer:
No, it does not have that build in. I think an easy way is to employ
MySQL Proxy
. Otherwise, but the
logic
(
```
if (fails) { connect to another }
```
) in your application, but that's not so pretty and great in terms of performance.


Question:
We have a custom collection of objects that we bind to a listbox control. When an item is added to the list the item appears in the listbox, however when one selects the item the currency manager position will not go to the position. Instead the currency manager position stays at the existing position. The listbox item is high lighted as long as the mouse is press however the cm never changes position.

If I copy one of the collection objects the listbox operates properly.

One additional note the collection also has collections within it, not sure if this would be an issue.

Answer:
Collections don't have a sense of "current item". Perhaps your custom collection does, but the
```
ListBox
```
is not using that. It has its own "current item" index into the collection. You need to handle
```
SelectedIndexChanged
```
events to keep them in sync.


Question:
I wish to search a database table on a nullable column.  Sometimes the value I'm search for is itself NULL.  Since Null is equal to nothing, even NULL, saying

where MYCOLUMN=SEARCHVALUE

will fail.  Right now I have to resort to

where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))

Is there a simpler way of saying that?

(I'm using Oracle if that matters)

Answer:
Try
```
```
WHERE NVL(mycolumn,'NULL') = NVL(searchvalue,'NULL')
```
```


Question:
I'm architecting a new app at the moment, with a high read:write ratio. At my current employer we have lots of denormalised data on our tables for performance reasons. Is it better practice to have totally 3NF tables and then use indexed views to do all the denormalisation? Should I run queries against the tables or views?

An example of some of the things I am interested are aggregates of columns child tables (e.g. having user post count stored somewhere).

Answer:
From your description, if you're looking for a pattern that matches better than Factory, try Strategy:
Strategy Pattern
Your
context
could be a custom class which encapsulates and abstracts the different report inputs (you could use the AbstractFactory pattern for this part)
Your
strategy
could implement any number of different query filters or additional logic needed.  And if you ever need to change the system in the future, you can switch between report tools by simply creating a new strategy.
Hope that helps!


Question: I installed wxWidgets 2.8.9 on a Windows XP SP2 box and built the library according to the directions and now I'm trying to get the Hello World! tutorial app to build from within Eclipse and I'm just missing something apparently.  Any idea how to get Cygwin, Eclipse and wxWidgets to play nice together?

Answer:
This
answer
was posted by Lars Uffmann to the comp.soft-sys.wxwindows newsgroup.  In a nutshell:
Add c:/cygwin/usr/local/bin to the path in the Eclipse project configuration
Add ``wx-config --cxxflags`‘ to the GCC C++ Compiler command
Move the ${FLAGS} variable to the
end of the GCC C++ Linker Command
Line Pattern
Add ``wx-config --libs`‘ to the GCC
C++ Linker flags.
Thank goodness for Mr. Uffmann sharing this information; this problem has been giving me headaches for days.
EDIT: Note that there is a literal backtick at each end of the wx-config strings.  The method of escaping the backtick doesn't seem to work correctly. Refer to the linked answer for more details on exact syntax.