q:
I have a string of test like this:

<customtag>hey</customtag>

I want to use a RegEx to modify the text between the "customtag" tags so that it might look like this:

<customtag>hey, this is changed!</customtag>

I know that I can use a MatchEvaluator to modify the text, but I'm unsure of the proper RegEx syntax to use. Any help would be much appreciated.

[A]
I'd chew my own leg off before using a regular expression to parse and alter HTML.
Use
XSL
or
DOM
.
Two comments have asked me to clarify.  The regular expression substitution works in the specific case in the OP's question, but in general regular expressions are not a good solution.  Regular expressions can match
regular languages
, i.e. a sequence of input which can be accepted by a finite state machine.  HTML can contain nested tags to any arbitrary depth, so it's not a regular language.
What does this have to do with the question?  Using a regular expression for the OP's question as it is written works, but what if the content between the
```
<customtag>
```
tags contains other tags?  What if a literal
```
<
```
character occurs in the text?  It has been 11 months since Jon Tackabury asked the question, and I'd guess that in that time, the complexity of his problem may have increased.
Regular expressions are great tools and I do use them all the time.  But using them in lieu of a real parser for input that needs one is going to work in only very simple cases.  It's practically inevitable that these cases grow beyond what regular expressions can handle.  When that happens, you'll be tempted to write a more complex regular expression, but these quickly become very laborious to develop and debug.  Be ready to scrap the regular expression solution when the parsing requirements expand.
XSL and DOM are two standard technologies designed to work with XML or XHTML markup.  Both technologies know how to parse structured markup files, keep track of nested tags, and allow you to transform tags attributes or content.
Here are a couple of articles on how to use XSL with C#:
http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63
http://www.csharphelp.com/archives/archive78.html
Here are a couple of articles on how to use DOM with C#:
http://msdn.microsoft.com/en-us/library/aa290341%28VS.71%29.aspx
http://blogs.msdn.com/tims/archive/2007/06/13/programming-html-with-c.aspx
Here's a .NET library that assists DOM and XSL operations on HTML:
http://www.codeplex.com/Wiki/View.aspx?ProjectName=htmlagilitypack


q:
Are there any issues with changing elements which will appear on a web page within a thread. I am from a windows programming background and obviously if a thread needs to change the GUI in some way you have to delegate it to the GUI thread.

Basically my page uses 3 sql queries which can be run concurrently to obtain the page data. So I setup 3 threads and have them run, if one fails or has no records it makes an error message visible about it, this is currently done within the thread and seems to work.

Note: The 3 sql queries are for very different data it is definitely fastest to run 3 separate queries and running them at the same time makes it even faster (In terms of how long it takes the page to display).

Edit: The threads are joined in the page load event

[A] You're going to have to join all 3 threads before rendering the page.  Once it's rendered out, there's no updating it.

s: huggingface

c: devops

d: intermediate


q:
I'm working on some Silverlight controls and I would like to explicitly handle the way they appear in Blend.
Specifically, these controls have dependencies that are initialized at runtime, and thus throw exceptions in the designer. But even in the absence of the exception, I would like to make them appear a certain way in Blend.

I know that this is possible with WPF (using myassembly.VisualStudio.Design.dll), but I haven't been able to find info on doing this with Silverlight.

I have seen the hack described here that checks does this:

bool designTime = (System.Windows.Browser.HtmlPage.IsEnabled == false);

I would prefer a more explicit solution though.

[A]
There is an extremely detailed post on
how to deal with design time extensibility here
. There you will find out how to do the Visual Studio and Blend design time stuff for Silverlight.
Control vendors and people who author custom controls often find themselves wishing they could give a better experience for their custom controls.
  However, there’s a huge lack of public information on this topic. And I’ve decided to correct this situation with this short 50+ pages article.
Like I said, it's long. :)


q:
I have got a template class as follows:

class MyClass<T>
{
    T field;
    public void myMethod()
    {
       field = new T(); // gives compiler error
    }
}

How do I create a new instance of T in my class?

[A]
After type erasure, all that is known about
```
T
```
is that it is some subclass of
```
Object
```
. You need to specify some factory to create instances of
```
T
```
.
One approach could use a
```
Supplier<T>
```
:
```
```
class MyClass<T> {

  private final Supplier<? extends T> ctor;

  private T field;

  MyClass(Supplier<? extends T> ctor) {
    this.ctor = Objects.requireNonNull(ctor);
  }

  public void myMethod() {
    field = ctor.get();
  }

}
```
```
Usage might look like this:
```
```
MyClass<StringBuilder> it = new MyClass<>(StringBuilder::new);
```
```
Alternatively, you can provide a
```
Class<T>
```
object, and then use reflection.
```
```
class MyClass<T> {

  private final Constructor<? extends T> ctor;

  private T field;

  MyClass(Class<? extends T> impl) throws NoSuchMethodException {
    this.ctor = impl.getConstructor();
  }

  public void myMethod() throws Exception {
    field = ctor.newInstance();
  }

}
```
```


q:
In C# if I want to convert a double (1.71472) to an int then I get the answer 2.  If I do this in Java using intValue() method, I get 1 as the answer.

Does Java round down on conversions?

Why do the Java API docs have such scant information about their classes i.e.

Returns the value of the specified
  number as an int. This may involve
  rounding or truncation.

A bit more info about the rounding would have been helpful!

[A]
Java rounds toward zero when narrowing from a floating point to an integer type.
There's more documentation about the general rules in the
Java Language Specification
. Note that while the documentation in
```
Number
```
leaves options open for subclasses, the documentation on the concrete boxing types is more explicit:
Returns the value of this Double as an
  int (by casting to type int).
When using
BigDecimal
, you can specify one of eight different rounding policies.


q: I am writing a text editor for Mac OS X.  I need to display hidden characters in an NSTextView (such as spaces, tabs, and special characters).  I have spent a lot of time searching for how to do this but so far I have not found an answer.  If anyone could point me in the right direction I would be grateful.

[A]
Have a look at the NSLayoutManager class. Your NSTextView will have a layout manager associated with it, and the layout manager is responsible for associating a character (space, tab, etc.) with a glyph (the image of that character drawn on the screen).
In your case, you would probably be most interested in the
```
replaceGlyphAtIndex:withGlyph:
```
method, which would allow you to replace individual glyphs.


q:
Where is the best documentation of ffmpeg and libavcodec?

It appears that ffmpeg supports many undocumented options that it is very hard to find a good reference.

[A]
One of the things that can be quite useful:
```
```
ffmpeg -formats
```
```
lists all the codecs and containers that can be used...I haven't found any other good place where these can be found, probably because they depend on what libraries your ffmpeg copy was built with.  This page (
http://ffmpeg.mplayerhq.hu/general.html
) has some of them, but don't tell you what to enter at the command line.
Also, howto-pages.org has a decent tutorial here:
http://howto-pages.org/ffmpeg/


q:
I have 2 tables, an active table and an inactive table. I want to move rows from the active to the inactive table. My first thought was

insert into inactive select * from active where ...
delete from active active where ...

However about .42 seconds later I noticed this will drop/duplicate rows if updates alter what the where clause selects.

In this case, I can easily prevent that but what should I do in cases where I can't?

edit: From the answers it look like there isn't an easy/trivial way to do this. I'm really surprised by this. I would think that there would be some substantial benefits to having it.

[A]
Status flags are your friend.
```
```
UPDATE old_data SET move="MARKED";
INSERT INTO somewhere... SELECT where move="MARKED";
DELETE FROM old_data WHERE move="MARKED";
```
```
If you do this with Autocommit off, it will seize locks all over the place.
You can COMMIT after each step, if you want to do a little less locking.


q:
I'm trying to develop some SharePoint workflows for the company I work for, and I'm not too familiar with the ins and outs of the technology.  Normally when I want to familiarize myself with something, I just play with it, look at the properties, find all the methods, etc.

When I fire up Visual Studio and try to create a SharePoint workflow, it gives me an error indicating I don't have a reference to "Microsoft.SharePoint.dll". Someone told me that it was normal to see that because you have to do all your development on the SharePoint Server itself if you want to do workflows.  Is this true?

If so, is there anyone out there that has successfully developed SharePoint workflows in a multi-developer environment without resorting to any "hacks"??  Thank you for reading and your responses...

[A]
Yes, you have to do all your development on a the SharePoint server itself.  Consider using a virtual machine and package up features that you can deploy to your staging and production environments.
http://weblogs.asp.net/erobillard/archive/2007/02/23/build-a-sharepoint-development-machine.aspx
http://www.wssdemo.com/Pages/EntDev.aspx


q: We were working on a design, and for that we created the skeleton of the classes in our main branch.  Now, we are starting to code, and for that we got a new branch.  So, it would be nice if I can move all the new files in the main branch into the new branch.  However, I cannot check them in yet.  So, is it possible to integrate the checked out changelist?  Thanks.

[A]
I never found a way to do that within perforce, but you can at least partially automate it.
Usually when I had to do something like that I'd check out the files in the branch I want to move things to, then use
WinMerge
to diff the branches and copy the changes over.  Once that's done you can revert the changes in the original branch and check them in in the new branch.
It's not the best solution (no automatic checkout/add/delete of files on the new branch), but was the fastest method I came up with.


q: Recently there has been quite some hype around all the different mocking frameworks in the .NET world. I still haven't quite grasped what is so great about them. It doesn't seem to be to hard to write the mocking objects I need myself. Especially with the help of Visual Studio I quickly can write a class that implements the interface I want to mock (it auto-generates almost everything for me) and then write an implementation for the method(s) I need for my test. Done! Why going through the hassle of understanding a mocking framework for the sole purpose of saving a few lines of code. Or is a mocking framework not only about saving lines of code?

[A]
Well I certainly don't think that you NEED a mocking framework. It's a framework like any other, and it's ultimately designed to save you some time and effort. You can also do things like roll your own common data structures like stacks and queues, but isn't it generally easier to just use the ones built into the class libraries that ship with the compiler/IDE of your language of choice?
I'm sure there are other compelling reasons for using mocking frameworks, though I'd leave it to the TDD and unit testing gurus to answer.


q: Which version of JavaScript does Google Chrome support in relation to Mozilla Firefox?  In other words, does Chrome support JavaScript 1.6, 1.7, or 1.8 which Firefox also supports or some combination of them?

[A]
Google Chrome supports up to Javascript 1.7:
```
```
<script language="javascript1.7">alert(1.7);</script> - Alerts
<script language="javascript1.8">alert(1.8);</script> - Doesn't alert
```
```


q: We have 2 flowdocuments that we'd like to compare similar to when using a diff viewer (winmerge, beyond compare, etc).  Has anybody done this or know how to get the text out of a flowdocument to do a compare?


q:
I want to embed a swf over a html page, like a floating video watching panel. I already have a swf file which will automatically adjust its size according to the browser size, and the swf file is partially transparent. I thought I can just add a div tag, make the position absolute and change z-index bigger, but that doesn't work because the swf just replaced everything that's on the page.

Here's what I did

<script>
      swfobject.embedSWF("swf/float.swf", "header", "100%", "100%", "9.0.0");
</script>

<body bgcolor="#000000">
      <div id="header"></div>
      <div id="shell">
          things in my html
      </div>
</body>

#header {
    position:absolute;
    z-index:100;

}

Any idea? Thanks.

[A]
I believe the problem with this is that the CSS doesn't work well with
```
<object />
```
tags.  The
```
swfobject.embedSWF
```
turns the
```
<div id="header"></div>
```
into an
```
<object />
```
tag with a bunch of attributes that might be effecting the CSS.  If you create a wrapper DIV around the header DIV and apply the CSS to the wrapper DIV, everything works better.  You also need to add 100% width and height in the CSS.  Here's the revised source:
```
```

        things in my html

#wrapper {
    position:absolute;
    z-index:100;
    width:100%;
    height:100%;
}
```
```


q:
for the following:

( a != b ) ? cout<<"not equal" : cout<<"equal";

suppose I don't care if it's equal, how can I use the above statement by substituting cout<<"equal" with a no-op.

[A]
This is very confusing code. You
could
just write
```
```
cond ? cout << "equal" : cout;
```
```
but you won't (will you?) because you've got conventional
```
if
```
for that.


q:
I am designing a web app and I intent to embed data on an xml island so that I can dynamically render it on an HTML table on the client-side based on options the users will select.

I have the broad concepts, but I need pointers on how to use DOM in navigating my xml. And how to update my xml island possibly for posting back to the server?

Please any links to online resources or a quick advice will be very appreciated.

NB: I understand most of the dynamic HTML concepts and server and client side stuff, so don't shy being very technical in your response:)

[A]
In
W3C
HTML there are no XML data islands (unless you're referring to external XML file linked via frames loaded using Javascript), but you can re-use HTML elements and insert metadata in
```
class
```
,
```
title
```
(if you care about HTML4 validity),
```
data-*
```
(HTML5) or your custom attributes.
For DOM navigation you've got
DOM Core
, like
```
element.childNodes
```
,
```
.nextSibling
```
,
```
.getAttribute()
```
, etc.
DOM can be verbose and tedious to use (e.g. when looking for elements in DOM you have to be careful to skip text nodes), so there are JS libraries like jQuery and Prototype built on top of it that offer more convenient API.
If you intend to a lot of DOM transformations, then Javascript API for
XPath
and
XSLT processor
will be handy.


q:
In javascript how do I get a handle on the frame that I'm in based on an element in that frame?

function myFunction(elementInFrame){
   // here I want to get a handle on the frame that elementInFrame lives in
}

[A]
In IE you can do
```
elementInFrame.document.parentWindow
```
Doesn't work in Firefox unfortunately.
Edit: If you're using frames then in FF you could do it the long way... loop through all the frames until you find the element you're looking for.


q:
I need to be able to display some data in Eclipse in a grid/table control... I need things like paging, multiple column sorting, column choosing, etc. There is an SWT Table and the Nebula project has a grid in alpha.

Does what I need exist? 3rd party maybe? Doesn't have to be free, we can pay for the functionality.

[A]
You could use the facilities of table presentation offered by the
BIRT plugin
, that is if you are really advance
table layout needs
.
(source:
theserverside.com
)
(otherwise the classic SWT
TableViewer
offers already some of the feature you are after
(source:
richclient2.eu
)
)


q:
I've saved an entire webpage's html to a string, and now I want to grab the "href" values from the links, preferably with the ability to save them to different strings later. What's the best way to do this?

I've tried saving the string as an .xml doc and parsing it using an XPathDocument navigator, but (surprise surprise) it doesn't navigate a not-really-an-xml-document too well.

Are regular expressions the best way to achieve what I'm trying to accomplish?

[A]
Regular expressions are one way to do it, but it can be problematic.
Most HTML pages can't be parsed using standard html techniques because, as you've found out, most don't validate.
You could spend the time trying to integrate
HTML Tidy
or a similar tool, but it would be much faster to just build the regex you need.
UPDATE
At the time of this update I've received 15 up and 9 downvotes.  I think that maybe people aren't reading the question nor the comments on this answer.  All the OP wanted to do was grab the href values.
That's it.
From that perspective, a simple regex is just fine.  If the author had wanted to parse other items then there is no way I would recommend regex as I stated at the beginning, it's problematic at best.


q: If I have an embedded browser in a windows form, is it possible to initiate a javascript method from the container application?

[A]
You can use Document.InvokeScript, as outlined in this excellent MSDN article:
How to: Implement Two-Way Communication Between DHTML Code and Client Application Code


q:
I have an html like this:

<div id="container1">
    <div class="dragme">drag me</div>
</div>
<div id="container2">
    <div class="dragme">drag me</div>
</div>
<div id="droponme"></div>

$(".dragme").draggable();
$("#droponme").droppable({
    accept: ".dragme",
    drop: function(e, u) { alert( /* find id of the container here*/ ); };
});

I want to find the container of the draggable object on drop event handler. How can I do this?

[A]
```
```
$(".dragme").draggable();
$("#droponme").droppable({
    accept: ".dragme",
    drop: function(e, u) {
        alert(u.draggable.parent().attr('id') );
        // in your example: container1 or container2
    }
});
```
```


q: What is the differences between those 2 assuming I'm using SQL Server as my database? Are they the same?

[A]
Long answer: google.
Short answer: using entity framework, you will be able to create something based on classes (partial, that you can "extend") resembling domain objects (not true DDD though, that's why NHibernate still exists and linq to nhibernate is being developed), using sql you will be just thinking database and tables.


q:
I have a third-party library in my SVN repository and I'd like to associate source/javadoc with it locally in Eclipse. I.e., there should be some local setting (for example, an entry in the local.properties file) that associates the source/javadoc with the JAR file, but which doesn't introduce local dependencies into the repository via .classpath. Ideally I'd have

lib_src_dir = /my/path/to/lib/src

in local.properties and then

<classpathentry kind="lib" path="lib.jar" sourcepath="${lib_src_dir}">

in .classpath. Can this be done?

[EDIT] @VonC's answer is helpful... Is there a way to load Path Variables from a text file (e.g., local.properties) instead of going through Window -> Preferences -> General -> Workspace -> Linked Resources?

[A]
I believe this would be better achieved through:
the creation of a linked folder combined with
the declaration of a linked resource
The linked resource defines a path variable which would be equals to
```
/my/path/to/lib/src
```
The linked folder would refers to your linked resource
(you can use a variable and not a fixed path, with the "Variable" button)
The variable is actually always local (to one's workspace), and will be modified through the
```
Linked Resources
```
preference screen.
The linked folder can also be... a linked
file
, thus allowing the reference of an archive through a relative path (relative to the variable).
Then this linked file (here a linked archive) can be associated to your
```
classpathentry
```
in the "
```
source
```
" attribute.
The problem with Linked Resources is they are local to the workspace, in the preferences.
You can
export the preferences in a
```
[myPrefs.epf]
```
file
, and then trim the exported file in order to leave only the lines containing
```
pathvariable
```
:
```
```
/instance/org.eclipse.core.resources/pathvariable.MY_DIRECTORY=/my/path/to/lib/src
```
```
Anyone can then import this special preference file, which will only affect the "
```
Linked Resources
```
" part.
That solution is not very satisfying, since the
```
.epf
```
preference file can not be loaded automatically in the project
.
When I setup a project with a linked resources defining a path, I always leave a big
```
README.txt
```
at the root of my project, in order to incite the user of said project to define that same linked resources with his/her own fixed local path.
Several bugs
are in progress to enhance this situation or around the
Linked Resources topic
.
Especially:
Exporting a project with linked resources
Relative paths without variables
Have linked resources relative to workspace paths
Would like to use path relative to workspace root
DevByStarlight
mentions in
the comments
the project (not very active since Oct. 2011)
workspacemechanic
.
The Workspace Mechanic automates maintenance of your Eclipse environment by tweaking preferences, adding extension locations, and so on. You can use it to:
Create a consistent environment among groups as large as the entire company, your local team, or even among your own many workspaces
Save time setting up new workspaces
Create tasks that ensure your favorite new preferences are applied to all your current and future workspaces. (This is one of our favorite features!)
The key to the Workspace Mechanic's behavior is the
```
Task
```
.
A task describes a simple test and an action that, when run, changes the environment so the test will subsequently pass.
```
Tasks
```
can come in many forms: preference files, Java classes, Groovy scripts and Eclipse extensions. You can easily define your own Tasks.
It comes with a collection of scripts:
workspace-mechanic
workspacemechanic-settings


q: Can anyone tell me how to display all the selected value of my multi value parameter in SSRS report. When giving parameter.value option it gives error.

[A]
You can use the "Join" function to create a single string out of the array of labels, like this:
```
```
=Join(Parameters!Product.Label, ",")
```
```


q:
I have a class which has a private member $content. This is wrapped by a get-method:

class ContentHolder
{
    private $content;
    public function __construct()
    {
        $this->content = "";
    }

    public function getContent()
    {
        return $this->content;
    }
}
$c = new ContentHolder();
$foo = array();
$foo['c'] = $c->getContent();

Now $foo['c'] is a reference to content, which is what I don't understand. How can I get the value? Thank You in advance.

[A]
In PHP, you don't say: "
```
$foo = new array();
```
"
Instead, you simply say: "
```
$foo = array();
```
"
I ran your code (PHP 5.2.6) and it seems to work fine.  I tested it by dumping the array:
```
```
var_dump($foo);
```
```
This outputs:
```
```
array(1) {
  ["c"]=>
  string(0) ""
}
```
```
I can also simple use
```
echo
```
:
```
```
echo "foo[c] = '" . $foo['c'] . "'\n";
```
```
This outputs:
```
```
foo[c] = ''
```
```


q:
I want to create buttons with icons in Flex dynamically using Actionscript.

I tried this, with no success:

var closeButton = new Button();
closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png");

[A]
I'm assuming you're adding it to the stage?
Also, I think your Embed is missing a close quote / paren.
```
```
closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png");
```
```
should be:
```
```
closeButton.setStyle("icon", "@Embed(source='images/closeWindowUp.png')");
```
```


q:
I'm trying to select the "name" field from the author node in an ATOM feed using LINQ. I can get all the fields I need like so:

XDocument stories = XDocument.Parse(xmlContent);
XNamespace xmlns = "http://www.w3.org/2005/Atom";
var story = from entry in stories.Descendants(xmlns + "entry")
            select new Story
            {
                Title = entry.Element(xmlns + "title").Value,
                Content = entry.Element(xmlns + "content").Value
            };

How would I go about selecting the author -> name field in this scenario?

[A]
You basically want:
```
```
entry.Element(xmlns + "author").Element(xmlns + "name").Value
```
```
But you might want to wrap that in an extra method so you can easily take appropriate action if either the author or name elements are missing. You might also want to think about what you want to happen if there's more than one author.
The feed might also have an author element... just another thing to bear in mind.


q:
I have some Jasper reports which are displayed in HTML format. I would like the width of the columns in the HTML tables to automatically resize to fit the content of the widest cell (in that column), such that all the data is displayed.

Currently this does not happen because the HTML generated by Jasper specifies fixed widths for the <table> and some <td> elements, e.g.

<td style="width: 20px; height: 17px;">
  <span style="font-family: Arial; font-size: 11px;">foo-bar-baz@examp</span>
</td>

I can't simply remove all these width properties (using JavaScript), because (as shown in the HTML above) any data that would be hidden when using these widths is not even returned to the client-side

Cheers,
Don

[A]
While not perfect, you could flag the field to stretch with overflow. This would at least give you all the data. In your jrxml file it would be similar to:
```
```
<textField isStretchWithOverflow="true" hyperlinkType="None">
    <reportElement style="Report Sub-Title" x="0" y="84" width="802" height="20"/>
    <textElement/>
    <textFieldExpression class="java.lang.String">
        <![CDATA["For the period ...]]>
    </textFieldExpression>
</textField>
```
```
I'm afraid I don't know of any feature of Jasper reports that would allow the dynamic resizing of column widths - It is probably one of those things that makes sense for HTML but little sense for other output formats such as PDF.


q:
i am programatically adding Webcontrols in to a User Control i am also adding a javascript event passing the controlID as a parameter but the clientID is the one i assigned a it does not contain the one that asp.net generates

   var txt = new TextBox();
   txt.ID = "MyID"+Number;

   chkBox.Attributes.Add("onClick", "EnableTxtBox('" +txt.ClientID + "');");

i can workAround this by adding the parent control ID

   chkBox.Attributes.Add("onClick", "EnableTxtBox('" + this.ClientID+"_"+txt.ClientID + "');");

On which Page life cycle are the Client IDs generated?

[A]
You need to add the control to the control hierarchy before you add the attribute.
```
```
var txt = new TextBox();
   txt.ID = "MyID"+Number;
   Controls.Add ( txt );
   chkBox.Attributes.Add("onClick", "EnableTxtBox('" +txt.ClientID + "');");
```
```
ControlCollection is no ordinary collection; it notifies the owner control when controls are added, and the control can take appropriate actions.


q:
When I make the same query twice, the second time it does not return new rows form the database (I guess it just uses the cache).

This is a Windows Form application, where I create the dataContext when the application starts.

How can I force Linq to SQL not to use the cache?

Here is a sample function where I have the problem:

public IEnumerable<Orders> NewOrders()
{
    return from order in dataContext.Orders
           where order.Status == 1
           select order;
}

[A]
The simplest way would be to use a new DataContext - given that most of what the context gives you is caching and identity management, it really sounds like you just want a new context. Why did you want to create just the one and then hold onto it?
By the way, for simple queries like yours it's more readable (IMO) to use "normal" C# with extension methods rather than query expressions:
```
```
public IEnumerable<Orders> NewOrders()
{
    return dataContext.Orders.Where(order => order.Status == 1);
}
```
```
EDIT: If you
never
want it to track changes, then set
ObjectTrackingEnabled
to false before you do anything. However, this will severely limit it's usefulness. You can't just flip the switch back and forward (having made queries between). Changing your design to avoid the singleton context would be much better, IMO.


q:
I have HTML code edited by FCKEditor stored in a database and would like to display (well render) it onto a view. So, for instance, something stored as:

&lt;&gt;pre&lt;&gt;This is some sample text&lt;&gt;pre&lt;/&gt

Will be displayed to the user as:

This is some sample text

(With the appropriate style for pre-formatted-text)

The view already has the required string to display from ViewData, I'm just not sure what the best way to show it to the user is.

[A]
Try this:
```
```
<%= System.Web.HttpUtility.HtmlDecode(yourEncodedHtmlFromYouDatabase) %>
```
```
More info
here
.


q:
I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode.
Apparently urllib.unquote does not support unicode.

[A]
```
```
def unquote(text):
    def unicode_unquoter(match):
        return unichr(int(match.group(1),16))
    return re.sub(r'%u([0-9a-fA-F]{4})',unicode_unquoter,text)
```
```


q: I have an application which is fully unicode compatible in Delphi 2006. I had replaced all AnsiStrings with WideStrings, replaced all VCL controls with TNT controls, and changed all string functions from AnsiStrings to WideStrings. It looks like all that work was for nothing, because I'm going to have to reverse it all. Is there anyway to Trick Delphi 2009 into thinking Widestrings are in fact UnicodeStrings?

[A]
No, there really isn't. But you won't regret the work to truly Unicode enable your application.
The TNT controls can easily be replaced with the regular VCL controls.  You can do that pretty simply using the wizard from GExperts (
http://www.gexperts.org
) that replaces one control type with another automatically.
Then, you can change all your WideString declarations to regular strings.  String is now an alias for UnicodeString, and so all your strings can hold Unicode data just fine.
BTW, the author of the TNT controls, Troy Wolbrink, now vastly prefers Delphi 2009 over his own controls.


q:
Looking in the gnuwin32/bin directory, there is an odd-looking program file named [.exe

I couldn't find it in the documentation, gnuwin32.sourceforge.net or in a google search, so I ran it and got:

$ [
[: missing `]'
$

so I gave it ] as a parameter and got

$ [ ]

$

It didn't complain, so I assumed it was on the right track. I tried:

$ [ hello ]

again, no complaints. so I tried an arithmetic expression:

$ [ 1 + 1 ]
[: +: binary operator expected
$

I tried a bunch of different combinations, including prefix & postfix notation but nothing seemed to work. What does this thing do?

[A]
```
```
test a
```
```
==
```
```
[ a ]
```
```
It's just sugar
Edit: To clarify, that's the conditional syntax, e.g. [ "a" = "a" ]


q:
Observing one year of estimations during a project I found out some strange things that make me wonder if evidence based scheduling would work right here?

individual programmers seem to have favorite numbers (e.g. 2,4,8,16,30 hours)

the big tasks seem to be underestimated by a fix value (about 2) but the standard deviation is low here

the small tasks (1 or 2 hours) are absolutely wide distributed. In average they have the same average underestimation factor of 2, but the standard deviation is high:

some 5 minute spelling issues are estimated with 1 hour

other bugfixes are estimated with 1 hour too, but take a day

So, is it really a good idea to let the programmers break down the 30 hours task down to 4 or 2 hours steps during estimations? Won't this raise the standard deviation? (Ok, let them break it down - but perhaps after the estimations?!)

[A]
I think it is a good idea. When people break tasks down - they figure out the specifics of the task, You may get small deviations here and there, this way or the other, they may compensate or not...but you get a feeling of what is happening.
If you have a huge task of 30 hours - can take all 100. This is the worst that could happen.
Manage the risk - split down. You already figured out these small deviation - you know what to do with them.
So make sure developers also know what they do and say :)


q: Why is it bad to check in lines with trailing whitespace to your source control?  What kinds of problems could that cause?

[A]
False differences, basically. It's helpful if diffs only show "real" changes. Some diff programs will ignore whitespace, but it would be better just to avoid the dummy change in the first place.
Of course, it also doesn't help if it makes the line wrap on a colleague's machine.


q:
I'm trying to implement paging using row-based limiting (for example: setFirstResult(5) and setMaxResults(10)) on a Hibernate Criteria query that has joins to other tables.

Understandably, data is getting cut off randomly; and the reason for that is explained here.

As a solution, the page suggests using a "second sql select" instead of a join.

How can I convert my existing criteria query (which has joins using createAlias()) to use a nested select instead?

[A]
You can achieve the desired result by requesting a list of distinct ids instead of a list of distinct hydrated objects.
Simply add this to your criteria:
```
```
criteria.setProjection(Projections.distinct(Projections.property("id")));
```
```
Now you'll get the correct number of results according to your row-based limiting. The reason this works is because the projection will perform the distinctness check
as part of
the sql query, instead of what a ResultTransformer does which is to filter the results for distinctness
after
the sql query has been performed.
Worth noting is that instead of getting a list of objects, you will now get a list of ids, which you can use to hydrate objects from hibernate later.


q:
I am developing a .NET application which uses a few projects that I've pieced together from other internal projects.  I was thinking about merging the .exe and the DLLS into a single executable file with a tool called ILMerge.

I may be sending the executable outside the company, so merging everything into a single file would be easier to pass out.  But, I was wondering if there are any downsides to merging DLLs with the executable?

[A]
As long as they're your libraries, I don't think there's any big problem with it. Unless it makes the image absolutely and monstrously huge, I think it's better if the executable relies on itself as much as it can (exceptions being, of course, when you're replicating system functionality... no point in that).
On the other hand, if the libraries don't actually belong to you, you had better make sure that their terms of use allow for this. You may not be allowed to package them up into your executable and distribute them as your own code (even if you give your product away and the library was "free", you may still have to acknowledge that you use it some how so make sure to check the terms of use for
all
the libraries you include).


q:
From a Java program, I need to launch the default browser on a local HTML file, pointed to an anchor inside the file.  In Java SE 6, the java.awt.Desktop.browse method will open the file, but will not honor the anchor, so something like the following opens the file at the top, but does not page the browser to the anchor:

Desktop.getDesktop("file:///C:/foo/bar.html#anchor");

Sun says here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6477862 that anchors are not supported in the file URI protocol.

Does anyone have a better answer?

I can use Java SE 6.  I would be OK with a Windows only solution.

[A]
For Windows only, you could try
```
```
System.exec("cmd.exe start file:///C:/foo/bar.html#anchor")
```
```


q: Is there really that much of a difference between the performance of Vector and ArrayList?  Is it good practice to use ArrayLists at all times when thread safety isn't an issue?

[A]
If thread safety is not an issue,
```
ArrayList
```
will be faster as it does not have to synchronize.  Although, you should always declare your variable as a
```
List
```
so that the implementation can be changed later as needed.
I prefer to handle my synchronization explicitly because a lot of operations require multiple calls.  For example:
```
```
if (!myList.isEmpty()) {
    myList.get(0);
}
```
```
should be:
```
```
synchronized (myList) {
   if (!myList.isEmpty()) {
       myList.get(0);
   }
}
```
```


q:
Is it possible to do a cross table join in mysql spaning different tables? in different databases.

This seem to be easily possible in MSSQL, and greatly speeds up data transfer?

How about mysql, do you need to use a powerful IDE to achieve this? or do you have to write a program to do something like this?

UPDATE tblUser
SET tblUser.ReceiveInfo=old_database.dbo.contact.third_party_info_yn
FROM tblUser inner join old_database.dbo.contact
ON old_database.dbo.contact.id=tblUser.oldid

[A]
Sure, very easy.  Prefix the table name with the database name, like you show.  We do cross-database joins on a regular basis.  For example:
SELECT COUNT(*) FROM newusers1.users
  JOIN newusers2.users
It certainly won't speed up data transfer compared to having both tables in the same database, though.
Now, if your tables are sitting on different database servers, the answer is no.  An example of this is if your database is too big and you need to shard your tables.  Things get more than a little messy.  But given that you seem to be happy with the MS SQL solution, that does not seem to apply here.


q: Is there a standard Java library that handles common file operations such as moving/copying files/folders?

[A]
Not yet, but the
New NIO (JSR 203)
will have support for these common operations.
In the meantime, there are a few things to keep in mind.
File.renameTo
generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.
When a rename doesn't work you will need to actually copy the file (deleting the original with
File.delete
if it's a "move" operation). To do this with the greatest efficiency, use the
FileChannel.transferTo
or
FileChannel.transferFrom
methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.


q:
I am developing a map control in WPF with C#. I am using a canvas control e.g. 400 x 200 which is assigned a map area of e.g. 2,000m x 1,000m.

The scale of the map would be:  canvas_size_in_meters / real_size_in_meters.

I want to find the canvas_size_in_meters.

The canvas.ActualWidth gives the Width in DIU's (Device Independant Units). So, 400 DIU's is 400/96 = 4,17 inches, PROVIDED that the physical resolution of my monitor is 96 dpi.

However, using a ruler, I found that the physical resolution of my monitor is 87 dpi. (There are only few monitors that ACTUALLY have 96 physical dpi)

That DPI difference (10%) translates to a +10% difference in the actual map control width on screen.

How do I measure the size of a WPF control in inches EXACTLY and regardless of screen resolution and DPI setting ?

[A]
How do I measure the size of a WPF control in inches EXACTLY and regardless of screen resolution and DPI setting ?
This isn't actually possible, because for it to work, WPF would have to know the resolution (in terms of DPI) of your monitor. Sounds nice in theory, but in practice windows doesn't know this information. This is why windows itself always assumes 96dpi blindly instead of being smarter about it.
Even if there were some way to manually tell it, or if your particular monitor has a custom driver that does pass the correct information to windows, this isn't going to work on anyone else's computer, so windows doesn't pass this information on to any applications.
The best you can do is draw a scale like google maps does. You know that 1
pixel
== 1 mile, so you can draw a 50 pixel line on your map, with a label saying "this line equals 50 miles"


q: How do get the startup path ( system.windows.forms.application.StartupPath ) of my exe without adding a reference to system.windows.forms?

[A]
EDIT: @KiwiBastard's answer is the correct method:
```
```
System.AppDomain.CurrentDomain.BaseDirectory
```
```
Add a reference to
```
System.Reflection
```
and use
```
```
Assembly.GetExecutingAssembly().Location
```
```
EDIT: Depending where you intend getting the startup path, this might be more appropriate:
```
```
Assembly.GetEntryAssembly().Location
```
```


q:
What would be a clever way to make a 'please wait' control for a Flex application for long running operations like calling a webservice.

I am not asking about the graphical portion of it - just the 'controller' part. How should I trigger it and hide it. I am planning to make just a simple canvas with text in.

For instance :

can I somehow intercept all web service calls - and not have to activate it for every web service

how should i add it to my canvas. should it be added to 'stage' as a top level component?

should it have a 'cancel' button to cancel the web service request if it takes too long. that sounds kind of complicated because I'm not even sure if I can terminate a running async web request?

FYI: This is for a reporting application so long running queries are to be expected

[A]
One way I have done it in the past is to have a global integer and increment / decrement the value based on the web services running. When the counter was 0, I would hide the loading text, when it was greater than 0, I would display the loading text. Here is a simplified version of it:
```
```
<mx:Application>
    <mx:Script>
        [Bindable]public var ws_count:int = 0;
    </mx:Script>
    <mx:Label text = "loading..." visible="{ws_count > 0}" />
</mx:Application>
```
```
I then had a little helper class to control the global counter:
```
```
package ws {
    import mx.core.Application;
    public class WSCounter {
        public static function sent():void {
            Application.application.ws_count += 1;
        }
        public static function receive():void {
            Application.application.ws_count -= 1;
        }
    }
}
```
```
Then all that needs to be done is to call the helper function when a web service is called...e.g:
```
```
import ws.WSCounter;
import mx.rpc.http.HTTPService;

var srv:HTTPService = new HTTPService();
srv.url = "http://localhost/service.py";
srv.addEventListener(ResultEvent.RESULT,function(event:ResultEvent):void {
    WSCounter.receive();
});
srv.send();
WSCounter.sent();
```
```
I always have thought there was a better way to do this, like you said have some type of hook to detect if a service is running...I'm looking forward to other responses in this post...


q:
I'm writing a direct3d application and after noticing strange bugs such as anti-aliasing occurring even when it was turned off and the mouse pointer not lining up to things with the same coordinates as itself I discovered that when creating a window the width and height parameters include the border.  The program was rendering a 800x600 graphics output to a window of the same size, but because of the borders it was squished into 792x566 rectangle.  I've increased the size of the window to compensate, but this does not work if the system uses a border style other the standard XP style.  (Classic style, for example)

Is there a way to tell what the border width and heights will be before I create the window?

[A]
It sounds like you are looking for the GetSystemMetrics function.  For example, the border width in pixels is returned by
```
```
GetSystemMetrics(SM_CXBORDER)
```
```
ADDED:
For the total size you will need to add together the various "pieces" of the non-client area: border, frame sizes, title bars, etc.


q:
I have seen many apps that take instrument classes and take -javaagent as a param when loading also put a -noverify to the command line.

The Java doc says that -noverify turns off class verification.

However why would anyone want to turn off verification even if they are instrumenting classes?

[A]
Start-up time, I'd say. Verification that classes are correct takes some time when the class is loaded. Since classes might be loaded in a lazy fashion (not on app start, but when being used for the first time), this might cause unexpected and undesired runtime delays.
Actually the class does not need to be checked in general. The compiler will not emit any invalid bytecode or class construct. The reason for verification is that the class may be build on one system, get hosted online and is transmitted to you through the unprotected internet. On this path, a malicious attacker might modify the bytecode and create something the compiler might never create; something that can crash the JVM or possibly circumvents security restrictions. Thus the class is verified before it is used. If this is a local application, there is usually no need to check the bytecode again.


q:
I'm using a WPF RichTextBox control to input some text with user formatting capability, including font size adjustment.  The built-in commands for IncreaseFontSize and DecreaseFontSize will adjust the font size by 0.75pt each time the command is executed.  I would like to increase the granularity to 2pt.

Can this be done without implementing my own custom commands?

[A]
Unfortunately the value is hard-coded and you cannot change it. The fastest way to implement this is to use the TextRange class. Something like this:
```
```
var range = new TextRange( rtb.Document.ContentStart, rtb.Document.ContentEnd );
range.ApplyPropertyValue( TextElement.FontSizeProperty, 30.0 );
```
```


q: How would you use set! in a simple procedure f such that evaluating (+ (f 0) (f 1)) will return 0 if the arguments to + are evaluated from left to right but will return 1 if the arguments are evaluated from right to left?

[A]
Easiest approach is probably to store some external state and have the implementation of f affect it's contents.
```
```
(define x 0)
(define (f n) (let ((tmp x)) (set! x n) tmp))
```
```
Thus, x is initially 0 and each call to f will return the current value of x and save the argument as the new value of x. Thus (f 0) followed by (f 1) will both return 0, leaving the final x value of 1. While evaluating (f 1) followed by (f 0) will yield 0 then 1, with a final x of 0.


q:
I know I can loop over the string or build a regex or invert the set (ASCII isn't that big after all) and search for the first instance of that, but Yuck.

What I'm looking for is a nice one liner.

fewer features is better, LINQ is out (for me, don't ask, it's a long story)

The solution I'm going with (unless I see something better)

static int FirstNotMeta(int i, string str)
{
    for(; i < str.Length; i++)
        switch(str[i])
        {
            case '\\':
            case '/':
            case '.':
                continue;
            default:
                return i;
        }
    return -1;
}

OK, I cheated, I know in advance what char's I care about.

[A]
Not all that efficient, but:
```
```
char f(string str, IEnumerable<char> list)
{
  return str.ToCharArray().First(c => !list.Contains(c))
}
```
```


q:
I want to insert something into a STL list in C++, but I only have a reverse iterator. What is the usual way to accomplish this?

This works: (of course it does)

std::list<int> l;
std::list<int>::iterator forward = l.begin();
l.insert(forward, 5);

This doesn't work: (what should I do instead?)

std::list<int> l;
std::list<int>::reverse_iterator reverse = l.rbegin();
l.insert(reverse, 10);

[A]
```
l.insert(reverse.base(), 10);
```
will insert '10' at the end, given your definition of the 'reverse' iterator. Actually,
```
l.rbegin().base() == l.end()
```
.


q:
How do I launch an app and capture the output via stdout and maybe stderr?

I am writing an automated build system and I need to capture the output to analyze. I'd like to update the svn repo and grab the revision number so I can move the files in autobuild/revNumber/ if successful. I also would like to build using make and upload the compile text to my server for everyone to see the warnings and errors on a failed build.

I can't find the system() function, but I found the CreateProcess() function on MSDN. I am able to launch what I need but I have no idea how to capture the stderr and stdout.  I notice the process launches separately unless I set a breakpoint and keep my app exiting which it then will keep all the text in my app console window. I would also want to wait until all processes are finished and then scan the data it produced to do any additional operations I need. How do I do any of this?

[A]
In real shells (meaning, not sea shells - I mean, not in C Shell or its derivatives), then:
```
```
program arg1 arg2 >/tmp/log.file 2>&1
```
```
This runs program with the given arguments, and redirects the stdout to /tmp/log.file; the notation (
hieroglyph
) '
```
2>&1
```
' at the end sends stderr (file descriptor 2) to the same place that stdout (file descriptor 1) is going.  Note that the sequence of operations is important; if you reverse them, then standard error will go to where standard output was going, and then standard output (but not standard error) will be redirected to the file.
The choice of file name shown is abysmal for numerous reasons - you should allow the user to choose the directory, and probably should include the process ID or time stamp in the file name.
```
```
LOG=${TMPDIR:-/tmp}/log.$$.$(date +%Y%m%d-%H%M%S)
program arg1 arg2 >$LOG 2>&1
```
```
In C++, you can use the
```
system()
```
function (inherited from C) to run processes.  If you need to know the file name in the C++ program (plausible), then generate the name in the program (
```
strftime()
```
is your friend) and create the command string with that file name.
(Strictly, you also need
```
getenv()
```
to get $TMPDIR, and the POSIX function
```
getpid()
```
to get the process ID, and then you can simulate the two-line shell script (though the PID used would be of the C++ program, not the launched shell).
You could instead use the POSIX
```
popen()
```
function; you'd have to include the '
```
2>&1
```
' notation in the command string that you create to send the standard error of the command to the same place as standard output goes, but you would not need a temporary file:
```
```
FILE *pp = popen("program arg1 arg2 2>&1", "r");
```
```
You can then read off the file stream.  I'm not sure whether there's a clean way to map a C file stream into a C++ istream; there probably is.


q: I would like to generate documentation for a RESTful web service API that is written in Python. Ideally it would look like Yahoo's RESTful web service docs. Does anyone have any ideas or references?

[A]
Unfortunately I don't know anything specific that will help you in Python specifically -- However just as points of reference, you might take a peak at the WADL specification that the JAX-RS java spec is using --
https://wadl.dev.java.net/
-- Additionally, there is a xslt that will transform the wadl into html --
http://www.mnot.net/webdesc/
They use the yahoo REST API's as examples.


q:
I'd like to know how to convert Perforce depot locations to client view locations for the purpose of script writing.

I have a script that first checks out a file for edit in perforce and then interacts with the file.   I need to have the depot location (i.e. \Projects\Project6) converted to the client view location.  (i.e. d:\Projects\Project6).

Is this possible?

[A]
Check out the
```
p4 have
```
command. You give it
either
a depot location
or
a client filename and it gives you the depot location, client filename,
and
what version of that file you have.


q:
I have the following code:

for attribute in site.device_attributes
  device.attribute
end

where I would like the code to substitute the value of "attribute" for the method name.

I have tried device."#{attribute}" and various permutations.

Is this completely impossible? Am I missing something?

I have considered overriding method_missing, but I can't figure out how that would actually help me when my problem is that I need to call an "unknown" method.

[A]
The "send" method should do what you're looking for:
```
```
object = "upcase me!"
method = "upcase"
object.send(method.to_sym) # => "UPCASE ME!"
```
```


q:
Right now a project I'm working on has reached a level of complexity that requires more than a few steps (actually its become arcane!) to produce a complete/usable product. And unfortunately we didn't start out with a Continuos Integration mindset, so as you can imagine its kind of painful at times, and at others I can easily waste half a day trying to get a clean/tested build.

Anyways as any HUGE project it consists of many components in many different languages (not only enterprise style Java or C# for example), as well as many graphical, and textual resources. Now the problem is that when I look for Continuos Integration, I always find best practices and techniques that assume one is starting a new project, from the ground up.  However this isn't a new project, so I was wondering what are some good resources to proactively start migrating from Arcane Integration towards Continuos Integration :)

Thanks in advance!

[A]
I would guess that migrating isn't really an option--Half-ass solutions will only make it worse.
My approach would be to take one creative engineer who understands the build process, sit him down and say "Fix this".  Give him a week or two.
The end goal would be a process that runs beginning to end with a single make command.
I also recommend an automated "Setup" procedure where you simply do a checkout and run a batch file from a network share to install and build all your tools.  The amount of time this will save overall is staggering if you bring in new programmers.  Most projects take one to three days to get set up on a new computer--and it's always the "new" programmer who doesn't know what's going on doing the installs on his own system...


q:
Okay, I guess this is entirely subjective and whatnot, but I was thinking about entropy sources for random number generators. It goes that most generators are seeded with the current time, correct? Well, I was curious as to what other sources could be used to generate perfectly valid, random (The loose definition) numbers.

Would using multiple sources (Such as time + current HDD seek time [We're being fantastical here]) together create a "more random" number than a single source? What are the logical limits of the amount of sources? How much is really enough? Is the time chosen simply because it is convenient?

Excuse me if this sort of thing is not allowed, but I'm curious as to the theory behind the sources.

[A]
Don't worry about a "good" seed for a random number generator.  The statistical properties of the sequence do not depend on how the generator is seeded.  There are other things, however. to worry about.  See
Pitfalls in Random Number Generation
.
As for hardware random number generators, these physical sources have to be measured, and the measurement process has systematic errors. You might find "pseudo" random numbers to have higher quality than "real" random numbers.


q: I've looked into and considered many JavaScript unit tests and testing tools, but have been unable to find a suitable option to remain fully TDD compliant. So, is there a JavaScript unit test tool that is fully TDD compliant?

[A]
Take a look at
the Dojo Object Harness (DOH) unit test framework
which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at
Unit testing Web 2.0 applications using the Dojo Objective Harness
.
If you want to automate the UI testing (a sore point of many developers) — check out
doh.robot
(temporary down. update: other link
http://dojotoolkit.org/reference-guide/util/dohrobot.html
)
and
dijit.robotx
(temporary down)
. The latter is designed for an acceptance testing.
Update:
Referenced articles explain how to use them, how to emulate a user interacting with your UI using mouse and/or keyboard, and how to record a testing session, so you can "play" it later automatically.


q:
For a deleted file what's the command to use to view the content of a old revision

E:\Downloads\eeli\eel\eel>svn cat eel-scalable-font.h -r 2
svn: warning: 'eel-scalable-font.h' is not under version control

[A]
I think what your looking for is:
```
```
svn cat eel-scalable-font.h@2
```
```


q:
Joomla has a built-in function on its login screen "I've forgotten my user name", so that you can type in your email address and the username is sent to you via email.

I was thinking of changing it so that the username was displayed on screen immediately, without any form of authentication. This would greatly reduce the friction for our users who are returning after a long while, but it would allow anyone to type in any email address and see the associated username (definitely not the other way around though).

Does this create any security risks? Is it a good idea at all?

[A]
I would say it is a
slight
security risk for your less savvy users.  For a user with a weak password, particularly if it is related to their username or e-mail address, exposing their user name leaves them open to having their account hijacked.  Other than that, I can't think of a reason it would be a problem.  If the user has good passwords, it shouldn't matter at all.
I guess there is a slight anonymity concern.  On a forum for example, I wouldn't want someone who "knows" me to find out my username without me telling them.  In this case they could take my e-mail and get it.  But whether that is an issue depends on your site and your user base.


q:
I have a label function like :

private function formatDate (item:Object, column:DataGridColumn):String
{
    var df:DateFormatter = new DateFormatter();
    df.formatString = "MM/DD/YY";

    if (column.dataField == "startDate") {
        return df.format(item.startDate);
    }

    return "ERR";
}

Which I use in a datacolumn by using labelFunction.

This works just fine if my data field is called 'startDate'. I want to make this function generic so I can use it everywhere.

How can I do this. i think i need to use some kind of 'reflection' - or perhaps another approach altogether?

[A]
You can define another function, let's call it
```
partial
```
that binds some extra arguments to your function:
```
```
function partial( func : Function, ...boundArgs ) : Function {
  return function( ...dynamicArgs ) : * {
    return func.apply(null, boundArgs.concat(dynamicArgs))
  }
}
```
```
Then you change your function like this:
```
```
private function formatDate( dataField : String, item : Object, column : DataGridColumn ) : String {
  var df : DateFormatter = new DateFormatter();

  df.formatString = "MM/DD/YY";

  if ( column.dataField == dataField ) {
    return df.format(item[dataField]);
  }

  return "ERR";
}
```
```
Notice that I have added a new argument called
```
dataField
```
first in the argument list, and replaced all references to "startDate" with that argument.
And use it like this:
```
```
var startDateLabelFunction : Function = partial(formatDate, "startDate");
var endDateLabelFunction   : Function = partial(formatDate, "endDate");
```
```
The
```
partial
```
function returns a new function that calls the original function with the parameters from the call to partial concatenated with the parameters to the new function... you with me? Another way of putting it is that it can return a new function where N of the arguments are pre-bound to specific values.
Let's go through it step by step:
```
partial(formatDate, "startDate")
```
returns a function that looks like this:
```
```
function( ...dynamicArgs ) : * {
  return func.apply(null, boundArgs.concat(dynamicArgs));
}
```
```
but the
```
func
```
and
```
boundArgs
```
are what you passed as arguments to
```
partial
```
, so you could say that it looks like this:
```
```
function( ...dynamicArgs ) : * {
  return formatDate.apply(null, ["startDate"].concat(dynamicArgs));
}
```
```
which, when it is called, will be more or less the same as this
```
```
function( item : Object, column : DataGridColumn ) : * {
  return formatDate("startDate", item, column);
}
```
```
Tada!


q:
I love grids - especially the cool third party ones like Devex, C1 etc..

Our programmer doesn't think end users can handle them - so he always designs his forms with read-only grids (with read-only classes).  Choosing to edit an item in the grid opens up a detail form that allows editing.

This app is going to be used by general business folk - not geeks.  But they are all very good Excel users - which I think is kinda 'grid' like. Should I trust my lead developer, or go with my gut which says that users like fast editing - which the grid does much better than the detail forms?  I do want to have a consistent feel to the application, so prefer not to mix it up too much.

[A]
Users can totally handle grids. It's more intuitive than an edit button and a detail form.
However, is this application a multiple user application? Could the underlying data be changed by more than one user at a time?
If so, then you have some concurrency design decisions to make, and sometimes, that can be easier to solve when users can only edit one row at a time.
It smells a little fishy though, and I suspect your programmer is making convenient excuses because it's easier for him to design read-only grids in a master / detail pattern.
Stick with your gut instinct. :)


q:
I am using several NSButtonCell objects in an NSTableView. They are simple square buttons with custom images on them.

These buttons draw properly when they are not highlighted: all that is visible is the image, and the rest of the button rectangle is transparent. However, when I click on them, the entire button rectangle is highlighted, inverting the background in the parts that were transparent.

I would prefer to see the image drawn inverted, and the transparent parts remain transparent. How can this be done?

[A]
Try setting your cell's
```
highlightsBy
```
property to
```
NSContentsCellMask
```
. I think you'll have to do this in code (probably in
```
awakeFromNib
```
); I don't see a way to do it in IB alone.


q: Is there ever a good reason to not declare a virtual destructor for a class?  When should you specifically avoid writing one?

[A]
There is no need to use a virtual destructor when any of the below is true:
No intention to derive classes from it
No instantiation on the heap
No intention to store with access via a pointer to a superclass
No specific reason to avoid it unless you are really so pressed for memory.


q:
To calculate a top position for an element of variable height, I was thinking of doing the following:

Move the element 1000px off the top of the viewport

Set the element to display: block

Get the height of the element

Set the element to display: none

Continue on as if everything is normal and good

Any pitfalls in this approach? Is there a more elegant solution?

[A]
I'd look at
prototype's implementation
of
```
getDimensions
```
.
It sets the position to absolute, visibility to hidden, and display to block briefly. I've written one which handles getting the height of something which is contained within a
```
display:none
```
element, but it's a bit shonky in some edge cases.


q:
We were using stringstream to prepare select queries in C++. But we were strongly advised to use QUERY PARAMETERS to submit db2 sql queries to avoid using of stringstream. Can anyone share what exactly meant by query parameter in C++? Also, share some practical sample code snippets.

Appreciate the help in advance.

Edit: It is stringstream and not strstream.

Thanks,
Mathew Liju

[A]
I suspect this refers to parameterized queries in general, rather than constructing the query in a string, they supply sql variables (or parameters) and then pass those variables separately.  These are much better for handling SQL Injection Attacks.  To illustrate with an example:
```
```
"SELECT * FROM Customers WHERE CustomerId = " + _customerId;
```
```
Is bad, while this:
```
```
"SELECT * FROM Customers where CustomerId = @CustomerId"
```
```
is good.  The catch is that you have to add the parameters to the query object (I don't know how this is done in C++.
References to other questions:
https://stackoverflow.com/questions/1973/what-is-the-best-way-to-avoid-sql-injection-attacks
Stored Procedures vs Parameterized Queries
Wild Wild Web:
http://www.justsoftwaresolutions.co.uk/database/database-tip-use-parameterized-queries.html


q:
I recently started diving into low level OS programming. I am (very slowly) currently working through two older books, XINU and Build Your Own 32 Bit OS, as well as some resources suggested by the fine SO folks in my previous question, How to get started in operating system development.

It could just be that I haven't encountered it in any of those resources yet, but its probably because most of these resources were written before ubiquitous multicore systems, but what I'm wondering is how interrupts work in a multicore/multiprocessor system.

For instance, say the DMA wants to signal that a file read operation is complete.  Which processor/core acknowledges that an interrupt was signaled?  Is it the processor/core that initiated the file read? Is it whichever processor/core that gets to it first?

[A] In the old days the interrupt went to all processors.  In modern times some kinds of hardware can be programmed by an OS to send an interrupt to one particular processor.  Of course if you could choose a processor dynamically instead of statically, you wouldn't want to send the interrupt to whichever processor initiated the I/O, you'd want to send it to whichever processor is least burdened at the present time and can most efficiently start the next I/O operation, and/or whichever processor is least burdened at the present time and can most efficiently execute the thread that was waiting for the results.


q:
I'm writing a function for an installer DLL to verify the Authenticode signature of EXE files already installed on the system.

The function needs to:

A) verify that the signature is valid.

  B) verify that the signer is our organization.

Because this is in an installer, and because this needs to run on older Win2k installations, I don't want to rely on CAPICOM.dll, as it may not be on the target system.

The WinVerifyTrust API works great to solve (A).

I need to find a way to compare a known certificate (or properties therein) to the one that signed the EXE in question.

[A]
If the signature is valid, its certificate chain will contain your certificate.
CertGetCertificateChain
will get that chain.


q:
Is it possible to re-assign the Win+L hotkey to another executable/shortcut?

Use-case - I would like to switch off the monitor of my laptop as soon as it is locked. I know of a executable which can lock and turn off the monitor but I do not want to change the way the system is locked (by running the program explicitly or by some other shortcut). It would be best if Win+L can be assigned to this executable.

[A]
Looks like you can't.
You can disable all built-in Windows
  hotkeys
except Win+L
and Win+U by
  making the following change to the
  registry (this should work on all OSes
  but a reboot is probably required):
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer
  NoWinKeys REG_DWORD 0x00000001 (1)
(
http://www.autohotkey.com/docs/misc/Override.htm
)
But you could try using Tweak UI. Under the Explorer tree view item, uncheck "Enabled Windows+X" hotkeys.
Hoekey
also might work, haven't tried it.
Source
.


q:
How can I determine if a Win32 thread has terminated?

The documentation for GetExitCodeThread warns to not to use it for this reason since the error code STILL_ACTIVE can be returned for other reasons.

Thanks for the help! :)

[A]
The documentation you link to warns against using
```
STILL_ACTIVE
```
as a return code, since it can't be distinguished from the return value used to indicate an active thread.
So don't use it as a return value and you won't have this problem.


q: say I want to find the latest added rows (UPDATE by any user, not necessarily the one which is executing UPDATE)  in XX table.

[A]
Please refer to SQL Docs & look for OUTPUT clause (that you can use with UPDATE/INSERT to get the affected records).
http://msdn.microsoft.com/en-us/library/ms177564.aspx


q:
I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:

>>> foo = 'baz "\"'
>>> foo
'baz ""'

So instead of baz "\" like I want I'm getting baz "". If I then try to escape the backslash, it doesn't help either:

>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'

Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?

[A]
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)
```
```
>>> foo = 'baz "\\"'
>>> foo
'baz "\\"'
>>> print(foo)
baz "\"
```
```
Incidentally, there's another string form which might be a bit clearer:
```
```
>>> print(r'baz "\"')
baz "\"
```
```


q:
I realize that this could probably be done easier in any number of other scripting languages but started to do it quick in cmd and now Im curious.

Looking to start a process at an offset to the time that another process started.  Lets say 5 minutes to keep it simple.  Is there a way to add to the %TIME% variable?

For instance:

start /b foo.exe
at %TIME% + 5 minutes bar.exe

Thanks for any assistance

[A]
I just typed
```
set/?
```
and discovered cmd is much better than old bat... :-)
```
```
set h=%TIME:~0,2%
set m=%TIME:~3,2%
set/a m2="m+5"
set t2=%h%:%m2%
set t2
```
```
Obviously, you can get 62 minutes, etc., I let you do the extra math... :-D


q: How would I implement "close all other tabs" function for a tab control using Context menu strip?

[A]
I made a small app with just one tabcontrol in the main window and a context menu connected to that tabcontrol.
The following is the handler for the context menu item:
```
```
private void closeAllOtherToolStripMenuItem_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < this.tabControl1.TabCount; i++)
            if (i != tabControl1.SelectedIndex)
                tabControl1.TabPages.RemoveAt(i--);
    }
```
```


q: My program works already, I have Perl (GUI Window) where I can input data, data passed to the webpage (using to Tomcat server, JSP) and then saved it to oracle database. What I want is to make search parameter (webapp) that retrieve/extract data from the Oracle database using Perl CGI. Is it possible? Or any suggestions to solve my program? Thanks!:-)

[A]
Any specific reason for the mix in technologies? Why not use a servlet/JSP?
If you must use Perl, then you need to choose what web-server will run your Perl script.
Normally, this would be Apache using
mod_perl
.
But if you only intend to use this for a few admin scripts, then you can run Perl from tomcat as outlined
here
.
Once you have managed to get a simple perl script running, then I would look into using
DBI/DBD::Oracle
to access your database?
Hope this helps...


q:
I want to show a table of fixed width at the center of browser window. Now I use

<table width="200" align="center">

But Visual Studio 2008 gives warning on this line:

Attribute 'align' is considered outdated. A newer construct is recommended.

What CSS style should I apply to the table to obtain the same layout?

[A]
```
```
style="text-align:center;"
```
```
(i think)
or you could just ignore it, it still works


q: Is there a way to define the timezone for an application in ASP.NET such that all times read from/compared to current server time are implicitly converted, or do I need to put in conversion statements as each and every DateTime.Now call?

[A]
Internally use
DateTime.UtcNow
. For .NET 3.5, check out
TimeZoneInfo.ConvertTime
.


q:
How to delete a file which is in use/open by some process in runtime.
I am using vb.net for my project and a image is shown in picturebox,
and that should be deleted, without closing that file.

[A]
If the file is opened by another process in exclusive mode, you can't -- Windows won't let you.  In that case, the best you can do is to either wait for the other process to close the file and then delete it, or have it be deleted at the next reboot by using
```
MoveFileEx()
```
with the flag
```
MOVEFILE_DELAY_UNTIL_REBOOT
```
and a destination location of
```
NULL
```
.
If the file is opened non-exclusively by another process, you can just call
```
DeleteFile()
```
normally (assuming you have permission to do so).  The file will remain while the other process has it open, but it will be deleted as soon as the other process closes it.
(And yes, I realize those links are for the Win32 C API; the same functions should be available under VB .NET)


q:
I need to use a byte array as a profile property in a website. Normally I would declare the type as system.string or system.int32 but I have no idea what the type if for a byte array.

EDIT: I need to use this as profile property that is declared in the web.config like below:

<profile defaultProvider="ProfileProvider" enabled="true">
    <properties>
            <add name="Username" allowAnonymous="false" type="System.String" />
            <add name="LoginToken" allowAnonymous="false" type=" System.Byte()" />
        </properties>
</profile>


q: how do I get information about a photo like the author, the license using PHP?

[A]
This information is all available through the
Flickr API
, if you poke around their docs you may find what you're looking for.


q:
Although I'm doubtful, I'm curious as to whether it's possible to extract primitive-type template parameters from an existing type, perhaps using RTTI.

For example:

typedef std::bitset<16> WordSet;

Would it be possible to extract the number 16 in the above code without hard-coding it elsewhere? Compiler specific implementations are welcome, though I'm particularly interested in g++.

[A]
In the case of
```
std::bitset
```
, you can just use the
```
size()
```
member function:
```
```
size_t sz = oh_my_word.size();  // sz is now 16
```
```
In the general case, you can define a member function which returns the size in a similar manner:
```
```
template <int N>
class Foo
{
public:
  int size() const { return N; }
};
```
```


q:
I am executing a diff command in perl.

my @lines = `/usr/local/bin/diff -udr \"$expected_file\" \"$gen_file\"`;

if ($? != 0)
{
    print ERRFILE "Diff between $expected_file and $gen_file failed\n";
    return $diff_err;
}

Here the diff might have failed because of some reason. For example: the stderr showed that /usr/local/bin/diff: test.txt: No such file or directory. I want to read this message in the program. How I can find the stderr message of the diff command (or grep or any command I execute)?

Appreciate the help in advance.

Thanks,
Mathew Liju

[A]
This is answered in
perlfaq8: How can I capture STDERR from an external command?
If I want to read STDOUT and STDERR of a process, I use IPC::Open3, which comes with Perl. That way, I don't have to merge those streams and later figure out what part of the output came from what.
I would try to avoid temporary files whenever possible (so no
```
2>file.txt
```
). That's just too much work and code when I can read STDERR directly.


q: I am using Xcode to develop a GUI application. I have a model class and a controller class. I have a NSTextView data member in my controller class. How do I access this variable from the model class?

[A]
First of all, a model class shall not talk to a view class. A TextView is part of the view.
alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/cocoa_mvc.gif
The controller talks to view classes and view classes provide feedback to the controller. The model classes get updated by the controller and provide feedback to it. The model classes never talk to a view class, they don't even know about the existence of any view classes. So I think you have a basic design problem here. You probably implemented MVC as in this model:
alt text http://developer.apple.com/documentation/Cocoa/Conceptual/CocoaFundamentals/Art/traditional_mvc.gif
However this is not the way it is done in Mac OS X, this is not the way Apple does it and this is not the way how the whole Cocoa object structure has been designed! So the answer to your question is: You don't, because you should not.
Aside from the fact, that you have a design flaw, you access it like you access all data members in Objective-C. If it is public, you can access it directly:
```
```
MyController * c = [[MyController alloc] init];
// c has a member name textView, let's access it
[c->textView ...];
```
```
You should already know, that this is actually very bad programming style. You should not access data members of another object directly. You should actually not even make them public. If you declare them private, the code above will fail (the compiler enforces that you don't do this). The other way is to implement a getter and access it via the getter:
```
```
// This goes into the controller

- (NSTextView) textView
{
    return textView;
}

// This is called in the modell

[[c textView] ...];
```
```
However, this is also bad design. The model might do whatever it wants with this object and your controller won't see it! Why doesn't you model just tell the controller what it wants to happen?
```
```
// In the controller

- (void) notifyContentHasChanged:(NSString *)name
{
    // update the text view here ...
}

// In the modell

[c notifyContentHasChanged:...];
```
```
And voila, you have MVC the way Apple wants it to be. The model only notifies the controller of what's going on and the controller updates the view accordingly.


q:
I have a question regarding an update function I created...

CREATE OR REPLACE FUNCTION rm_category_update(icompany bpchar, iraw_mat_cat_code bpchar, iraw_mat_cat_desc bpchar)

RETURNS character AS

$BODY$

DECLARE
   loc_result    CHAR(50);

BEGIN

UPDATE rm_category

 SET
    raw_mat_cat_code    = iraw_mat_cat_code,
    raw_mat_cat_desc    = iraw_mat_cat_desc

WHERE company = icompany;

loc_result = 'success';

RETURN loc_result ;

END;

$BODY$

LANGUAGE 'plpgsql' VOLATILE;

ALTER FUNCTION rm_category_update(icompany bpchar, iraw_mat_cat_code bpchar, iraw_mat_cat_desc bpchar) OWNER TO postgres;

Okay, so if I input a record that doesn't exist, for example 9, it returns success even though I know it has updated nothing!

Does SQL not throw errors if it is updating a non-existent row??

Thanks


q: I am running a site about PHP Frameworks, but I can't find a exact definition for it, and I am always thinking a question, how to make out a good PHP framework? Features? Manual? Efficiency? Or something?

[A]
A PHP Framework in my eyes is a collection of classes which help you develop a web application.
In my company we use the Zend Framework. I have to say that getting started with this Framework is pretty hard, but if you get how to use the API and the Reference Guide you have a great Framework. Also its interessting because they have Zend people sitting on the project so they can use those internal tricks and get some performance boosts others can't get.
What also differs ZF from others is the ability to create MVC programms with no big hassles.


q:
Ours is an upcoming company, so we cannot buy two three third party controls and find out by ourselves which the best one is.(One of the better solutions)
We have a budget to buy just one.
So we would like to know which is third party control is the best to use in ASP.NET based on your experiences.

And also I definitely saw a question asked already here.

https://stackoverflow.com/questions/215993/best-3rd-party-aspnet-grid-control

Still asking this because

Wanna know not just about grid, i wanna know about the whole set.

Didn't see many answers for that.

So please provide us some advice on how to proceed.
Our requirements are

Bug Free working

Speed

Good documentation

Excellent Support Team

Also is there a third party ListView?

Regards,

Naveen

[A]
For all those requirements, there's only two companies to choose from:
Telerik
and
DevExpress
.  Both have fantastic support and incredible ASP.NET products.  They release often, and are known to be constantly adding new controls.  I had to decide between the two about a year ago, and went with DevExpress because of the productivity tools included.
The difference I see between these two companies and larger competitors like Infragistics is they are dedicated to making the best quality and best performing products possible.


q:
A C-program is placing what it considers to be 64-bit unsigned integers into a column in a Postgres database that is typed as int8.
To Postgres, int8 is always 'signed int8' (no such thing to it as 'unsigned int8').
So the Ruby program I have shows numbers retrieved from Postgres in the upper half of that space as negative.

What is the correct way, in Ruby, to take that -ve integer and convert it to the 64-bit unsigned integer that the C-programmer intended?


q:
I am developing a Java desktop application and would like to have an external configuration.xml.

I am developing the application using Netbeans and tried to add the configuration.xml file in the dist directory so that it resides in the application work folder. But when Netbeans executes its clean operation it deletes the dist directory,

Where should I put this configuration.xml file so that it will not be deleted and will exist in the application start-up directory.

[A]
You can add this to your build.xml :
```
```
<target name="-post-jar">
   <copy todir="${dist.jar.dir}">
       <fileset dir="resources" includes="**"/>
   </copy>
</target>
```
```
You can now put your configuration.xml file in the folder 'resources' (that you need to create) in your project and all files in it will be copied to the dist folder during the build process.


q:
I have example of code below.

<script type="text/javascript" src="assets/scripts/somescript.php">.
</script>

So, will my browser still cache this just by not setting this scripts headers meta tag cache to must-revalidate?

[A]
If you send a
```
Content-type: text/javascript; charset="your_charset"
```
the browser will recognize your PHP script as a valid Javascript resource and will handle it like any other Javascript. You can control browser caching behavior by issuing the correct headers in your PHP script using
```
header()
```
.


q: I want to increase the I/O priority of a process. Answers for both .NET and Windows Vista would be nice. processexplorer is ok as well.

[A]
The relevant information seems to be a bit scattered compared to the usual MS documentation. There is this white paper that discusses
I/O Prioritization in windows
. This doc seems to have beta flags all over it but I guess it's probably mostly pretty accurate.
Two important things to note:
You can only reduce the priority of IO requests below normal.
The driver can ignore any such request and treat it as normal anyway.
The useful APIs for client applications are
SetFileInformationByHandle
:
```
```
FILE_IO_PRIORITY_HINT_INFO priorityHint;
priorityHint.PriorityHint = IoPriorityHintLow;
result = SetFileInformationByHandle( hFile,
                                     FileIoPriorityHintInfo,
                                     &priorityHint,
                                     sizeof(PriorityHint));
```
```
SetPriorityClass
:
```
```
// reduce CPU, page and IO priority for the whole process
result = SetPriorityClass( GetCurrentProcess(),
                           PROCESS_MODE_BACKGROUND_BEGIN);
// do stuff
result = SetPriorityClass( GetCurrentProcess(),
                           PROCESS_MODE_BACKGROUND_END);
```
```
SetThreadPriority
which is similar:
```
```
// reduce CPU, page and IO priority for the current thread
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_BEGIN);
// do stuff
SetThreadPriority(GetCurrentThread(), THREAD_MODE_BACKGROUND_END);
```
```
SetFileBandwithReservation
:
```
```
// reserve bandwidth of 200 bytes/sec
result = SetFileBandwidthReservation( hFile,
                                  1000,
                                  200,
                                  FALSE,
                                  &transferSize,
                                  &outstandingRequests );
```
```
For .Net do the usual stuff with P/Invoke.


q:
I'm using RSACryptoServiceProvider in .NET 2 and it seems that the Private part of a Public/Private key pair always contains the Public part as well.

I need to encrypt some info using my Public key, and allow the other party to ONLY DECRYPT what I encrypted. I don't want them to be able to know how I encrypted my message. Is that possible using RSACryptoServiceProvider in .NET?

[A]
The private key always includes the public key.
What you might really want is Signing. Using the same .NET classes, you can sign data with your private key and verify the signature on the other party's side with the public key (which obviously doesn't contain the private key).
```
```
public static string Sign(string data, string privateAndPublicKey)
    {
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        RSACryptoServiceProvider provider = CreateProviderFromKey(privateAndPublicKey);
        byte[] signatureBytes = provider.SignData(dataBytes, "SHA1");
        return Convert.ToBase64String(signatureBytes);
    }

    public static bool Verify(string data, string signature, string publicKey)
    {
        byte[] dataBytes = Encoding.UTF8.GetBytes(data);
        byte[] signatureBytes = Convert.FromBase64String(signature);
        RSACryptoServiceProvider provider = CreateProviderFromKey(publicKey);
        return provider.VerifyData(dataBytes, "SHA1", signatureBytes);
    }

    private static RSACryptoServiceProvider CreateProviderFromKey(string key)
    {
        RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
        provider.FromXmlString(key);
        return provider;
    }
```
```


q:
If I have a template function, for example like this:

template<typename T>
void func(const std::vector<T>& v)

Is there any way I can determine within the function whether T is a pointer, or would I have to use another template function for this, ie:

template<typename T>
void func(const std::vector<T*>& v)

Thanks

[A]
Indeed, templates can do that, with partial template specialization:
```
```
template<typename T>
struct is_pointer { static const bool value = false; };

template<typename T>
struct is_pointer<T*> { static const bool value = true; };

template<typename T>
void func(const std::vector<T>& v) {
    std::cout << "is it a pointer? " << is_pointer<T>::value << std::endl;
}
```
```
If in the function you do things only valid to pointers, you better use the method of a separate function though, since the compiler type-checks the function as a whole.
You should, however, use boost for this, it includes that too:
http://www.boost.org/doc/libs/1_37_0/libs/type_traits/doc/html/boost_typetraits/reference/is_pointer.html


q:
I use the Autocomplete extender feature to get the list of suggestions from my database. There is no scroll bar for this control, so I have added a scroll bar in a panel (MS .net 2.0) which i attach to my autocomplete extender.Now the issue is with the srcoll bar.
like this

<asp:Panel ID="autocompleteDropDownPanel" runat="server"  ScrollBars="Auto"  Height="100px" HorizontalAlign="Left" />

and add it to autocompete extender  like this

:CompletionListElementID="autocompleteDropDownPanel"

When I call my page, I get the list of suggestions and the scroll bar appears. When I click on scroll bar or try to drag, everything just disappears.

Am i doing something wrong? Is there any other way to add a scroll bar to my autocomplete extender control

Any hints would be very helpful.

[A]
This does not directly answer your question - but I would ask if you're sure that the autocomplete extender is the best control to be using in this scenario.
From a usability perspective the great thing about autocomplete is that I can type a 3-4 characters, see a few available inputs and easily select them using the keyboard using a few down-cursor keypresses.
If you are displaying more items in the autocomplete list than can be easily viewed on screen then I'm not sure that the fix is to add a scrollbar.
In our scenario we had a list of 2800 names that were available in the autocomplete. We limited the number shown to 20, but set the
```
MinimumPrefixLength
```
to 1. This meant that when the user typed one character they would see an autocomplete list that effectively just lets them know that the textbox they're typing in has this ability. The list of results in the list only becomes really useful once the user has entered 3-4 characters though.


q:
I am probably doing something wrong -- but cant figure why.
I have a DateTime field in my DB keeping a UTC time

My server is in the US, and the browser is in Europe.

The PageLoad Code is as follow:

DateTime t = DateTime.SpecifyKind((DateTime)rdr["startTime"], DateTimeKind.Utc);
label1.Text = t.ToLocalTime().ToString();

The time displayed I get is US localtime and not Europe. What should I do to display the browser's localtime?

Thanks!

[A]
One technique is to detect the client timezone offset (in minutes) using JavaScript on the client browser:
```
```
alert((new Date()).getTimezoneOffset());
```
```
This can then be sent back to the server and stored in the session, or a cookie, and used to offset the UTC dates displayed to them. Alternatively, another technique is to have user profiles where they can specify their timezone.


q:
OK, deploying ASP.NET MVC seems to be painful. I want to deploy my ASP.NET MVC application on Windows XP (IIS 5.1), but can't seem to find how to do it. When I type the application name into the web browser address bar I get a "website not available" message.

There are workarounds for IIS 6.0, but what about IIS 5.1?

[A]
The
same
process (using Ionic rewriter) which works for 6.0 works for us on 5.x. What do you see in the Windows App Event log? And the IIS server log? Have you tried a rewriter?


q:
My team is responsible for the development of an API for a large system that we also write. We need to provide example code so that other developers using our API can learn how to use it. We have been documenting the code using the xml document comments.
eg.

/// <summary>Summary here</summary>
/// <example>Here is an example  <code>example code here</code> </example>
public void SomeFunction()

We then use Sandcastle and build the help files we need (chm and an online website).

It is quite embarrassing when the example code doesnt work, and this is usually because some functionality has changed or a simple error.

Has anyone ever done something like this, but also configured unit tests to run on the example code so that they are known to work during the build?

[A]
Simple solution:
Make a small application in which you include all the sample code headers and then call their respective entry points
```
```
#include "samples/sampleA.h"

void main()
{
  SomeFunction();
}
```
```
then after you make a build run these little apps you need to be sure they ran ok.
But can you verify that the code ran ok without having someone have a slumber party with the NightlyBuild server?
Better Solution:
Log the output and have someone look at it in the morning.
Even Better Solution:
Log the output and grep it or something so no one has to look at it unless its broken.
Best Solution:
Find a suitable test framework, hopefully something with all the bells and whistles you can get so it can email people if its broken or something like that. In our case we avoid the bells and whistles instead we connected a
USB Police Siren
that goes off when something breaks It's quite exciting!


q:
I am using Oracle form 10
I want to know how can I access the parameters of URL in oracle form

Ex:
whenever I run the form it opens in a browser and the URL for the same is

http://112.10.0.10:7778/forms/frmservlet?config=pkamble

I just want to know how can I access the value of 'config' parameter inside oracle form code.

when we run oracle form using 10g then

I will appreciate the help !!

[A]
I don't know if you can read config parameter, but to read another parameter from URL your URL have to be like:
```
```
http://112.10.0.10:7778/forms/frmservlet?config=pkamble&otherparams=name=value
```
```
In your .fmb you will have to add 'name' parameter in the parameters block and then you could do something like:
```
```
if :PARAMETER.name = 'value' then
 message('ok');
end if;
```
```
And for more than one parameter use:
```
```
http://112.10.0.10:7778/forms/frmservlet?otherparams=name1=value1+name2=value2+name3=value3
```
```


q: How do I declare a session variable in PL/SQL - one that will persist for the duration of the session only, without me having to store it in the database itself?

[A]
You create a package level variable.  This is a minimal example:
```
```
CREATE OR REPLACE PACKAGE my_package
AS
    FUNCTION get_a RETURN NUMBER;
END my_package;
/

CREATE OR REPLACE PACKAGE BODY my_package
AS
    a  NUMBER(20);

    FUNCTION get_a
    RETURN NUMBER
    IS
    BEGIN
      RETURN a;
    END get_a;
END my_package;
/
```
```
If you do this you should read up on (and handle correctly)
```
ORA-04068
```
errors.  Each database session will have it's own value for a.  You can try this with:
```
```
SELECT my_package.get_a FROM DUAL;
```
```


q:
In most programming languages, dictionaries are preferred over hashtables.
What are the reasons behind that?

[A]
Because
```
Dictionary
```
is a generic class (
```
Dictionary<TKey, TValue>
```
), so that accessing its content is type-safe (i.e. you do not need to cast from
```
Object
```
, as you do with a
```
Hashtable
```
).
Compare
```
```
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
```
```
to
```
```
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
```
```
However,
```
Dictionary
```
is implemented as hash table internally, so technically it works the same way.


q:
In a PHP application I am writing, I would like to have users enter in text a mix of HTML and text with pointed-brackets, but when I display this text, I want to let the HTML tags be rendered by the non-HTML tags be shown literary, e.g. a user should be able to enter:

<b> 5 > 3 = true</b>

when displayed, the user should see:

5 > 3 = true

What is the best way to parse this, i.e. find all the non-HTML brackets, convert them to &gt; and &lt;?

[A]
I'd recommend having the users enter BBcode style markup which you then replace with the html tags:
```
```
[b]This is bold[/b]
[i]this is italic with a > 'greater than' sign there[/i]
```
```
This gives you more control over how you parse user's input into html, though I admit it looks like an unnecessary burden.


q:
Coming from a java background, one of the things I am used to is telling the JVM what the maximum heap size should be.  If the running program tries to swallow more than is allowed, and the garbage collector cannot free any more resources, then OutOfMemoryError is thrown and it all goes bang.  So setting the maximum heap size is important in Java.

Does this apply in .net?  Can you set the heap size limits?  Does the CLR just keep growing its heap until it reaches the machine's physical limits?  Or is it not an issue in .net for some subtle reason that my Java blinkers stop me from seeing?

[A]
No, it doesn't apply in .NET. The heap does indeed keep growing until it can't grow any more. (Obviously this is "after attempting to recover memory through GC, grow the heap".) Basically there isn't nearly as much tuning available in the .NET GC as in Java. You can choose the server GC or the client one, and I think there's an option for turning on/off the concurrent GC (I'll find links in a minute) but that's basically it.
EDIT: It seems there's a little more to it, although not a huge amount.
Rick Minerich's blog entry on GC settings
and
the subsequent one
seem to know rather more than I do about the matter. They're probably a good starting point for any further investigation - but they're mostly flags rather than the sort of memory limits available in JVMs.
EDIT: Pop's answer raises a good point - I've been assuming a "normal" CLR hosting model (i.e. not under your control). If you want to go to the effort of hosting it yourself, you're likely to get a lot more control - at the cost of the extra work of hosting it. I can't say I've ever looked into that side of things.


q:
I am working with Rails fixtures for testing my rails application.  It is all good except one of my database columns is supposed to hold YAML content.  But, I am sure how to put the YAML markup I want to load into my database inside the YAML file.  Here is an example:

mvnforum:
    name: mvnforum
    abstraction_type: SVN
    url: src: test username: admin #is this possible?
    sourcepath: mvnforum/src/
    webroot:
    codesecure_project: mvnforum

If it is impossible to have YAML inside a YAML file what would be the best why to load this into a database for testing?

[A]
If you want to put YAML code inside a YAML document, you need to treat it like a string:
```
```
url: "src: test username: admin"
```
```
If you need a multiline string, you can do
```
```
mvnforum:
   name: mvnforum
   abstraction_type: SVN
   url: "
src: test\n
username: admin\n
"
   sourcepath: mvnforum/src/
   webroot:
   codesecure_project: mvnforum
```
```