q: There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!

[A]
The translate behavior is another of CakePHP's very useful but poorly documented features. I've implemented it a couple of times with reasonable success in multi-lingual websites along the following lines.
Firstly, the translate behavior will only internationalize the database content of your site. If you've any more static content, you'll want to look at Cake's
```
__('string')
```
wrapper function and
```
gettext
```
(there's some useful information about this
here
)
Assuming there's Contents that we want to translate with the following db table:
```
```
CREATE TABLE `contents` (
    `id` int(11) unsigned NOT NULL auto_increment,
    `title` varchar(255) default NULL,
    `body` text,
  PRIMARY KEY  (`id`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
```
```
The content.php model then has:
```
```
var $actsAs = array('Translate' => array('title'   => 'titleTranslation',
                     'body'    => 'bodyTranslation'
                     ));
```
```
in its definition. You then need to add the i18n table to the database thusly:
```
```
CREATE TABLE `i18n` (
  `id` int(10) NOT NULL auto_increment,
  `locale` varchar(6) NOT NULL,
  `model` varchar(255) NOT NULL,
  `foreign_key` int(10) NOT NULL,
  `field` varchar(255) NOT NULL,
  `content` mediumtext,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
```
```
Then when you're saving the data to the database in your controller, set the locale to the language you want (this example would be for Polish):
```
```
$this->Content->locale = 'pol';
$result = $this->Content->save($this->data);
```
```
This will create entries in the i18n table for the title and body fields for the pol locale. Finds will find based on the current locale set in the user's browser, returning an array like:
```
```
[Content]
  [id]
  [titleTranslation]
  [bodyTranslation]
```
```
We use the excellent
p28n component
to implement a language switching solution that works pretty well with the gettext and translate behaviours.
It's not a perfect system - as it creates HABTM relationships on the fly, it can cause some issues with other relationships you may have created manually, but if you're careful, it can work well.


q:
Emacs Lisp has replace-string but has no replace-char. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:

(replace-string (make-string 1 ?\x53979) "'")

I think it would be better with replace-char.

What is the best way to do this?

[A]
which would certainly be better with replace-char. Any way to improve my code?
Is it actually slow to the point where it matters? My elisp is usually ridiculously inefficient and I never notice. (I only use it for editor tools though, YMMV if you're building the next MS live search with it.)
Also, reading the docs:
```
```
This function is usually the wrong thing to use in a Lisp program.
What you probably want is a loop like this:
  (while (search-forward "’" nil t)
    (replace-match "'" nil t))
```
```
This answer is probably GPL licensed now.

s: huggingface

c: devops

d: intermediate


q:
I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.

What's the best way to do it? Something better/more elegant than what I am doing currently
which I post below..

[A]
NewItems is my List here... This is a bit clunky though.
```
```
for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper >= 0; iLooper--)
            {
                GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos));
            }
```
```


q:
I am fairly comfortable with standalone Java app development, but will soon be working on a project using a Java EE application server.

Does anyone know of a straightforward how-to tutorial to getting a hello-world type application working in an application server? I'm (perhaps naievly) assuming that the overall approach is similar between different frameworks, so I'm more interested in finding out the approach rather than getting bogged down in differences between the different frameworks.

If you are not aware of a good guide, then could you post bullet-point type steps to getting a hello-world running?, i.e.

Download XX

Write some code to do YY

Change file ZZ

Other steps...

Note: Just because I have a windows machine at home, I would prefer to run if this could be run on windows, but in the interest of a better answer, linux/mac based implementations are welcome.

[A]
The JavaEE (they dropped the 2) space is pretty big. A good tutorial to start is
the one from Sun
. For a simple hello world application, the web container only would suffice. A well known servlet jsp container is tomcat. See
here
for installation instructions. Try installing it with eclipse and create a web project. This will generate some files for you that you can look at and edit. Also starting and stopping the application server is simpler.


q:
In Emacs, C-x o takes me to the next window.

What keyboard macro takes me to the previous window in Emacs?

[A]
That'd be
C-- C-x o
In other words,
C-x o
with an argument of -1. You can specify how many windows to move by inserting a numeric argument between
C-u
and the command, as in
C-u 2 C-x o
. (
C--
is a shortcut for
C-u - 1
)


q: How do I get my C# program to sleep (pause execution) for 50 milliseconds?

[A]
```
```
System.Threading.Thread.Sleep(50);
```
```
Remember though, that doing this in the main GUI thread will block your GUI from updating (it will feel "sluggish")
Just remove the
```
;
```
to make it work for VB.net as well.


q:
How to match a single quote in sed if the expression is enclosed in single quotes:

sed -e '...'

For example need to match this text:

'foo'

[A]
You can either use:
```
```
"texta'textb" (APOSTROPHE inside QUOTATION MARKs)
```
```
or
```
```
'texta'\''textb' (APOSTROPHE text APOSTROPHE, then REVERSE SOLIDUS, APOSTROPHE, then APOSTROPHE more text APOSTROPHE)
```
```
I used unicode character names. REVERSE SOLIDUS is more commonly known as backslash.
In the latter case, you close your apostrophe, then shell-quote your apostrophe with a backslash, then open another apostrophe for the rest of the text.


q: How do I create an optional parameter in a mysql stored procedure?

[A]
According to
this bug
, there is currently no way to create optional parameters.


q: Are XMLSockets available in Flash Lite, and if yes in which versions, and are there differences between the regular and the lite objects?

[A]
I don't know enough to tell you the exact difference(s) between XML sockets in Flash and Flash Lite, but they are definitely supported in Flash Lite versions 2.1 and later.  See the
Flash Mobile Blog
for an example.


q: What things have to be done before I can honestly tell myself my web application is accessible by anyone? Or even better, convince Joe Clark. I don't have any video or audio to worry about, so I know I won't need transcripts. What else do I have to check?

[A]
Your question is very vague, but in short, you need to ensure that your site meets one of the three levels (A, AA, or AAA) of the
Web Content Accessibility Guidelines
.
FWIW, in my experience, if you are providing anything other than a purely static HTML site, aim for AA. Trying to follow the WCAG guidelines stringently to triple-A standard for a dynamic website is the road to hair loss IMO. This may change with WCAG 2.0.
Good luck!
EDIT:
@Blowdart suggests running your site through online checkers. This is fine so long as you realise that many of the WCAG guidelines (especially towards the higher end) are so arbitrary, they can only be validated with a human eye.
Do not trust the output of these online checkers and blindly stick a AAA badge on your site. If you are called on it, you may be in trouble.
+1 Blowdart for suggesting HTML and CSS validation, and Chris Pederick's add-on is
great
!


q:
this is my first question to stackoverflow so here it goes...

I use cruise control for my continuous integration scheme, i want to use obfuscation in order to add another protection layer to my assemblies. The thing is that i don't know how to go about it since i couldn't find articles describing about this. Suggestions that include other CI tools such as NAnt are also accepted.

Commercial tools are also an option so don't hesitate to include them in your answer. The applications that i am building and want to obfuscate are mostly written in Compact Framework 2.0, Dot Net 2.0-3.5.

At the moment cruise control checks for changes in the repository, then based on the script for the specific solution downloads and builds the project by using devenv, after the setup project has been run it copies the setup file into a different folder and thats more or less it. So i need obfuscate somewhere in this process..

[A]
Nice to hear someone is using CruiseControl.NET. That is a nice tool. You can use a command line tool for obfuscation as RemoteSoft .NET Obfuscator and integrate a call to the tool in the build script. See example on how to execute a file below from CruiseControl.NET wiki.
http://www.remotesoft.com/salamander/obfuscator.html
```
```
<exec>
    <executable>make</executable>
    <baseDirectory>D:\dev\MyProject</baseDirectory>
    <buildArgs>all</buildArgs>
    <buildTimeoutSeconds>10</buildTimeoutSeconds>
    <successExitCodes>0,1,3,5</successExitCodes>
    <environment>
        <variable>
            <name>MyVar1</name>
            <value>Var1Value</value>
        </variable>
        <variable name="MyVar2" value="Var2Value"/>
        ...
    </environment>
</exec>
```
```


q: I need to write code in python language for comparing the text of document using fingerprint techniques. I do not know to take fingerprint of a document or to generate fingerprint of a document. I'm asking if anyone knows the method or has source code for generating fingerprints of documents which is stored in bits form.


q:
I'm trying to draw a polygon using c# and directx

All I get is an ordered list of points from a file and I need to draw the flat polygon in a 3d world.

I can load the points and draw a convex shape using a trianglefan and drawuserprimitives.

This obviously leads to incorrect results when the polygon is very concave (which it may be).

I can't imagine I'm the only person to grapple with this problem (tho I'm a gfx/directx neophyte - my background is in gui\windows application development).

Can anyone point me towards a simple to follow resource\tutorial\algorithm which may assist me?

[A]
Direct3D can only draw triangles (well, it can draw lines and points as well, but that's besides the point). So if you want to draw any shape that is more complex than a triangle, you have to draw a bunch of touching triangles that equal to that shape.
In your case, it's a concave polygon triangulation problem. Given a bunch of vertices, you can keep them as is, you just need to compute the "index buffer" (in simplest case, three indices per triangle that say which vertices the triangle uses). Then draw that by putting into vertex/index buffers or using DrawUserPrimitives.
Some algorithms for triangulating simple (convex or concave, but without self-intersections or holes) polygons are at
VTerrain site
.
I have used Ratcliff's code in the past; very simple and works well. VTerrain has a dead link to it; the code can be found
here
. It's C++, but porting that over to C# should be straightforward.
Oh, and don't use triangle fans. They are of very limited use, inefficient and are going away soon (e.g. Direct3D 10 does not support them anymore). Just use triangle lists.


q: I'm a little confused about how the standard library will behave now that Python (from 3.0) is unicode-based. Will modules such as CGI and urllib use unicode strings or will they use the new 'bytes' type and just provide encoded data?

[A]
Logically a lot of things like MIME-encoded mail messages, URLs, XML documents, and so on should be returned as
```
bytes
```
not strings. This could cause some consternation as the libraries start to be nailed down for Python 3 and people discover that they have to be more aware of the
```
bytes
```
/
```
string
```
conversions than they were for
```
str
```
/
```
unicode
```
...


q:
I've been wanting to program for the Plan 9 operating system for a while. I'd really like to play around with a web app there. Of course, the only language I know for Plan 9 is C, and that doesn't seem ideal for web development. I also understand that it doesn't run apache or mysql either.

What is the best way to start coding web apps on Plan 9?

[A]
Check out Kenji Arisawa's
Pegasus
(
paper
) webserver for Plan 9.
Plan 9 may have a reputation for being C-only, but several langauges, including Scheme, Ruby, Python, and Perl have been ported. Check out the
Contrib Index
for the code.
Finally, start reading the Plan 9
white papers
so that you can understand its philosophy. If you want to do net-related things, the file protocol
9p
is essential.


q: mysql_real_escape_string and addslashes are both used to escape data before the database query, so what's the difference? (This question is not about parametrized queries/PDO/mysqli)

[A]
It seems that
```
mysql_real_escape_string
```
is binary-safe - the documentation states:
If binary data is to be inserted, this function must be used.
I think it's probably safer to always use
```
mysql_real_escape_string
```
than addslashes.


q:
Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make.

So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues.

All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening.

So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console.

I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make.

[A]
this should do the trick:
```
```
if not ERRORLEVEL 0 pause
```
```
type
```
help if
```
in DOS for more info on errorlevel usage.


q:
Any free alternative to Robohelp?  Prefer open source

Need some sort of online help authoring tool for an open source project.

[A]
Are you trying to make just CHM or other output formats too?
Take a look at DocBook. You can make (from one source file) pdf, html and chm - and some others, too. I've used it in the past but it's not very easy or convenient to use. If you only want to output chm (and need to use a free solution), see if you can get away with using the htmlhelp workshop (
http://www.microsoft.com/downloads/details.aspx?familyid=00535334-c8a6-452f-9aa0-d597d16580cc&displaylang=en
).


q:
SslStream is supposed to negotiate the cipher type, key length, hash algorithm, etc. with its peer SSL stack. When using it in my code, I find that the negotiation always defaults to RC4 & MD5. I would like to use 3DES or AES for some added security.

Looking around the web I find only a few references to this problem and no solutions; one poster is claiming this actually makes sense, since the lowest common denominator between the two stacks is secure while has the added benefit of being faster/using less CPU resources. While this may be technically correct, my particular trade-off between complexity and cost lies elsewhere (I prefer to use AES with a long key).

If anyone can help I'd appreciate it.

[A]
It should be using the most secure set of algorithms that were in both lists. I find it hard to believe that it isn't, because SslStream is wrapping the SChannel SSPI, and if that were broken then Internet Explorer, IIS and everything else on Windows would be broken too.
It could be that you have an outdated version of SChannel.dll/Secur32.dll. What OS and Internet Explorer version do you have installed?
It is possible to
disable protocols in SCHANNEL
. Could you check that this hasn't been done?


q:
Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own?

The ideal would be something like:

var myXML: XML = ???; // ... load xml data into the XML object

myXML.someAttribute = newValue;

[A]
Attributes are accessible in AS3 using the
```
@
```
prefix.
For example:
```
```
var myXML:XML = <test name="something"></test>;
trace(myXML.@name);
myXML.@name = "new";
trace(myXML.@name);
```
```
Output:
```
```
something
new
```
```


q:
When I use quick documentaion lookup (Ctrl+Q) on j2ee classes or annotations in IDEA I only get an empty javadoc. It only contains the basics like class name.

How do I add the javadoc to the libs IDEA provides itself?

[A]
You can attach javadoc to any library you have configure in your module or project. Just access the project structure windows
```
(File -> Project Structure)
```
, then select "modules" and select the module that has the dependency you want to configure.
Then select the "Dependencies" tab, select the dependency that's missing the javadoc and click "Edit". In the window that just showed up you see two buttons "Add" and "Specify Javadoc URL". If you have the javadoc in a jar file select the first one, if you want to point to a web site that contains the javadoc select the latest.
That's it.


q:
How can brackets be escaped in using string.Format?

For example:

String val = "1,2,3"
String.Format(" foo {{0}}", val);

This example doesn't throw an exception, but it outputs the string foo {0}.

Is there a way to escape the brackets?

[A]
For you to output
```
foo {1, 2, 3}
```
you have to do something like:
```
```
string t = "1, 2, 3";
string v = String.Format(" foo {{{0}}}", t);
```
```
To output a
```
{
```
you use
```
{{
```
and to output a
```
}
```
you use
```
}}
```
.
Or now, you can also use C# string interpolation like this (a feature available in C# 6.0)
Escaping brackets: String interpolation $("")
. It is new feature in C# 6.0.
```
```
var inVal = "1, 2, 3";
var outVal = $" foo {{{inVal}}}";
// The output will be:  foo {1, 2, 3}
```
```


q:
From a shell script, how do I check if a directory contains files?

Something similar to this

if [ -e /some/dir/* ]; then echo "huzzah"; fi;

but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).

[A]
Try:
```
```
if [ ! -z `ls /some/dir/*` ]; then echo "huzzah"; fi
```
```


q:
By default data extracted by the GROUP BY clause is ordered as ascending.
How to change it to descending.

[A]
Add
```
DESC
```
to the
```
GROUP BY
```
clause, e.g. :
```
```
GROUP BY myDate DESC
```
```


q: I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml


q: I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (http://docs.codehaus.org/display/JETTY/KeepGenerated) in webdefault.xml but it seems unclear how this works in embedded setups.

[A]
It is dumped already.
for example if you have a file called
```
index.jsp
```
, a file will be created called
```
index_jsp.java
```
Just search for something like that in the work directory.


q:
I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows).
I currently do this:
1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer
2. Use memcpy to copy from my original buffer to this new buffer from step 1
3. Use BitBlt to let GDI perform the color conversion

I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches:

a. Wrap my original mem buf in a DC to perform BitBlt directly from it

b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to.

So how do I do either (a) or (b)?

thanks!

[A]
OK, to address the two parts of the problem.
the following code shows how to get at the pixels inside of a bitmap, change them and put them back into the bitmap.  You could always generate a dummy bitmap of the correct size and format, open it up, copy over your data and you then have a bitmap object with your data:
```
```
private void LockUnlockBitsExample(PaintEventArgs e)
{

   // Create a new bitmap.
   Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");

   // Lock the bitmap's bits.
   Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
   System.Drawing.Imaging.BitmapData bmpData =
         bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,
         bmp.PixelFormat);

   // Get the address of the first line.
   IntPtr ptr = bmpData.Scan0;

   // Declare an array to hold the bytes of the bitmap.
   int bytes  = bmpData.Stride * bmp.Height;
   byte[] rgbValues = new byte[bytes];

   // Copy the RGB values into the array.
   System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

   // Set every third value to 255. A 24bpp bitmap will look red.
   for (int counter = 2; counter < rgbValues.Length; counter += 3)
       rgbValues[counter] = 255;

   // Copy the RGB values back to the bitmap
   System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);

   // Unlock the bits.
   bmp.UnlockBits(bmpData);

   // Draw the modified image.
   e.Graphics.DrawImage(bmp, 0, 150);
}
```
```
To convert the contents to 8bpp you'll want to use the System.Drawing.Imaging.ColorMatrix class.  I don't have at hand the correct matrix values for half-tone, but this example grayscales and adjustment of the values should give you an idea of the effect:
```
```
Graphics g = e.Graphics;
Bitmap bmp = new Bitmap("sample.jpg");
g.FillRectangle(Brushes.White, this.ClientRectangle);

// Create a color matrix
// The value 0.6 in row 4, column 4 specifies the alpha value
float[][] matrixItems = {
                            new float[] {1, 0, 0, 0, 0},
                            new float[] {0, 1, 0, 0, 0},
                            new float[] {0, 0, 1, 0, 0},
                            new float[] {0, 0, 0, 0.6f, 0},
                            new float[] {0, 0, 0, 0, 1}};
ColorMatrix colorMatrix = new ColorMatrix(matrixItems);

// Create an ImageAttributes object and set its color matrix
ImageAttributes imageAtt = new ImageAttributes();
imageAtt.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

// Now draw the semitransparent bitmap image.
g.DrawImage(bmp, this.ClientRectangle, 0.0f, 0.0f, bmp.Width, bmp.Height,
            GraphicsUnit.Pixel, imageAtt);

imageAtt.Dispose();
```
```
I shall try and update later with the matrix values for half-tone, it's likely to be lots 0.5 or 0.333 values in there!


q:
Suppose I have a simple XHTML document that uses a custom namespace for attributes:

<html xmlns="..." xmlns:custom="http://www.example.com/ns">
    ...
    <div class="foo" custom:attr="bla"/>
    ...
</html>

How do I match each element that has a certain custom attribute using jQuery? Using

$("div[custom:attr]")

does not work. (Tried with Firefox only, so far.)

[A]
You should use
```
$('div').attr('custom:attr')
```
.


q:
I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find crti.o. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this crti.o, wouldn't it use a library file, e.g. libc.a?

I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it?

crti.o is on one of the 'libraries' search path, but should it look for .o file on the library path?

Is the search path the same for gcc and ld?

[A]
```
crti.o
```
is the bootstrap library, generally quite small. It's usually statically linked into your binary. It should be found in
```
/usr/lib
```
.
If you're running a binary distribution they tend to put all the developer stuff into -dev packages (e.g. libc6-dev) as it's not needed to run compiled programs, just to build them.
You're not cross-compiling are you?
If you're cross-compiling it's usually a problem with gcc's search path not matching where your crti.o is. It should have been built when the toolchain was. The first thing to check is
```
gcc -print-search-dirs
```
and see if crti.o is in any of those paths.
The linking is actually done by ld but it has its paths passed down to it by gcc. Probably the quickest way to find out what's going on is compile a helloworld.c program and strace it to see what is getting passed to ld and see what's going on.
```
```
strace -v -o log -f -e trace=open,fork,execve gcc hello.c -o test
```
```
Open the log file and search for crti.o, as you can see my non-cross compiler:
```
```
10616 execve("/usr/bin/ld", ["/usr/bin/ld", "--eh-frame-hdr", "-m", "elf_x86_64", "--hash-style=both", "-dynamic-linker", "/lib64/ld-linux-x86-64.so.2", "-o"
, "test", "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."..., "-L/usr/lib/gcc/x86_64-linux-g
nu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/usr/lib/gcc/x86_64-linux-gnu/"..., "-L/lib/../lib", "-L/usr/lib/../lib", "-L/usr/lib/gcc/x86_64-linux-gnu
/"..., "/tmp/cc4rFJWD.o", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "/usr/lib/gcc/x86_
64-linux-gnu/4."..., "/usr/lib/gcc/x86_64-linux-gnu/4."...],  "COLLECT_GCC=gcc", "COLLECT_GCC_OPTIONS=\'-o\' \'test\' "..., "COMPILER_PATH=/usr/lib/gcc/x86_6"..., "LIBRARY_PATH=/usr/lib/gcc/x86_64"..., "CO
LLECT_NO_DEMANGLE="]) = 0
10616 open("/etc/ld.so.cache", O_RDONLY) = 3
10616 open("/usr/lib/libbfd-2.18.0.20080103.so", O_RDONLY) = 3
10616 open("/lib/libc.so.6", O_RDONLY)  = 3
10616 open("test", O_RDWR|O_CREAT|O_TRUNC, 0666) = 3
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crt1.o", O_RDONLY) = 4
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/../../../../lib/crti.o", O_RDONLY) = 5
10616 open("/usr/lib/gcc/x86_64-linux-gnu/4.2.3/crtbegin.o", O_RDONLY) = 6
10616 open("/tmp/cc4rFJWD.o", O_RDONLY) = 7
```
```
If you see a bunch of attempts to
```
open(...crti.o) = -1 ENOENT
```
,
```
ld
```
is getting confused and you want to see where the path it's opening came from...


q:
In static languages like Java you need interfaces because
otherwise the type system just won't let you do certain things.
But in dynamic languages like PHP and Python you just take
advantage of duck-typing.

PHP supports interfaces.
Ruby and Python don't have them.
So you can clearly live happily without them.

I've been mostly doing my work in PHP and have never really
made use of the ability to define interfaces. When I need a
set of classes to implement certain common interface, then
I just describe it in documentation.

So, what do you think? Aren't you better off without using
interfaces in dynamic languages at all?

[A]
Well, first of all, it's right that Ruby does not have Interface as is, but they have mixin, wich takes somehow the best of both interfaces and abstract classes from other languages.
The main goal of interface is to ensure that your object SHALL implement ALL the methods present in the interface itself.
Of course, interface are never mandatory, even in Java you could imagine to work only with classes and using reflection to call methods when you don't know wich kind of object you're manipulating, but it is error prone and should be discouraged in many ways.


q: I'm trying to match elements with a name that is 'container1$container2$chkChecked', using a regex of '.+\$chkChecked', but I'm not getting the matches I expect when the element name is as described.  What am I doing wrong?

[A]
try
```
```
string.match( /[$]chkChecked$/ )
```
```
alternatively, you could try
```
```
string.match( /[^a-zA-Z0-9]chkChecked/ )
```
```
( Also, make sure your using
```
//
```
around your regex, otherwise you might be matching using string literals. Not obvious tho without a larger code snippet )


q:
I am considering using Postsharp framework to ease the burden of application method logging.
It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment.
Any thoughts, experiences or better alternatives?

[A]
I apply logging with AOP using Castle Windsor DynamicProxies.  I was already using Castle for it's IoC container, so using it for AOP was the path of least resistence for me.   If you want more info let me know, I'm in the process of tidying the code up for releasing it as a blog post
Edit
Ok, here's the basic Intercepter code, faily basic but it does everything I need.  There are two intercepters, one logs everyhing and the other allows you to define method names to allow for more fine grained logging.  This solution is faily dependant on Castle Windsor
Abstract Base class
```
```
namespace Tools.CastleWindsor.Interceptors
{
using System;
using System.Text;
using Castle.Core.Interceptor;
using Castle.Core.Logging;

public abstract class AbstractLoggingInterceptor : IInterceptor
{
    protected readonly ILoggerFactory logFactory;

    protected AbstractLoggingInterceptor(ILoggerFactory logFactory)
    {
        this.logFactory = logFactory;
    }

    public virtual void Intercept(IInvocation invocation)
    {
        ILogger logger = logFactory.Create(invocation.TargetType);

        try
        {
            StringBuilder sb = null;

            if (logger.IsDebugEnabled)
            {
                sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(".{0}(", invocation.Method);

                for (int i = 0; i < invocation.Arguments.Length; i++)
                {
                    if (i > 0)
                        sb.Append(", ");

                    sb.Append(invocation.Arguments[i]);
                }

                sb.Append(")");

                logger.Debug(sb.ToString());
            }

            invocation.Proceed();

            if (logger.IsDebugEnabled && invocation.ReturnValue != null)
            {
                logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue);
            }
        }
        catch (Exception e)
        {
            logger.Error(string.Empty, e);
            throw;
        }
    }
}
}
```
```
Full Logging Implemnetation
```
```
namespace Tools.CastleWindsor.Interceptors
{
using Castle.Core.Logging;

public class LoggingInterceptor : AbstractLoggingInterceptor
{
    public LoggingInterceptor(ILoggerFactory logFactory) : base(logFactory)
    {
    }
}
}
```
```
Method logging
```
```
namespace Tools.CastleWindsor.Interceptors
{
using Castle.Core.Interceptor;
using Castle.Core.Logging;
using System.Linq;

public class MethodLoggingInterceptor : AbstractLoggingInterceptor
{
    private readonly string[] methodNames;

    public MethodLoggingInterceptor(string[] methodNames, ILoggerFactory logFactory) : base(logFactory)
    {
        this.methodNames = methodNames;
    }

    public override void Intercept(IInvocation invocation)
    {
        if ( methodNames.Contains(invocation.Method.Name) )
            base.Intercept(invocation);
    }
}
}
```
```


q:
My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a URLConnection.

How can I specify this?

[A]
The obvious portable way would be to set a Proxy in URL.openConnection. The proxy can be in local host, you can then write a very simple proxy that binds the local address of the client socket.
If you can't modify the source where the URL is connected, you can replace the URLStreamHandler either when calling the URL constructor or globally through URL.setURLStreamHandlerFactory. The URLStreamHandler can then delegate to the default http/https handler, modifying the openConnection call.
A more extreme method would be to completely replace the handler (perhaps extending the implementation in your JRE). Alternatively, alternative (open source) http clients are available.


q: What are the differences between a clustered and a non-clustered index?

[A]
Clustered indexes are stored physically on the table. This means they are the fastest and you can only have one clustered index per table.
Non-clustered indexes are stored separately, and you can have as many as you want.
The best option is to set your clustered index on the most used unique column, usually the PK. You should always have a well selected clustered index in your tables, unless a very compelling reason--can't think of a single one, but hey, it may be out there--for not doing so comes up.


q:
I am looking for a good way to consistently test my web applications from the end users point of view. I have all kinds of ways to check to make sure my code is working behind the scenes. I can't count the number of times that I make a change to a piece of code, test it and it works fine and then deploy it only to have it blow up somewhere else weeks later. I have by that time forgotten the change I made that caused it to blow up. I need something that I can run every time I make a change to assure me I did not break something somewhere else.

It needs to be able to input correct and incorrect entries so that client side validation can be tested also.

Thank you,

Scott and the Dev Team

[A]
I thin you need to investigate
Selenium
. We use it to do automated UI testing throughout our solution, and it is cross browser and cross platform.
You can use the
Selenium IDE
to record a walkthrough of your web application, and then you can either run it in the browser, or export it to various languages such as C#, and run it using NUnit. I find this is the easiest approach because I can create the basic walkthrough and then modify the code to use inputs from a file/database in order to create multiple scenarios.


q: I have heard the 'shard' technique mentioned several times with regard to solving scaling problems for large websites. What is this 'shard' technique and why is it so good?

[A]
Karl Seguin has a
good blog
post about sharding.
From the post:
Sharding is the separation of your
  data across multiple servers. How you
  separate your data is up to you, but
  generally it’s done on some
  fundamental identifier.


q: How do you update a summary field's value from post function in JIRA?

[A]
Ok, I'll try to explain... For simplicity, suppose we have a post function and we want summary value changed to "foobar":
```
```
public class SomePostFunction implements FunctionProvider {

    public void execute(Map transientVars, Map args, PropertySet ps) throws WorkflowException {
        String newValue = "foobar";
        // TODO update summary so it's value becomes newValue
    }

}
```
```


q:
I'm a little blockheaded right now…

I have a date string in european format dd.mm.yyyy and need to transform it to mm.dd.yyyy with classic ASP. Any quick ideas?

[A]
OK, I just found a solution myself:
```
```
payment_date = MID(payment_date,4,3) & LEFT(payment_date,3) & MID(payment_date,7)
```
```


q:
I am building a table using the DataGridView where a user can select items from a dropdown in each cell.   To simplify the problem, lets say i have 1 column.  I am using the DataGridViewComboBoxColumn in the designer.  I am trying to support having each row in that column have a different list of items to choose from.

Is this possible?

[A]
Yes. This can be done using the DataGridViewComboBoxCell.
Here is an example method to add the items to just one cell, rather than the whole column.
```
```
private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd)
{
    DataGridViewComboBoxCell dgvcbc = (DataGridViewComboBoxCell) dataGrid.Rows[rowIndex].Cells[colIndex];
    // You might pass a boolean to determine whether to clear or not.
    dgvcbc.Items.Clear();
    foreach (object itemToAdd in itemsToAdd)
    {
        dgvcbc.Items.Add(itemToAdd);
    }
}
```
```


q:
How can I set the background color of a specific item in a  System.Windows.Forms.ListBox?

I would like to be able to set multiple ones if possible.

[A]
Probably the only way to accomplish that is to draw the items yourself.
Set the
```
DrawMode
```
to
```
OwnerDrawFixed
```
and code something like this on the DrawItem event:
```
```
private void listBox_DrawItem(object sender, DrawItemEventArgs e)
{
    e.DrawBackground();
    Graphics g = e.Graphics;

    g.FillRectangle(new SolidBrush(Color.Silver), e.Bounds);

    // Print text

    e.DrawFocusRectangle();
}
```
```
The second option would be using a ListView, although they have an other way of implementations (not really data bound, but more flexible in way of columns).


q:
To create a new event handler on a control you can do this

c.Click += new EventHandler(mainFormButton_Click);

or this

c.Click += mainFormButton_Click;

and to remove an event handler you can do this

c.Click -= mainFormButton_Click;

But how do you remove all event handlers from an event?

[A]
From
Removing All Event Handlers
:
Directly no, in large part because you
  cannot simply set the event to null.
Indirectly, you could make the actual
  event private and create a property
  around it that tracks all of the
  delegates being added/subtracted to
  it.
Take the following:
```
```
List<EventHandler> delegates = new List<EventHandler>();

private event EventHandler MyRealEvent;

public event EventHandler MyEvent
{
    add
    {
        MyRealEvent += value;
        delegates.Add(value);
    }

    remove
    {
        MyRealEvent -= value;
        delegates.Remove(value);
    }
}

public void RemoveAllEvents()
{
    foreach(EventHandler eh in delegates)
    {
        MyRealEvent -= eh;
    }
    delegates.Clear();
}
```
```


q:
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.)
The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it.

Is there something that will take any python object and display it in a more rational manner. e.g.

[0, 1,
    [a, b, c],
    2, 3, 4]

instead of:

[0, 1, [a, b, c], 2, 3, 4]

I know that's not a very good example, but I think you get the idea.

[A]
```
```
from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)
```
```
Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.


q:
I have a model class:

class Person(db.Model):
  first_name = db.StringProperty(required=True)
  last_name = db.StringProperty(required=True)

I have an instance of this class in p, and string s contains the value 'first_name'. I would like to do something like:

print p[s]

and

p[s] = new_value

Both of which result in a TypeError.

Does anybody know how I can achieve what I would like?

[A]
```
```
getattr(p, s)
setattr(p, s, new_value)
```
```


q:
Is there a version of FitNesse that works on Delphi 2006/2007/2009?

If so where can I find It?

Are there any other programs like FitNesse that work on Delphi 2006?


q:
Say I have the following web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <authentication mode="Windows"></authentication>
    </system.web>
</configuration>

Using ASP.NET C#, how can I detect the Mode value of the Authentication tag?

[A]
Try
```
Context.User.Identity.AuthenticationType
```
Go for PB's answer folks


q:
How many people actually write an SDD document before writing a single line of code?

How do you handle large CSCI's?

What standard do you use for SDD content?

What tailoring have you done?

[A] Most big software companies have their own practices. For example Motorola has detailed documentation for every aspect of software development process. There are standard templates for each type of documents. Having strict standards allows effectively maintain huge number of documents and integrate it with different tools. Each document obtains tracking number from special document-tracking system. They even have system (last time I seen it was in stage of early development) for automatically requirements tracking - you can say which line of code relate to given requirement\design guideline.


q: Can I safely rename the cygdrive folder? Also, I would like to add other folders at root and map them to folders on windows in the same way as /cygdrive/c maps to my C drive. Is that possible?

[A]
I wouldn't rename cygdrive as I don't know what that would do, but you can map other directories at root to various windows directories using the
```
mount
```
command.


q:
Looking for an open source library, for C++, Java, C# or Python, for reading the data from Quicken .qdf files.

@Swati:  Quicken .qif format is for transfer only and is not kept up to date by the application  like the .qdf file is.

[A]
http://www.west-wind.com/Weblog/posts/10491.aspx
And i know one other blog where the author was developing a parser for qfx/qif... lemme look it up... googling hasnt helped yet :(
Update: Found one more:
http://blogs.msdn.com/lucabol/archive/2007/08/31/parsing-qif-quicken-files-in-c.aspx


q: I want to add a mailto link on our web page. I want to add a urgent priority to this mail.

[A]
mailto links just doesn't support this feature , sorry.
however, you could use a specific subject and filter it in your inbox
```
```
Send a email
```
```


q: How does it work, what is it used for and when should one use it?

[A]
Directly from the
Strategy Pattern Wikipedia article
:
The strategy pattern is useful for situations where it is necessary to dynamically swap the algorithms used in an application. The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.


q:
I've got the following SQL:

select * from transaction_log where stoptime like '%2008%'

How do I write this in LINQ to SQL syntax?

[A]
If you want to use the literal method, it's like this:
```
```
var query = from l in transaction_log
            where SqlMethods.Like(l.stoptime, "%2008%")
            select l;
```
```
Another option is:
```
```
var query = from l in transaction_log
        where l.stoptime.Contains("2008")
        select l;
```
```
If it's a DateTime:
```
```
var query = from l in transaction_log
        where l.stoptime.Year = 2008
        select l;
```
```
That method is in the
System.Data.Linq.SqlClient
namespace


q:
AKA - What's this obsession with pointers?

Having only really used modern, object oriented languages like ActionScript, Java and C#, I don't really understand the importance of pointers and what you use them for. What am I missing out on here?

[A]
Pointers are for directly manipulating the contents of memory.
It's up to you whether you think this is a good thing to do, but it's the basis of how anything gets done in C or assembler.
High-level languages hide pointers behind the scenes: for example a reference in Java is implemented as a pointer in almost any JVM you'll come across, which is why it's called NullPointerException rather than NullReferenceException. But it doesn't let the programmer directly access the memory address it points to, and it can't be modified to take a value other than the address of an object of the correct type. So it doesn't offer the same power (and responsibility) that pointers in low-level languages do.
[Edit: this is an answer to the question 'what's this obsession with pointers?'. All I've compared is assembler/C-style pointers with Java references. The question title has since changed: had I set out to answer the new question I might have mentioned references in languages other than Java]


q:
How do I programmatically set the record pointer in a C# DataGridView?

I've tried "DataGridView.Rows[DesiredRowIndex].Selected=true;", and that does not work.  All it does is highlight that row within the grid; it doesn not move the record pointer to that row.

[A]
To change the active row for the datagrid you need to set the current cell property of the datagrid to a non-hidden non-disabled, non-header cell on the row that you have selected. You'd do this like:
```
```
dataGridView1.CurrentCell = this.dataGridView1[YourColumn,YourRow];
```
```
Making sure that the cell matches the above criteria. Further information can be found at:
http://msdn.microsoft.com/en-us/library/yc4fsbf5.aspx


q:
I have a datagridview  with a DataGridViewComboboxColumn column with 3 values:

"Small", "Medium", "Large"

I get back the users default which in this case is "Medium"

I want to show a dropdown cell in the datagridview but default the value to "Medium".  i would do this in a regular combobox by doing selected index or just stting the Text property of a combo box.

[A]
Are you retrieving the user data and attempting to set values in the DataGridView manually, or have you actually bound the DataGridVew to a data source? Because if you've bound the grid to a data source, you should just need to set the DataPropertyName on the column to be the string name of the object Property:
```
```
[DataGridViewComboboxColumnName].DataPropertyName = "PropertyNameToBindTo";
```
```
Or do you mean you want it to default to Medium for a new row?


q:
What are the typical average bytes-per-character rates for different unicode encodings in different languages?

E.g. if I wanted the smallest number of bytes to encode some english text, then on average UTF-8 would be 1-byte per character and UTF-16 would be 2 so I'd pick UTF-8.

If I wanted some Korean text, then UTF-16 might average about 2 per character but UTF-8 might average about 3 (I don't know, I'm just making up some illustrative numbers here).

Which encodings yield the smallest storage requirements for different languages and character sets?

[A]
For any given language, your bytes-per-character rates are fairly constant, because most languages are allocated to contiguous code pages. The big exception is accented Latin characters, which are allocated higher in the code space than the unaccented forms. I don't have hard numbers for these.
For languages with contiguous character allocation, there is a
table with detailed numbers for various languages
on Wikipedia. In general, UTF-8 works well for most small character sets (except the ones allocated on high code pages), and UTF-16 is great for two-byte character sets.
If you need denser compression, you may also want to look at
Unicode Technical Note 14
, which compares some special-purpose encodings designed to reduce data size for a variety of languages. But these techniques aren't especially common.


q:
Why does C++ Builder 6 always compile all files?

I make some changes on one file but BCB 6 compiles all files when I start the app. Any idea? I use Windows XP SP2.

[A]
Are you source files and binary objects located on the same machine? If not sounds like you have a network time sync issue.
If they are its most likely a header file issue, either the compiler include files have a modified date some time in the future or your application is dependent on some header file that changes during compilation say from a COM import.
EDIT: Check the setting VS has a flag to always re-compile, this might be true for BCB too, if set then unset it. Another possibility is that pre-compiled headers are miss-configured to generate on every source file.
I am not familiar with BCB 6 to give a more precise answer.


q: How can I add a column with a default value to an existing table in SQL Server 2000 / SQL Server 2005?

[A]
```
```
ALTER TABLE ADD ColumnName {Column_Type} Constraint
```
```
The MSDN article
ALTER TABLE (Transact-SQL)
has all of the alter table syntax.


q:
I am working on a SQL query that reads from a SQLServer database to produce an extract file. One of the  requirements to remove the leading zeroes from a particular field, which is a simple VARCHAR(10) field. So, for example, if the field contains '00001A', the SELECT statement needs to return the data as '1A'.

Is there a way in SQL to easily remove the leading zeroes in this way? I know there is an RTRIM function, but this seems only to remove spaces.

[A]
```
```
select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)
```
```


q: What do you find is the optimal setting for mysql slow query log parameter, and why?

[A]
Whatever time /you/ feel is unacceptably slow for a query on your systems.
It depends on the kind of queries you run and the kind of system; a query taking several seconds might not matter if it's some back-end reporting system doing complex data-mining etc where a delay doesn't matter, but might be completely unacceptable on a user-facing system which is expected to return results promptly.


q: Is there any way that I can programmatically create (and I guess access) hidden folders on a storage device from within c#?

[A]
```
```
using System.IO;

string path = @"c:\folders\newfolder"; // or whatever
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
di.Attributes = FileAttributes.Directory | FileAttributes.Hidden;
}
```
```


q:
I've always wondered this - why can't you declare variables after a case label in a switch statement?  In C++ you can declare variables pretty much anywhere (and declaring them close to first use is obviously a good thing) but the following still won't work:

switch (val)
{
case VAL:
  // This won't work
  int newVal = 42;
  break;
case ANOTHER_VAL:
  ...
  break;
}

The above gives me the following error (MSC):

initialization of 'newVal' is skipped by 'case' label

This seems to be a limitation in other languages too.  Why is this such a problem?

[A]
The whole switch statement is in the same scope. To get around it, do this:
```
```
switch (val)
{
    case VAL:
    {
        // This **will** work
        int newVal = 42;
    }
    break;

    case ANOTHER_VAL:
      ...
    break;
}
```
```
Note
the brackets.


q:
I have a SQL Server 2000, C# & ASP.net web app.  We want to control access to it by using Active Directory groups.  I can get authentication to work if the group I put in is a 'Global' but not if the group is 'Universal'.

How can I make this work with 'Universal' groups an well?
Here's my authorization block:

  <authorization>
  <allow roles="domain\Group Name Here"/>
  <allow roles="domain\Group Name Here2"/>
  <allow roles="domain\Group Name Here3"/>
  <deny users="*"/>
  </authorization>

[A]
Depending on your Active Directory topology, you might have to wait for the Universal Group membership to replicate around to all the Domain Controllers.  Active Directory recommends the following though:
Create a Global group for each domain, e.g., "Domain A Authorized Users", "Domain B Authorized Users"
Put the users you want from Domain A in the "Domain A Authorized Users" group, etc
Create a Universal group in the root domain "All Authorized Users"
Put the Global groups in the Universal group
Secure the resource using the Universal group: <allow roles="root domain\All Authorized Users/>
Wait for replication
One advantage of this scheme is that when you add a new user to one of the Global groups, you won't have to wait for GC replication.


q:
Based on a simple test I ran, I don't think it's possible to put an inline <style> tag into an ASP.NET server control.  The style did not end up rendering to the output HTML.  Even if it was possible, I'm sure it is bad practice to do this.

Is it possible to do this?  I can see it being useful for quick prototypes that just have 1 or 2 CSS classes to apply.

[A]
I think you will have to add it as an attribute to the server control... for it to render to HTML.
So basically (in C#),
```
```
ControlName.Attributes["style"] = "color:red";
```
```


q:
I use to run

$s =~ s/[^[:print:]]//g;

on Perl to get rid of non printable characters.

In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not.

What would you do?

EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character.

[A]
The best I've come up with now is (thanks to the python-izers above)
```
```
def filter_non_printable(str):
  return ''.join([c for c in str if ord(c) > 31 or ord(c) == 9])
```
```
This is the only way I've found out that works with Unicode characters/strings
Any better options?


q:
I've started a conversion of a project to Moose and the first thing I noticed was that my critic/tidy tests go to hell. Moose, Tidy and Critic don't seem to like each other as much as they used to.

Are there docs anywhere on how to make critic/tidy be more appreciative of the Moose dialect? What do most Moose users do? Relax/ditch critic for the more heavy Moose modules? Custom policies?

[A]
Both of them can be configured into detail.
I have no idea why perltidy wouldn't like it,
it has nothing to do with it
. Perltidy only governs style. You can change the style of your code without changing any functionality, it's mostly a matter of whitespace really. You should either change your style or change the perltidy configuration using the .perltidyrc file.
I don't know what problems perlcritic has with it (lvalue methods perhaps?), but you could consider turning off those specific policies using the .perlcriticrc file. Also, if your perlcritic is old you may want to upgrade it, as some old versions gave some incorrect errors in Moose classes.


q:
I've implemented a stopwatch that works fine without considering that bank holidays and weekends shouldn't be counted in the total duration. I was looking for some open-source library where I could get the elapsed time, passing a start instant, end instant and a set of bank holidays (weekends aren't counted in). The only library that makes me things easier is net.sf.jtemporal, but I have still to amplify the functionality.
Could anyone tell me if there is some useful library to get the wanted functionality?

[A] Do you only count Bank Hours too?  9AM - 3PM?  Or is it 24 hours a day?


q:
I'm trying to create a self signed certificate for use with Apache Tomcat 6.  Every certificate I can make always results in the browser connecting with AES-128.  The customer would like me to demonstrate that I can create a connection at AES-256.

I've tried java's keytool and openssl.  I've tried with a variety of parameters, but can't seem to specify anything about the keysize, just the signature size.

How can I get the browser-tomcat connection to use AES-256 with a self signed certificate?

[A]
danivo, so long as the server's cert is capable of AES encryption, the level of encryption between the browser and the server is independent of the cert itself -- that level of encryption is negotiated between the browser and server.  In other words, my understanding is that the cert doesn't specify the level of encryption, just the
type
of encryption (e.g., AES).  See
this link
(PDF) for verification of this, and how the cert resellers upsell "256-bit-capable" certs despite the cert not being what determines 256-bit capability.
So you're just fine with the cert you have that supports AES-128 -- and they key is to figure out how to get Tomcat to support AES-256 (since most, if not all, major browsers certainly support it).


q:
Is there any way to create a ODBC DSN with C#?

Maybe a P/invoke?

[A]
Following resources might be helpful:
MSDN:
How To Use the ODBC .NET Managed Provider in Visual C# .NET and Connection Strings
CodeProject.com
An ODBC (DSN/Driver) Manager DLL written in C#
You can try to invoke functions:
SQLWriteDSNToIni and ConfigDSN (MSDN links are dead for some reason, try to google by functions names)


q:
I'm just getting started with learning about Unit testing (and TDD in general).  My question is does the latest version of NUnit support working in VS2008 with .NET 3.5?  I've looked at the documentation pages at NUnit and they don't mention it.

If anyone has worked with it in 3.5 are there any limitations or features that don't work/need workarounds?

[A] I've been using nUnit with 3.5. As long as you have a version that works with 2.0 you should be fine - same CLR and all that. :)


q:
I have some code which is supposed to display a short message.  Here's the pertinent code:

DATA    SEGMENT 'DATA'
MSG DB  0AH, 0DH, 'Hello, Adam', '$'
CHAR    DB  00H
DATA ENDS

CODE    SEGMENT 'CODE'
PRINT_MSG:
    MOV AH, 09H ;Command to print string of characters
    MOV DX, OFFSET MSG  ;Mov address of message into DX
    INT 21H     ;DOS Interrupt
    JMP WAITING ;Loop back to waiting state
CODE ENDS

And the output is:

E:\ece323\software\lab2>MAIN.EXE
?F ^?¶ ? N?   ?               -!-

Hello, Adam-

What is going on here?

[A]
My guess is that your DS does not point to your data-segment.
Int21 Function 0x09 takes the string from DS:DX.
Remember that DX is only a 16 bit register. To access data outside the 16 bit range you have to use segment registers. These are called DS and ES for data, CS for code and SS for the stack (there are FS and GS on i386 as well).
The exact address you load from is given by 16 * segment_register + offset_register. Int21 cannot guess where your DS is, so you have to load it prior to call the interrupt.
I guess you have never initialized your DS register, so it most likely points to the code, not the data-segment.
Try to replace your
```
```
MOV DX, offset MSG
```
```
by:
```
```
LDS DX, MSG  ; Check that, it's been ages since I've written 16 bit code.
```
```
Unfortunatley it's been years since I've last played with 16 bit assembler, so I can't check it, but LDS should do the trick.
You may also load DS indirectly at your program startup by something like this:
```
```
MOV AX, SEG DATA  ; check that - can be SEGMENT or so as well.
  MOV DS, AX
```
```


q: We are currently testing a Java Swing application for it's performance. I wonder if there is a good tool to automate this?

[A]
A few years ago I used
JMeter
for such a task. I generally enjoyed using it, though I never did much research on what else is available and I don't know if it's still actively developed.


q:
I'm looking for an Access 2007 equivalent to SQL Server's COALESCE function.

In SQL Server you could do something like:

Person

John
Steve
Richard

SQL

DECLARE @PersonList nvarchar(1024)
SELECT @PersonList = COALESCE(@PersonList + ',','') + Person
FROM PersonTable

PRINT @PersonList

Which produces: John, Steve, Richard

I want to do the same but in Access 2007.

Does anyone know how to combine rows like this in Access 2007?

[A]
I think Nz is what you're after, syntax is
```
Nz(variant, [if null value])
```
. Here's the documentation link:
Nz Function
```
```
---Person---
John
Steve
Richard

DECLARE @PersonList nvarchar(1024)
SELECT @PersonList = Nz(@PersonList + ',','') + Person
FROM PersonTable

PRINT @PersonList
```
```


q:
I have a web page that includes a bunch of images. Sometimes the image isn't available, so a broken image is displayed in the client's browser.

How do I use jQuery to get the set of images, filter it to broken images then replace the src?

--I thought it would be easier to do this with jQuery, but it turned out much easier to just use a pure JavaScript solution, that is, the one provided by Prestaul.

[A]
Handle the
```
onError
```
event for the image to reassign its source using JavaScript:
```
```
function imgError(image) {
    image.onerror = "";
    image.src = "/images/noimage.gif";
    return true;
}
```
```
```
```

```
```
Or without a JavaScript function:
```
```

```
```
The following compatibility table lists the browsers that support the error facility:
http://www.quirksmode.org/dom/events/error.html


q:
Has anyone else experienced (and possibly solved) unintentional pitch changes using MS SAPI TTS voices?

I'm using the SpVoice automation interface with SAPI 5.1.

Right now, my application (VB6 app) can get into a state where the TTS (Microsoft Anna) starts to sound like a chipmunk (proper rate, but high pitch) and even a reboot of Vista does not correct the issue.

I'm passing in XML to the Voice.Speak() function. I've tried sending < pitch absmiddle="0" /> before all other XML and it still does not correct the pitch issue. When I try the TTS voice preview in the Speech control panel, the voice has a normal pitch.

The issue has occurred for me in XP in the past, however a reboot seemed to correct it.

[A]
I haven't seen that happen, although my experience is mostly with SAPI 5.3 with SSML, which gets translated (under the covers) to SAPI TTS.
Have you tried surrounding your text with the
```
<pitch absmiddle="0">
```
Your Text Here  instead of just at the front of the text?


q:
I need to reverse engineer a Microsoft SQL Server 2008 in order to create a Microsoft Visio 2007 Database Model Diagram. So I choose "Reverse Engineer" from the Database menu to connect to the DB.

I configured the Microsoft SQL Server Visio driver so that is uses SQL Server Native Client 10.0 as the ODBC driver. Afterwards I created a User DSN which connects to my DB. This DSN works (at least the provided test is successful). After clicking next in the Reverse Engineer Wizard, Visio kindly asks for my credentials which I properly provide, but after clicking OK I receive the following message:

The currently selected Visio driver is not compatible with the data source.

I tried using the old SQL Server ODBC driver, by also reconfiguring the Visio driver of course. It does not work too.

[A]
From
Microsoft support
via the Microsoft forums:
Further investigation reveals that this is expected behavior for Visio 2007. When Visio opens a connection using the Visio SQL Server Driver it checks the server version and since SQL Server 2008 shipped after Visio 2007 it doesn't recognise SQL Server 2008 as a supported version and closes the connection. You can wait for a future version of Visio to ship which does recognise SQL Server 2008 or use the Visio Generic ODBC driver which can successfully open connections to SQL Server 2008. A third option is to use a copy of SQL Server 2005 for initial reverse engineering. The Visio team is aware of this issue.


q:
class A : IFoo
{
}

...

A[] arrayOfA = new A[10];

if(arrayOfA is IFoo[])
{
    // this is not called
}

Q1: Why is arrayOfA not an array of IFoos?

Q2: Why can't I cast arrayOfA to IFoo[]?

[A]
You could try
```
```
if (arrayofA[0] is IFoo) {.....}
```
```
which sort of answers your question.
```
arrayOfA
```
is an array. An array is an object which implements
```
ICloneable
```
,
```
IList
```
,
```
ICollection
```
, &
```
IEnumerable
```
.
```
IFoo
```
isn't among them.


q: I have an announcements list on one site. I want to add it as a web part to the top of each subsite. How can I do this in MOSS?

[A]
I've used the Data View Web Part in this case.  Create a web service data source to get the data from the other site's list.
Much like this:
http://www.sharepointblogs.com/ssa/archive/2007/02/23/showing-web-service-data-in-a-data-view-web-part.aspx


q: I am using CodeDom to generate dynamic code based on user values. One of those values controls what the name of the class I'm generating is. I know I could sterilize the name based on language rules about valid class names using regular expressions, but I'd like to know if there is a specific method built into the framework to validate and/or sterilize a class name.

[A]
I found an answer to my question. I can call
```
```
CodeCompiler.ValidateIdentifiers(class1);
```
```
where class1 is a CodeObject to validate all identifiers in that CodeDom tree and below. So I can call this right after I create my CodeTypeDeclaration class1 to validate just the class name, or I can build up my CodeDom and then call this at the end to validate all the identifiers in my tree. Just what I needed!


q:
I have a Win-CGI application I am currently converting to ISAPI.

The application uses the TDataset descendants for Extended Systems Advantage Database Server.

As there can be only one instance of a TAdsSettings object, this must be
in the main thread.

TAdsQuery objects are needed in the request threads.

Will this work - that is, will the AdsQueries in the request threads
pick up the global settings from the AdsSettings object in the main
thread, and will this be thread safe?

[A]
Make sure the AdsQueries use Synchronize to access the TAdsSettings directly (or use a messaging system to comunicate between worker threads and main thread instead of accessing directly) if they are not in the main thread (i.e.
```
System.MainThreadID <> Windows.GetCurrentThreadID
```
)


q: Does anyone know of an IDE for F# development that does not involve me shelling out $300? I will gladly move to F# VS Express if they ever release one, but spending money to just get started with a new language is not in my budget.

[A]
http://msdn.microsoft.com/en-us/vsx2008/products/bb933751.aspx
Visual Studio Shell - Free, and F# supports it out of the box.
(edited)
http://blogs.msdn.com/dsyme/archive/2008/04/04/tackling-the-f-productization.aspx
Theres a link talking about using the Shell and such too


q:
I've been wondering about the performance improvements touted in Java SE 6 - is it in the compiler or the runtime? Put another way, would a Java 5 application compiled by JDK 6 see an improvement run under JSE 5 (indicating improved compiler optimization)? Would a Java 5 application compiled by JDK 5 see an improvement run under JSE 6 (indicating improved runtime optimization)?

I've noticed that compiling under JDK 6 takes almost twice as long as it did under JDK 5 for the exact same codebase; I'm hoping that at least some of that extra time is being spent on compiler optimizations, hopefully leading to more performant JARs and WARs. Sun's JDK info doesn't really go into detail on the performance improvements they've made - I assume it's a little from column A, and a little from column B, but I wonder which is the greater influence. Does anyone know of any benchmarks done on JDK 6 vs. JDK 5?

[A] Its almost 100% the runtime.  While it is possible for some basic compilation tricks to make it into the Java compiler itself, I don't believe there are any significant improvements between Java 1.5 and 1.6.


q: Why is it that they decided to make String immutable in Java and .NET (and some other languages)? Why didn't they make it mutable?

[A]
It's largely for security reasons.  It's much harder to secure a system if you can't trust that your
```
String
```
s are tamperproof.


q: What is the difference between Object-Oriented Modeling and Object-Oriented Programming? I overheard a conversation on my subway train this morning and it seems that these things are different. Aren't they?

[A]
I'd say the modeling precludes the programing, where the modeling is the physical design, before the programming is implemented.
http://en.wikipedia.org/wiki/Object-Oriented_Modeling
http://en.wikipedia.org/wiki/Object_oriented_programming


q: Need a function that takes a character as a parameter and returns true if it is a letter.

[A]
This was part of the code posted by
rpetrich
in response to a
question
by
Joel Spolsky
.  I felt it needed a post specific to the problem it solves.  It really is brilliant.
```
```
Private Function IsLetter(ByVal character As String) As Boolean
    IsLetter = UCase$(character) <> LCase$(character)
End Function
```
```
You may be thinking to yourself, "Will this always work?"  The documentation on the UCase and LCase functions, confirms that it will:
UCase Function
Only lowercase letters are converted to uppercase;
all uppercase letters and nonletter characters remain unchanged
.
LCase Function
Only uppercase letters are converted to lowercase;
all lowercase letters and nonletter characters remain unchanged
.


q:
I'm importing a MySQL dump and getting the following error.

$ mysql foo < foo.sql
ERROR 1153 (08S01) at line 96: Got a packet bigger than 'max_allowed_packet' bytes

Apparently there are attachments in the database, which makes for very large inserts.

This is on my local machine, a Mac with MySQL 5 installed from the MySQL package.

Where do I change max_allowed_packet to be able to import the dump?

Is there anything else I should set?

Just running mysql --max_allowed_packet=32M … resulted in the same error.

[A]
This can be changed in your
```
my.ini
```
file (on Windows, located in \Program Files\MySQL\MySQL Server) under the server section, for example:
```
```
[mysqld]

max_allowed_packet = 10M
```
```


q:
In our project we have a standard auto-generated designer.cs file, linked to a DBML file, that contains all our object classes that map onto our database tables.

We want to pass these objects directly through a WCF Service and so they need decorating with the [DataContract] and [DataMember] attributes where appropriate. What is the best approach to doing this so the changes won't get wiped out when the designer.cs file is re-generated upon a change to the database scheme or some other change.

Partial classes are an option, but if the property I want to decorate with the DataMember attribute is already defined in the autogenerated designer.cs file then I can't add the same property definition to the partial class as this means the property will have been defined twice.

[A]
The dbml files give partial classes, so you can create a new .cs file, define the partial class that you want to extend, and then decorate that with the attributes that you want. For instance if you have a generated data context that looks like
```
```
public partial class MyDataContext : System.Data.Linq.DataContext
{
...
}
```
```
you can define the following in a separate .cs file:
```
```
[DataContract]
public partial class MyDataContext
{
...
}
```
```
This way you can extend the generated classes without worrying about them being overwritten when your dbml file is re-generated.


q: Apparently you can easily obtain a client IP address in WCF 3.5 but not in WCF 3.0.  Anyone know how?

[A]
This doesn't help you in 3.0, but I can just see people finding this question and being frustrated because they are trying to get the client IP address in 3.5. So, here's some code which should work:
```
```
using System.ServiceModel;
using System.ServiceModel.Channels;

OperationContext context = OperationContext.Current;
MessageProperties prop = context.IncomingMessageProperties;
RemoteEndpointMessageProperty endpoint =
    prop[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty;
string ip = endpoint.Address;
```
```


q:
When using the Eclipse->Team->Show History view, what's the difference between using Subclipse "Get Contents" and "Get Revision" options on a revision of a file?

Is there any way to see what svn commands Subclipse is issuing behind the scenes?

[A]
From the Subclipse manual (Help > Help Contents):
Get Contents
Use this option to update the contents
  of the selected file in your working
  copy with the contents of the revision
  in the repository. The revision number
  of your local file is not changed by
  this option.
This option is only valid when the
  resource history was launched for an
  individual file in a local working
  copy.
Get Revision
Use this option to replace the file in
  your working copy with the selected
  revision in the repository. The
  revision number of your local file is
  changed to the selected revision.
This option is only valid when the
  resource history was launched for an
  individual file in a local working
  copy.
Pretty self-explanatory.


q: I'd like to automatically generate database scripts on a regular basis. Is this possible.

[A]
To generate script for an object you have to pass up to six parameters:
```
```
exec proc_genscript
    @ServerName = 'Server Name',
    @DBName = 'Database Name',
    @ObjectName = 'Object Name to generate script for',
    @ObjectType = 'Object Type',
    @TableName = 'Parent table name for index and trigger',
    @ScriptFile = 'File name to save the script'
```
```
http://www.databasejournal.com/features/mssql/article.php/2205291


q:
Given the code from the Complex Form part III how would you go about testing the virtual attribute?

  def new_task_attributes=(task_attributes)
    task_attributes.each do |attributes|
      tasks.build(attributes)
    end
  end

I am currently trying to test it like this:

  def test_adding_task_to_project
    p = Project.new
    params = {"new_tasks_attributes" => [{ "name" => "paint fence"}]}
    p.new_tasks_attributes=(params)
    p.save
    assert p.tasks.length == 1
  end

But I am getting the following error:

NoMethodError: undefined method `stringify_keys!' for "new_tasks_attributes":String

Any suggestions on improving this test would be greatly appreciated.

[A]
It looks as if new_task_attributes= is expecting an array of hashes, but you're passing it a hash. Try this:
```
```
def test_adding_task_to_project
  p = Project.new
  new_tasks_attributes = [{ "name" => "paint fence"}]
  p.new_tasks_attributes = (new_tasks_attributes)
  p.save
  assert p.tasks.length == 1
end
```
```


q: I recently received an email from my girlfriend that spamassassin marked as spam, mostly because spamassassin detected a tracker ID... except there wasn't one.  I'd like to know what triggered it, so that I can report a sensible bug.


q:
I'm having a problem debugging an Eclipse Application from Eclipse.  When I launch the Debug Configuration, the Eclipse Application starts up and then stops repeatedly.  It shows the splash screen and then disappears.  This is the farthest it gets before restarting:

MyDebugConfiguration [Eclipse Application]
    org.eclipse.equinox.launcher.Main at localhost:2599
        Thread [main] (Running)
        Daemon Thread [Signal Dispatcher] (Running)
        Daemon Thread [State Data Manager] (Running)
        Daemon Thread [Framework Event Dispatcher] (Running)
        Thread [State Saver] (Running)
        Daemon Thread [Start Level Event Dispatcher] (Running)
        Thread [Refresh Packages] (Running)
    C:\MyApp\eclipse\jdk\jre\bin\javaw.exe (Sep 18, 2008 9:38:19 AM)

I am using Version 3.4.0 of the Eclipse SDK.

What is causing this?


q:
I am reading about COFF file formats, which is commonly used to create an executable file format (it has some variants also).

While reading, I came across the relocation section of the format. How is this relocation section used to create an executable file.

It would be very useful if you point me to some links which will help me.

[A]
Relocation is used to place executable code in its own memory space in a process.  For example, if you try to load two dlls that both request the same base address (ie, the same place in memory), then one of the dlls will have to be relocated to another address.
NTCore
is a useful site for exploring Portable Executable (PE) files, which is what COFF is now called.
Here
is another site that explains relocation pretty well.


q:
I have created a foreign key (in SQL Server) by:

alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;

I then run this query:

alter table company drop column CountryID;

and I get this error:

Msg 5074, Level 16, State 4, Line 2

  The object 'Company_CountryID_FK' is dependent on column 'CountryID'.

  Msg 4922, Level 16, State 9, Line 2

  ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column

I have tried this, yet it does not seem to work:

alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;

What do I need to do to drop the CountryID column?

Thanks.

[A]
Try
```
```
alter table company drop constraint Company_CountryID_FK

alter table company drop column CountryID
```
```


q:
I have a rails form with a datetime_select field. When I try to submit the form, I get the following exception:

ActiveRecord::MultiparameterAssignmentErrors in WidgetsController#update
1 error(s) on assignment of multiparameter attributes

If it's a validation error, why don't I see an error on the page?

This is in Rails 2.0.2

[A]
It turns out that rails uses something called Multi-parameter assignment to transmit dates and times in small parts that are reassembled when you assign params to the model instance.
My problem was that I was using a datetime_select form field for a date model field. It apparently chokes when the multi-parameter magic tries to set the time on a Date object.
The solution was to use a
```
date_select
```
form field rather than a
```
datetime_select
```
.


q: I want to make a small app that displays a PDF, presenting zoom-able single pages with a previous-next page function.

[A]
The iPhone and iPod touch can view PDFs already, as one of the TV adverts in the UK shows an email with a .pdf attachment (of swimming lessons) being viewed. It can also view .doc, .xls, and so on, so if he is creating a viewer type application then supporting those as well could be a nice feature addition later on.
This means there is a PDF framework on these devices that you will need to access. Presumably Apple can provide support here if he is a paid up developer. Syncing the PDFs to the device is the actual real difficulty, as this isn't supported by iTunes. I assume that you would need to write a network based synchronisation tool, or have an online cloud for holding people's PDFs.
The device doesn't support Flash, so using PDF to Flash conversion tools will not work.


q:
I'm porting a C++ 32 bit application to 64 bit on windows. The application is a client of IBM WebSphere MQ. It uses the MQ client API.

Now, as the port progresses, I'm trying to find a 64 bit client. So far, no luck.

Does anyone here happen to know if where I can find one or confirm that there isn't one?

[A]
I found this page on IBM's site:
IA94: IBM Message Service Client for C/C++
. On it there is a link to a
readme.txt file
which, under "Supported environments" lists "Windows 2003 Server x64 edition - Microsoft Visual C++ .NET 2005 Service Pack1".
Hope that helps!


q:
I need to make a random list of permutations.  The elements can be anything but assume that they are the integers 0 through x-1.  I want to make y lists, each containing z elements.  The rules are that no list may contain the same element twice and that over all the lists, the number of times each elements is used is the same (or as close as possible).  For instance, if my elements are 0,1,2,3, y is 6, and z is 2, then one possible solution is:

0,3
1,2
3,0
2,1
0,1
2,3

Each row has only unique elements and no element has been used more than 3 times.  If y were 7, then 2 elements would be used 4 times, the rest 3.

[A]
Ok, one way to approximate that:
1 - shuffle your list
2 - take the y first elements to form the next row
4 - repeat (2) as long as you have numbers in the list
5 - if you don't have enough numbers to finish the list, reshuffle the original list and take the missing elements, making sure you don't retake numbers.
6 - Start over at step (2) as long as you need rows
I think this should be as random as you can make it and will for sure follow your criteria. Plus, you have very little tests for duplicate elements.


q:
I saw some code like the following in a JSP

<c:if test="<%=request.isUserInRole(RoleEnum.USER.getCode())%>">
    <li>user</li>
</c:if>

My confusion is over the "=" that appears in the value of the test attribute. My understanding was that anything included within <%= %> is printed to the output, but surely the value assigned to test must be a Boolean, so why does this work?

For bonus points, is there any way to change the attribute value above such that it does not use scriptlet code? Presumably, that means using EL instead.

Cheers,
Don

[A]
Attributes in JSP tag libraries in general can be either static or resolved at request time.  If they are resolved at request time the JSP will resolve their value at runtime and pass the output on to the tag.  This means you can put pretty much any JSP code into the attribute and the tag will behave accordingly to what output that produces.
If you look at the jstl taglib docs you can see which attributes are reuest time and which are not.
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/index.html


q:
I use maxframe.el to maximize my Emacs frames.

It works great on all three major platforms, except on my dual-head Mac setup (Macbook Pro 15-inch laptop with 23-inch monitor).

When maximizing an Emacs frame, the frame expands to fill the width of both monitors and the height of the larger monitor.

Obviously, I would like the frame to maximize to fill only the monitor it's on. How can I detect the resolutions of the two individual monitors using elisp?

Thanks,
Jacob

EDIT: As Denis points out, setting mf-max-width is a reasonable workaround. But (as I should have mentioned) I was hoping for a solution that works on both monitors and with any resolution. Maybe something OSX-specific in the style of the Windows-specific w32-send-sys-command.

[A]
Does customising `mf-max-width' work?  Its documentation:
```
```
"*The maximum display width to support.  This helps better support the true
nature of display-pixel-width.  Since multiple monitors will result in a
very large display pixel width, this value is used to set the stop point for
maximizing the frame.  This could also be used to set a fixed frame size
without going over the display dimensions."
```
```


q:
What is considered as best practice when it comes to assemblies and releases?

I would like to be able to reference multiple versions of the same library - solution contains multiple projects that depend on different versions of a commonutils.dll library we build ourselves.

As all dependencies are copied to the bin/debug or bin/release, only a single copy of commonutils.dll can exist there despite each of the DLL files having different assembly version numbers.

Should I include version numbers in the assembly name to be able to reference multiple versions of a library or is there another way?

[A]
Assemblies can coexist in the GAC (Global Assembly Cache) even if they have the same name given that the version is different. This is how .NET Framework shipped assemblies work. A requirement that must be meet in order for an assembly to be able to be GAC registered is to be signed.
Adding version numbers to the name of the Assembly just defeats the whole purpose of the assembly ecosystem and is cumbersome IMHO. To know which version of a given assembly I have just open the Properties window and check the version.


q:
when an SQL Server Express DB is 'in recovery', you are unable to connect using SQL Authentication.

Is there a simple way of determining the stat of the DB prior to connecting to it?
(Using .Net)

[A]
```
```
SELECT DATABASEPROPERTYEX ('master', 'STATUS') AS 'Status';
```
```
Replace 'master' with your database name


q: Site 1 has dll's for x amount of object and data calls.  Can Site 2 (a separate .net web app) call the objects/dll's of Site 1 ?

[A]
This may be more semantics:
You can't call an object of another process.  You can however potentially instantiate a class within a dll as long as there is a reference to that dll in the calling web application.
If you GAC the dll, the classes (not objects) will be accessible to the entire machine.


q:
The IIS 6.0 is serving my Classical ASP pages in a serial fashion (one at a time)

The #2 request will be handled by the web server only when the #1 request ends.

If the #1 request takes a little longer, the #2 request will have to wait for the #1 ends to starts being handled by IIS.

Is this a missconfiguration in IIS?

The operation system is Windows Server 2003 Standard Edition (Service Pack 2)

[A]
Yes, IIS or the site is most likely configured for server-side debugging, which causes all requests to the site to go through a single thread.
To check if this is the case/turn it off:
In the Properties pages for any Web site or Web virtual directory, click the Home Directory or Virtual Directory tab.
Under Application Settings, click Configuration. An application must be created for the button to be active.
Click the Debugging tab.
Un-check the Enable ASP server-side script debugging check box.
(Above steps were copied from the
Debugging ASP Applications in IIS
KB article)


q: What is the difference between Views and Materialized Views in Oracle?

[A]
Materialized views are disk based and are updated periodically based upon the query definition.
Views are virtual only and run the query definition each time they are accessed.


q: I have a custom user control with a textbox on it and I'd like to expose the baseline (of the text in the textbox) snapline outside of the custom control.  I know that you create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.

[A]
You're on the right track.  You will need to override the SnapLines property in your designr and do something like this:
```
```
Public Overrides ReadOnly Property SnapLines() As System.Collections.IList
    Get
        Dim snapLinesList As ArrayList = TryCast(MyBase.SnapLines, ArrayList)

        Dim offset As Integer
        Dim ctrl As MyControl = TryCast(Me.Control, MyControl)
        If ctrl IsNot Nothing AndAlso ctrl.TextBox1 IsNot Nothing Then
            offset = ctrl.TextBox1.Bottom - 5
        End If

        snapLinesList.Add(New SnapLine(SnapLineType.Baseline, offset, SnapLinePriority.Medium))

        Return snapLinesList

    End Get
End Property
```
```
In this example the usercontrol contains a textbox.  The code adds a new snapline that represents the baseline for the textbox.  The important thing is to calculate the offset correctly.


q:
For example, if I declare a long variable, can I assume it will always be aligned on a "sizeof(long)" boundary? Microsoft Visual C++ online help says so, but is it standard behavior?

some more info:

a. It is possible to explicitely create a misaligned integer (*bar):

char foo[5]

int * bar = (int *)(&foo[1]);

b. Apparently, #pragma pack() only affects structures, classes, and unions.

c. MSVC documentation states that POD types are aligned to their respective sizes (but is it always or by default, and is it standard behavior, I don't know)

[A]
Yes, all types are always aligned to at least their alignment requirements.
How could it be otherwise?
But note that the sizeof() a type is not the same as it's alignment.
You can use the following macro to determine the alignment requirements of a type:
```
```
#define ALIGNMENT_OF( t ) offsetof( struct { char x; t test; }, test )
```
```


q:
is it possible to create java application that will
work as background process on symbian smartphones?

[A]
You can approximate it but J2ME (the version of java on mobile phones) may not be the right technology to do this.
starting a MIDlet (a Java application for mobile phones) when the phone is switched on is tricky at best without coding a small Symbian OS C++ module that will start it for you. If you want to try anyway, look at the PushRegistry class in the MIDP specs
(
http://java.sun.com/javame/reference/apis/jsr118/
). The Content Handling API might provide some way to do it too (
http://java.sun.com/javame/reference/apis/jsr211
). When you are ready to give up, do it in C++.
Backgrounding a MIDlet isn't hard. The phone's "menu" key will do it for you. Programatically, Canvas.setCurrent(null) has a good chance of working. Trying to trick the phone by providing a fully transparent GUI and not handling any keypad activity will absolutely not work. Creating and starting a separate Thread in the MIDlet should allow you to keep something running even after your overload of MIDlet.pauseApp() has been called by the application management system.
The real issue is that the MIDlet will not have any Inter Process Communication system unless you make one. The usual way of doing that is a loopback socket connection over which you transfer data. Not a nice or efficient way of simulating IPC. Sharing a RMS record can only be done from within the same MIDlet suite (you can package several MIDlets into the same .jar file), I think. The code to create a provider/consumer data flow over a file connection is even uglier and will raise security issues.
Without any more information about what you want to use it for, my answer is : maybe but you should probably not try.


q:
I cannot use the Resource File API from within a file system plugin due to a PlatSec issue:

*PlatSec* ERROR - Capability check failed - Can't load filesystemplugin.PXT because it links to bafl.dll which has the following capabilities missing: TCB

My understanding of the issue is that:

File system plugins are dlls which are executed within the context of the file system process.  Therefore all file system plugins must have the TCB PlatSec privilege which in turn means they cannot link against a dll that is not in the TCB.

Is there a way around this (without resorting to a text file or an intermediate server)? I suspect not - but it would be good to get a definitive answer.

[A]
The Symbian file server has the following capabilities:
```
```
TCB ProtServ DiskAdmin AllFiles PowerMgmt CommDD
```
```
So any DLL being loaded into the file server process must have at least these capabilities. There is no way around this, short of writing a new proxy process as you allude to.
However, there is a more fundamental reason why you shouldn't be using
```
bafl.dll
```
from within a fileserver plugin: this DLL provides utility functions which interface to the file servers client API. Attempting to use it from within the filer server will not work; at best, it will lead to the file server deadlocking as it attempts to connect to itself.
I'd suggest rethinking that you're trying to do, and investigating an internal file-server API to achieve it instead.


q:
In a asp.net web application, I want to write to a file.  This function will first get data from the database, and then write out the flat file.

What can I do to make sure only 1 write occurs, and once the write occurrs, the other threads that maybe want to write to the file don't since the write took place.

I want to have this write done ONLY if it hasn't been done in say 15 minutes.

I know there is a lock keyword, so should I wrap everything in a lock, then check if it has been updated in 15 minutes or more, or visa versa?

Update

Workflow:

Since this is a web application, the multiple instances will be people viewing a particular web page.  I could use the build in cache system, but if asp.net recycles it will be expensive to rebuild the cache so I just want to write it out to a flat file.  My other option would be just to create a windows service, but that is more work to manage that I want.

[A]
Synchronize your writing code to lock on a shared object so that only one thread gets inside the block. Others wait till the current one exits.
```
```
lock(this)
{
  // perform the write.
}
```
```
Update: I assumed that you have a shared object. If these are different processes on the same machine, you'd need something like a Named Mutex.
Looky here for an example


q:
I have a list with two <div>s in every <li> and I want to float them one next to the other and I want the <li> to take the whole availabe space. How do I do it?

<html>
    <head>
        <title></title>
        <style type="text/css">
            body {
            }
            ul {
            }
            li {
            }
            .a {
            }
            .b {
            }
        </style>
    </head>
    <body>
        <ul>
            <li>
                <div class="a">
                    content
                </div>
                <div class="b">
                    content
                </div>
            </li>
        </ul>
    </body>
</html>

[A]
```
```
li{width:100%;}
.a{}
.b{float: left;}
```
```
That should do as required from my knowledge of CSS


q:
I have a CakePHP application that in some moment will show a view with product media (pictures or videos) I want to know if, there is someway to include another view that threats the video or threats the pictures, depending on a flag. I want to use those "small views" to several other purposes, so It should be "like" a cake component, for reutilization.

What you guys suggest to use to be in Cake conventions (and not using a raw include('') command)

[A]
In the interest of having the information here in case someone stumbles upon this, it is important to note that the solution varies depending on the CakePHP version.
For CakePHP 1.1
```
$this->renderElement('display', array('flag' => 'value'));
```
in your view, and then in
```
/app/views/elements/
```
you can make a file called
```
display.thtml
```
, where
```
$flag
```
will have the value of whatever you pass to it.
For CakePHP 1.2
```
$this->element('display', array('flag' => 'value'));
```
in your view, and then in
```
/app/views/elements/
```
you can make a file called
```
display.ctp
```
, where
```
$flag
```
will have the value of whatever you pass to it.
In both versions the element will have access to all the data the view has access to + any values you pass to it. Furthermore, as someone pointed out,
```
requestAction()
```
is also an option, but it can take a heavy toll in performance if done without using cache, since it has to go through all the steps a normal action would.


q:
I have a WPF app with many list based controls in a window, which all are bound to different CollectionViews.

At the window level is there a way to get the current selected item for the currently in focus list based control?  I know I can do this with some fairly trivial code by looking for the in focus element but does WPF support this as a concept out of the box?

Something like Window.CurrentSelectedDataItem would be great.  I am looking into using this as a way to centralize command management for enabling disabling commands based on a current selected data item.

[A]
I don't think that there is a property like you specify, but as an alternative you could register a ClassHandler for the ListBox.SelectionChanged event in your Window class:
```
```
EventManager.RegisterClassHandler(typeof(ListBox), ListBox.SelectionChanged,
    new SelectionChangedEventHandler(this.OnListBoxSelectionChanged));
```
```
This will get called whenever the selection changes in any ListBox in your application. You can use the sender argument to determine which ListBox it was that changed its selection, and cache this value for when you need it.


q:
We require all requests for downloads to have a valid login (non-http) and we generate transaction tickets for each download. If you were to go to one of the download links and attempt to "replay" the transaction, we use HTTP codes to forward you to get a new transaction ticket. This works fine for a majority of users. There's a small subset, however, that are using Download Accelerators that simply try to replay the transaction ticket several times.

So, in order to determine whether we want to or even can support download accelerators or not, we are trying to understand how they work.

How does having a second, third or even fourth concurrent connection to the web server delivering a static file speed the download process?

What does the accelerator program do?

[A]
From:
http://askville.amazon.com/download-accelerator-protocol-work-advantages-benefits-application-area-scope-plz-suggest-URLs/AnswerViewer.do?requestId=9337813
Quote:
The most common way of accelerating downloads is to open up parllel downloads. Many servers limit the bandwith of one connection so opening more in parallel increases the rate. This works by specifying an offset a download should start which is supported for HTTP and FTP alike.
Of course this way of acceleration is quite "unsocial". The limitation of bandwith is implemented to be able to serve a higher number of clients so using this technique lowers the maximum number of peers that is able to download. That's the reason why many servers are limiting the number of parallel connection (recognized by IP), e.g. many FTP-servers do this so you run into problems if you download a file and try to continue browsing using your browser. Technically these are two parallel connections.
Another technique to increase the download-rate is a peer-to-peer-network where different sources e.g. limited by asynchron DSL on the upload-side are used for downloading.


q: How do you apply stroke (outline around text) to a textblock in xaml in WPF?

[A]
In Blend you could convert the TextBlock to a Path, and then use the normal Stroke properties.  But I'm assuming you wanted something that you could make dynamic...
Otherwise I would think it would have to be some sort of bitmap effect or special brush.