Question:
Anybody have a good example how to deep clone a WPF object, preserving databindings?

The marked answer is the first part.

The second part is that you have to create an ExpressionConverter and inject it into the serialization process.  Details for this are here:

http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571

Answer:
How about:
```
```
public static T DeepClone<T>(T from)
    {
        using (MemoryStream s = new MemoryStream())
        {
            BinaryFormatter f = new BinaryFormatter();
            f.Serialize(s, from);
            s.Position = 0;
            object clone = f.Deserialize(s);

            return (T)clone;
        }
    }
```
```
Of course this deep clones any object, and it might not be the fastest solution in town, but it has the least maintenance... :)


Question:
Is there some way I can use URLs like:

http://www.blog.com/team-spirit/

instead of

http://www.blog.com/?p=122

in a Windows hosted PHP server?

Answer:
This is how I did it with WordPress on IIS 6.0
http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/
However it all depends on what version of IIS you are using.  If you are lucky enough to use IIS 7.0 you don't really have to worry about pretty urls because everything is supported out of the box.  However if you are using IIS 6.0 you are going to have to use a rewriter and some rules to force the IISness out of IIS.


Question:
Is there an easy way to discover a File's creation time with Java?  The File class only has a method to get the "last modified" time.  According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.

The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time.  I guess this works, I only need to support Windows, but it seems very error prone to me.

Are there any third party libraries that provide the info I need?

Update: In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a  good choice for anyone else that has this problem.

Answer:
I like the answer on
jGuru
that lists the option of using
JNI
to get the answer. This might prove to be faster than shelling out and you may encounter other situations such as this that need to be implemented specifically for windows.
Also, if you ever need to port to a different platform, then you can port your library as well and just have it return -1 for the answer to this question on *ix.


Question:
What are the best practices in setting up a new instance of TFS 2008 Workgroup edition?

Specifically, the constraints are as follows:

Must install on an existing Windows Server 2008 64 bit

TFS application layer is 32 bit only

Should I install SQL Server 2008, Sharepoint and the app layer in a virtual instance of Windows Server 2008 or 2003(I am already running Hyper-V) or split the layers with a database on the host OS and the app layer in a virtual machine?

Edit: Apparently, splitting the layers is not recommended

Answer: I just upgraded our team to TFS 2008, from TFS 2005. The hardest part was upgrading SharePoint 2.0 to 3.0, so I would make sure to do that first, if you have not already installed TFS 2008. We had a couple of other difficulties, but they were all either related to the SharePoint upgrade, or to the fact that we were using an aftermarket Policy package - Scrum for TeamSystem. We are on SQL Server 2005, so I cannot address SQL Server 2008. As for  splitting the layers, we did not do this either, as we are running on                          Windows Server 2003 and everything ran under the host OS.


Question:
I'm new to NHibernate (my 1st big project with it).

I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block.

This doesn't work in a situation where lazy-loading is required, however.

For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception.

Anyone using a different method?

Answer:
Keep your session open for your entire unit of work.  If your session is life is too small, you cannot benefit from the session level cache (which is significant).  Any time you can prevent a roundtrip to the database is going to save a lot of time.   You also cannot take advantage of lazy loading, which is crucial to understand.
If your session lifetime is too big, you can run into other issues.
If this is a web app, you'll probably do fine with the session-per-httpRequest pattern.  Basically this is an HttpModule that opens the session at the beginning of the request and flushes/closes at the end.  Be sure to store the session in HttpContext.Items  NOT A STATIC VARIABLE.  <--- leads to all kinds of problems that you don't want to deal with.
You might also look at
RhinoCommons
for a unit of work implementation.


Question:
I'm trying to find the latitude and longitude of the corners of my map while in birdseye view.  I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map.

In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values).  The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses.

In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed).  How can I decode these values in version 6.1?

Answer:
According to
http://dev.live.com/virtualearth/sdk/
this should do the trick:
```
```
function GetInfo()
{
  alert('The latitude,longitude at the center of the map is: '+map.GetCenter());
}
```
```


Question:
I am consuming the Twitter API and want to convert all URLs to hyperlinks.

What is the most effective way you've come up with to do this?

from

string myString = "This is my tweet check it out http://tinyurl.com/blah";

to

This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>

Answer:
Regular expressions are probably your friend for this kind of task:
```
```
Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "$1");
```
```
The regular expression for matching URLs might need a bit of work.


Question:
So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".

I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.

I'm using latest version of rhino mocks

Answer:
Using MoQ it looks something like this:
```
```
var request = new Mock<HttpRequestBase>();
request.Expect(r => r.HttpMethod).Returns("GET");
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object
, new RouteData(), new Mock<ControllerBase>().Object);
```
```
I think the Rhino Mocks syntax is similar.


Question: Where can I find a good tutorial on learning ASP.NET MVC using VB.net 2008 as the language? Most in-depth tutorials that I found in searching the web were written in C#.

Answer:
Have you tried adding the word "VB" to your searches??
http://www.myvbprof.com/2007_Version/MVC_Intro_Tutorial.aspx
http://www.asp.net/learn/mvc/tutorial-07-vb.aspx
<
Link
>


Question:
When making changes using SubmitChanges(), LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found or changed, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.

Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?

Additionally, does anybody know whether this exception occurs when any data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?

Answer:
I've gotten this error in a circumstance completely unrelated to what the error message describes.
What I did was load a LINQ object via one DataContext, and then tried to SubmitChanges() for the object via a different DataContext - gave this exact same error.
What I had to do was call DataContext.Table.Attach(myOldObject), and then call SubmitChanges(), worked like a charm.
Worth a look, especially if you're of the opinion that there really shouldn't be any conflicts at all.


Question:
Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

Int16

Int32

Int64

UInt16

UInt32

UInt64

I'm aware of the where keyword, but can't find an interface for only these types,

Something like:

static bool IntegerFunction<T>(T value) where T : INumeric

Answer:
There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.
I'd go further and say we need
```
```
static bool GenericFunction<T>(T value)
    where T : operators( +, -, /, * )
```
```
Or even
```
```
static bool GenericFunction<T>(T value)
    where T : Add, Subtract
```
```
Unfortunately you only have interfaces, base classes and the keywords
```
struct
```
(must be value-type),
```
class
```
(must be reference type) and
```
new()
```
(must have default constructor)
You could wrap the number in something else (similar to
```
INullable<T>
```
) like
here on codeproject
.
You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.


Question:
How do I get today's date in C# in mm/dd/yyyy format?

I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.

BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.

Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.

kronoz's answer

Answer:
```
```
DateTime.Now.ToString("M/d/yyyy");
```
```
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx


Question: I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit?

Answer:
@jmein
Actually the problem is that the Validator client script's don't work when placed inside of an updatePanel (UpdatePanels refresh using .innerHTML, which adds the script nodes as text nodes, not script nodes, so the browser does not run them).
The fix was a patch released by microsoft that fixes this issue. I found it with the help of Google.
http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx


Question: So I'm interested in hearing different thoughts about what is the best way to go about unit testing XNA Game/Applications.  Astute googlers can probably figure out why I'm asking, but I didn't want to bias the topic :-)

Answer:
I would that this question is geared more toward the approach of
unit testing in game development
.  I mean, XNA is a framework.  Plug in
NUnit
, and begin writing test cases while you develop.
Here
is a post on SO about unit testing a game.  It'll give you a little insight into how you need to think while progressing.


Question:
I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.

The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?

Thanks.

Answer:
A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application.
```
```
<configuration>
  <system.diagnostics>
    <switches>
       <add name="Remote.Disable" value="1" />
    </switches>
  </system.diagnostics>
</configuration>
```
```
The information is debug information that the receiving service can use to help trace things back to the client.  (maybe, I am guessing a little)
I have proposed a follow up
question
to determine were the magic switch actually comes from.


Question:
This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.

/*
   ... some Java code ...
   ... "... */ ..." ...
   ... more Java code ...
*/

Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.

Answer:
Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See
JLS §3.7
.


Question:
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:

import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequence(unittest.TestCase):
    def testsample(self):
        for name, a,b in l:
            print "test", name
            self.assertEqual(a,b)

if __name__ == '__main__':
    unittest.main()

The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?

Answer:
This is called "parametrization".
There are several tools that support this approach. E.g.:
pytest's decorator
parameterized
The resulting code looks like this:
```
```
from parameterized import parameterized

class TestSequence(unittest.TestCase):
    @parameterized.expand([
        ["foo", "a", "a",],
        ["bar", "a", "b"],
        ["lee", "b", "b"],
    ])
    def test_sequence(self, name, a, b):
        self.assertEqual(a,b)
```
```
Which will generate the tests:
```
```
test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok

======================================================================
FAIL: test_sequence_1_bar (__main__.TestSequence)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda>
    standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
  File "x.py", line 12, in test_sequence
    self.assertEqual(a,b)
AssertionError: 'a' != 'b'
```
```
For historical reasons I'll leave the original answer circa 2008):
I use something like this:
```
```
import unittest

l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]

class TestSequense(unittest.TestCase):
    pass

def test_generator(a, b):
    def test(self):
        self.assertEqual(a,b)
    return test

if __name__ == '__main__':
    for t in l:
        test_name = 'test_%s' % t[0]
        test = test_generator(t[1], t[2])
        setattr(TestSequense, test_name, test)
    unittest.main()
```
```


Question: I'd like to render to svg data in a swf at runtime (not in Flex - not using degrafa) - how would I go about doing that?

Answer:
The Ajaxian blog had a post about this today.
http://ajaxian.com/archives/the-state-of-svg-browser-support-using-flash-for-svg-in-internet-explorer


Question:
I'd like to add dvd burning functionality to my .Net app (running on Windows Server 2003), are there any good components available?  I've used the NeroCOM sdk that used to come with Nero but they no longer support the sdk in the latest versions of Nero.  I learned that Microsoft has created an IMAPI2 upgrade for Windows XP/2003 and there is an example project at CodeProject but not having used it myself I can't say how easy/reliable it is to use.

I'm not really worried about burning audio/video to DVD as this is for file backup purposes only.

Answer:
At my last job I was tasked with finding a cross platform and preferably free way to write our application specific files to cd/dvd.  I quickly found that writing CD's wasn't hard on windows, but I couldn't write DVD's easily, and that only worked on windows.
I ended up writing a wrapper around
cdrecord
cdrecord is an open source project that builds easily with cygwin.  I would create a staging directory where I added the files that needed to be written, called mkisofs on that directory to make a cd iso, and then called cdrecord to burn the image.  This may not be the best solution if you have a strictly windows audience, but it was the only thing I could find that did window, Linux, and OS X.
Another option worht checking out is the
StarBurn SDK
, I download the trial and used it, it worked well, but in the end it wasn't free so it was too expensive for my purposes.


Question:
In C# is there a shorthand way to write this:

public static bool IsAllowed(int userID)
{
    return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}

Like:

public static bool IsAllowed(int userID)
{
    return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}

I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.

Answer:
I would encapsulate the list of allowed IDs as
data
not
code
. Then it's source can be changed easily later on.
```
```
List<int> allowedIDs = ...;

public bool IsAllowed(int userID)
{
    return allowedIDs.Contains(userID);
}
```
```
If using .NET 3.5, you can use
```
IEnumerable
```
instead of
```
List
```
thanks to extension methods.
(This function shouldn't be static. See this posting:
using too much static bad or good ?
.)


Question:
I'm using Ruby on Rails for an internal site. Different users of the site have access to a wide variety of data and highly disparate perspectives of the data. Within those different classes of users, there needs to be levels of access. Within the levels of access I need to be able to add features from other classes of users.

In the released "Version 1.0" of the intranet site I have implemented the general classes of users. I am now needed to implement much finer-grained control of a users access.

The question is how?

What is the generally accepted practice for coding up user preferences (display the map (or not); access to this feature, but not this feature) without exploding the database schema and populating the view code with <% if feature_allowed %> tags everywhere.

Answer:
Another totally different approach would be to use acts_as_authenticated and authorization plugins. The tables will be built by the plugins (ie
users
,
roles
and
roles
_users). From the doc:
The authorization plugin provides the following:
A simple way of checking authorization at either the class or instance method
level using #permit and #permit?
Authorization using roles for the entire application, a model class, or an
instance of a model (i.e., a particular object).
Some english-like dynamic methods that draw on the defined roles. You will be
able to use methods like "user.is_fan_of angelina" or "angelina.has_fans?",
where a 'fan' is only defined in the roles table.
Pick-and-choose a mixin for your desired level of database complexity. For
all the features, you will want to use "object roles table" (see below)


Question: I know that if you have a loop that modifies the count of the items in the loop, using the NSEnumerator on a set is the best way to make sure your code blows up, however I would like to understand the performance tradeoffs between the NSEnumerator class and just an old school for loop

Answer:
They are very similar. With Objective-C 2.0 most enumerations now default to
```
NSFastEnumeration
```
which creates a buffer of the addresses to each object in the collection that it can then deliver. The one step that you save over the classic for loop is not having to call
```
objectAtIndex:i
```
each time inside the loop. The internals of the collection you are enumerating implement fast enumeration with out calling
```
objectAtIndex:i method
```
.
The buffer is part of the reason that you can't mutate a collection as you enumerate, the address of the objects will change and the buffer that was built will no longer match.
As a bonus the format in 2.0 looks as nice as the classic for loop:
```
```
for ( Type newVariable in expression ) {
    stmts
}
```
```
Read the following documentaion to go deeper:
NSFastEnumeration Protocol Reference


Question:
The leaving your wireless network open question reminded me of this.

I typically share the root drive on my machines across my network, and tie login authorization to the machines NT ID, so there is at least some form of protection.

My question, how easy is it to gain access to these drives for ill good? Is the authorization enough, or should I lock things down more?

Answer:
I can't answer the main question, but do keep in mind that Windows, by default, is always sharing the roots of your drives. Try:
```
```
\\yourmachine\c$
```
```
(And then try not to freak out.)


Question:
I have a very large code base that contains extensive unit tests (using CppUnit). I need to work out what percentage of the code is exercised by these tests, and (ideally) generate some sort of report that tells me on a per-library or per-file basis, how much of the code was exercised.

Here's the kicker: this has to run completely unnatended (eventually inside a continuous integration build), and has to be cross platform (well, WIN32 and *nix at least).

Can anyone suggest a tool, or set of tools that can help me do this? I can't change away from CppUnit (nor would I want to - it kicks ass), but otherwise I'm eager to hear any recommendations you might have.

Cheers,

Answer:
Which tool should I use?
This
article describes
another developers frustrations searching for C++ code coverage tools.  The author's final solution was
Bullseye Coverage
.
Bullseye Coverage
features:
Cross Platform Support
(win32, unix, and embedded), (supports linux gcc compilers and MSVC6)
Easy to use
(up and running in a few hours).
Provides "best" metrics
: Function Coverage and Condition/Decision Coverage.
Uses source code instrumentation.
As for hooking into your continuous integration, it depends on which CI solution you use, but you can likely hook the instrumentation / coverage measurement steps into the make file you use for automated testing.
Testing Linux vs Windows?
So long as all your tests run correctly in both environments, you should be fine measuring coverage on one or the other.  (Though Bullseye appears
to support both platforms
).  But why aren't you doing continuous integration builds in both environments??  If you deliver to clients in both environments then you
need
to be testing in both.
For that reason, it sounds like you might need to have two continuous build servers set up, one for a linux build and one for a windows build.  Perhaps this can be easily accomplished with some virtualization software like
vmware
or
virtualbox
.  You may not need to run code coverage metrics on both OSs, but you should definitely be running your unit tests on both.


Question: Suppose you have an ActiveRecord::Observer in one of your Ruby on Rails applications - how do you test this observer with rSpec?

Answer:
Disclaimer: I've never actually done this on a production site, but it looks like a reasonable way would be to use mock objects,
```
should_receive
```
and friends, and invoke methods on the observer directly
Given the following model and observer:
```
```
class Person < ActiveRecord::Base
  def set_status( new_status )
    # do whatever
  end
end

class PersonObserver < ActiveRecord::Observer
  def after_save(person)
    person.set_status("aha!")
  end
end
```
```
I would write a spec like this (I ran it, and it passes)
```
```
describe PersonObserver do
  before :each do
    @person = stub_model(Person)
    @observer = PersonObserver.instance
  end

  it "should invoke after_save on the observed object" do
    @person.should_receive(:set_status).with("aha!")
    @observer.after_save(@person)
  end
end
```
```


Question:
How do I make diff ignore temporary files like foo.c~? Is there a configuration file that will make ignoring temporaries the default?

More generally: what's the best way to generate a "clean" patch off a tarball? I do this rarely enough (submitting a bug fix to an OSS project by email) that I always struggle with it...

EDIT: OK, the short answer is

diff -ruN -x *~ ...

Is there a better answer? E.g., can this go in a configuration file?

Answer:
This doesn't strictly answer your question, but you can avoid the problem by configuring Emacs to use a specific directory to keep the backup files in. There are different implementations for Emacs or XEmacs.
In GNU Emacs
```
(defvar user-temporary-file-directory
      (concat temporary-file-directory user-login-name "/"))
    (make-directory user-temporary-file-directory t)
    (setq backup-by-copying t)
    (setq backup-directory-alist
      `(("." . ,user-temporary-file-directory)
        (,tramp-file-name-regexp nil)))
    (setq auto-save-list-file-prefix
      (concat user-temporary-file-directory ".auto-saves-"))
    (setq auto-save-file-name-transforms
      `((".*" ,user-temporary-file-directory t)))
```
In XEmacs
```
(require 'auto-save)
    (require 'backup-dir)

    (defvar user-temporary-file-directory
      (concat (temp-directory) "/" (user-login-name)))
    (make-directory user-temporary-file-directory t)
    (setq backup-by-copying t)
    (setq auto-save-directory user-temporary-file-directory)
    (setq auto-save-list-file-prefix
         (concat user-temporary-file-directory ".auto-saves-"))
    (setq bkup-backup-directory-info
      `((t ,user-temporary-file-directory full-path)))
```
You can also remove them all with a simple find command
```
find . -name “*~” -delete
```
Note that the asterisk and tilde are in double quotes to stop the shell expanding them.
By the way, these aren't strictly
temporary
files. They are a backup of the previous version of the file, so you can manually "undo" your last edit at any time in the future.


Question:
In a web application, I have a page that contains a DIV that has an auto-width depending on the width of the browser window.

I need an auto-height for the object.  The DIV starts about 300px from the top screen, and its height should make it stretch to the bottom of the browser screen.  I have a max height for the container DIV, so there would have to be minimum-height for the div.  I believe I can just restrict that in CSS, and use Javascript to handle the resizing of the DIV.

My javascript isn't nearly as good as it should be.  Is there an easy script I could write that would do this for me?

Edit:
The DIV houses a control that does it's own overflow handling (implements its own scroll bar).

Answer:
What should happen in the case of overflow?  If you want it to just get to the bottom of the window, use absolute positioning:
```
```
div {
  position: absolute;
  top: 300px;
  bottom: 0px;
  left: 30px;
  right: 30px;
}
```
```
This will put the DIV 30px in from each side, 300px from the top of the screen, and flush with the bottom.  Add an
```
overflow:auto;
```
to handle cases where the content is larger than the div.
Edit: @Whoever marked this down, an explanation would be nice... Is something wrong with the answer?


Question: I'm using the ASP.NET Login Controls and Forms Authentication for membership/credentials for an ASP.NET web application.  It keeps redirecting to a Login.aspx page at the root of my application that does not exist.  My login page is within a folder.

Answer:
I found the answer at
CoderSource.net
.  I had to put the correct path into my web.config file.
```
```
<?xml version="1.0"?>
<configuration>
    <system.web>
        ...
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Forms">
            <forms loginUrl="~/FolderName/Login.aspx" />
        </authentication>
        ...
    </system.web>
    ...
</configuration>
```
```


Question: I've noticed that some sites (usually banks) suppress the ability to paste text into text fields. How is this done? I know that JavaScript can be used to swallow the keyboard shortcut for paste, but what about the right-click menu item?

Answer:
Probably using the
```
onpaste
```
event, and either
```
return false
```
from it or use
```
e.preventDefault()
```
on the Event object.
Note that
```
onpaste
```
is
non standard
, don't rely on it for production sites, because it will not be there forever.
```
```
$(document).on("paste",function(e){
  console.log("paste")
  e.preventDefault()
  return false;
})
```
```


Question:
I would like to extend some existing applications' drag and drop behavior, and I'm wondering if there is any way to hack on drag and drop support or changes to drag and drop behavior by monitoring the app's message loop and injecting my own messages.

It would also work to monitor for when a paste operation is executed, basically to create a custom behavior when a control only supports pasting text and an image is pasted.

I'm thinking Detours might be my best bet, but one problem is that I would have to write custom code for each app I wanted to extend.  If only Windows was designed with extensibility in mind!

On another note, is there any OS that supports extensibility of this nature?

Answer:
With jQuery newer than 1.2 you can use
JSONP


Question:
Would it be possible to print Hello twice using single condition?

if  "condition"
  printf ("Hello");
else
  printf("World");

Answer:
The
```
if
```
statement executes one or the other of the controlled statements (both
```
printf
```
in your example). No matter what you use for
```
condition
```
, that snippet will either print "Hello", or "World", but never both.
Edit: Okay, so it's a trick question and you can put whatever you like in the condition (including a call to an entire other function that does anything you want). But that's hardly interesting. I can't believe I got downmodded for giving a correct answer.


Question: How can you implement trackbacks on a custom-coded blog (written in C#)?

Answer:
If you're custom coding your own blog you have too much time on your hands.  Start with something like
dasBlog
or
SubText
and customize that to your needs.  Then you get trackbacks for free.


Question:
Winform on CF is a bit heavy, initialising a lot of windows handles takes serious time and memory. Another issue is the lack of inbuilt double buffering and lack of control you have over the UI rendering means that during processor intensive operations the UI might leave the user staring at a half rendered screen. Nice!

To alleviate this issue I would seek a lightweight control framework, is there one kicking about already or would one have to homebrew?

By lightweight I mean a control library that enables one to fully control painting of controls and doesn't use many expensive windows handles.

NOTE: Please don't suggest that I am running too much on the UI thread. That is not the case.

Answer:
Actually, you can override the paint event.
And the idea is that you offload long-running operations to a separate thread.  That's no different from any other event-driven framework, really.
Anything
that relies on a handling a Paint event is going to be susceptible to that.
Also, there's no system that lets you determine when the paint event is raised. That kind of event is generally raised by the window manager layer, which is outside of the application (or even the framework). You can handle the event yourself and just do no work some of the time, but I wouldn't recommend it.


Question:
Assuming such a query exists, I would greatly appreciate the help.

I'm trying to develop a permissions script that will grant "select" and "references" permissions on the user tables and views in a database.  My hope is that executing the "grant" commands on each element in such a set will make it easier to keep permissions current when new tables and views are added to the database.

Answer:
```
```
select * from information_schema.tables
where table_type = 'view'
```
```


Question:
Imagine you homebrew a custom gui framework that doesn't use windows handles (compact framework, so please don't argue with "whys"). One of the main disadvantages of developing such a framework is that you lose compatability with the winform designer.

So my question is to all of you who know a lot about VS customisation, would there be a clever mechanism by which one could incorperate the gui framework into the designer and get it to spit out your custom code instead of the standard windows stuff in the InitialiseComponent() method?

Answer:
```
```
select * from information_schema.tables
where table_type = 'view'
```
```


Question:
Within an application, I've got Secret Keys uses to calculate a hash for an API call.  In a .NET application it's fairly easy to use a program like Reflector to pull out information from the assembly to include these keys.

Is obfuscating the assembly a good way of securing these keys?

Answer:
Probably not.
Look into cryptography and Windows' built-in information-hiding mechanisms (DPAPI and storing the keys in an ACL-restricted registry key, for example). That's as good as you're going to get for security you need to keep on the same system as your application.
If you are looking for a way to stop someone physically sitting at the machine from getting your information, forget it. If someone is determined, and has unrestricted access to a computer that is not under your control, there is no way to be 100% certain that the data is protected under all circumstances. Someone who is determined will get at it if they want to.


Question:
I have a JavaScript method that I need to run on one of my pages, in particular, the onresize event.

However, I don't see how I can set that event from my content page.  I wish I could just put it on my master page, but I don't have the need for the method to be called on all pages that use that master page.

Any help would be appreciated.

Answer:
Place the following in your content page:
```
```
<script type="text/javascript">

// here is a cross-browser compatible way of connecting
// handlers to events, in case you don't have one
function attachEventHandler(element, eventToHandle, eventHandler) {
    if(element.attachEvent) {
       element.attachEvent(eventToHandle, eventHandler);
    } else if(element.addEventListener) {
       element.addEventListener(eventToHandle.replace("on", ""), eventHandler, false);
    } else {
    element[eventToHandle] = eventHandler;
  }
}

attachEventHandler(window, "onresize", function() {
    // the code you want to run when the browser is resized
});

</script>
```
```
That code should give you the basic idea of what you need to do. Hopefully you are using a library that already has code to help you write up event handlers and such.


Question:
When trying to execute from within Visual Studio 2008 your application and you get the (uninformative) message "The operation could not be completed".

The solution to this is to turn off the "Visual Studio Hosting Process".

The problem with turning off this "hosting process" is that all the "run and rewrite" functionality is no longer available. OK, so this isn't a big deal, but I'm always getting this message no matter what machine I use (and it might be nice once in a while to use the rewrite and execute functionality).

Am I doing something wrong? How come this "feature" within VS seems to complain so readily? Do other people have success with enabling the hosting process and making use of it?

Answer: I honestly have never seen this message and I work with Visual Studio for at least 8 hours a day.  Is this reproducible on other machines?  If so is there anything weird or abnormal in your code that could cause this to crash?


Question:
I'm considering developing a website similar to stackoverflow, but the answers may also consist of drawings (schematics, in this case).  I want to have an area in the answer form where they can make this schematic without requiring special plugins, etc.

Are we to the point where SVG has or should have critical mass soon (1-2 years) such that designing a website where script-run SVG as a primary feature is reasonable (ie, requiring Firefox or another SVG/AJAX compliant browser)?

What are some good resources for learning cross platform SVG scripting (likely in javascript)?

-Adam Davis

Answer:
1/ probably never - if IE wanted to add it, then I would have though it would have done so by now; but there are workarounds using
SilverLight
and
Gecko
to provide rendering. On the other hand, there are cross-browser graphics APIs available. I've done largish front ends using XULRunner and SVG, but nothing on the web which had to cater for IE.
2/ The two I referred to most often were the
SVG pages on mozilla.org
and this
SVG DOM reference
. All of my SVG links are here on
delicious
There's one existing editor at
http://www.bpel4chor.org/editor/
; also if all you want is schematics where all arcs are on a grid, you can do that quite well using divs and images without SVG. Or you could just go the
lo-fi route


Question:
I using SharePoint Designer to create a workflow. I'm trying to get at a sub-folder in a document library in the "Define Workflow Lookup" dialog.  There are two issues with this:

I can't look up items by URL Path. If I look up by Title, I can
output the URL Path, but selecting by path doesn't work.  What
fields can/can't I use?

I can't get at any sub-folders.  I can get at the top-level folder,
but the sub-folders don't seem to be available. Noticed the same
things is true when looking at the data for a document library in
the "Data Source Library" in Designer.

To clarify, the workflow is on a different list, not on the document library.

UPD: Also, I know how to do this through the object model, the question is how to do it in SharePoint Designer without deploying code to the server.

Answer:
I really don't have much experience with Sharepoint, but I thought I could at least provide
some
answer - even if it's the wrong one.
From another dev I've spoken to it sounds like it's tough to get into any subfolders, so you might need to look at making your own custom workflow.
Maybe something like LINQ to Sharepoint might be able to help you with actually getting in and enumerating the subfolders and getting to the data that you need?
LINQ to Sharepoint


Question: What's the best lifetime model for a DataContext? Should I just create a new one whenever I need it (aka, function level), should I keep one available in each class that would use it (class level), or should I create a static class with a static DataContext (app-domain level)? Are there any considered best practices on this?

Answer:
I think Jeff Atwood talked about this in the
Herding Code podcast
, when he was questioned about the exact same thing. Listen to it towards the last 15-20 minutes or so.
I think in SO, the datacontext is created in the Controller class. Not sure about a lot of details here. But that's what it looked like.


Question:
After reading Jeff's blog post on Protecting Your Cookies: HttpOnly. I'd like to implement HttpOnly cookies in my web application.

How do you tell tomcat to use http only cookies for sessions?

Answer:
For session cookies it doesn't seem to be supported in Tomcat yet. See the bug report
Need to add support for HTTPOnly session cookie parameter
. A somewhat involved work-around for now can be found
here
, which basically boils down to manually patching Tomcat. Can't really find an easy way to do it at this moment at this point I'm affraid.
To summarize the work-around, it involves downloading the 5.5
source
, and then change the source in the following places:
org.apache.catalina.connector.Request.java
```
```
//this is what needs to be changed
//response.addCookieInternal(cookie);

//this is whats new
response.addCookieInternal(cookie, true);
}
```
```
org.apache.catalina.connectorResponse.addCookieInternal
```
```
public void addCookieInternal(final Cookie cookie) {
addCookieInternal(cookie, false);
}

public void addCookieInternal(final Cookie cookie, boolean HTTPOnly) {

if (isCommitted())
return;

final StringBuffer sb = new StringBuffer();
//web application code can receive a IllegalArgumentException
//from the appendCookieValue invokation
if (SecurityUtil.isPackageProtectionEnabled()) {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run(){
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(),
cookie.getValue(), cookie.getPath(),
cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
return null;
}
});
} else {
ServerCookie.appendCookieValue
(sb, cookie.getVersion(), cookie.getName(), cookie.getValue(),
cookie.getPath(), cookie.getDomain(), cookie.getComment(),
cookie.getMaxAge(), cookie.getSecure());
}
//of course, we really need to modify ServerCookie
//but this is the general idea
if (HTTPOnly) {
sb.append("; HttpOnly");
}

//if we reached here, no exception, cookie is valid
// the header name is Set-Cookie for both "old" and v.1 ( RFC2109 )
// RFC2965 is not supported by browsers and the Servlet spec
// asks for 2109.
addHeader("Set-Cookie", sb.toString());

cookies.add(cookie);
}
```
```


Question:
I am using Hibernate in a Java application to access my Database and it works pretty well with MS-SQL and MySQL. But some of the data I have to show on some forms has to come from Text files, and by Text files I mean Human-Readable files, they can be CSV, Tab-Delimited, or even a key, value pair, per line since my data is as simple as this, but my preference of course is XML files.

My question is: Can I use hibernate to read those files using HQL, Query , EntityManager and all those resources Hibernate provides me to access files. Which file format should I use and How I configure My persistence.xml file to recognize files as Tables?

Answer:
Hibernate is written against the JDBC API. So, you need a JDBC driver that works with the file format you are interested in. Obviously, even for read-only access, this isn't going to perform well, but it might still be useful if that's not a high priority. On a Windows system, you can set up ODBC datasources for delimited text files, Excel files, etc. Then you can set up the JdbcOdbcDriver in your Java application to use this data source.
For most of the applications I work on, I would not consider this approach; I would use an import/export mechanism to convert from a real database (even if it's an in-process database like Berkeley DB or Derby) to the text files. Yes, it's an extra step, but it could be automated, and the performance isn't likely to be much worse than trying to use the text files directly (it will likely be much better, overall), and it will be more robust and easy to develop.


Question: Is there a way to call out from a TSQL stored procedure or function to a webservice?

Answer:
Not in T-SQL code itself, but with SQL Server 2005 and above, they've enabled the ability to write CLR stored procedures, which are essentially functions in .NET code and then expose them as stored procedures for consumption. You have most of the .NET framework at your fingertips for this, so I can see consumption of a web service possible through this.
It is a little lengthy to discuss in detail here, but here's a link to an
MSDN article
on the topic.


Question:
Does anyone have a definitive answer to whether Sql Server Management Objects is compatible with Sql Server 7.0?
The docs state:

Because SMO is compatible with SQL Server version 7.0, SQL Server 2000, SQL Server 2005, and SQL Server 2008, you easily manage a multi-version environment.

But trying to connect to a Sql 7 instance gets me:

"This SQL Server version (7.0) is not supported."

Has anyone been successful in getting these 2 to play nice?

Answer:
you can use SMO to connect to SQL Server versions 7, 2000, and 2005, but SMO does not support databases set to compatibility levels 60, 65, and 70.
for SQL Server 7.0 the compatibility level is 70
Obviously this is conflicting information...I assume if your compatibility level of your DB is 70 you can not connect.
To check run: EXEC sp_dbcmptlevel '
databasename
'
Looking through this link
, it seems you might be able to change the compatibility level by running this:
EXEC sp_dbcmptlevel '
databasename
', 80
Obviously make a back up before changing anything.


Question:
Is it possible to use a flash document embedded in HTML as a link?

I tried just wrapping the object element with an a like this:

<a href="http://whatever.com">
    <object ...>
        <embed ... />
    </object>
</a>

In Internet Explorer, that made it show the location in the status bar like a link, but it doesn't do anything.

I just have the .swf file, so I can't add a click handler in ActionScript.

Answer:
Though the object really should respond to being wrapped in an a href tag, you could open the swf in vim and just throw in an
```
_root.onPress=function(){getURL("http://yes.no/");};
```
or if it's AS3, something like
```
_root.addEventHandler(MouseEvent.PRESS, function (e:event) {getURL("http://yes.no/");});
```
But if editing the swf is your route, you'd likely have more success with
a tool for the purpose
.


Question: I'm starting a new web project and I am considering two presentation frameworks. I am thinking either about ASP.NET MVC or Silverlight. I would tend toward Silverlight since I'm quite experienced .NET developer while I have just a basic knowledge of ASP.NET controls.

Answer:
It's hard to recommend one over the other without knowing what your application is.  Whatever you do decide, make sure you keep your target audience in mind; not everyone is going to have Silverlight installed on their computers.
Personally, unless I was designing an incredibly interactive and beautiful web app, I would go with ASP.NET (with or without the MVC framework) if only for the fact that there is a
ton
of reference material for it while Silverlight is still relatively new territory.


Question:
Right now, I keep all of my projects on my laptop. I'm thinking that I shouldn't do this, but instead use a version control system and check them in/out from an external hosting repository (Google Code, SourceForge, etc). I see several benefits here - first, I don't have to worry about losing my code if my computer crashes and burns or my external HDD crashes and burns; second, I can share my code with the world and perhaps even get more help when I need it.

Is this a good idea? If so, what are some other project hosts that I should investigate (other than Google Code and SourceForge)?

Answer:
Assembla
is
awesome.
EDIT: Yes, this is a good idea - I used to use a personal copy of
Vault
and found it was more than I cared to manage (in case my server went down or hard drive crashed - not only was it painful to worry about losing and backing up data, but the downtime). Of course, it doesn't hurt to have your own backup as well. Cover all your bases!


Question:
Inspired by this CodingHorror article, "Protecting Your Cookies: HttpOnly"

How do you set this property? Somewhere in the web config?

Answer:
With props to Rick (second comment down in the blog post mentioned), here's the
MSDN article
on httpOnlyCookies.
Bottom line is that you just add the following section in your system.web section in your web.config:
```
```
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
```
```


Question:
I want to check out all files in all subdirectories of a specified folder.

(And it is painful to do this using the GUI, because there is no recursive checkout option).

Answer:
```
```
cleartool find somedir -exec "cleartool checkout -nc \"%CLEARCASE_PN%\""
```
```
Also an article "
ClearCase: The ten best scripts
" might be helpful


Question:
Obviously, that's 64-bit windows.

Also, what's the maximum amount of memory a single 64-bit process can use?
I was kind of counting on using it all...
(Yes, I know what I'm doing, please don't tell me that if I need that much RAM i must be doing something wrong)

Also, is this the same for a .Net 2.0 process? Or is there a lower limit for .Net?

Answer: Something we found out recently: with MySQL running on Win32, you can only use up to 2GB per process. On Win64, the memory is not managed as well and a single MySQL instance will run your memory into the ground. Ours used up all 16GB we have. So regarding how much memory 1 64-bit process can use: the answer is however much the OS allows.


Question: I assume it doesn't connect to anything (other than the satelite I guess), is this right? Or it does and has some kind of charge?

Answer:
There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing.  Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.
If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.
Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.
Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.


Question:
As you develop an application database changes inevitably pop up.  The trick I find is keeping your database build in step with your code.  In the past I have added a build step that executed SQL scripts against the target database but that is dangerous in so much as you could inadvertanly add bogus data or worse.

My question is what are the tips and tricks to keep the database in step with the code?  What about when you roll back the code?  Branching?

Answer:
Version numbers embedded in the database are helpful.  You have two choices, embedding values into a table (allows versioning multiple items) that can be queried, or having an explictly named object (such as a table or somesuch) you can test for.
When you release to production, do you have a rollback plan in the event of unexpected catastrophe?  If you do, is it the application of a schema rollback script?  Use your rollback script to rollback the database to a previous code version.


Question:
I'm a PHP developer, and I use the MVC pattern and object-oriented code. I really want to write applications for the iPhone, but to do that I need to know Cocoa, but to do that I need to know Objective-C 2.0, but to do that I need to know C, and to do that I need to know about compiled languages (versus interpreted).

Where should I begin?
Do I really need to begin with plain old "C", as Joel would recommend?

Caveat: I like to produce working widgets, not elegant theories.

Answer:
I think starting with C would be a smart thing to do. After all, Objective-C is C language with some extensions.
To develop in Cocoa you are required to know well how pointers and memory allocation work (there's no garbage collection on the iPhone), plus you will have to use some standard C libraries,
because a lot of the frameworks that are used to develop for the iPhone are C libraries
not Cocoa libraries. Take for example CoreGraphics, the library you have to use to draw on the screen on the iPhone. That's a C framework, meaning that it is not written in Objective-C.
Of course after learning C to a modest level, you could start reading about Objective-C and Cocoa, and in that case I would start with the
Objective-C language specification
(link to PDF)
and the Aaron Hillegas book on Cocoa.


Question:
I'm working on a visual studio 2005 vb.net windows forms project that's been around for several years.  It's full of default textboxes, labels, dropdowns, datagrids, datetime pickers -- all the standard stuff.  The end result is a very gray, old-looking project.

What would be the best approach to making this project look fresh and snazzy?  I'd rather not rewrite the entire solution with all brand new forms objects, but would that be avoidable?

Answer:
This depends on how the existing "gray old looking" project is structured in terms of code.  For example, is data access code separated from the UI in a Data Access Layer, is the business logic in a Business Logic Layer?  If yes, then cleaning the UI for a snazzy look should be relatively simple.
If everything is all there in the "Button Click" event, then a rewrite is the only way in my humble opinion as otherwise it will just be too time consuming trying to work with the existing code base.
Cheers


Question:
How would I change the initial templates created by Xcode when creating a new Cocoa Class.

I am referring to the comments and class name created when using Xcode's new class wizard.

Answer:
You wouldn't change the existing templates.  In other words, don't
modify
anything under the
```
/Developer
```
hierarchy (or wherever you installed your developer tools).
Instead, clone the templates you want to have customized variants of.  Then change their names and the information in them.  Finally, put them in the appropriate location in your account's
```
Library/Application Support
```
folder, specifically:
File templates:
```
~/Library/Application Support/Developer/Shared/Xcode/File Templates/
```
Target templates:
```
~/Library/Application Support/Developer/Shared/Xcode/Target Templates/
```
Project templates:
```
~/Library/Application Support/Developer/Shared/Xcode/Project Templates/
```
That way they won't be overwritten when you install new developer tools, and you can tweak them to your heart's content.
Update
For newer versions of Xcode the updated path will be:
```
~/Library/Developer/Xcode/Templates/File Templates/Source
```


Question:
I would like to add the following MIME type to a site run by Apache:

<mime-mapping>
  <extension>jnlp</extension>
  <mime-type>application/x-java-jnlp-file</mime-type>
</mime-mapping>

That is the Tomcat format.

I'm on a shared host, so I can only create an .htaccess file. Would someone please specify the complete contents of such a file?

Answer:
You should be able to just add this line:
```
```
AddType application/x-java-jnlp-file     .jnlp
```
```


Question:
Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters that belong to a stored procedure on a SQL Server before I actually execute it?

I have an a "multi-environment" scenario where there are multiple versions of the same database schema. Examples of environments might be "Development", "Staging", & "Production". "Development" is going to have one version of the stored procedure and "Staging" is going to have another.

All I want to do is validate that a parameter is going to be there before passing it a value and calling the stored procedure. Avoiding that SqlException rather than having to catch it is a plus for me.

Joshua

Answer:
```
```
SqlCommandBuilder.DeriveParameters(command)
```
```
This statement does what I need it to.
Here is a full code sample for the way I solved this problem.
```
```
Public Sub GetLogEntriesForApplication(ByVal settings As FilterSettings,
                              Optional ByVal RowGovernor As Integer = -1)

    Dim command As New SqlCommand("GetApplicationActions",
        New SqlConnection(m_environment.LoggingDatabaseConnectionString))
    Dim adapter As New SqlDataAdapter(command)

    Using command.Connection

        With command

            .Connection.Open()
            .CommandType = CommandType.StoredProcedure

            SqlCommandBuilder.DeriveParameters(command)

            With .Parameters

                If settings.FilterOnLoggingLevel Then
                    If .Contains("@loggingLevel") Then
                        .Item("@loggingLevel").Value = settings.LoggingLevel
                    End If
                End If

                If settings.FilterOnApplicationID Then
                    If .Contains("@applicationID") Then
                        .Item("@applicationID").Value = settings.ApplicationID
                    End If
                End If

                If settings.FilterOnCreatedDate Then
                    If .Contains("@startDate") Then
                        .Item("@startDate").Value = settings.CreatedDate.Ticks
                    End If
                End If

                If settings.FilterOnEndDate Then
                    If .Contains("@endDate") Then
                        .Item("@endDate").Value = settings.EndDate.Ticks
                    End If
                End If

                If settings.FilterOnSuccess Then
                    If .Contains("@success") Then
                        .Item("@success").Value = settings.Success
                    End If
                End If

                If settings.FilterOnProcess Then
                    If settings.Process > -1 Then
                        If .Contains("@process") Then
                            .Item("@process").Value = settings.Process
                        End If
                    End If
                End If

                If RowGovernor > -1 Then
                    If .Contains("@topRows") Then
                        .Item("@topRows").Value = RowGovernor
                    End If
                End If

            End With

        End With

        adapter.TableMappings.Clear()
        adapter.TableMappings.Add("Table", "ApplicationActions")
        adapter.TableMappings.Add("Table1", "Milestones")

        LogEntries.Clear()
        Milestones.Clear()
        adapter.Fill(m_logEntryData)

    End Using

End Sub
```
```


Question: I run Flex Builder 3 on a mac and as my project grows - the compile time gets longer and longer and longer.  I am using some SWC's and there is a fair amount of code but it shouldn't take minutes to build and crash daily should it?

Answer:
You may want to explore the command-line compiler found in the Flex SDK,
```
mxmlc
```
. As I recall, Flex Builder 3 seems to hide all the compiler details, but perhaps there are arguments you can append that will help you speed up the compilation.
For example, you may want to set
```
optimize=false
```
which will skip the step of optimizing the bytecode (perhaps reducing compilation time)?  This of course comes at the price of performance and file size of the actual application.
More documentation on
```
mxmlc
```
can be found at:
http://livedocs.adobe.com/flex/3/html/compilers_13.html
.
Good luck!


Question:
I am currently using the following command to upload my site content:

scp -r web/* user@site.com:site.com/

This works great except that the .htaccess file is not sent. Presumably, this is because it's hidden.

I have tried adding a second line to send the file explicitely:

scp -r web/.htaccess user@site.com:site.com/.htaccess

This works great except now I have to enter my password twice.

Any thoughts on how to make this deploy with only 1 or 0 entries of my password?

Answer:
Just combine the two commands:
```
```
scp -r web/* web/.htaccess user@site.com:site.com/
```
```
If you want 0 entries of your password you can set up
public key authentication
for ssh/scp.


Question:
I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like

<img src="example.jpg"
alt="example">

If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then re-inserting them at the closest >, but this seems like a kludge.

Ideally, I'd be able to detect a tag that spans lines, conjoin only those to lines, and continue processing.

So what's the best method to detect this?

Answer:
Well, this doesn't answer the question and is more of an opinion, but...
I think that the best scraping strategy (and consequently, to eliminate this problem) is not to analyze an HTML line by line, which is unnatural to HTML, but to analyze it by its natural delimiter: <> pairs.
There will be two types of course:
Tag elements that are immediately closed, e.g., < br />
Tag elements that need a separate closing tag, e.g., < p > text < /p >
You can immediately see the advantage of using this strategy in the case of paragraph(p) tags: It will be easier to parse mutiline paragraphs instead of having to track where the closing tag is.


Question:
I have an application which really should be installed, but does work fine when deployed using JNLP.

However, it would seem that some Java functions such as Runtime.exec don't work using the default security options.

I would like to therefore disable UI functionality that relies upon such functions.

So my question is, how do I detect at runtime whether certain functions are available or not?

The case study, here of course, is Runtime.exec.

Answer:
You want to ask to the
SecurityManager
if you have Exec right with the checkExec method.


Question:
I'm planning on doing more coding from home but in order to do so, I need to be able to edit files on a Samba drive on our dev server. The problem I've run into with several editors is that the network latency causes the editor to lock up for long periods of time (Eclipse, TextMate). Some editors cope with this a lot better than others, but are there any file system or other tweaks I can make to minimize the impact of lag?

A few additional points:

There's a policy against having company data on personal machines, so I'd like to avoid checking out the code locally.

The mount is over a PPTP VPN connection.

Mounting to Linux or OS X client

Answer:
Use a source control system — Subversion, Perforce, Git, Mercurial, Bazaar, etc. — so you're never editing code on a shared server.  Instead you should be editing a local work area and committing changes to a repository located on the network.
Also, convince your company to adapt their policy such that company code is allowed on personal machines
if
it's on an encrypted volume.  Encrypted disk images that you can use for this are
trivial
to create using Disk Utility, and can use strong cryptography.  You can get even more security by not storing your encryption passphrase in your keychain, and instead typing it every time you mount the encrypted volume; this means that even if your local user account is compromised, as long as you don't have the volume mounted, nobody else will be able to mount it.
I did this all the time when I was consulting and none of my clients — some of whom had similar rules about company code — ever had a problem with it once I explained how things worked.  (I think some of them even started using encrypted disk images even within their offices.)


Question:
In my (PHP) web app, I have a part of my site that keeps a history of recent searches. The most recent queries get shown in a side box. If the query text is too long, I truncate it and show ellipses. Eg: "My very long query is..."

Currently, I truncate after a certain number of characters. Since the font is not monotype, a query of all I's is more narrow than a query of all W's. I'd like them to all be about the same width prior to the ellipses. Is there a way to get the approximate width of the resulting string so that the ellipses for any given string will occur in about the same number of pixels from the beginning? Does CSS have a way? Does PHP? Would this be better handled by JavaScript?

Answer:
Does CSS have a way?
No
Does PHP?
No
-
To do that you'd have to get the font metrics for each character, and apply them to all your letters in your string. While you could do this by using a drawing/rendering library like ImageMagick on the server, it wouldn't really work because different browser on different OS's render fonts differently.
Even if it did work, you wouldn't want to do it, because it would also take forever to render. Your server would be able to push 1 page per second (if that) instead of several thousand.
If you can live without the trailing ..., then you can nicely fake it using
```
div
```
tags and css
```
overflow: hidden
```
, like this:
```
```
.line_of_text {
    height:1.3em;
    line-height:1.3em;
    overflow:hidden;
}

 Some long text which will arbitrarily be cut off at whatever word fits best

```
```


Question:
Today I was listening to the Hanselminutes show about .NET 3.5 SP1...What's inside, and they twice mentioned the Office 2007-like Ribbon control that is included in Visual Studio 2008 Service Pack 1.

I am very interested about this, as I was previously looking at purchasing this from a 3rd party vendor (likely DevComponent's DotNetBar).  However, I did some research this morning and have found nothing about this control being included for use with C# and WPF.  Does anyone know more about the included Ribbon control and whether or not it is available for C# or WPF?

Answer:
Yeah I did a double-take when I heard them say that too.
The ribbon control, along with a DatePicker and DataGrid, are being developed out of band
over here
on CodePlex. I'm not sure why Carl and Scott were suggesting that it was part of the SP1 release.
Vincent Sibal
posts about DataGrid (which is available already in some form) on his blog.


Question: Whilst starting to learn lisp, I've come across the term tail-recursive. What does it mean exactly?

Answer:
I'm not a Lisp programmer, but I think
this
will help.
Basically it's a style of programming such that the recursive call is the last thing you do.


Question:
I have the following textarea in a table:

<table width="300"><tr><td>

<textarea style="width:100%">
longstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstringlongstring
</textarea>

</td></tr></table>

With a long string in the textarea, the textarea stretches out to accommodate it in one line in IE7, but retains its 300px width in other browsers.

Any ideas as to how to fix this in IE?

Answer:
did you try...
```
overflow: hidden;
```
??
I'm not sure if it should be in the table of the textarea... experiment a bit


Question:
What is the minimum I need to add to a .NET 2.0 WebSite's web.config to make it .NET 3.5?

Visual Studio adds all the config sections and script handlers, but if you aren't using those are they are really necessary?

Is there a command line tool to "upgrade" a .NET 2.0 web.config to 3.5?

Answer:
There is a good description of the 3.5 web.config available here:
https://web.archive.org/web/20211020153237/https://www.4guysfromrolla.com/articles/121207-1.aspx
The assemblies and config sections are important because they tell the runtime to use the new 3.5 dlls instead of the 2.0 dlls
The
codedom
section tells the compiler to use 3.5.
If you're not using ASP.Net Ajax you can probably skip the rest.  I've never tested that though.


Question:
Could someone tell me what the units the SetTimeout(int) method in the ICriteria interface uses?

Is it milliseconds, seconds, minutes or other?

Answer:
I think it's seconds.  The NHibernate API closely mirrors Hibernate Core for Java, where the
Criteria.setTimeout(int)
method uses seconds as the units (see also
Statement.setQueryTimeout(int)
).
Also, after looking at some NHibernate source, it appears that it's using that value to set the timeout for the underlying ADO.NET query, which uses seconds.


Question:
Assume that I have a field called price for the documents in Solr and I have that field faceted. I want to get the facets as ranges of values (eg: 0-100, 100-500, 500-1000, etc). How to do it?

I can specify the ranges beforehand, but I also want to know whether it is possible to calculate the ranges (say for 5 values) automatically based on the values in the documents?

Answer:
There may well be a better Solr-specific answer, but I work with straight Lucene, and since you're not getting much traction I'll take a stab. There, I'd create a populate a
```
Filter
```
with a
```
FilteredQuery
```
wrapping the original
```
Query
```
. Then I'd get a
```
FieldCache
```
for the field of interest. Enumerate the hits in the filter's bitset, and for each hit, you get the value of the field from the field cache, and add it to a SortedSet. When you've got all of the hits, divide the size of the set into the number of ranges you want (five to seven is a good number according the user interface guys), and rather than a single-valued constraint, your facets will be a range query with the lower and upper bounds of each of those subsets.
I'd recommend using some special-case logic for a small number of values; obviously, if you only have four distinct values, it doesn't make sense to try and make 5 range refinements out of them. Below a certain threshold (say 3*your ideal number of ranges), you just show the facets normally rather than ranges.


Question:
I would like to retrieve the ethernet address of the network interface that is used to access a particular website.

How can this be done in Java?

Solution Note that the accepted solution of getHardwareAddress is only available in Java 6. There does not seem to be a solution for Java 5 aside from executing i(f|p)confing.

Answer:
You can get the address that connects to your ServerSocket using
http://java.sun.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()
However if your client is connecting via a NAT, then you will get the address of the router and NOT the Ethernet address. If it is on your local network (via a hub/switch, no router with NAT) the it wil work as intended.


Question:
I've switched over to a Mac recently and, although things have been going quite well, the very different text-editing behaviours across applications is driving me insane.

Home, End, Page Up, Page Down, Apple-arrow, Ctrl-arrow, alt-arrow etc. quite often do different things depending on the application.

Is there a way to standardise this behaviour?

Answer:
There are standards, but they are not based around what you're used to from windows. It drove me mad until I got over myself and decided to learn what the actual standards were. Since then I've been sold.
The ones I use:
Command
-
Left
/
Right
- Jump to start/end of line
Can also do this with
ctrl
-
a
/
e
which is great if you're used to ssh
Command
-
Up
/
Down
- Jump to top/bottom of text field or document
Option
-
Left
/
Right
- Jump to start/end of word or previous/next word
These basically replace
home
/
end
/
pgup
/
pgdown
, and
ctrl
-
left
/
right
from the windows world.
I find this to be a massive win due to the fact I have a macbook pro and almost no laptops have proper
home
/
end
/
pgup
/
pgdown
keys - not needing them in OSX is a godsend
Here's a big list of the rest of them


Question: How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.

Answer:
I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:
PySizer, "a memory profiler for Python," found at
http://pysizer.8325.org/
.  However the page seems to indicate that the project hasn't been updated for a while, and refers to...
Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at
http://guppy-pe.sourceforge.net/#Heapy
.
Hope that helps.


Question:
How can you allow a PHP script to write to a file with high-security restrictions, such as only allowing a single user to write to it?

The difficulty seems to be that a PHP script is running as a low-permissions user (maybe apache, or www, or nobody?), and even if I chown apache the_writable_file, the directory it's in might not be writable for the low-level user.  In general, what's the usual way that PHP can work with local files in a secure way?

Answer:
Sure,
```
chgrp apache the_writable_file
```
and
```
chmod g+w the_writable_file
```
.  After that, only your secure user and the apache user will be able to write to the file.  Since the apache user is typically forbidden from logging in, you only have to worry about web users writing to your secure file using through the http daemon.


Question: A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether.  What can said about this rumor?

Answer: I've used it in several applications and have never had nor heard of threading being anything other than 100% reliable, as long as you know its limits.  You can't spawn 1000 threads at the same time and expect your program to run properly on Windows, however you can easily write a worker pool and just feed it 1000 operations, and keep everything nice and under control.


Question:
Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I:

Safely determine that such a key exists.

Programmatically (i.e. with code) get its value.

I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly.

Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.

Answer:
RegQueryValueEx
This gives the value if it exists, and returns an error code ERROR_FILE_NOT_FOUND if the key doesn't exist.
(I can't tell if my link is working or not, but if you just google for "RegQueryValueEx" the first hit is the msdn documentation.)


Question: What's the best way to specify a proxy with username and password for an http connection in python?

Answer:
This works for me:
```
```
import urllib2

proxy = urllib2.ProxyHandler({'http': 'http://
username:password@proxyurl:proxyport'})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler)
urllib2.install_opener(opener)

conn = urllib2.urlopen('http://python.org')
return_str = conn.read()
```
```


Question: I've been given a job of 'translating' one language into another. The source is too flexible (complex) for a simple line by line approach with regex. Where can I go to learn more about lexical analysis and parsers?

Answer:
I've recently been working with
PLY
which is an implementation of lex and yacc in Python. It's quite easy to get started with it and there are some simple examples in the documentation.
Parsing can quickly become a very technical topic and you'll find that you probably won't need to know all the details of the parsing algorithm if you're using a parser builder like PLY.


Question:
<xsl:for-each select="./node [position() &lt;= (count(*) div 2)]">
    <li>foo</li>
</xsl:for-each>
<xsl:for-each select="./node [count(*) div 2 &lt; position()]">
    <li>bar</li>
</xsl:for-each>

My list has 12 nodes, but the second list is always 8 and the first is always 4. What's wrong with my selects?

Answer:
I'm not at all sure, but it seems to me that
```
count(*)
```
is not doing what you think it is.  That counts the number of children of the current node, not the size of the current node list.  Could you print it out to check that it's 8 or 9 instead of 12?
Use
```
last()
```
to get the context size.


Question: I want to apply an XSLT Stylesheet to an XML Document using C# and write the output to a File.

Answer:
I found a possible answer here:
http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
From the article:
```
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;
```
```
Edit:
But my trusty compiler says,
```
XslTransform
```
is obsolete: Use
```
XslCompiledTransform
```
instead:
```
```
XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);
```
```


Question:
MS CRM Dynamics 4.0 incorporates the MS WF engine.  The built in designer allows the creation of sequential workflows whos activities have native access to CRM entities.

Is it possible to:

Create a state machine workflow
outside of CRM (i.e. in visual studio) and import it into CRM?

Have this workflow access the CRM
entities?

Answer:
I don't know the answer to your specific question, but hopefully this information will point you in the right direction.
The "native" format for WF workflows is ".xoml" files.  These are basically identical to XAML files, and both are nothing more than generic persistence formats for a .NET object tree.  If you can access the saved data that is output by the Dynamics designer, it should be in the same format.  If it is, you should be able to open it from the Visual Studio designer.
The key here is that CRM undoubtedly defines its own set of custom activities that you'll need to be able to reference from within the alternate designer.  With any luck, these will be in assemblies with obvious names and/or in the GAC.


Question:
I would like to know which dependency described in my pom.xml brings a transitive dependency in my target directory.

To be more precise, I have the library "poi-2.5.1-final-20040804.jar" in my WEB-INF/lib directory and I would like to know which dependency in my pom.xml brings that.

Answer:
Using the
Maven Dependency Plugin
:
```
```
mvn dependency:tree
```
```


Question:
Is the following safe?

I am new to threading and I want to delegate a time consuming process to a separate thread in my C++ program.
Using the boost libraries I have written code something like this:

thrd = new boost::thread(boost::bind(&myclass::mymethod, this, &finished_flag);

Where finished_flag is a boolean member of my class. When the thread is finished it sets the value and the main loop of my program checks for a change in that value.
I assume that this is okay because I only ever start one thread, and that thread is the only thing that changes the value (except for when it is initialised  before I start the thread)
So is this okay, or am I missing something, and need to use locks and mutexes, etc

Answer:
You never mentioned the type of finished_flag...
If it's a straight
bool
, then it might work, but it's certainly bad practice, for several reasons. First, some compilers will cache the reads of the
finished_flag
variable, since the compiler doesn't always pick up the fact that it's being written to by another thread. You can get around this by declaring the
bool
volatile
, but that's taking us in the wrong direction. Even if reads and writes are happening as you'd expect, there's nothing to stop the OS scheduler from interleaving the two threads half way through a read / write. That might not be such a problem here where you have one read and one write op in separate threads, but it's a good idea to start as you mean to carry on.
If, on the other hand it's a thread-safe type, like a
CEvent in MFC
(or
equivilent in boost
) then you should be fine. This is the best approach: use thread-safe synchronization objects for inter-thread communication, even for simple flags.


Question: I have the following situation: I built an Access form with a subform (which records are linked to the records of main form via certain key). When I try to delete any record in the subform, I get the following message: “Access has suspended the action because you and another user tried to change the data” (approximate translation from German). Does anyone know how to delete those records from the subform (and, respectively, from the table behind the form).

Answer:
If you are currently 'editing' the current form then it will not allow the action. Editing a record can sometimes be triggered by simply clicking inside a field, or other simple actions you wouldn't normally consider 'editing'.
This is usually avoided in Access by using the RunCommand method to undo any edits before deleting the record:
```
```
DoCmd.RunCommand acCmdUndo
```
```


Question: I want to get an overview of files that are updated in TFS (that someone else checked in) that I don't have the latest version for.

Answer:
if they checked them in as part of a single changeset then you can find them that way.
(right click file in solution explorer, view history, double-click on the relevant changeset and you'll see all the related files for that checkin)
Is your question about finding this info via the TFS API via the website, or via the visual studio interface?


Question:
I've been asked to create a Delphi compatible dll in C++ to do simple 64bit memory management.

The background is that the system in Delphi needs to allocate a lots of chunks of memory that would go well outside 32bit addressable space. The Delphi developer explained to me that he could not allocate memory with the Delphi commands available to him. He says that he can hold a 64bit address, so he just wants to call a function I provide to allocate the memory and return a 64bit pointer to him. Then another function to free up the memory later.

Now, I only have VS 2008 at my disposal so firstly I'm not even sure I can create a Delphi compatible dll in the first place.

Any Delphi experts care to help me out. Maybe there is a way to achieve what he requires without re-inventing the wheel. Other developers must have come across this before in Delphi.

All comments appreciated.

Answer:
Only 64 bit processes can address 64 bit memory. A 64 bit process can only load 64 bit dlls and 32 bits processes can only load 32 bits dlls. Delphi's compiler can only make 32 bits binaries.
So a 32 bits Delphi exe can not load your 64 bit c++ dll. It could load a 32 bit c++ dll, but then that dll wouldn't be able to address the 64 bit memory space. You are kind of stuck with this solution.
Delphi could, with the right compiler options and Windows switches address 3GB of memory without problems. Even more memory could be accessed by a 32 bits process if it uses
Physical Address Extension
. It then needs to swap memory pages in and out of the 32 bits memory through the use of
Address Windowing Extensions
.


Question:
I was wondering if anyone that has experience in both this stuff can shed some light on the significant difference between the two if any?

Any specific strength of each that makes it suitable for any specific case?

Answer:
I found SimpleTest was even easier than PHPUnit to set up. Just extract it and you are good to go. A benefit of this is if you are working at more than one machine, since you can store the whole testing framework the same way as your source code, and thereby know that you are using the same framework code. Especially if you modify it in any way.
So, I would say that a strength of SimpleTest is that it is very light weight and portable.
SimpleTest also ships with a very simple HTML GUI, which is quite easy to extend if you want to. As far as I know, PHPUnit does not include a HTML GUI, but there are GUI:s available to download, such as
Cool
.


Question:
I want to implement search functionality for a website (assume it is similar to SO). I don't want to use Google search of stuff like that.

My question is:

How do I implement this?

There are two methods I am aware of:

Search all the databases in the application when the user gives his query.

Index all the data I have and store it somewhere else and query from there (like what Google does).

Can anyone tell me which way to go? What are the pros and cons?

Better, are there any better ways to do this?

Answer:
Use lucene,
http://lucene.apache.org/java/docs/
Apache Lucene is a high-performance, full-featured text search engine library written entirely in Java. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform.
It is available in java and .net. It is also in available in php in the form of a zend framework module.
Lucene does what you wanted(indexing of the searched items), you have to keep track of a lucene index but it is much better than doing a database search in terms of performance. BTW, SO search is powered by lucene. :D


Question:
I have a multi dimensional OLAP cube with a number of dimensions. Some of these dimensions have hierarchies. The users would like to perform 'what-if' analysis on the measures in the cube by changing the hierarchies in the dimensions.

For example, they want to know the impact on departmental resource budgets by moving employees between departments or the movement in cost of manufacture if a product is moved from one factory to another.

Does anyone have a straight forward way to do this in a modern OLAP engine?

Answer:
There may be tools that allow this sort of analysis, but I only have experience of writing MDX, which ought to be able to help you.
Typical 'what if' analysis is more about changing values in the OLAP cube (e.g. change net sales from 845.45 to 700.00 and see what happens to gross profit). Your case is a bit different as you want to move members within a hierarhy, but keep the same values.
I haven't worked through a full solution, but the way I would approach it would be to create a new 'calculated member' or set (on the fly) and use that to build up the new hierarchy that you want. Your query can then use that on one axis.
Look carefully into 'visual totals' as there may be potential pitfalls there!


Question: Here's a wierd one. I'm reusing a code base that unfortunately must not be updated. This code makes a call to HttpContext.Current.Request.QueryString. Ideally, I need to push a value into this collection with every request that is made. Is this possible - perhaps in an HTTP Module?

Answer:
Without using reflection, the simplest way to do it would be to use the RewritePath function on the current HttpContext object in order to modify the querystring.
Using an
IHttpModule
, it might look something like:
```
```
context.RewritePath(context.Request.Path, context.Request.PathInfo, newQueryStringHere!);
```
```
Hope this helps!


Question:
Since there are no header sections for user controls in asp.net, user controls have no way of knowing about stylesheet files. So css classes in the user controls are not recognized by visual studio and produces warnings. How can I make a user control know that it will relate to a css class, so if it is warning me about a non-existing css class, it means that the class really do not exist?

Edit: Or should I go for a different design like exposing css classes as properties like "HeaderStyle-CssClass" of GridView?

Answer:
If you are creating composite UserControl, then you can set the
CSSClass
property on the child controls..
If not, then you need to expose properties that are either of the
Style
type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a
style
attribute to the HTML tags when rendering).


Question:
How would you programmacially abbreviate XHTML to an arbitrary number of words without leaving unclosed or corrupted tags?

i.e.

<p>
    Proin tristique dapibus neque. Nam eget purus sit amet leo
    tincidunt accumsan.
</p>
<p>
    Proin semper, orci at mattis blandit, augue justo blandit nulla.
    <span>Quisque ante congue justo</span>, ultrices aliquet, mattis eget,
    hendrerit, <em>justo</em>.
</p>

Abbreviated to 25 words would be:

<p>
    Proin tristique dapibus neque. Nam eget purus sit amet leo
    tincidunt accumsan.
</p>
<p>
    Proin semper, orci at mattis blandit, augue justo blandit nulla.
    <span>Quisque ante congue...</span>
</p>

Answer:
If you are creating composite UserControl, then you can set the
CSSClass
property on the child controls..
If not, then you need to expose properties that are either of the
Style
type, or (as I often do) string properties that apply CSS at the render type (i.e. take them properties and add a
style
attribute to the HTML tags when rendering).


Question: I would like to put a string into a byte array, but the string may be too big to fit.  In the case where it's too large, I would like to put as much of the string as possible into the array.  Is there an efficient way to find out how many characters will fit?

Answer:
In order to truncate a string to a UTF8 byte array without splitting in the middle of a character I use this:
```
```
static string Truncate(string s, int maxLength) {
    if (Encoding.UTF8.GetByteCount(s) <= maxLength)
        return s;
    var cs = s.ToCharArray();
    int length = 0;
    int i = 0;
    while (i < cs.Length){
        int charSize = 1;
        if (i < (cs.Length - 1) && char.IsSurrogate(cs[i]))
            charSize = 2;
        int byteSize = Encoding.UTF8.GetByteCount(cs, i, charSize);
        if ((byteSize + length) <= maxLength){
            i = i + charSize;
            length += byteSize;
        }
        else
            break;
    }
    return s.Substring(0, i);
}
```
```
The returned string can then be safely transferred to a byte array of length maxLength.


Question: I have an html file with an unordered list.  I want to show the list items horizontally but still keep the bullets.  No matter what I try, whenever I set the style to inline to meet the horizontal requirement I can't get the bullets to display.

Answer:
Did you try
```
float: left
```
on your
```
<li/>
```
? Something like this:
```
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
                      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

test

test2

```
```
I only tested Firefox 3.0.1, works there. The
```
margin
```
is set because else your bullet overlaps the previous item.
addition:
Be wary that when you float the items you remove them from the normal flow, which in turn causes the
```
<ul/>
```
to have no height. If you want to add a border or something, you'll get weird results.
One way to fix that is to add the following to your styles:
```
```
ul {
    overflow: auto;
    background: #f0f;
}
```
```


Question: I always tend to forget these built-in Symfony functions for making links.

Answer:
This advice is for symfony 1.0. It probably will work for later versions.
Within your sfAction class
:
string  genUrl($parameters = array(), $absolute = false)
eg.
$this->getController()->genUrl('yourmodule/youraction?key=value&key2=value', true);
In a template
:
This will generate a normal link.
string link_to($name, $internal_uri, $options = array());
eg.
link_to('My link name', 'yourmodule/youraction?key=value&key2=value');


Question: Is there a simple way to format numbers in a Winforms 1.1 datagrid?  The Format property of the DataGridTextBoxColumn seems to be completely ignored.  I know there is a solution that involves subclassing a Column control, and it's fairly simple, but was hoping there might be some trick to making the Format property just work.

Answer:
My personal opinion is that a datagridcolumnstyle is the way to go.  Without seeing the code that you have, I can't say for certain why your formatting isn't taking hold when no style is defined - but mixing in formatting with data calculations and other parts of the code can get very messy very quickly.
Creating a new column style class is very clean, and if you have to use the same formatting again in another datagrid, it's as easy as pie to reuse it.
Here's the
Microsoft Documentation
that may get you started in the right direction.


Question:
Given a Python object of any kind, is there an easy way to get the list of all methods that this object has?

Or,

if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?

Answer:
For many objects
, you can use this code, replacing 'object' with the object you're interested in:
```
```
object_methods = [method_name for method_name in dir(object)
                  if callable(getattr(object, method_name))]
```
```
I discovered it at
diveintopython.net
(now archived), that should provide some further details!
If you get an
```
AttributeError
```
, you can use this instead
:
```
getattr()
```
is intolerant of pandas style Python 3.6 abstract virtual sub-classes.  This code does the same as above and ignores exceptions.
```
```
import pandas as pd
df = pd.DataFrame([[10, 20, 30], [100, 200, 300]],
                  columns=['foo', 'bar', 'baz'])
def get_methods(object, spacing=20):
  methodList = []
  for method_name in dir(object):
    try:
        if callable(getattr(object, method_name)):
            methodList.append(str(method_name))
    except Exception:
        methodList.append(str(method_name))
  processFunc = (lambda s: ' '.join(s.split())) or (lambda s: s)
  for method in methodList:
    try:
        print(str(method.ljust(spacing)) + ' ' +
              processFunc(str(getattr(object, method).__doc__)[0:90]))
    except Exception:
        print(method.ljust(spacing) + ' ' + ' getattr() failed')

get_methods(df['foo'])
```
```


Question: SHA Hash functions

Answer:
```
```
require 'digest/sha1'
Digest::SHA1.hexdigest 'foo'
```
```


Question:
When writing multithreaded applications, one of the most common problems experienced is race conditions.

My questions to the community are:

What is the race condition?

How do you detect them?

How do you handle them?

Finally, how do you prevent them from occurring?

Answer:
A race condition is a kind of bug, that happens only with certain temporal conditions.
Example:
Imagine you have two threads, A and B.
In Thread A:
```
```
if( object.a != 0 )
    object.avg = total / object.a
```
```
In Thread B:
```
```
object.a = 0
```
```
If thread A is preempted just after having check that object.a is not null, B will do
```
a = 0
```
, and when thread A will gain the processor, it will do a "divide by zero".
This bug only happen when thread A is preempted just after the if statement, it's very rare, but it can happen.


Question:
When writing multi-threaded applications, one of the most common problems experienced are deadlocks.

My questions to the community are:

What is a deadlock?

How do you detect them?

Do you handle them?

And finally, how do you prevent them from occurring?

Answer:
A
lock
occurs when multiple processes try to access the same resource at the same time.
One process loses out and must wait for the other to finish.
A
deadlock
occurs when the waiting process is still holding on to another resource that the first needs before it can finish.
So, an example:
Resource A and resource B are used by process X and process Y
X starts to use A.
X and Y try to start using B
Y 'wins' and gets B first
now Y needs to use A
A is locked by X, which is waiting for Y
The best way to avoid deadlocks is to avoid having processes cross over in this way. Reduce the need to lock anything as much as you can.
In databases avoid making lots of changes to different tables in a single transaction, avoid triggers and switch to optimistic/dirty/nolock reads as much as possible.


Question: Is there a standard convention (like phpdoc or python's docstring) for commenting C# code so that class documentation can be automatically generated from the source code?

Answer:
```
```
/// <summary>
///
/// </summary>
/// <param name="strFilePath"></param>
```
```
http://msdn.microsoft.com/en-us/magazine/cc302121.aspx


Question: How do you sort an array of strings naturally in different programming languages? Post your implementation and what language it is in in the answer.

Answer:
JavaScript
```
```
Array.prototype.alphanumSort = function(caseInsensitive) {
  for (var z = 0, t; t = this[z]; z++) {
    this[z] = [], x = 0, y = -1, n = 0, i, j;

    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
      var m = (i == 46 || (i >=48 && i <= 57));
      if (m !== n) {
        this[z][++y] = "";
        n = m;
      }
      this[z][y] += j;
    }
  }

  this.sort(function(a, b) {
    for (var x = 0, aa, bb; (aa = a[x]) && (bb = b[x]); x++) {
      if (caseInsensitive) {
        aa = aa.toLowerCase();
        bb = bb.toLowerCase();
      }
      if (aa !== bb) {
        var c = Number(aa), d = Number(bb);
        if (c == aa && d == bb) {
          return c - d;
        } else return (aa > bb) ? 1 : -1;
      }
    }
    return a.length - b.length;
  });

  for (var z = 0; z < this.length; z++)
    this[z] = this[z].join("");
}
```
```
Source