Question:
All,

I currently have my solution comprising of 2 Class librarys and a Web Site building within teamCity using Msbuild. Now I want to precompile the website and make it available as an artifact. However when i try to Precompile it using

<Target Name="PrecompileWeb" DependsOnTargets="Build">
    <AspNetCompiler
        PhysicalPath="$(BuildDir)\Location\"
        TargetPath="$(BuildDir)\Publish"
        Force="true"
        Debug="true"

        />
  </Target>

I get an error becasue it is looking for a virtual path (which i don't have as all I want to do it precompile the files I am not interested in publishing the site) if I put a dummy path in I get another error (correctly) about it not being an application under IIS

Any ideas

Answer:
Is this a Web Site or Web Application Project? If the latter, instead of doing an AspNetCompiler task, do an MSBuild task to the csproj/vbproj file, calling the targets
```
Rebuild;ResolveReferences;_CopyWebApplication
```
and specifying the
```
OutDir
```
property.
If you are using a website, then specify the VirtualPath to be a valid IIS path. What is happening is that, when you don't specify the VirtualPath property, it tries to resolve it using the PhysicalPath and IIS. I believe that's just an artifact of how the AspNetCompiler works.


Question:
I'm preparing a string that will be eval'ed. The string will contain a clause built from an existing Array. I have the following:

def stringify(arg)
    return "[ '" + arg.join("', '") + "' ]" if arg.class == Array
    "'#{arg}'"
end

a = [ 'a', 'b', 'c' ]
eval_str = 'p ' + stringify(a)
eval(eval_str)

which prints the string ["a", "b", "c"].

Is there a more idiomatic way to do this? Array#to_s doesn't cut it. Is there a way to assign the output from the p method to a variable?

Thanks!

Answer:
I may be misunderstanding you, but does this look better at all?
```
```
>> a = %w[a b c]
=> ["a", "b", "c"]
>> r = "['#{a.join("', '")}']"
=> "['a', 'b', 'c']"
>> r.class
=> String
```
```
I suppose I'm confused by the need for eval, unless that's a part of something outside of what I see here.


Question:
I need a method to return a random string in the format:

Letter Number Letter  Number Letter Number

Answer:
You just need 2 methods.
1) Random a char (You can use
ASCII
to random between number than cast to char)
2) Random number.
Both can use this utility method:
```
```
private int RandomNumber(int min, int max)
{
    Random random = new Random();
    return random.Next(min, max);
}
```
```
For the letter you need to call
```
RandomNumber(65,90);
```
and for the number you call :
```
RandomNumber(1,9);
```
You just need to concatenate.
Than you call these methods to create your string, Hope this help you.
Update
You should put the random object in your class... it was just to show you how to do it. You still need to work a little but I think it's a good start to show you how to manipulate char from ascii.


Question:
What is the proper way to split up SQL statements to send to an Oracle ADO.NET client?  For instance, lets say you have the following code in a text file and want to execute these statements:

CREATE TABLE foo (bar VARCHAR2(100));
INSERT INTO foo (bar) VALUES('one');
INSERT INTO foo (bar) VALUES('two');

I believe trying to send all those in one Command will cause Oracle to complain about the ";".  My first thought would be to split on ";" character, and send them one at a time.

But, Stored procedures can contain semi-colons as well, so how would I make it so the split routine would keep the whole stored proc together?  Does it need to look for begin/end statements as well, or "/"?

Is there any difference in these respects between ODP.NET and the Micrsoft Oracle Provider?

Answer:
Without the DDL, you could create an anonymous PL/SQL block by surrounding the statements with BEGIN and END:
```
```
BEGIN
  INSERT INTO foo (bar) VALUES('one');
  INSERT INTO foo (bar) VALUES('two');
END;
```
```
To perform DDL (like CREATE TABLE) you would need to use dynamic PL/SQL:
```
```
BEGIN
  EXECUTE IMMEDIATE 'CREATE TABLE foo (bar VARCHAR2(100))';
  EXECUTE IMMEDIATE 'INSERT INTO foo (bar) VALUES(:v)' USING 'one';
  EXECUTE IMMEDIATE 'INSERT INTO foo (bar) VALUES(:v)' USING 'two';
END;
```
```
The INSERTS are also dynamic, as the table does not exist prior to running the block and so it would fail to compile.
NOTE: This would be an unusual requirement: applications should not normally be creating tables!


Question:
It is really annoying.

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new mainForm()); <-- pausing visual studio breaks here.

Thanks guys.

Answer:
@sramey are you sure pausing always breaks on the said line? If I may hazard a guess here I think when you press the pause button you application is idle and the program is spending most of its time in the Win32 message loop abstracted by Application.Run(). Hence there is a high probability that VS breaks the execution of the main thread there.
I think pressing pause is not always the best way of debugging things. You need to make educated guesses about problem areas and set breakpoints in relevant methods (like Constructors, API calls etc)
Need more info on what you are trying to accomplish here.


Question: In a comment on this answer to another question, someone said that they weren't sure what functools.wraps was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?

Answer:
When you use a decorator, you're replacing one function with another.  In other words, if you have a decorator
```
```
def logged(func):
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging
```
```
then when you say
```
```
@logged
def f(x):
   """does some math"""
   return x + x * x
```
```
it's exactly the same as saying
```
```
def f(x):
    """does some math"""
    return x + x * x
f = logged(f)
```
```
and your function
```
f
```
is replaced with the function
```
with_logging
```
.  Unfortunately, this means that if you then say
```
```
print(f.__name__)
```
```
it will print
```
with_logging
```
because that's the name of your new function.  In fact, if you look at the docstring for
```
f
```
, it will be blank because
```
with_logging
```
has no docstring, and so the docstring you wrote won't be there anymore.  Also, if you look at the pydoc result for that function, it won't be listed as taking one argument
```
x
```
; instead it'll be listed as taking
```
*args
```
and
```
**kwargs
```
because that's what with_logging takes.
If using a decorator always meant losing this information about a function, it would be a serious problem.  That's why we have
```
functools.wraps
```
.  This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc.  And since
```
wraps
```
is itself a decorator, the following code does the correct thing:
```
```
from functools import wraps
def logged(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging

@logged
def f(x):
   """does some math"""
   return x + x * x

print(f.__name__)  # prints 'f'
print(f.__doc__)   # prints 'does some math'
```
```


Question:
I have a small ajax php application, which outputs data from a mysql db into a table. The rows are links, which when clicked will call an ajax function, which in turn will call another php file, which displays a different query from the same database in a layer without reloading the page.

I would like to know how to synchronize queries between both php files. So when I click on a row in the base page, the layer will be expanded to include additional information, or indeed the whole query.

I was thinking I could do this by having the primary key in the first query for the table, however I don't want it displayed and was wondering if there was a better approach to this?

Answer:
You don't want it displayed, does that mean for security issues or something else.
If you want to lose the primary key in the table you can go with a query cache placed into  a session object and then just retreive by place in array.
so something like:
page1:
create array with db objects
store array into session
display objects in table
add display layer function for eachrow in table using the index from the array as a parameter.
page2:
retrieve session object
show data for array spot


Question:
I'd like to find all the types inheriting from a base/interface. Anyone have a good method to do this? Ideas?

I know this is a strange request but its something I'm playing with none-the-less.

Answer:
Use Assembly.GetTypes() to get all the types, and Type.IsAssignableFrom() to check for inheritance. Let me know if you need code - and also whether or not you're using .NET 3.5. (A lot of reflection tasks like this are simpler with LINQ to Objects.)
EDIT: As requested, here's an example - it finds everything in
```
mscorlib
```
which implements
```
IEnumerable
```
. Note that life is somewhat harder when the base type is generic...
```
```
using System;
using System.Collections;
using System.Linq;
using System.Reflection;

class Test
{
    static void Main()
    {
        Assembly assembly = typeof(string).Assembly;
        Type target = typeof(IEnumerable);
        var types = assembly.GetTypes()
                            .Where(type => target.IsAssignableFrom(type));

        foreach (Type type in types)
        {
            Console.WriteLine(type.Name);
        }
    }
}
```
```


Question: How (i.e. using which API) is the virtual keyboard opened on Symbian S60 5th edition? The documentation seems to lack information about this.

Answer:
You are right, this should obviously be a published API and it should be highlighted in the documentation. No such luck.
If you are using one of the platform native controls, the virtual keyboard will automatically popup when the user accesses a text-editing control.
If you are making a custom control, you need to deal with its selection by adding your own version of the virtual keyboard: make a new text-editing, window-owning virtual keyboard look-alike custom control with the right buttons. Reuse it accross all your applications. One day, Nokia will realize they have made an obvious mistake and make the API publicly available.
If you are using direct screen access, well, you wouldn't exactly expect the very s60-looking virtual keyboard to popup out of nowwhere. Again, draw a nice image on the screen to let the user know where the virtual keys are and react to pointer events. This is going to be less reusable unless you build a good amount of customization (background, button edges...) into it.
EDIT: Nokia may be relying on Qt to fix this issue. I would expect the control to be part of the current 4.7 version of Qt.


Question:
I'm optimizing a directx graphics application to take advantage of nVidia's SLI technology.  I'm currently investigating some of the techniques mentioned in their 'Best Practices' web page, but wanted to know what advice/experience any of you have had with this?

Thanks!

Answer:
This is not really an answer to you question, more of a comment on SLI.
My understanding is that SLI is only really a cost-effective means of gaining performance when you buy two cards right away, which few people actually do. Many people buy an SLI motherboard and card thinking it will give them a better upgrade path down the road, but the reality is that by the time you get to that point, it is going to be cheaper to buy a new, faster card, than it is to duplicate the one you already have just to get SLI going.
Just a thought before you pour too much energy into it. If you have a requirement to support SLI, then that's what you have to do. But personally, I would rather see optimization energy put towards non-SLI implementations.


Question: How do I get the GridView control to render the <thead> <tbody> tags? I know .UseAccessibleHeaders makes it put <th> instead of <td>, but I cant get the <thead> to appear.

Answer:
This should do it:
```
```
gv.HeaderRow.TableSection = TableRowSection.TableHeader;
```
```


Question:
I got the following class :

class ConstraintFailureSet(dict, Exception) :
    """
        Container for constraint failures. It act as a constraint failure itself
        but can contain other constraint failures that can be accessed with a dict syntax.
    """

    def __init__(self, **failures) :
        dict.__init__(self, failures)
        Exception.__init__(self)

print isinstance(ConstraintFailureSet(), Exception)
True
raise ConstraintFailureSet()
TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet

What the heck ?

And the worst is that I can't try super() since Exception are old based class...

EDIT : And, yes, I've tried to switch the order of inheritance / init.

EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...

Answer:
What version of Python?
In 2.5.1, I can't even define a class the inherits from both
```
dict
```
and
```
Exception
```
:
```
```
>>> class foo(dict, Exception):
...   pass
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
    multiple bases have instance lay-out conflict
```
```
If you're using an older version, maybe it doesn't do this check during type definition and the conflict causes oddities later on.


Question:
When generating graphs and showing different sets of data it usually a good idea to difference the sets by color. So one line is red and the next is green and so on. The problem is then that when the number of datasets is unknown one needs to randomly generate these colors and often they end up very close to each other (green, light green for example).

Any ideas on how this could be solved and how it would be possibler to generate distinctly different colors?

I'd be great if any examples (feel free to just discuss the problem and solution without examples if you find that easier) were in C# and RGB based colors.

Answer:
I would start with a set brightness 100% and go around primary colors first:
FF0000, 00FF00, 0000FF
then the combinations
FFFF00, FF00FF, 00FFFF
next for example halve the brightness and do same round. There's not too many really clearly distinct colors, after these I would start to vary the line width and do dotted/dashed lines etc.


Question:
Is there a way to link to a chm file, and therein to a certain topic, from a Microsoft Word docx document? Something in the lines of:

"For more information about this Property see [link ref="./SomeDirectory/somedocument.chm!Sometopic.Somesubtopic" text="MyClass.MyProperty"]

Answer:
You should be able to do it by setting the hyperlink to the file and use the "#" header anchor (I'm not sure what it is called...) but here is an example:
```
```
C:\Helpfiles\Help.chm#Topic
```
```


Question: Is it a simple case of just never using the this.XYZ construct?

Answer:
It's only considered poor style if it violates your style guidelines. Sometimes using
```
this
```
is necessary to qualify a member variable over a local variable:
```
```
public MyType(int arg)
{
    this.arg = arg;
}
```
```
This problem can also be mitigated with style guidelines. For example, prefix members with "_":
```
```
public MyType(int arg)
{
    _arg = arg;
}
```
```


Question: Let's say I have an int with the value of 1. How can I convert that int to a zero padded string, such as 00000001?

Answer:
Another way is:
```
```
DECLARE @iVal int = 1
select REPLACE(STR(@iVal, 8, 0), ' ', '0')
```
```


Question:
I used a new Date() object to fill a field in a MySQL DB, but the actual value stored in that field is in my local timezone.

How can I configure MySQL to store it in the UTC/GMT timezone?

I think, configuring the connection string will help but I don't know how. There are many properties in the connection string like useTimezone, serverTimzone, useGmtMillisForDatetimes, useLegacyDatetimeCode, ...

Answer:
Well, if we're talking about using
```
PreparedStatement
```
s, there's a
form of setDate
where you can pass in a Calendar set to a particular time zone.
For instance, if you have a PreparedStatement named stmt, a Date named date, and assuming the date is the second parameter:
```
```
stmt.setDate(2, date, Calendar.getInstance(TimeZone.getTimeZone("GMT")));
```
```
The best part is, even if GMT is an invalid time zone name, it still returns the GMT time zone because of the default behavior of getTimeZone.


Question: Is the index value of the first record in a dbf file 0 or 1?  Is the index zero-based?

Answer:
i'm not sure but this might give you a clue.
http://www.dbase.com/knowledgebase/int/db7_file_fmt.htm
1.3.1 Standard Property and Constraint Descriptor Array
Table field offset - base one. 01 for
    the first field in the table, 02 for
    the second field, etc. Note: this will
    be 0 in the case of a constraint.


Question:
Currently this expression "I ([a-zA-z]\d]{3} " returns when the following pattern is true:

I AAA
I Z99

I need to modify this so it will return a range of alphanumerics after the I from 2 to 13 that do not have a space.

Example:

I AAA
I A321
I ASHG310310

Thanks,

Dave

Answer:
Without the quotes:
```
"I ([a-zA-Z\d]{2,13}) "
```


Question:
I have an enum construct like this:

public enum EnumDisplayStatus
{
    None    = 1,
    Visible = 2,
    Hidden  = 3,
    MarkedForDeletion = 4
}

In my database, the enumerations are referenced by value. My question is, how can I turn the number representation of the enum back to the string name.

For example, given 2 the result should be Visible.

Answer:
You can convert the
```
int
```
back to an enumeration member with a simple cast, and then call
```
ToString()
```
:
```
```
int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();
```
```


Question:
Say I have a xml document that looks like this

<foo>
<bar id="9" />
<bar id="4" />
<bar id="3" />
</foo>

I would like to use linq to reset the id's to 0, 1 ,2.
What would be the easiest way to do this?

Thanks

Answer:
```
```
XElement xml = GetXml();
var i = 0;
foreach (var e in xml.Elements("bar"))
  e.SetAttributeValue("id", i++);
```
```


Question:
Currently, we're storing the user's HTTP_REFERER so we can redirect the user back to the previous page they were browsing before they logged in.

Http Referer comes from the client and can be spoofed or blank. Is there a more secure/reliable method to deliver this handy user redirect?

Answer:
somehow running
```
```
history.go(-1);
```
```
is the only alternative i can think of (javascript)


Question:
Is there any way to install Setuptools for Python 2.6 in Windows without having an exe installer?

There isn't one built at the moment, and the maintainer of Setuptools has stated that it will probably be a while before he'll get to it.

Does anyone know of a way to install it anyway?

Answer:
First Option - Online Installation (i.e. remaining connected to the Internet during the entire installation process):
Download
setuptools-0.6c9.tar.gz
Use
7-zip
to extract it to a folder(directory) outside your Windows Python installation folder
Go the folder (refer step 2) and run ez_setup.py from the corresponding dos (command) prompt
Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Second Option:
Download
setuptools-0.6c9.tar.gz
Download
setuptools-0.6c9-py2.6.egg
to a folder(directory) outside your Windows Python installation folder
Use
7-zip
to extract ez_setup.py in the same folder as
setuptools-0.6c9-py2.6.egg
Go to the corresponding dos prompt and run python ez_setup.py setuptools-0.6c9-py2.6.egg from the command prompt
Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory
Third Option (assuming that you have Visual Studio 2005 or MinGW on your machine)
Download
setuptools-0.6c9.tar.gz
Use
7-zip
to extract it to a folder(directory) outside your Windows Python installation folder
Go the folder (refer step 2) and run python setup.py install from the corresponding dos (command) prompt
Please provide feedback.


Question:
I'm using PayPal Website Payments Standard.  Whenever the user lands on PayPal with the variables I sent, it shows a PayPal Login form and at the bottom it shows "Don't have a PayPal account? Use your credit card or bank account (where available)."

I want it to default to always ask for credit card and maybe say "Have PayPal?  Use that!".  Any ideas?

Answer:
On
a thread in the PayPal Developer Community
they explain it with cookies based visits to the checkout page.
Basically if PayPal detects you being a user and spots their cookie, they will show the login form by default.
If they can't see that cookie, then they will show the credit card option first with a note that if you already have a PayPal account, to log in.
So the answer is no.


Question:
If you have a java.io.InputStream object, how should you process that object and produce a String?

Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) {
// ???
}

Answer:
A nice way to do this is using
Apache commons
```
IOUtils
```
to copy the
```
InputStream
```
into a
```
StringWriter
```
... something like
```
```
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();
```
```
or even
```
```
// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding);
```
```
Alternatively, you could use
```
ByteArrayOutputStream
```
if you don't want to mix your Streams and Writers


Question:
I'm developing an iPhone app. A simple image is the background of the main view.
I've set an UIImageView in the background and set an image in, using IB.

the image is a 160dpi PNG image. It appears like CRAP in IB. When running in the simulator it is ok, crisp.

How am I supposed to work and place my controls precisely on a such poor resolution image ?
Is this a bug ?

Thanks for you help!

Answer: IB is not a tool for designing a UI, it is a tool for implementing one. It is designed to perform well rather than display well (this is more important in complex desktop UI design than mobile but the tool is the same for both). The best advice is perhaps to take a cue from the publishing world (where this is a common practice for applications that display large amounts of high resolution graphics such as Adobe InDesign) and keep track of exact measurements for controls - the x,y coordinate positions and height/width. Then you can use the inspector to precisely position controls.


Question:
I'm currently using Win32ShellFolderManager2 and ShellFolder.getLinkLocation to resolve windows shortcuts in Java. Unfortunately, if the Java program is running as a service under Vista, getLinkLocation, this does not work. Specifically, I get an exception stating "Could not get shell folder ID list".

Searching the web does turn up mentions of this error message, but always in connection with JFileChooser. I'm not using JFileChooser, I just need to resolve a .lnk file to its destination.

Does anyone know of a 3rd-party parser for .lnk files written in Java I could use?

I've since found unofficial documentation for the .lnk format here, but I'd rather not have to do the work if anyone has done it before, since the format is rather scary.

Answer:
The code plan9assembler linked to appears to work with minor modification. I think it's just the "
```
& 0xff
```
" to prevent sign extension when
```
byte
```
s are upcast to
```
int
```
s in the
```
bytes2short
```
function that need changing. I've added the functionality described in
http://www.i2s-lab.com/Papers/The_Windows_Shortcut_File_Format.pdf
to concatenate the "final part of the pathname" even though in practice this doesn't seem to be used in my examples. I've not added any error checking to the header or dealt with network shares. Here's what I'm using now:
```
```
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class LnkParser {

    public LnkParser(File f) throws Exception {
        parse(f);
    }

    private boolean is_dir;

    public boolean isDirectory() {
        return is_dir;
    }

    private String real_file;

    public String getRealFilename() {
        return real_file;
    }

    private void parse(File f) throws Exception {
        // read the entire file into a byte buffer
        FileInputStream fin = new FileInputStream(f);
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        byte[] buff = new byte[256];
        while (true) {
            int n = fin.read(buff);
            if (n == -1) {
                break;
            }
            bout.write(buff, 0, n);
        }
        fin.close();
        byte[] link = bout.toByteArray();

        // get the flags byte
        byte flags = link[0x14];

        // get the file attributes byte
        final int file_atts_offset = 0x18;
        byte file_atts = link[file_atts_offset];
        byte is_dir_mask = (byte) 0x10;
        if ((file_atts & is_dir_mask) > 0) {
            is_dir = true;
        } else {
            is_dir = false;
        }

        // if the shell settings are present, skip them
        final int shell_offset = 0x4c;
        final byte has_shell_mask = (byte) 0x01;
        int shell_len = 0;
        if ((flags & has_shell_mask) > 0) {
            // the plus 2 accounts for the length marker itself
            shell_len = bytes2short(link, shell_offset) + 2;
        }

        // get to the file settings
        int file_start = 0x4c + shell_len;

        // get the local volume and local system values
        final int basename_offset_offset = 0x10;
        final int finalname_offset_offset = 0x18;
        int basename_offset = link[file_start + basename_offset_offset]
                                + file_start;
        int finalname_offset = link[file_start + finalname_offset_offset]
                                + file_start;
        String basename = getNullDelimitedString(link, basename_offset);
        String finalname = getNullDelimitedString(link, finalname_offset);
        real_file = basename + finalname;
    }

    private static String getNullDelimitedString(byte[] bytes, int off) {
        int len = 0;
        // count bytes until the null character (0)
        while (true) {
            if (bytes[off + len] == 0) {
                break;
            }
            len++;
        }
        return new String(bytes, off, len);
    }

    /*
     * convert two bytes into a short note, this is little endian because it's
     * for an Intel only OS.
     */
    private static int bytes2short(byte[] bytes, int off) {
        return ((bytes[off + 1] & 0xff) << 8) | (bytes[off] & 0xff);
    }
}
```
```


Question:
How can I initialize a const / static array of structs as clearly as possible?

class SomeClass
{

    struct MyStruct
    {
        public string label;
        public int id;
    };

    const MyStruct[] MyArray = {
          {"a", 1}
          {"b", 5}
          {"q", 29}
    };
};

Answer:
Firstly, do you
really
have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with
```
ValueTuple
```
) but they're pretty rare in my experience.
Other than that, I'd just create a constructor taking the two bits of data:
```
```
class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}
```
```
Note the use of
ReadOnlyCollection
instead of exposing the array itself - this will make it immutable, avoiding
the problem exposing arrays directly
. (The code show does initialize an array of structs - it then just passes the reference to the constructor of
```
ReadOnlyCollection<>
```
.)


Question:
My company has a requirement that all production sites pass an AppScan security scan. Sometimes, when we scan a SharePoint installation, the software detects a blind SQL injection vulnerability. I'm pretty sure this is a false positive--AppScan is probably interpreting some other activity in the HTTP response as success of the blind injection. But it's difficult to prove that this is the case.

I suspect that SharePoint, both MOSS 07 and WSS 3.0, uses stored procedures exclusively behind the scenes. Does anyone know if there is any documentation from Microsoft to this effect, and furthermore, whether any of the stored procedures use dynamically-generated SQL? If everything were sprocs, and none of them dynamic, we would have pretty good evidence that SharePoint has no SQL injection vulnerability.

Answer:
They aren't all stored procs. In particular, things like cross-lists joins produce some horrendous syntax. For an example, look at the SQL Trace window from
this article
. Also, since both user controls and API calls can be written by developers, there is no guarantee that you aren't subject to SQL Injection if you are using custom modules.
My guess would be that SharePoint always uses, at the very least, named parameters. However, your best option might to be running a SQL trace and comparing the results. Also, if you are a large enough customer, you might just try calling your local MSFT evangelist (or posting a question on
connect.microsoft.com
) and seeing if you can get a response.


Question:
(This is related to Floor a date in SQL server.)

Does a deterministic expression exist to floor a DATETIME? When I use this as a computed column formula:

DATEADD(dd, DATEDIFF(dd, 0, [datetime_column]), 0)

the I get an error when I place an index on that column:

Cannot create index because the key column 'EffectiveDate' is non-deterministic or imprecise.

But both DATEDIFF and DATEADD are deterministic functions by definition. Where is the catch? Is it possible?

Answer:
Does your column [datetime_column] have a default value set to "getDate()" ??
If so, since getdate() function is non-deterministic, this will cause this error...
Whether a user-defined function is deterministic or nondeterministic depends on how the function is coded. User-defined functions are deterministic if:
The function is schema-bound.
All built-in or user-defined
functions called by the user-defined
function are deterministic.
The body of the function references
no database objects outside the
scope of the function. For example,
a deterministic function cannot
reference tables other than table
variables that are local to the
function.
The function does not call any
extended stored procedures.
User-defined functions that do not meet these criteria are marked as nondeterministic. Built-in nondeterministic functions are not allowed in the body of user-defined functions.


Question:
I have a webservice @ http://recpushdata.cyndigo.com/Jobs.asmx but I'm not able to access it though I am adding it as a WebReference properly.

Any Help would be great.

Answer:
Does your column [datetime_column] have a default value set to "getDate()" ??
If so, since getdate() function is non-deterministic, this will cause this error...
Whether a user-defined function is deterministic or nondeterministic depends on how the function is coded. User-defined functions are deterministic if:
The function is schema-bound.
All built-in or user-defined
functions called by the user-defined
function are deterministic.
The body of the function references
no database objects outside the
scope of the function. For example,
a deterministic function cannot
reference tables other than table
variables that are local to the
function.
The function does not call any
extended stored procedures.
User-defined functions that do not meet these criteria are marked as nondeterministic. Built-in nondeterministic functions are not allowed in the body of user-defined functions.


Question:
I would like to generate a list of files within a directory. Some of the filenames contain Chinese characters.

eg: [试验].Test.txt

I am using the following code:

require 'find'
dirs = ["TestDir"]
for dir in dirs
    Find.find(dir) do |path|
    if FileTest.directory?(path)
    else
        p path
    end
    end
end

Running the script produces a list of files but the Chinese characters are escaped (replaced with backslashes followed by numbers). Using the example filename above would produce:

"TestDir/[\312\324\321\351]Test.txt" instead of "TestDir/[试验].Test.txt".

How can the script be altered to output the Chinese characters?

Answer:
Ruby needs to know that you are dealing with unicode in your code. Set appropriate character encoding using KCODE, as below:
```
```
$KCODE = 'utf-8'
```
```
I think utf-8 is good enough for chinese characters.


Question:
GWT seems like a really nice technology for Java developers who don't like (or don't know) HTML/JS/CSS to build rich web interfaces. On the server-side Grails also looks really nice, it's often described as "Rails for Java developers". I've read that Grails' "convention over configuration" approach, together with the benefits of dynamic languages (Groovy) can really reduce the amount of (boilerplate) code that needs to be written, while still leveraging best-of-breed Java technologies such as Spring and Hibernate.

Anyway, I haven't read much about how well these technologies play together. How easy is it to integrate GWT with Grails on the server-side? I'd be interested to learn about experiences of anyone that has build an application with these technologies? Recommendations on resources (books/websites) for building a GWT-Grails website would also be very welcome.

Cheers,
Don

Answer:
with the benefits of dynamic languages
  (Groovy) can really reduce the amount
  of (boilerplate) code that needs to be
  written
That's what folks from RoR camp was preaching all the time. After some initial boom RoR projects got into inevitable trouble with bigger projects. The bigger projects the more work one should delegate to compiler, i.e. the more valuable are static languages. Currently, RoR boom is all but gone.
The amount of (extra) code you need to write now with JPA/Hibernate, for instance, is almost zero. Annotations only. It even finds the mapped beans itself, in runtime, via classpath! SpringFramework makes many other "boilerplate" codepieces obsolete too.
In my GWT project (one so far, have to admit) I use JPA (Hibernate), DAO layer, business delegate pattern and it's easy and robust.


Question: I'm using the StAX event based API's to modify an XML stream. The stream represents an HTML document, complete with DTD declaration. I would like to copy this DTD declaration into the output document (written using an XMLEventWriter). When I ask the factory to disregard DTD's it will not download the DTD, but remove the whole statement and only leave a "<!DOCUMENTTYPE" string. When not disregarding, the whole DTD gets downloaded, and included when verbatim outputting the DTD event. I don't want to use the time to download this DTD, but include the complete DTD specification (resolving entities is already disabled and I don't need that). Does anyone know how to disable the fetching of external DTD's.

Answer:
You should be able to implement a custom XMLResolver that redirects attempts to fetch external DTDs to a local resource (if your code parses only a specific doc type, this is often a class resource right in a JAR).
```
```
class CustomResolver implements javax.xml.stream.XMLResolver {

  public Object resolveEntity(String publicID,
                              String systemID,
                              String baseURI,
                              String namespace)
                  throws XMLStreamException
  {
    if ("The public ID you expect".equals(publicID)) {
      return getClass().getResourceAsStream("doc.dtd");
    } else {
      return null;
    }
  }
```
```
Note that some documents only include the "systemID", so you should fall back to checking that. The problem with system identifier is that it's supposed to be "system" specific URL, rather than a well-known, stable URI. In practice, it's often used as if it were a URI though.
See the
setXMLResolver
method.


Question: What is the difference between a const_iterator and an iterator and where would you use one over the other?

Answer:
```
const_iterator
```
s don't allow you to change the values that they point to, regular
```
iterator
```
s do.
As with all things in C++, always prefer
```
const
```
, unless there's a good reason to use regular iterators (i.e. you want to use the fact that they're not
```
const
```
to change the pointed-to value).


Question:
I want to diaplay message boxes that looks good, with the possibillity to use bold/italic text and text with different colors. The standard MessageBox.Show doesn't provide this functionality.

I have been trying to create a message box using the WebBrowser control to display nicely formatted text using HTML-syntax. But I haven't succeeded.

Do you know if this is possible, or do you know any other way to show a message box with formatted text? I want the message box to size itself dynamically to it's content.

(For Windows Forms)

Answer:
You could create your own Form class that hosts the WebBrowser control (or an RTF control) to display the formatted content. Just give it an interface (API) similar to MessageBox so you can use it much the same way (e.g., checking the user's Yes/No or Ok/Cancel/etc responses).
For the sizing, you would likely need to check the content being displayed and use some System.Drawing capabilities to get the size of the fonts/content for it. Then size your window accordingly and/or show and hide scrollbars so they're only shown when absolutely necessary.


Question: How can I prevent the pocket PC device from shutting down from my application when the power button pressed? I am using C#.

Answer:
You can try changing the power requirements for the device "BLK1:", which is the blacklight device. Be aware that the behavior may not be the same on all devices and version of the OS or Vendor specific Extensions.
To do this, you can write something like :
```
```
[DllImport("coredll")]
    private extern static IntPtr SetPowerRequirement(string pvDevice, int deviceState,
                int deviceFlags, IntPtr pvSystemState, int stateFlags);

    [DllImport("coredll")]
    private extern static int ReleasePowerRequirement(IntPtr handle);
```
```
and call it this way :
```
```
IntPtr handle = SetPowerRequirement("BLK1:", 0 /* D0, Full On */, 1, IntPtr.Zero, 0);
    // Do something that requires the device to stay on ...
    ReleasePowerRequirement(handle);
```
```
But this is generally not a good practice, leaving a device with the backlight on for extended periods might reduce dramatically its autonomy.


Question: I'm new to development on the iPhone.  Just about every sample project (as well as the default project templates) have one or more delegates and controllers.  Can someone give me a breakdown of what the delegates are responsible for vs. what the controllers are supposed to do?

Answer:
The simplest way I can think to differentiate the two are:
A delegate is a protocol (interface) that defines methods that an object implements in order to receive specific messages from other objects.  Delegates objects are most often used to receive asynchronous callbacks such as user input, I/O.
A controller is an object that usually contains UI elements (views, controls, etc.) and data, and both receives and send messages to the various objects within it.  In many cases, a controller
is
a delegate and can implement several delegate protocols to receive events from multiple objects.
Keep in mind that many UI elements and controls let you pass events back to the controller by linking them to an IBAction method in Interface Builder.  This is very handy as it doesn't require extra code to implement delegates.  However, some other APIs such as the ABPeoplePickerNavigationController or NSURLConnection have no visualization in Interface Builder and so must use delegates to handle their events.


Question:
Our web team has been asked to build some user interfaces in Sharepoint.  The UI's would primarily be forms that would need to write to a  SQL Server database.

Is ASP.NET the best way to do this?  If so what's the best way to integrate the ASP.NET application into Sharepoint?

Answer:
You have 4 options:
```
```
1. Build web parts
2. build user controls , and use smart part to display them.
3. use infopath
4. host the asp.net in an iframe (page viewer web part).
```
```
I would go with building web parts, however user controls and smart part are probably quicker, and quickest still is infopath, but infopath wont use the page layouts or master pages that you specify.
if the web app has already been developed then youre looking at option 4, if its not already developed then I would suggest 1 or 2 which gives you the flexibility of reusing the controls elsewhere in the site as well as utilising the sharepoint metadata.


Question:
I'm writing a HTML form that's divided in fieldsets, and I need to get the form fields from a specific fiedset in a function.

Currently it's like this:

function conta(Fieldset){
    var Inputs = Fieldset.getElementsByTagName("input");
    var Selects = Fieldset.getElementsByTagName("select");
    /* Doing the stuff I need to do in two iterations, one for each field type */
}

But who knows what the future may hold, and if the form gets some new field types (radios, checkboxes) this could become awful to mantain.

I know that form elements have the  elements attribute that returns all the form fields and I was hoping I could use something like that.

(I know I still gotta discriminate the field type in a bunch of conditionals inside the iteration, but I think it would be faster and easier to keep. Unless it isn't and I should not be doing it)

Answer:
Haven't tested this and don't know how it would work, but you could use JQuery here to select all the elements into a JQuery object
```
```
//$("input select textarea").each(function() {
$(":input").each(function() { //even better
    // do stuff here
});
```
```
this would at least cleanup the code, although you would still have to add conditional statements based on field type like you mentioned.


Question:
I have a page with a few fields and a runtime-generated image on it. The contents of this page are inside an UpdatePanel. There is a button to take the user to a secondary page, which has a button that calls javascript:history.go(-1) when clicked.

The problem is, the first page does a full request instead of a postback or just using the state it was in before navigating away from it. That is, the fields are all reset to their default values, thereby confusing the user. I'd like their values to be retained regardless of navigation. I do not want to create a new history state for every field change.

Any ideas?

Answer:
Haven't tested this and don't know how it would work, but you could use JQuery here to select all the elements into a JQuery object
```
```
//$("input select textarea").each(function() {
$(":input").each(function() { //even better
    // do stuff here
});
```
```
this would at least cleanup the code, although you would still have to add conditional statements based on field type like you mentioned.


Question: How do I check to see if a variable is a number, or contains a number, in UNIX shell?

Answer:
Shell variables have no type, so the simplest way is to use the return type
```
test
```
command:
```
```
if [ $var -eq $var 2> /dev/null ]; then ...
```
```
(Or else parse it with a regexp)


Question: How do I force Postgres to use an index when it would otherwise insist on doing a sequential scan?

Answer:
Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found
here
. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.
As a very blunt hammer, useful for testing, you can use the
```
enable_seqscan
```
and
```
enable_indexscan
```
parameters. See:
Examining index usage
```
enable_
```
parameters
These are
not suitable for ongoing production use
. If you have issues with query plan choice, you should see
the documentation for tracking down query performance issues
. Don't just set
```
enable_
```
params and walk away.
Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?
For small tables, it's faster to do sequential scans.
Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
Your planner settings might be causing problems.
See also
this old newsgroup post
.


Question:
In Java, what is the difference between the twin methods?

public void methodA() throws AnException {
    //do something
    throw new AnException();
}

public void methodA() {
    //do the same thing
    throw new AnException();
}

I have a intuition that it has something to do with being a well-designed method (because I put methodA in an interface, declared it the way methodA* does in its implementation and received a warning from Java that "A* cannot override A because A* doesn't throw AnException").

Is this speculation correct?

Is there any other subtle connotations in the two ways of doing things?

Answer:
If AnException is a checked exception (in other words, if it doesn't extend RuntimeException) then methodA won't compile.  Checked exceptions must always be declated.
If AnException is an unchecked exception (if it does extend RuntimeException), then either is allowed by the java compiler, and either is interpreted equivalently by the java runtime.
methodA is still probably still preferred in this case, for the reasons of documentation.  The javadoc for your method will show that it might throw AnException.  It's good to let users of your method know what Exceptions they should expect.


Question: Is there any way to set an event handler without doing it manually in the classname.designer.cs file other than double clicking the UI element?

Answer:
If I follow your question correctly, you can just do it in your code-behind like this:
```
```
myButton.Click += myHandler;
```
```
Or you could use an anonymous delegate:
```
```
myButton.Click += delegate
{
    MessageBox.Show("Clicked!");
};
```
```


Question: How do you control the column width in a gridview control in ASP.NET 2.0?

Answer:
I do it using the header style for the column:
```
```
<asp:BoundField HeaderText="Name" DataField="LastName">
   <HeaderStyle Width="20em" />
</asp:BoundField>
```
```


Question:
Where can I find pascal-style railroad diagrams to describe C++ syntax?
(As an alternative to EBNF)

Answer: There don't exist any, as far as I know. The C++ syntax can't even be expressed in a proper EBNF - it's a context-sensitive grammar, and anything attempting to parse it has to be capable of processing C++ code at least as far as template instantiation and overload resolution (not to mention macros).


Question:
I'm try to extract info from a MySQL DB into a MS SQL DB. The DB is a mess and the developer is no longer available.

All dates are in char fields, and I use

SELECT concat( mid(DueDate, 7, 4), mid(DueDate, 4, 2), mid(DueDate, 1, 2)) as DueDate FROM TableName

to get the date field in a format so MS sql server can import them.

Now, I want to export only the record with the date greater than today, so the questions are:

What is the equivalent of GetDate() in MySQL?

Is there a better way to cast the date to make the comparison?

Answer:
In MySQL you can convert a string to a date using the
STR_TO_DATE
function.
An example usage is:
```
```
mysql> SELECT STR_TO_DATE('04/31/2004', '%m/%d/%Y');
        -> '2004-04-31'
```
```
To get the current date in MySQL simply use the NOW() function. You can then check if a parsed date is later than today using something like
```
```
WHERE STR_TO_DATE('04/31/2009', '%m/%d/%Y') > NOW()
```
```


Question:
Wondering how to open many new windows with Javascript.  I have found plenty of places on the internet that show you how to open a new browser window with Javascript, but I want to open a new UNIQUE window.  For Example.

I have two links on a page.  the user clicks on both links and they are both opened in the same window.  I want each link to open a new window WITH JAVASCRIPT.

Another Example.
I just opened a window with javascript and I have a link inside my newly opened window.  I click on the link and it opens in the same window.  I want to pop it out of that window WITH JAVASCRIPT, NOT use the same window.

Help?

Answer:
```
```
window.open('page.html','WindowTitle','width=400,height=200')
```
```


Question: Is it only to allow logical grouping?

Answer: It gives you flexibility. For example, you might have a bunch of constructors, some public, some protected, some private - wouldn't you want them all grouped together?


Question:
Need to an expression that returns only things with an "I" followed by either a "J" or a "V" (No Quotes) and then a minimum of 1 number up to 3 numbers.

I J###

I V###

I J##

I V##

I J#

I v#

Answer:
Depends on your flavor
```
```
I(J|V)[0-9]{1,3}
```
```
Do you also need a space after an "I"?
```
```
I (J|V)[0-9]{1,3}
```
```


Question:
Is it possible to catch an error when using JSONP with jQuery? I've tried both the $.getJSON and $.ajax methods but neither will catch the 404 error I'm testing. Here is what I've tried (keep in mind that these all work successfully, but I want to handle the case when it fails):

jQuery.ajax({
    type: "GET",
    url: handlerURL,
    dataType: "jsonp",
    success: function(results){
        alert("Success!");
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert("Error");
    }
});

And also:

jQuery.getJSON(handlerURL + "&callback=?",
    function(jsonResult){
        alert("Success!");
    });

I've also tried adding the $.ajaxError but that didn't work either:

jQuery(document).ajaxError(function(event, request, settings){
   alert("Error");
});

Thanks in advance for any replies!

Answer:
It seems that JSONP requests that don't return a successful result never trigger any event, success or failure, and for better or worse that's apparently by design.
After searching their bug tracker, there's
a patch
which may be a possible solution using a timeout callback.  See
bug report #3442
.  If you can't capture the error, you can at least timeout after waiting a reasonable amount of time for success.


Question: How do I learn PLC programming? Would it differ greatly for different brands of PLCs? Is ladder programming the same as PLC programming?

Answer: PLC is the term used for the devices that use ladder logic.  The devices that are programmed in more typical programming languages are generally called microcontrollers.  However, there are some of us that on occasion lump them all under the PLC name.  :-)  Not sure how much ladder logic varies, but microcontroller code can vary significantly.


Question: Is a cfront tool available for the new C++? For any other modern languages?

Answer:
What do you mean by “cfront tool”? Cfront was the first C++ compiler. But since failure to add exception support,
it has been discontinued
. Modern C++ is way beyond the scope of Cfront.
For any other modern languages?
And what do you mean by that? If you mean whether other compilers exist that compile a high-level language into C code then the answer is yes, there are plenty. The
Glasgow Haskell Compiler
is just one out of many.


Question: Is there any GUI-based tools to assist you with writing and maintaining the configuration file? Any code tools to codegen the config file? What are the best ways to make this a little bit easier? Are most people just using Castle ActiveRecord now?

Answer:
I'm just learning NHibernate myself (from the
excellent Summer of NHibernate
series).  I don't know of any GUI tools, but I thought that I'd point out that if you install the NHibernate schmema files (found in the root folder of the installation) to C:\Program Files\Microsoft Visual Studio 9.0\Xml\Schemas, you then get intellisense help with both the general configuration file and the mapping configuration file.  I found that to be a big help.


Question: I am using Borland Builder C++ 2009. I want to add a button to a form that allows the user to open a file in Excel that I specify. I can't think of how to do this. I know how to link with other code and executables -- is there a Microsoft Excel executable that I could use? How could I specify the file then? Any hints on this, or at least a place to look online, would be greatly appreciated.

Answer:
Assuming that the file type is registered with Excel, you could call ShellExecute() on the file, using the "open" verb. This will cause the file to be opened as if double clicked by the user in Explorer and will invoke Excel.
If that isn't the case, and you can assume that Excel is installed, you could instead pass "excel" to ShellExecute() as the application, and the path of the file as the parameter. (Note that I didn't test this, but it worked from the Run dialog, so I think that it should work from ShellExecute() as well).


Question: When printing a single character in a C program, must I use "%1s" in the format string? Can I use something like "%c"?

Answer:
yes,
```
%c
```
will print a single char:
```
```
printf("%c", 'h');
```
```
also,
```
putchar
```
/
```
putc
```
will work too. From "man putchar":
```
```
#include <stdio.h>

int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

* fputc() writes the character c, cast to an unsigned char, to stream.
* putc() is equivalent to fputc() except that it may be implemented as a macro which evaluates stream more than once.
* putchar(c); is equivalent to putc(c,stdout).
```
```
EDIT:
Also note, that if you have a string, to output a single char, you need get the character in the string that you want to output. For example:
```
```
const char *h = "hello world";
printf("%c\n", h[4]); /* outputs an 'o' character */
```
```


Question:
I can handle the process that file part, but before I go crazy, has someone built a simple wcf service & client (running under windows services or IIS) that I can use to upload a file, and download that file back? with the fewest lines of code? (C# or VB)

compression & encryption would be cool, but i'll layer that on later!!

Thanks!!

Answer:
You should be able to do this fairly easily.  The service contract would probably look like this:
```
```
[ServiceContract]
public interface IFileService
{
  [OperationContract]
  byte[] ProcessFile(byte[] FileData);
}
```
```
The encryption part could be handled natively by WCF using transport level security.  I don't believe that WCF supports compression directly, but you could add that using the GZipStream class.
I have not built a file handling service as you describe, but I have built a service that handles byte array data that is passed back and forth between a WCF client and service.  It works just fine.


Question:
In the tradition of this question and in light of the documentation, how does one make this function deterministic:

ALTER FUNCTION [udf_DateTimeFromDataDtID]
(
    @DATA_DT_ID int -- In form YYYYMMDD
)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
    RETURN CONVERT(datetime, CONVERT(varchar, @DATA_DT_ID))
END

Or this one (because of the string/date literals - and yes, I've also tried '1900-01-01'):

ALTER FUNCTION udf_CappedDate
(
    @DateTimeIn datetime
)
RETURNS datetime
WITH SCHEMABINDING
AS
BEGIN
    IF @DateTimeIn < '1/1/1900'
        RETURN '1/1/1900'
    ELSE IF @DateTimeIn > '1/1/2100'
        RETURN '1/1/2100'

    RETURN @DateTimeIn
END

Answer:
From the articles you linked:
To be deterministic, the style parameter must be a constant. Additionally, styles less than or equal to 100 are nondeterministic, except for styles 20 and 21. Styles greater than 100 are deterministic, except for styles 106, 107, 109 and 113.
You need to use a style parameter in your conversions to datetime.
For example:
```
```
CONVERT(datetime, '2008-01-01', 121)
```
```
Except don't use 121...


Question:
I am writing a script which is likely to be modified by users. Currently I am storing the configuration settings inside the script. It exists in the form of a hash-of-hashes.

I would like to guard against people accidentally using lowercase characters in the hash keys, because that will break my script.

It would be simple to inspect the hash keys and merely issue warnings for any keys with lowercase characters, but I would rather fix the case sensitivity automatically.

In other words, I want to convert all the hash keys in the top-level hash to uppercase.

Answer:
Walk through the hash and replace any lowercase keys with their uppercase equivalents, and delete the old ones.  Roughly:
```
```
for my $key ( grep { uc($_) ne $_ } keys %hash ) {
    my $newkey = uc $key;
    $hash{$newkey} = delete $hash{$key};
}
```
```


Question:
Caveat:
I try all the posibilities listed here: How can I ignore everything under a folder in Mercurial.

None works as I hope.

I want to ignore every thing under the folder test. But not ignore srcProject\test\TestManager

I try

syntax: glob
test/**

And it ignores test and srcProject\test\TestManager

With:

syntax: regexp
^/test/

It's the same thing.

Also with:

syntax: regexp
test\\*

I have install TortoiseHG 0.4rc2 with Mercurial-626cb86a6523+tortoisehg, Python-2.5.1, PyGTK-2.10.6, GTK-2.10.11 in Windows

Answer:
You can use zero-width negative look-ahead and look-behind assertions to specify that you want to ignore
```
test
```
only when it's not preceded by
```
srcProject
```
and not followed by
```
TestManager
```
:
```
```
syntax: regexp
(?<!srcProject\\)test\\(?!TestManager)
```
```
Mercurial uses Python regular expressions, so you can find more info on zero-width assertions in the Python docs:
https://docs.python.org/library/re.html#regular-expression-syntax


Question: In HTML in the td of a table you can break text by using <BR> between the words. This also works in the HeaderText of a TemplateItem but not the HeaderText of a BoundField. How do I  break up the Header text of a BoundField.

Answer:
Set
```
HtmlEncode = false
```
inside the
```
BoundField
```
```
```
<asp:BoundField DataField="SomeDataField"
        HeaderText="SomeHeader<br />(OtherData)"
        HtmlEncode="false" />
```
```
```
BoundField.HtmlEncode
```
is true by default which means that if HTML is added in the text it will be encoded.
If HtmlEncode is set to false the text is not encoded and the br will work as expected. Unfortunately is not possible to specify this only for the header text, it will affect the cell contents as well.


Question:
I'm experimenting with WCF Services, and have come across a problem with passing Interfaces.

This works:

[ServiceContract]
public interface IHomeService
{
    [OperationContract]
    string GetString();
}

but this doesn't:

[ServiceContract]
public interface IHomeService
{
    [OperationContract]
    IDevice GetInterface();
}

When I try to compile the client it fails on the GetInterface method. I get an Exception saying that it can't convert Object to IDevice.

On the clientside the IHomeService class correctly implements GetString with a string as it's returntype, but the GetInterface has a returntype of object. Why isn't it IDevice?

Answer:
You need to tell the WCF serializer which class to use to serialize the interface
```
```
[ServiceKnownType(typeof(ConcreteDeviceType)]
```
```


Question:
At the XmlSerializer constructor line the below causes an InvalidOperationException which also complains about not having a default accesor implemented for the generic type.

Queue<MyData> myDataQueue = new Queue<MyData>();

// Populate the queue here

XmlSerializer mySerializer =
  new XmlSerializer(myDataQueue.GetType());

StreamWriter myWriter = new StreamWriter("myData.xml");
mySerializer.Serialize(myWriter, myDataQueue);
myWriter.Close();

Answer:
It would be easier (and more appropriate IMO) to serialize the
data
from the queue - perhaps in a flat array or
```
List<T>
```
. Since
```
Queue<T>
```
implements
```
IEnumerable<T>
```
, you should be able to use:
```
```
List<T> list = new List<T>(queue);
```
```


Question:
My log file is:

 Wed Nov 12 blah blah blah blah cat1
 Wed Nov 12 blah blah blah blah
 Wed Nov 12 blah blah blah blah
 Wed Nov 12 blah blah blah blah cat2
     more blah blah
     even more blah blah
 Wed Nov 12 blah blah blah blah cat3
 Wed Nov 12 blah blah blah blah cat4

I want to parse out the full multiline entries where cat is found on the first line. What's the best way to do this in sed and/or awk?

i.e. i want my parse to produce:

 Wed Nov 12 blah blah blah blah cat1
 Wed Nov 12 blah blah blah blah cat2
     more blah blah
     even more blah blah
 Wed Nov 12 blah blah blah blah cat3
 Wed Nov 12 blah blah blah blah cat4

Answer:
Assuming your log file does not contain the control characters
```
'\01'
```
and
```
'\02'
```
, and that a continued line begins with precisely four spaces, the following might work:
```
```
c1=`echo -en '\01'`
c2=`echo -en '\02'`
cat logfile | tr '\n' $c1 | sed "s/$c1    /$c2/g" | sed "s/$c1/\n/g" | grep cat | sed "s/$c2/\n    /g"
```
```
Explanation: this replaces each newline with ASCII 1 (a control character that should never appear in a log file) and each sequence "newline-space-space-space-space" with ASCII 2 (another control character).  It then re-replaces ASCII 1 with newlines, so now each sequence of multiple lines is put into one line, with the old line breaks replaced by ASCII 2.  This is grepped for cat, and then the ASCII 2's are re-replaced with the newline-space-space-space-space combination.


Question:
I am battling regular expressions now as I type.

I would like to determine a pattern for the following example file: b410cv11_test.ext. I want to be able to do a search for files that match the pattern of the example file aforementioned. Where do I start (so lost and confused) and what is the best way of arriving at a solution that best matches the file pattern? Thanks in advance.

Further clarification of question:

I would like the pattern to be as follows: must start with 'b', followed by three digits, followed by 'cv', followed by two digits, then an underscore, followed by 'release', followed by .'ext'

Answer:
To avoid confusion, read the following, in order.
First, you have the
glob
module, which handles file name regular expressions just like the Windows and unix shells.
Second, you have the
fnmatch
module, which just does pattern matching using the unix shell rules.
Third, you have the
re
module, which is the complete set of regular expressions.
Then ask another, more specific question.


Question:
I'm an end-user of one of my company's products. It is not very suitable for integration into Spring, however I am able to get a handle on the context and retrieve the required bean by name.  However, I would still like to know if it was possible to inject a bean into this class, even though the class is not managed by Spring itself.

Clarification: The same application which is managing the lifecycle of some class MyClass, is also managing the lifecycle of the Spring context. Spring does not have any knowledge of the instance of MyClass, and I would like to some how provide the instance to the context, but cannot create the instance in the context itself.

Answer:
suppose that u have the following dependency chain:
A --> B --> C --> x --> y -- > Z
A, B, C are spring managed beans (constructed and manged  by spring framework)
x, y are really simple POJOs that constructed by your application, without spring assistance
now if you want that y will get a reference to Z using spring that you need to have a 'handle' to the spring ApplicationContext
one way to do it is to implement
ApplicationContextAware
interface . In this case I would suggest that either A, B or C will implement this interface and will store the applicationContext reference in a static member.
so lets take Class C for example:
```
```
class C implmenets ApplicationContextAware{
    public static ApplicationContex ac;
     void setApplicationContext(ApplicationContext applicationContext)  {
               ac = applicationContext;
     }
 .............
}
```
```
now, in class y you should have:
```
```
(Z)(C.ac.getBean("classZ")).doSomething()
```
```
HTH -- Yonatan


Question:
The default behavior of NHibernate is the write all changes to objects to the database when Session.Flush() is called. It does this whether you want it to or not.

How do we prevent writing bad data to the database when we need to do things like validate business rules or input?

For instance ..

Customer Name is not null.

User opens a web browser (without javascript) and deletes the customer name.

Hits update.

Customer.Name property is updated and ..

Customer.IsValid() is called.

Even if IsValid() is false and we show error messages NHibernate still updates the database.

Answer:
Use the ISession.Evict(objectToEvict) method to evict invalid objects.
See:
http://www.tobinharris.com/2007/2/3/nhibernate-faq
and
http://www.surcombe.com/nhibernate-1.2/api/html/M_NHibernate_ISession_Evict.htm


Question: A quick search gave me this announcement of Parrot DBDI from January 2004 and a dbdi-dev mailing list which appears to be long dead. Is Parrot DBDI still being developed? Is anyone working on a different database API or interface for Parrot?

Answer:
The lookup is done at a time when the constness of
```
this
```
is not known.  You just have to give it a hint via casting.  Try this:
```
```
typedef void (abc::*fptr)(int) const; // or remove const
std::tr1::bind((fptr)&abc::hello, x , _1)(a);
```
```
You may also notice here that removing the
```
const
```
still works.  This is because you should be passing x by pointer (because the first argument to a C++ member function, the implicit
```
this
```
parameter, is always a pointer).  Try this instead:
```
```
typedef void (abc::*fptr)(int) const; // won't compile without const (good!)
std::tr1::bind((fptr)&abc::hello, &x , _1)(a);
```
```
As discovered during within my comments below, if you omit the
```
&
```
as you originally did, you'll be passing x
by value
, which is usually not what you want (though it makes little practical difference in your particular example).  This actually seems like an unfortunate pitfall for
```
bind
```
.


Question:
Currently I have a table that I search upon 4 fields, FirstName, LastName, MiddleName, And AKA's. I currently have a CONTAINSTABLE search for the rows and it works. Not well but it works. Now I want to make the First Name weighted higher and middle name lower.

I found the command ISABOUT but that seems pretty worthless if I have to do it by word not column (hopefully I understood this wrong). This is not an option if its by word because I do not know how many words the user will enter.

I found the thread here that talks about this same solution however I was unable to get the accepted solution to work. Maybe I have done something wrong but regardless I cannot get it to work, and its logic seems really... odd. There has to be an easier way.

Answer:
The key to manipulating the rankings is to use a union.  For each column you use a separate select statement.  In that statement, add an identifier that shows from which column each row was pulled then.  Insert the results into a table variable, then you can manipulate the ranking by sorting on the identifier or multiplying the rank by some value based on the identifier.
The key is to give the appearance of modifying the ranking, not to actually change sql server's ranking.
Example using a table variable:
```
```
DECLARE @Results TABLE (PersonId Int, Rank Int, Source Int)
```
```
For table People with Columns
```
PersonId Int PK Identity, FirstName VarChar(100), MiddleName VarChar(100), LastName VarChar(100), AlsoKnown VarChar(100)
```
with each column added to a full text catalog, you could use the query:
```
```
INSERT INTO @Results (PersonId, Rank, Source)

SELECT PersonId, Rank, 1
FROM ContainsTable(People, FirstName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

UNION
SELECT PersonId, Rank, 2
FROM ContainsTable(People, MiddleName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

UNION
SELECT PersonId, Rank, 3
FROM ContainsTable(People, LastName, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

UNION
SELECT PersonId, Rank, 4
FROM ContainsTable(People, AlsoKnown, @SearchValue) CT INNER JOIN People P ON CT.Key = P.PersonId

/*
Now that the results from above are in the @Results table, you can manipulate the
rankings in one of several ways, the simplest is to pull the results ordered first by Source then by Rank.  Of course you would probably join to the People table to pull the name fields.
*/

SELECT PersonId
FROM @Results
ORDER BY Source, Rank DESC

/*
A more complex manipulation would use a statement to multiply the ranking
by a value above 1 (to increase rank) or less than 1 (to lower rank), then
return results based on the new rank.  This provides more fine tuning,
since I could make first name 10% higher and middle name 15% lower and
leave last name and also known the original value.
*/

SELECT PersonId, CASE Source WHEN 1 THEN Rank * 1.1 WHEN 2 THEN Rank * .9 ELSE Rank END AS NewRank FROM @Results
ORDER BY NewRank DESC
```
```
The one downside is you'll notice I didn't use
```
UNION ALL
```
, so if a word appears in more than one column, the rank won't reflect that.  If that's an issue you could use
```
UNION ALL
```
and then remove duplicate person id's by adding all or part of the duplicate record's rank to the rank of another record with the same person id.


Question:
To do the equivalent of Python list comprehensions, I'm doing the following:

some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3}

Is there a better way to do this...perhaps with one method call?

Answer:
If you really want to, you can create an Array#comprehend method like this:
```
```
class Array
  def comprehend(&block)
    return self if block.nil?
    self.collect(&block).compact
  end
end

some_array = [1, 2, 3, 4, 5, 6]
new_array = some_array.comprehend {|x| x * 3 if x % 2 == 0}
puts new_array
```
```
Prints:
```
```
6
12
18
```
```
I would probably just do it the way you did though.


Question: Both static_cast and reinterpret_cast seem to work fine for casting void* to another pointer type. Is there a good reason to favor one over the other?

Answer:
Use
```
static_cast
```
: it is the narrowest cast that exactly describes what conversion is made here.
There’s a misconception that using
```
reinterpret_cast
```
would be a better match because it means “completely ignore type safety and just cast from A to B”.
However, this doesn’t actually describe the effect of a
```
reinterpret_cast
```
. Rather,
```
reinterpret_cast
```
has a number of meanings, for all of which holds that “the mapping performed by
```
reinterpret_cast
```
is implementation-defined.” [5.2.10.3]
But in the particular case of casting from
```
void*
```
to
```
T*
```
the mapping is completely well-defined by the standard; namely, to assign a type to a typeless pointer without changing its address.
This is a reason to prefer
```
static_cast
```
.
Additionally, and arguably more important, is the fact that every use of
```
reinterpret_cast
```
is downright dangerous because it converts anything to anything else really (for pointers), while
```
static_cast
```
is much more restrictive, thus providing a better level of protection. This has already saved me from bugs where I accidentally tried to coerce one pointer type into another.


Question:
I'm trying to find a way to get the open tasks in C#.  I've been searching on google and can only find how to get a list of the processes.  I want the only the tasks that would show up on the taskbar.

Also, along with that, it would be cool if I could get the process the task is associated with.  And if possible get the thumbnail images that Vista uses for the ALT-TAB menu, like in this image:

I assume that I will have to use pinvokes because it really doesn't look like there are any libraries to do this already.  Any ideas?

Answer:
From an API (Win32) perspective there is no such thing as Tasks (at least not the one that Windows Task Manager/Alt-Tab shows).
Those "Tasks" are actually top level windows.
So in order to get a list of those, you need to
enumerate the windows
(here is the
PInvoke
for it).
Then look at the style of the windows to determine if they are actually top level windows.


Question:
In ASP.NET (not MVC), what is the best approach to programmatically setting styles on an unordered list used for navigation so the appropriate menu item is styled as the active item if that page is being viewed?

This would most likely be used in conjunction with a MasterPage.

Answer:
The answer to your question depends a lot on how you have your list implemented {User control or not, etc}.  How I would do it, is implement the list to be generated by a user control.
I'd have the UserControl tag each element with something like:
```
```
<{...} class="GeneratedMenuItem"> {...}
```
```
And I'd have the appropriate styles in the Style Sheet; of course if it was in a user control then you might be able to use Themes (but that depends on which version of ASP.net you are using.


Question: I want a workflow that, when an entry is created in List A, will generate one entry in List B for each entry in List C. Is this possible? If so, how?

Answer:
I propose:
```
```
numpy.resize(my_ar, (3,3)).transpose()
```
```
You can of course adapt the shape
```
(my_ar.shape[0],)*2
```
or whatever


Question:
I have a server behind a firewall. It runs a web application (Java servlets under Apache Tomcat) and responds only to port 443 (HTTPS). There is no scripting code in the pages served - the forms use HTTP POST to receive the form, process the data (with appropriate input filtering) and then output an HTTP result page.

I am currently using an appliance firewall, but it is 'hardware-flakey'. I have been looking at upgrading to a more 'industrial strength' solution, but the vendor is quite insistant that I purchase a subscription to their "deep packet inspection" software. He claims that even web servers need this kind of protection.

I am not convinced, but do not have the security background to be certain. The firewall would sit between the "world" and my server, and use "port forwarding" to allow only ports 443 and 22 (for maintenance) to reach the server.

So - do I really need this deep packet inspection, or not?

Answer:
Given that the only protocols that you're interested in (ssh and https) are "negotiate encryption on connect" there's little that a standard firewall will be able to inspect after that point. Once the SSL/SSH session is established the firewall will only see encrypted packets. Ask your vendor what their product examines in this context.
Alternatively, it is possible that the device acts more like a proxy -- that it acts as the server-side end-point for the connection before relaying on to your real server -- in which case it is possible that the product does something deeper, although this isn't the case if the firewall really is "port forwarding" as you say. Again, your vendor should be able to explain how their device operates.
Also you may want to ask what vulnerabilities/risks the inspection system is intended to protect against. For example: Does it look out for SQL injection? Is it targetted to a particular platform? (If your web server runs on a SPARC CPU, for example, then there's little point inspecting URLs for x86 shellcode).


Question: I've always been using the cookie-based session store, and never even knew about Cookies until now. So is there any situation where I'd need the cookies hash?

Answer:
You shouldn't store anything you don't want the user to see or change in cookie. If you store a member ID then the user could easily change the value and pretend to be someone else. Cookies are also sent with every single request to your web server including image, JS and CSS requests. If you are storing lots of information in cookies, this could have an impact on speed.
Cookie-based sessions (in a general context, I can't say I know what Rails does) means your session variables are associated with a session ID which is randomly generated. This ID, and only the ID, is returned to the the user as a cookie. This allows you to associate the users request (because you have session ID cookies)  with the user's sessions. This is safer because it would be very difficult for someone to guess the ID of another user's session.


Question:
I'm looking for a good Java obfuscator.

I've done initial research into the following Java obfuscators: proguard, yguard, retroguard, dasho, allatori, jshrink, smokescreen, jobfuscate, marvin, jbco, jode, javaguard, jarg, joga, cafebabe, donquixote, mwobfu, bbmug, zelix klassmaster, sandmark, jcloak, thicket, blufuscator, and java code protector.

I tried proguard and it has a really nice GUI, seems really stable, and seems to be the most popular, but it seemed to not like some enumeration on a referenced jar file (not within the code I was trying to obfuscate) which was weird.  Yguard seems to require some interaction with ant, which I didn't know too much about.

What is a good java obfuscator?  It doesn't need to be free, it just needs to work well and be easy to use.

Answer:
What is the issue with ProGuard ? (which is recommended both by
this question
and
this one
).
There is a section of
troubleshooting
about enumerator, but they seem to be taken into account
just fine
.
However, Obfuscation breaks some attempts at reflection, even though modern obfuscators can detect and to some extend adjust usages of reflection in the code they're obfuscating.


Question:
Are there any good references for best practices for storing postal addresses in an RDBMS?  It seems there are lots of tradeoffs that can be made and lots of pros and cons to each to be evaluated -- surely this has been done time and time again?  Maybe someone has at least written done some lessons learned somewhere?

Examples of the tradeoffs I am talking about are storing the zipcode as an integer vs a char field, should house number be stored as a separate field or part of address line 1, should suite/apartment/etc numbers be normalized or just stored as a chunk of text in address line 2, how do you handle zip +4 (separate fields or one big field, integer vs text)? etc.

I'm primarily concerned with U.S. addresses at this point but I imagine there are some best practices in regards to preparing yourself for the eventuality of going global as well (e.g. naming fields appropriately like region instead of state or postal code instead of zip code, etc.

Answer:
You should certainly consult "
Is this a good way to model address information in a relational database
", but your question is not a direct duplicate of that.
There are surely a lot of pre-existing answers (check out the example data models at
DatabaseAnswers
, for example).  Many of the pre-existing answers are defective under some circumstances (not picking on DB Answers at all).
One major issue to consider is the scope of the addresses.  If your database must deal with international addresses, you have to be more flexible than if you only have to deal with addresses in one country.
In my view, it is
often
(which does not mean
always
) sensible to both record the 'address label image' of the address and separately analyze the content.  This allows you to deal with differences between the placement of postal codes, for example, between different countries.  Sure, you can write an analyzer and a formatter that handle the eccentricities of different countries (for instance, US addresses have 2 or 3 lines; by contrast, British addresses can have considerably more; one address I write to periodically has 9 lines).  But it can be easier to have the humans do the analysis and formatting and let the DBMS just store the data.


Question:
Here's the goal: to replace all standalone ampersands with &amp; but NOT replace those that are already part of an HTML entity such as &nbsp;.

I think I need a regular expression for PHP (preferably for preg_ functions) that will match only standalone ampersands. I just don't know how to do that with preg_replace.

Answer:
You could always run
```
html_entity_decode
```
before you run
```
htmlentities
```
? Works unless you only want to do ampersands (and even then you can play with the charset parameters).
Much easier and faster than a regex.


Question: What win32 calls can be used to detect key press events globally (not just for 1 window, I'd like to get a message EVERY time a key is pressed), from a windows service?

Answer:
You want to use Win32 Hooks.  In particular a keyboard hook.
You can read more about it here
The type of hook you want is WH_KEYBOARD and you can set it via the Win32 API SetWindowsHookEx.
Basically windows will call a function in a dll that you create everytime a key is pressed in any application system wide.
The hook will call your function which will have this interface:
```
```
LRESULT CALLBACK KeyboardProc(
    int code,
    WPARAM wParam,
    LPARAM lParam
);
```
```
More information about this callback here
.
With windows hooks you can not only track system wide events across all processes, but you can also filter them and stop them altogether.


Question:
Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?

NOTE: I don't want to set this up in my IIS settings.

Answer:
Found the answer myself.
Richard Dingwall
has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)
For the global.asax, just add this code as your last route to register:
```
```
routes.MapRoute(
    "404-PageNotFound",
    "{*url}",
    new { controller = "StaticContent", action = "PageNotFound" }
    );
```
```


Question: I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.

Answer:
you can load script dynamically by adding
```
<script src="...">
```
tag to DOM tree.


Question:
Are there any known methods of finding peers without using a dedicated central server?

ie: If I have peers which are disconnecting and reconnecting to the internet but getting a new IP address each time, and I want to connect to them without setting up a dedicated server to register with.

I was thinking about using peers email address to send a manifest of connected peers periodically, with some sort of timecode, negating the need for a dedicated server.  This would be a fallback if none of the peers could be connected to after trying all the previously known peer addresses.  But existing models of finding peers would be preferable.

Answer:
Three ways, off the top of my head, though you're always going to need some central server to start the connection unless you went with option 3.
Central server that maintains known list of peers, with keep-alive.
One or more central servers that maintain some common resource peers can use to discover one another, but once connected no longer need the central server as long as the peer remains connected (something like BitTorrent); can chain peered connections as well.
Port/IP scanning (
strongly not recommended
).
In your example, you'd still have some kind of central server where the peers would be registered; the protocol is the only difference.


Question:
I need to write some methods for loading/saving some classes to and from a binary file. However I also want to be able to accept the binary data from other places, such as a binary string.

In c++ I could do this by simply making my class methods use std::istream and std::ostream which could be a file, a stringstream, the console, whatever.

Does python have a similar input/output class which can be made to represent almost any form of i/o, or at least files and memory?

Answer:
The Python way to do this is to accept an object that implements read() or write().  If you have a string, you can make this happen with
StringIO
:
```
```
from cStringIO import StringIO

s = "My very long string I want to read like a file"
file_like_string = StringIO(s)
data = file_like_string.read(10)
```
```
Remember that Python uses duck-typing: you don't have to involve a common base class. So long as your object implements read(), it can be read like a file.


Question:
I'm creating a list of the Slices in my Merb app, like this:

Merb::Slices.each_slice do |slice|

I'd like to get the list of dependencies for each of this slice, any idea how to access it?

I'm still reading merb code, solution might come soon ;)

Answer:
I haven't used slices yet, but from my understanding they are like a mini merb app in themself, therefore wouldn't each slice have a
```
/config/dependencies.rb
```
? Maybe this gets parsed into the program and is available somewhere.
There may be something
here in the docs
.
Also, here are the methods available on the Merb constant (which you get things like the environment from). There's one called dependencies which returns an array (which is empty when I'm running with
```
merb -i
```
in an app).
```
```
>> Merb.methods.sort
=> ["<", "<=", "<=>", "==", "===", "=~", ">", ">=", "JSON", "__caller_info__", "__caller_lines__", "__id__", "__profile__", "__send__", "abstract_method", "adapter", "adapter=", "add_generators", "add_mime_type", "add_rakefiles", "ancestors", "args_and_options", "assigns", "at_exit", "at_exit_procs", "autoload", "autoload?", "available_accepts", "available_mime_types", "b64encode", "blank?", "bundled?", "class", "class_eval", "class_variable_defined?", "class_variables", "clone", "config", "const_defined?", "const_get", "const_missing", "const_set", "constants", "context", "debugger", "decode64", "decode_b", "deep_clone", "deferred_actions", "dependencies", "dependency", "describe", "dir_for", "disable", "disabled?", "disabled_components", "disabled_components=", "display", "dup", "encode64", "encoded_hash", "enforce!", "enum_for", "env", "env?", "environment", "environment=", "environment_info", "environment_info=", "eql?", "equal?", "exception", "exiting", "exiting=", "extend", "extract_options_from_args!", "fatal!", "find_const", "forking_environment?", "framework_root", "freeze", "frozen?", "full_const_get", "full_const_set", "generators", "given", "glob_for", "hash", "id", "in?", "include?", "included_modules", "inline", "inspect", "instance_eval", "instance_method", "instance_methods", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "is_haml?", "j", "jj", "kind_of?", "klass_hashes", "klass_hashes=", "load_config", "load_dependencies", "load_dependency", "load_paths", "load_paths=", "log_path", "log_stream", "logger", "make_module", "merb", "merge_env", "meta_class", "method", "method_defined?", "methods", "mime_transform_method", "module_eval", "modules", "name", "nil?", "object_id", "on_jruby?", "on_windows?", "options", "orm", "orm=", "orm_generator_scope", "present?", "print_colorized_backtrace", "private_class_method", "private_instance_methods", "private_method_defined?", "private_methods", "protected_instance_methods", "protected_method_defined?", "protected_methods", "public_class_method", "public_instance_methods", "public_method_defined?", "public_methods", "push_path", "quacks_like?", "rakefiles", "reload", "remove_mime_type", "remove_paths", "rescue_require", "reset_logger!", "respond_to?", "restart_environment", "root", "root=", "root_path", "send", "share_as", "share_examples_for", "shared_examples_for", "should", "should_not", "singleton_methods", "start", "start_environment", "started", "started=", "started?", "taguri", "taguri=", "taint", "tainted?", "template_engine", "template_engine=", "test_framework", "test_framework=", "test_framework_generator_scope", "testing?", "to_a", "to_enum", "to_json", "to_s", "to_yaml", "to_yaml_properties", "to_yaml_style", "track_dependency", "trap", "try_dup", "type", "untaint", "use_orm", "use_template_engine", "use_test", "use_testing_framework", "yaml_as", "yaml_tag_class_name", "yaml_tag_read_class"]
```
```


Question:
I am working on a very large legacy code base. We are looking to introduce FindBugs into the development practice.

I intend to have FindBugs run whenever the code is built by eclipse.

I would like to be able to make the findbugs warnings appear as errors in the code much in this way you can change the severity level in eclipse

Is it possible for eclipse to report the warnings it produces as errors?

Thanks

Answer:
No, it isn't possible to have the FindBugs Eclipse plugin mark potential bugs as errors in the code.
I did some checking and the
FindBugs Maven plugin
doesn't provide an option to do this either (so no luck there too).
I would suggest logging an RFE (request for enhancement) to the FindBugs Eclipse plugin developers.  Their bug tracking database is available
here
.


Question:
I'm retrieving a gzipped web page via curl, but when I output the retrieved content to the browser I just get the raw gzipped data. How can I decode the data in PHP?

One method I found was to write the content to a tmp file and then ...

$f = gzopen($filename,"r");
$content = gzread($filename,250000);
gzclose($f);

.... but man, there's got to be a better way.

Edit: This isn't a file, but a gzipped html page returned by a web server.

Answer:
I use curl and:
```
```
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
```
```


Question: I am using the functions strpos(string, string) in javascript. In Firefox, Opera and IE the page loads fine, but in Chrome I get the error: Uncaught ReferenceError: strpos is not defined. The page I am working on is http://seniorproject.korykirk.com/0xpi2.php

Answer:
Use
```
haystack.indexOf(needle)
```
.


Question:
Does anyone have any idea why the following code sample fails with an XmlException "Data at the root level is invalid. Line 1, position 1."

var body = "<?xml version="1.0" encoding="utf-16"?><Report> ......"
XmlDocument bodyDoc = new XmlDocument();
bodyDoc.LoadXml(body);

Answer:
I figured it out.  Read the MSDN documentation and it says to use .Load instead of LoadXml when reading from strings.  Found out this works 100% of time.  Oddly enough using StringReader causes problems.  I think the main reason is that this is a Unicode encoded string and that could cause problems because StringReader is UTF-8 only.
```
```
MemoryStream stream = new MemoryStream();
            byte[] data = body.PayloadEncoding.GetBytes(body.Payload);
            stream.Write(data, 0, data.Length);
            stream.Seek(0, SeekOrigin.Begin);

            XmlTextReader reader = new XmlTextReader(stream);

            // MSDN reccomends we use Load instead of LoadXml when using in memory XML payloads
            bodyDoc.Load(reader);
```
```


Question: I have a situation where I have a bunch of SQL Update commands that all need to be executed.  I know that DataSets can do batch updates, but the only way I've been able to accomplish it is to load the whole table into a dataset first.  What if I want to only update a subset of the records in a table?

Answer:
EDITED: Based on your comment, I'd recommend using the Bulk Copy method to go to a staging table first. Then you can do a single update on your real table based on the staging table.
=========
One way is to build the SQL Command yourself; however, I'd recommend reading about the SQL Injection possibilities to protect yourself. Depending on your situation and your platform there are other options.
For example if you are dealing with a lot of data, then you could do a bulk import into a holding table, which you would then issue a single update command off of. I've also had good success passing records in as XML (I found in my environment that I needed at least 50 rows to offset the cost of loading the DOM, and I knew that the scalability issues were not a factor in my case).
Some other things I've seen was people package the updates into a binary field, for example one binary field for each column, then they have a function which unpacks the binary field. Again you will want to test with your environment.
With that said, have you verified that simply calling a single update command or stored procedure for each update you need is not sufficent? You might not even need to batch the commands up.
Josh
Watch out for Premature Optimization it can be killer!


Question:
Can someone explain the main benefits of different types of references in C#?

Weak references

Soft references

Phantom references

Strong references.

We have an application that is consuming a lot of memory and we are trying to determine if this is an area to focus on.

Answer:
Soft and phantom references come from Java, I believe.  A long weak reference (pass true to C#'s WeakReference constructor) might be considered similar to Java's PhantomReference.  If there is an analog to SoftReference in C#, I don't know what it is.
Weak references do not extend the lifespan of an object, thus allowing it to be garbage collected once all strong references have gone out of scope.  They can be useful for holding on to large objects that are expensive to initialize, but should be available for garbage collection if they are not actively in use.
Whether or not this will be useful in reducing the memory consumption of your application will depend completely on the specifics of the application.  For example, if you have a moderate number of cached objects hanging around that may or may not be reused in the future, weak references could help improve the memory consumption of the caches.  However, if the app is working with a very large number of small objects, weak references will make the problem worse since the reference objects will take up as much or more memory.


Question: can anyone provide/refer a proper OO type helper class for managing a singleton of the SessionFactory and then also for managing Sessions?

Answer:
Sure, this is what I used when I was getting started with NHibernate:
Session Factory
```
```
public class BaseDataAccess
{

  protected ISession m_session;

  public BaseDataAccess()
  {
    m_session = NHibernateHttpModule.CurrentSession;
  }

  public static ISession OpenSession()
  {
    Configuration config;
    ISessionFactory factory;
    ISession session;
    config = new Configuration();

    if (config == null)
    {
      throw new ArgumentNullException(nameof(config));
    }
    if (factory == null)
    {
      throw new ArgumentNullException(nameof(factory);
    }
    if (session == null)
    {
      throw new ArgumentNullException(nameof(session));
    }

    config.AddAssembly("My.Assembly.Here");
    factory = config.BuildSessionFactory();
    session = factory.OpenSession();

    return session;
  }
}
```
```
Let me know if that helps.


Question: I'm using Emma in my ant build to perform coverage reporting.  For those that have used Emma, is there a way to get the build to fail if the line coverage (or any type of coverage stat) does not meet a particular threshold?  e.g. if the line coverage is not 100%

Answer:
Not out of the box.
However, the
```
report.metrics
```
property or attribute of
```
<report></report>
```
can be set for
```
name, class, method, block
```
, and
```
line
```
.  See
Coverage Metrics
in the Emma reference.
Use a plain-text report then a regexp filter to set up a fail condition.


Question:
Does anyone know what this means. Getting this in C# winforms applications:

Not a legal OleAut date

Answer: It means you provided an invalid date somewhere, attempting to convert to or from an OLE Automation date outside the valid range 1-January-4713 BC to 31-December-9999 AD.  A possible cause is that it might have slipped through because OLE Automation Dates are represented as a double.


Question:
I am using Maven (and the Maven Eclipse Integration) to manage the dependencies for my Java projects in Eclipse. The automatic download feature for JAR files from the Maven repositories is a real time saver. Unfortunately, it does not include API documentation and source code.

How can I set up Maven to automatically also get the source and javadoc attachments and register them properly with Eclipse?

Answer:
```
```
mvn eclipse:eclipse -DdownloadSources=true
```
```
or
```
```
mvn eclipse:eclipse -DdownloadJavadocs=true
```
```
or you can add both flags, as Spencer K points out.
Additionally, the
```
=true
```
portion is not required, so you can use
```
```
mvn eclipse:eclipse -DdownloadSources -DdownloadJavadocs
```
```