q:
I'm in the process of developing a social network site.

And been thinking of scalability from day one of the project, I've fine tuned the site and queries to the best of my ability.

However; Certain pages are very data heavy and I'm not quite sure if they are loading as fast as they could so I was thinking of implementing a distributed caching solution.

But not quite sure what I should cache and not cache. Or if current page load times of 1 second is good or bad.

The heaviest query is grabbing member information this query gets all the member's info and anything related to them such as in this site's case their goals, blog type entries, encouragements, photos, status updates (like twitter), blog info (for crossposting their entries) etc etc.

Anyhow, should I cache this info? And do you think 1 second page load times are reasonably fast? Some pages are less than a second between 4-6 10ths of a second.

[A]
The page loading question was already asked:
What is considered a good response time for a dynamic, personalized web application?
In terms of caching, you have to measure the amount of time that would be spent loading the data each time versus loading from the cache. The bigger the cache, the less effective it becomes. So you don't want to load too much data into the cache. What we use here is a rolling cache, with the least recently used data being dropped once we hit the cache size limit. You then tune the limit according to actual performance results.


q:
I am wondering how the JBoss ExceptionSorter classes are able to check for database errors.

The application (the EJB or persistence framework) is holding the reference to the database Connection, so SQLExceptions are caught by the application. How is JBoss able to see the contents of the exception?

Does JBoss wrap the connection and intercept these messages or something like that?

[A]
JBoss uses a connection pool for its datasources (org.jboss.resource.adapter.jdbc.local.LocalTxDataSource). The ExceptionSorter takes an SQLException as a parameter which it then just checks for certain strings which map to certain errors. If the errors represent a physical connection problem then they will look somewhat like "Socket error" or "broken pipe".
This Exception Sorter will then return a boolean value representing the state of the connection back to the connection pool which will then invalidate and remove any connections that returned false.
For an Oracle database:
```
```
<property name="exceptionSorterClassName"><value>org.jboss.resource.adapter.jdbc.vendor.OracleExceptionSorter</value></property>
```
```
This will work for an Oracle database. Here is the code for that ExceptionSorter implementation:
http://kickjava.com/src/org/jboss/resource/adapter/jdbc/vendor/OracleExceptionSorter.java.htm
How the internal programming of where or how the connection pool checks the connection is unknown to me. Check the JBoss source code.

s: huggingface

c: devops

d: intermediate


q:
I have three Java JCheckboxes in a column, arranged by setting the layout of the container JPanel to GridLayout(3, 1, 1, 1).  When I run the program, there is too much vertical space between the JCheckBoxes; it looks like more than 1 pixel.  Since I've already set the vertical space between the JCheckboxes in the layout to be 1 pixel, how else can I reduce the vertical space between these JCheckboxes?

Thanks.

[A]
I explored using
```
GridLayout
```
,
```
BorderLayout
```
, and
```
GridBagLayout
```
and I believe that any extra vertical space that is present in your application is due to the sizing of the JCheckBox component, not related to the layout manager. All of the examples below have no space between components in the layout manager.
GridLayout
```
```
//Changing to 3,1,1,0 makes slightly smaller (1 pixel) gap vertically
GridLayout layout = new GridLayout( 3, 1, 1, 0 );
JPanel main = new JPanel( layout );
main.add( new JCheckBox( "box 1" ) );
main.add( new JCheckBox( "box 2" ) );
main.add( new JCheckBox( "box 3" ) );
```
```
GridBagLayout
```
```
GridBagConstraints gbc = new GridBagConstraints();
JPanel main = new JPanel( new GridBagLayout() );
gbc.gridx=0;
gbc.gridy=0;
gbc.ipady=0;
main.add( new JCheckBox( "box 1" ), gbc );
gbc.gridy=1;
main.add( new JCheckBox( "box 2" ), gbc );
gbc.gridy=2;
main.add( new JCheckBox( "box 3" ), gbc );
```
```
BorderLayout
```
```
JPanel main = new JPanel( new BorderLayout() );
main.add( new JCheckBox( "box 1" ), BorderLayout.NORTH );
main.add( new JCheckBox( "box 2" ), BorderLayout.CENTER );
main.add( new JCheckBox( "box 3" ), BorderLayout.SOUTH );
```
```


q:
I need to give users the ability to optionally add metadata to documents. Another way to state this is the fact that users need to add at least 5 categories to a document.

Basically what I want to do is dynamically add metadata (or categories) to a document on an ad hoc basis. Here are the options that I have thought of:

Option 1:
Should I do this by dynamically creating new table columns in the database?

Option 2:
Should I define 5 columns called attirbute1,attirbute2,attirbute3,attirbute4,attirbute5 and then only use and show them if the user requires the attributes.

Option 3:
Should I create a metadata table that keeps track of the columns and the data associated with them?

What do you think is the best way to achieve this? Can you think of any other ways to easily add this functionality. The problem is that the functionality needs to be very generic.

[A]
Each document has a unique DocumentID.
Just add another table that has three columns:
```
DocumentID
MetaName
MetaData
```
Then they can add as many pieces of metadata to a given document.  If all their documents use the same metanames then it's trivial to search the metadata.
-Adam


q:
I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:

Org1     Emp1 Name, Emp1 Phone, Emp1 Address
         Emp2 Name, Emp2 Phone, Emp2 Address

Org2     Emp1 Name, Emp1 Phone, Emp1 Address
         Emp2 Name, Emp2 Phone, Emp2 Address

How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?

Many Thanks.

[A]
Classic.
Workaround: only display the name if different than the previous one. You can even not bother about the rowspan (you keep an empty cell).
```
```
$currentOrg = '';
while ($row = mysql_fetch_object($query)) {
   if ($row->org != $currentOrg) {
      echo "$row->org".
   }
   $currentorg = $row->org;
}
```
```
Not the most beautiful but so simple.


q:
We all know the good old "disable the submit button" trick but what are the best ways to handle multiple submissions server side? I have an application where it is absolutely critical that a form only be sent once - it processes a credit card. I didn't write how it is right now but as a quick fix I threw on the disable-on-submit technique, however some impatient users that have javascript disabled are still getting charged twice.

So, what are ways to avoid this? I can think of a few - I have used a few in the past - but I'd like to see if there's any "best practices" on how to tackle this one. I am using PHP but I'm more interested in concepts.

edit: I am aware of the token technique and it is what I have used in the past, this question is more or less to see if my approach is in line with what the rest of you fine programmers use.

[A]
One really effective way is to submit a token along with the request, and keep a list of used tokens. If the token is not valid, or the token has already been processed, then abort.
The token can be as simple as an incrementing integer, stored in a hidden text field, or you can encrypt it to increase security. This feature can be made more robust by generating the token when the page is created, encrypting it, then confirming the token has been generated AND has not been processed.


q:
Is there a best way to turn an integer into its month name in .net?

Obviously I can spin up a datetime  to string it and parse the month name out of there. That just seems like a gigantic waste of time.

[A]
Why not just use
```
somedatetime.ToString("MMMM")
```
?


q: I'm trying to connect from my Java application to a development server that has port 8088 closed which is used for RMI. I appreciate any help on how to open that port.

[A]
Slicehost have some good documentation on setting up iptables on Ubuntu:
http://articles.slicehost.com/2008/4/25/ubuntu-hardy-setup-page-1
http://articles.slicehost.com/2008/9/2/mail-server-opening-ports-in-the-firewall


q: I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome.

[A]
This is pretty much Python-independent!  It's a classic example of Unix interprocess communication.  One good option is to use
```
popen()
```
to open a pipe between the parent and child processes, and pass data/messages back and forth along the pipe.
Take a look at the
```
subprocess
```
module
, which can set up the necessary pipes automatically while spawning child processes.


q: Is there a simple Model Checker tool. I am planning to implement a model checker tool which will analyze the code for some of the predefined properties.

[A]
CBMC
is one simple-ish tool I'm aware of that actually operates on code.  Model checking in general is a heavily-researched field, but as folks have already commented, this breadth makes it difficult to suggest something with the info provided.  There are thousands of SAT solvers, formal tools for HDL/state machine verification, and plenty of commercial static source analyzers.
In any case, CBMC is a good tool, but don't take my word for it; Ed Clarke, the main faculty member behind this work, won the Turing Award this year ;-)


q:
I want to use Sharepoint with python (C-Python)

Has anyone tried this before ?

[A]
SharePoint exposes several web services which you can use to query and update data.
I'm not sure what web service toolkits there are for Python but they should be able to build proxies for these services without any issues.
This article should give you enough information to get started.
http://www.developer.com/tech/article.php/3104621


q:
We have inherited an ant build file but now need to deploy to both 32bit and 64bit systems.

The non-Java bits are done with GNUMakefiles where we just call "uname" to get the info.  Is there a similar or even easier way to mimic this with ant?

[A]
You can just pass a parameter into the build file with the value you want. For example, if your target is
```
dist
```
:
```
```
ant -Dbuild.target=32 dist
```
```
or
```
```
ant -Dbuild.target=64 dist
```
```
and then in your Ant build script, take different actions depending on the value of the
```
${build.target}
```
property (you can also use
conditions
to set a default value for the property if it is not set).
Or, you can check the value of the
built-in
system properties
, such as
```
${os.arch}
```
.


q:
I am still new to sharepoint and would like to know if it is possible to make a query that works across several lists. My list looks like this

Customers (id, name and so forth)
Orders ( id, order number, customer and some additional info)
OrderItems (id, name, price, description and so on)

I would like to create a view that will display the OrderItems grouped by Order which again will be grouped by Customer.

In pure .net code that is pretty easy but is it possible to implement it only using sharepoint lists?

[A]
Without custom code or third party components you would have only a few options. Using SharePoint Designer to create a Data View or creating a custom Query with some complex CAML which I'm not even sure is entirely possible.
Personally I would look more towards using Master Detail functionality using a combination of web part connections and filtering. By activating Enterprise features you have available a number of Filter Web Parts that should be able to be combined to filter lists to selected values.
Personally I have gone with custom code to bring back list data based on queries and then used the GetDataTable() method of the SPListItemCollection object. Once you have the list items in DataTables you have numerouse ways to sort filter and aggregate the information.
I should add to this that there is a great article on displaying information from a dataset using the SPGridView and SPMenuField. Once you have your DataTables you could establish relationships in a dataset to display the information using these controls:
http://blogs.msdn.com/powlo/archive/2007/02/25/displaying-custom-data-through-sharepoint-lists-using-spgridview-and-spmenufield.aspx


q:
If I view the HTML generated by one of my Jasper reports in IE7 I see the following:

<BR /><BR />
<A name="JR_PAGE_ANCHOR_0_1">
<TABLE style="WIDTH: 1000px" cellSpacing="0" cellPadding="0" bgColor="#ffffff" border="0">
<-- table body omitted -->
</TABLE>

The two BR tags are added via the JRHtmlExporterParameter.HTML_HEADER parameter. After these tags and before the beginning of the report table that there's an unclosed anchor tag that is generated by Jasper reports. The fact that this tag is not correctly closed is messing up the formatting of my report because IE is hyperlinking the entire report TABLE. I'm not using this anchor tag, so if I could prevent Jasper from generating it, that would solve my problem.

Incidentally, this problem only occurs in IE, in Firefox everything works fine because the anchor tag is properly closed.

Thanks in advance,
Don

[A]
That's odd code, the
```
<br />
```
tags are XHTML-style, while the unclosed
```
a
```
tags are good old HTML, like the upper case tag names. If you serve such page with plain HTML header/content-type, perhaps IE will be happy.
When you write that Firefox closes the tag, I suppose you mean it correctly doesn't extend the hyperlink span over block tags. Note that FF's view source can display closing tags that are not there when you save the page to disk!
Frankly, I don't know if you can get rid of these anchors with some config. If nobody comes with a real solution, maybe you can download Jasper's source code and search JR_PAGE_ANCHOR in it, looking if the code generating it is conditionally driven.
Or, if you can, you can apply post-processing of the generated code.


q:
Our clients use a vb6 version of our software.

We are upgrading them to a .NET application written in C#...

Is there less bulk using .net 2.0 than .net 3.5?

My definition of less bulk would be: Smaller size, smaller installation time, etc.

Most of them probably already have 2.0 anyway.

I only ask because I would like to take advantage of LINQ in 3.5.

[A] If you would like to take advantage of LINQ, then go for 3.5! I find there's not more 'bulk' when using it myself, but unless you want to use LINQ, then either is fine.


q:
In ActivePerl, "ppm" installs a package from the Internet, "ppm install x.ppd" installs from a ppd file, but most CPAN packages are distributed as .tar.gz

How do you supply modules to a machine running ActivePerl that doesn't have an Internet connection?  ("make" will probably not be available.)

Update: an Internet connection can be used to download files and transfer them to the machine with a USB key, etc.


q:
When my application opens too many windows the taskbar groups them into one button. Each window has its own icon, but the grouping icon is the default "unknown"-kind icon.

How can I set the grouping icon?

[A]
The taskbar group icon can be set in the registry on a per application basis.
For explorer, this would be here:
```
```
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Applications\explorer.exe]
"TaskbarGroupIcon"="C:\Windows\Explorer.exe,13"
```
```


q:
Obviously I could create a Calendar object with the date and use get(DAY) on it, but knowing Groovy, I would guess there is an easier, quicker way I just don't know about?

Answer

(date1..date2).size() == 1 // true if two dates are on same calendar day

[A]
Quickly opened the Groovy In Action book and found the following sample that should help:
```
```
def today = new Date()
def yesterday = today-1
assert (yesterday..today).size() == 2
```
```


q:
I have been reading carefully through the mediawiki documentation but I have not been able to find out how to create new groups.

When I look at Special:Userrights, I see only 3 groups :
Bots, Sysops, Bureaycrats

I would like to create my own custom groups, so I can use some extensions like the http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control.

Can someone tell me how it's done, or point me to some documentation?

[A]
I beleive I have found the answer, I just need to add the UserGroup and the permission to the wgGroupPermissions array in the LocalSettings.php file.
```
```
$wgGroupPermissions['TomatoUsers']['read']  = true;
$wgGroupPermissions['TomatoUsers']['edit']  = false;
```
```


q:
I need to run a Linux CLI command and get its stdout output from C.

I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.

Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.

There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status.

[A]
Use
```
popen()
```
and
```
pclose()
```
.
```
popen()
```
does not actually wait, of course, but reads on the pipe will block until there is data available.
```
pclose()
```
waits, but calling it prematurely could cut off some output from the forked process. You'll want to determine from the stream when the child is done...
Possibly already discussed at
How can I run an external program from C and parse its output?


q:
We've got a fairly large amount of code that just made the jump to Java 5. We've been using generics in those components targeted at being released in the Java 5 version, but the remaining code is, of course, full of raw types. I've set the compiler to generate an error for raw types and started manually clearing them, but at the present rate it'll take a very long time to go through with it (there are about 2500 errors). And that's with Eclipse's helpful Infer Generic Type quick fix, which always gets rid of the errors, but often generates code that needs further work.

Is there any better way to dealing with this? Are there any automated tools better than Eclipse? Any way to apply the refactoring to all occurences instead of doing them one-by-one? Or do you just ignore the warnings?

[A]
I would suggest ignoring the warnings.  Otherwise, you'll be putting a lot of time into updating the legacy code without making any improvements to its functionality.
Update:
Great comment from
Luke
that I thought should get more visibility:
"Generics are a way to catch run time bugs at compile time. Unless this legacy code has bugs in it that you think are related to casting I would leave it alone (if it ain't broke, don't fix it)"


q: I installed Python 2.6 for one user on Windows Vista.  Python works okay, but when I try: import Tkinter, it says the side-by-side configuration has errors.  I've tried tinkering with the Visual Studio runtime, with no good results.  Any ideas on how to resolve this?

[A] Maybe you should downgrade to 2.5 version?


q: Is it possible to to change a <span> tag (or <div>) to preformat its contents like a <pre> tag would using only CSS?

[A]
Look at the
W3C CSS2.1 Default Style Sheet
or the
CSS2.2 Working Draft
. Copy all the settings for PRE and put them into your own class.
```
```
pre {
    display: block;
    unicode-bidi: embed;
    font-family: monospace;
    white-space: pre;
}
```
```


q:
function Submit_click()
{
  if (!bValidateFields())
    return;
}

function bValidateFields() {
/// <summary>Validation rules</summary>
/// <returns>Boolean</returns>
...
}

So, when I type the call to my bValidateFields() function intellisence in Visual Studio doesn't show my comments. But according to this it should. Should it?

[A]
Did you try adding the
```
/// <reference>
```
comment at the top of the external library?  I've run into this in the past and it resolved my issue.


q:
I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral

Here is the select I am using now:

SELECT SomeStringColumn from SomeTable

Here is the select I would like to use:
    SELECT hex( SomeStringColumn ) from SomeTable

Unfortunately nothing is that simple... Informix gives me that message:
Character to numeric conversion error

Any idea?

[A]
Can you use Cast and the fn_varbintohexstr?
```
```
SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary))
FROM SomeTable
```
```
I'm not sure if you have that function in your database system, it is in MS-SQL.
I just tried it in my SQL server MMC on one of my tables:
```
```
SELECT     master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM         Customer
```
```
This worked as expected. possibly what I know as master.dbo.fn_varbintohexstr on MS-SQL, might be similar to informix hex() function, so possibly try:
```
```
SELECT     hex(CAST(Addr1 AS VARBINARY)) AS Expr1
FROM         Customer
```
```


q: Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files  we write ourselves.  How do you manage them all?  How do you minify them in an organized way?

[A]
First of all,
YUI Compressor
.
Keeping them organized is up to you, but most groups that I've seen have just
come up with a convention
that makes sense for their application.
It's generally optimal to
package up your files
in such a way that you have a small handful of packages which can be included on any given page for optimal caching.
You also might consider dividing your javascript up into segments that are
easy to share
across the team.


q: We have a small 3 developer team that is currently using Subversion for our source control. We expect the team to group to 8 members within the next 6 to 12 months. We are considering changing our source control to either TFS or Mercurial for improved branching. I know TFS is overkill for just branching, but that is the immediate need, and the other features of TFS could aid our team. One of our main concerns with TFS is we've heard that there is a lot of overhead deploying it, especially on a small team. I'm hoping to get some community insight into just how much overhead there may be involved, suggestions to make the process easier, and anything else the community may feel is useful in making the decision to implement.

[A]
It's been awhile, but I'm thinking that it takes about a half-day to get setup, plus some time reading the manuals beforehand to make sure you know what you're doing.  Configuration doesn't take too long -- you need to add all of your developers in as licensed users.  Setting up projects is not too hard.  I usually set up AD groups to map on the project roles and add those groups to the appropriate roles.  I set up a new project in about 1/2 hour.
Note: I don't use any of the features of TFS except source control.  If you plan to item tracking, use the project sharepoint site, etc., your mileage will vary quite a bit.  I've found that on our projects (2-3 developers) a wiki works just as well for project management.


q:
I want to display some WPF elements near to the selected item of a ListView. How can I obtain the coordinates (screen or relative) of the selected ListViewItem?

<ListView
    x:Name="TechSchoolListView"
    ClipToBounds="False"
    Width="Auto" Height="Auto"
    HorizontalContentAlignment="Stretch"
    VerticalContentAlignment="Top"
    ItemTemplate="{DynamicResource TechSchoolDataTemplate}"
    ItemsSource="{Binding Path=TechSchoolResearchList, Mode=Default}"
    SelectedIndex="1"
    SelectedValue="{Binding Path=SelectedTechSchool, Mode=Default}"
    SelectionChanged="TechSchoolList_SelectionChanged"
    ItemContainerStyle="{DynamicResource TechSchoolItemContainerStyle}"
    ScrollViewer.CanContentScroll="False"
    ScrollViewer.VerticalScrollBarVisibility="Disabled" >
    <ListView.Background>
        <SolidColorBrush Color="{DynamicResource PanelBackgroundColor}"/>
    </ListView.Background>
</ListView>

[A]
You should use
ContainerFromElement
to get the item's container, which is a visual and from there you can get the coordinates. You can't express this in XAML, however. You need to do it in code, on one of the ListView events, raised when the selected item is changed. Btw, keep in mind that the item can be its own container.
You can't do this in XAML, as there's no attached property on the item that shows the item is selected. (though I haven't played with WPF in a while, so that might have changed)


q:
I'm writing a mobile content adaptation plugin for a bespoke CMS in PHP. The CMS contains <img/> links to images with absolute URLs which are all 400 pixels wide and vary in height.

I'd like to parse the HTML (which is stored in MySQL) and re-scale each image to a new width - this will vary according to the device. I'd also like to cache the images to prevent needlessly resizing them on-the-fly every time the page is loaded

What's the best way for me to achieve this in PHP using either ImageMagick or GD?

[A]
what about doing something a bit different. basically off load the caching/resizing to an on demand model. so say your application is being run on device A, which requires 200x200 images. you'd change the image links to:
```
```
<img src="/images/image.php?height=200&width=200&source=filename.jpg" />
```
```
image.php could be a script which does the following:
make sure the existing file exists, and grab it from cache if it exists at this size
if not, resize the image and cache it
the next time your app looks for that image, it would be sent back at the 200px size. alternatively, if the app is now looking for a 300x300 image, that would be built/cached on the new request.


q:
I'm currently maintaining a CVS repository for source control.  There is a push afoot to move to StarTeam.  It has already been purchased and is a corporate standard for most projects.  I was told by the corporate owners of the StarTeam servers that there is no known way to do a complete migration of our current CVS repository to StarTeam.  We have been advised to do a checkout of the latest version and import that into StarTeam.

I would really prefer to keep all of my version history and not have to choose between simply losing all of the data or maintaining my CVS repository indefinitely.

Has anybody had any luck doing this?  Any recommended tools or processes?  Or am I just wasting my time and I should just migrate and cut my losses?

UPDATE: The official response from Borland is that this is definitely doable, but not with the boxed software.  I can purchase services from Borland to help me accomplish this.

[A]
I wonder why a "professional" tool does not provide any means to import from well known legacy systems...
Although it may sound queer at first, i would recommend converting the cvs repos to subversion ( using e.g.
cvs2svn
, offered by tigris.org ), and then creating your own script to update from the subversion repos and commit into the starteam repository, provided it does offer an api or an command line client.
The advantage is that subversion supports nicely things like omitting branches or directories, and offer access via an api, which cvs does not.
Also, the documentation on subversion is quite extensive. (
example
on using the subversion api from python
Good luck!


q:
I've developed an application (C#) that currently sits on a a number of workstations.  Each workstation accesses the same database (MS-SQL).  I've been asked to port this to Citrix.  Can anyone offer insight into documentation or suggestion of where someone would start with this?  Is the application installed on the Citrix server and then simply made available to users or do I need to do further development to make it ready for this type of deployment?

Can anyone offer insight into Citrix application development?

[A]
For fairly straight forward app things just run.
Does you app need use localization configuration?  i.e. time / date or currency formatting?  There are Citrix settings that can do many things in this area.  The users computer settings can be "projected" into Citrix or they could be overridden in Citrix.
Also do you use the machine name for anything?  That will be the server name and not the users local machine name.
You can get a bit of a simulation in a Windows Server environment by getting a couple of remote desktop sessions running your app.


q:
Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char * and return a pointer to a new char *. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:

char * reverse(const char * str)
{
  int length = strlen(str);
  char * reversed_string = new char[length+1];

  for(int i = 0; i < length; ++i)
  {
    reversed_string[i] = str[(length-1) - i];
  }
  //need to null terminate the string
  reversed_string[length] = '\0';

  return reversed_string;

}

int main(int argc, char * argv[])
{

  char * rev_str = reverse("Testing");

  cout << "Your string reversed is this: " << rev_str << endl;

  delete rev_str;
  rev_str = 0;

  return 0;
}

[A]
I had this question once. That's the first answer that comes to mind, but the follow-up is, "now do it without allocating any memory."
```
```
int length = strlen(string);
for(int i = 0; i < length/2; i++) {
  char c = string[i];
  string[i] = string[length - i];
  string[length - i] = c;
}
```
```
EDIT: Some folks have expressed disdain for not using pointers. This is a tiny bit more readable, though not completely optimal. Others have entered the pointer solution, so I won't repeat it here.
One commenter challenged that it should be doable without a (stack based) holding cell for the swap. The mechanism for doing that is bitwise XOR. Replace the inside of the loop with
```
```
string[i] = string[i] ^ string[length - i];
string[length - i] = string[i] ^ string[length - i];
string[i] = string[i] ^ string[length - i];
```
```
But in general, modern compilers can optimize out the local variable of a naive swap. For details,
See Wikipedia


q:
What query can return the names of all the stored procedures in a SQL Server database

If the query could exclude system stored procedures, that would be even more helpful.

[A]
```
```
select *
  from dbo.sysobjects
 where xtype = 'P'
   and status > 0
```
```


q:
I have two methods that I need to call in my WCF application from the client.

Authenticate(username, password)
GetUser(username)

Is it possible to combine these calls to avoid so many calls being sent back/forth?

[A]
There are a few ways to handle this type of thing. First, you can use WCF sessions to initiate a group of commands that need to maintain some context between calls:
http://msdn.microsoft.com/en-us/library/ms733136.aspx
Secondly, you can take advantage of WCF's support for WS-Security standards to avoid the need to pass credentials as a second call:
http://msdn.microsoft.com/en-us/library/aa702565.aspx


q:
I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.

Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.

[A]
Let's suppose you can use a character set of, say, 40 symbols of unambiguous upper,lower and numeric characters.
For a sequence of n chars, you've got 40
n
combinations
40
4
= 2,560,000
40
5
= 102,400,000
40
6
= 4,096,000,000
40
7
= 163,840,000,000
40
8
= 6,553,600,000,000
Thus 8 chars gives a pretty good space to work in - if you generated 10 million codes, you'd have to try hundreds of thousands of combinations to brute force a code.
Or you come at from the other direction - give the number of
possible
codes, how many codes
should
you generate to avoid the trap they call the
Birthday Paradox
?
Taking the 8 char code, 6,553,600,000,000 is approx 2
42
, thus you might reasonably generate 2
21
codes from it, or 2,097,152


q:
What I'm looking for is a basic equivalent of JavaScript's Array::join() whereby you pass in a separator character and uses that in its return string of all the subscripts.  I could certainly write my own function using a StringBuilder or whatnot, but there must be something built into the .NET BCL.

EDIT: Array of anything, not necessarily string or char.  I'd prefer the method to simply call ToString() on each subscript object.  String.Join() is great except that you pass it an array of strings.

[A]
If the array contains strings, you can just use
```
String.Join()
```
.  If the array does not contain strings, you'll need something a little more complicated so you can handle the cast or conversion process for each item it contains.
Update:
Using @JaredPar's code as the basis for a more generic example:
```
```
char sep = GetSeparatorChar();
object[] toJoin = GetToJoin();
string joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());
```
```
Obviously you could do anything you wanted to x and y in that example to get the string to look how you wanted.


q:
I remember working on a project with a group of developers and they always wanted static
 html text to be inside of an out tag (<c:out value="words" />). I don't remember why
 this was the case.

Is this really a best practice when building jsp pages?  What are the
advantages/disadvantages of such an approach?

[A]
If you're just printing out plain text it's better to do it in HTML.  The advantage of the
```
c:out
```
tag is that you can evaluate expressions inside the tag.
```
```
<c:out value="Hello ${user.firstName} ${user.lastName}"/>
```
```


q:
I have a site I'm working on that has an event page.  The owner wants to be able to edit the event page weekly.  Would it be easier to teach the site owner how to edit this one page and upload it or use a CMS just for this one page??

Apart from a contact form that posts to an email addy, the rest of the site is static.  Therefore I'd need to add in a db to store the username and password for CMS login.

If CMS then which one would be most suitable for this case?

[A]
It depends on the complexity of the page. If it's a fixed structure where the client won't want to add links of photos you may want to give them the ability to edit a simple data file (not the page itself). Then read in the data file. I like to use a simple JSON format for this type of thing.
At least with a data file you can revert to an older version or handle the error gracefully, rather than having the client break the whole page.
If you want to go the CMS route,
Drupal
has a very well-established comunity with plenty of add-ons.
If you're more into roll-your-own programming, you can also look at the
Google Calendar API
,


q: I need to store a url in a MySQL table. What's the best practice for defining a field that will hold a URL with an undetermined length?

[A]
```
VARCHAR(512)
```
(or similar) should be sufficient.  However, since you don't really know the maximum length of the URLs in question, I might just go direct to
```
TEXT
```
.  The danger with this is of course loss of efficiency due to
```
CLOB
```
s being far slower than a simple string datatype like
```
VARCHAR
```
.


q:
I was asked for a comprehensive breakdown on space used within a specific database.
I know I can use sys.dm_db_partition_stats in SQL Server 2005 to figure out how much space each table in a database is using, but is there any way to determine the individual and total size of the stored procedures in a database? (Short of opening each one and counting the characters, of course.)

Total space used by stored procs is not likely to be significant (compared to actual data), but with hundreds of them, it could add up.

[A]
A slightly better way than counting the characters, is to use information schema.routines.  You could sum the length of each Routine Definition as (Note each routine definition will max out at 4,000 characters, see below for a method that doesn't have this restriction):
```
select Sum(Len(Routine_Definition)) from information_schema.routines
where routine_type = 'PROCEDURE'
```
Or you could return the length of each sp
```
select Len(Routine_Definition), * from information_schema.routines
where routine_type = 'PROCEDURE'
```
It's unlikely that the length of your stored procedures is the problem.  Usually running out of space with a database is due to things like not backing up the log file (and then shrinking it using dbcc shrinkfile or dbcc shrinkdatabase).
In Sql 2000, here is a routine that would provide the length without the 4000 character limit of above:
```
DECLARE @Name VarChar(250)
DECLARE RoutineCursor CURSOR FOR
   select Routine_Name from information_schema.routines where routine_type = 'PROCEDURE'

DECLARE @Results TABLE
   (   SpName   VarChar(250),
       SpLength   Int
   )

CREATE TABLE ##SpText
   (   SpText   VarChar(8000)   )

OPEN RoutineCursor
FETCH NEXT FROM RoutineCursor INTO @Name

WHILE @@FETCH_STATUS = 0
   BEGIN
      INSERT INTO ##SpText   (SpText)   EXEC sp_helptext @Name

      INSERT INTO @Results (SpName, SpLength) (SELECT @Name, Sum(Len(SpText)) FROM ##SpText)
      TRUNCATE TABLE ##SpText

      FETCH NEXT FROM RoutineCursor INTO @Name
   END

CLOSE RoutineCursor
DEALLOCATE RoutineCursor
DROP TABLE ##SpText

SELECT SpName, SpLength FROM @Results ORDER BY SpLength DESC
SELECT Sum(SpLength) FROM @Results
```


q: I'm looking to add a tooltip to each row in a bound datagrid in vb.net winforms.  How can this be done?

[A]
I haven't tried this myself but I would give it a shot:
```
```
System.Windows.Forms.ToolTip formToolTip = new System.Windows.Forms.ToolTip();
formToolTip .SetToolTip(item, "Row Tooltip");
```
```
Where
```
item
```
corresponds to the cell you're setting the tool tip for.


q:
What is the best way to localize a collection (IEnumerable)?
From the BL I retrieve a collection of entities which still need to localized, I figured I write a method which extends the IEnumerable and returns the localized list.

How can i get the code underneath working? Any ideas? Maybe better options?

public static IEnumerable Localize(this IEnumerable items, CultureInfo cultureInfo)
{
    foreach(string item in items)
    {
        /*Error underneath, cannot assign to item*/
        item = ResourceHelper.GetString(item, cultureInfo);
    }
    return (items);
}

[A]
have you tried something where you
yield
the item?
```
```
public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo culture)
{
    foreach (string item in items)
    {
        yield return ResourceHelper.GetString(item,culture);
    }
}
```
```
this won't change any other the items in the collection you are enumerating over, but it will return what you want it to.


q:
I'm wondering what the best way is to have a "if all else fails catch it".

I mean, you're handling as much exceptions as possible in your application,
but still there are bound to be bugs, so I need to have something that
catches all unhandled exceptions so I can collect information and store
them in a database or submit them to a web service.

Does the AppDomain.CurrentDomain.UnhandledException event capture everything?
Even if the application is multithreaded?

Side note: Windows Vista exposes native API functions that allow any application
to recover itself after a crash... can't think of the name now... but I'd rather not
use it, as many of our users are still using Windows XP.

[A]
In ASP.NET, you use the
```
Application_Error
```
function in the
```
Global.asax
```
file.
In WinForms, you use the
```
MyApplication_UnhandledException
```
in the
```
ApplicationEvents
```
file
Both of these functions are called if an unhandled exception occurs in your code. You can log the exception and present a nice message to the user from these functions.


q:
How would you convert a parapraph to hex notation, and then back again into its original string form?

(C#)

A side note:  would putting the string into hex format shrink it the most w/o getting into hardcore shrinking algo's?

[A]
```
```
public string ConvertToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}
```
```


q: My application uses an event tap to capture keyboard events, and I'd like to know which device (i.e. which keyboard) each event comes from. Is there an sort of device-identifying information along with the CGEvent that a tap gets? I've looked at NSEvent's methods, and the various CGEventField keys, but none of them seem to be device-unique. Any help?

[A]
You might want to take a look at DDHidLib, Dave Dribin's excellent framework to work with USB HID devices independently.
http://www.dribin.org/dave/blog/archives/2007/03/19/ddhidlib_10
(not just about joysticks, so read more than the first paragraph of that blog post)
Some of the functionality of DDHidLib no longer works under Leopard, due to some security concerns at Apple regarding capturing an HID device, but if you're lucky it might provide you with what you need.


q:
The code is,

set VAR=before

if "%VAR%" == "before" (

  set VAR=after;

  echo %VAR%

)

What will the preceding Windows .bat file code segment display?  Why? (i.e. why doesn't it behave as you might first think)?

[A]
Obviously, you'd think the output would be "after", given that we reset the env variable inside the loop.
But the output will actually be "before".  The reason is that variable substitution is done in .bat files by the interpreter when a command is read, rather than when it's executed.  So, for the compound statement, the variables in the body are evaluated when the if statement is first encountered.
You can make this work by using delayed environment variable expansion (need to enable it).  If it's enabled, you can then do:
```
```
set VAR=before

if "%VAR%" == "before" (

  set VAR=after;

  echo !VAR!

)
```
```
You can enable delayed environment variable expansion using the /v option when starting cmd.exe.
[Backstory--many of us still use legacy .bat files to drive things like make procedures, etc.  Obviously there are better scripting tools, but not always an option to use them.  I ran into this issue a while back and recently found two other people who had pulled their hair out over the same thing.  So it's useful to understand how the interpreter does variable substitution].


q:
Could someone please explain the best way to connect to an Interbase 7.1 database using .NET/C#?

The application will be installed on many end user computers so the less "add-ons" that I will have to package with my application the better.

[A]
Check this providers:
Interbase and Firebird Developer's for Visual Studio .Net
Firebird .NET Data Provider
FireBird - InterBase .NET (Mono) Providers


q:
A cross join performs a cartesian product on the tuples of the two sets.

SELECT *
FROM Table1
CROSS JOIN Table2

Which circumstances render such an SQL operation particularly useful?

[A]
You're typically not going to want a full Cartesian product for most database queries.  The whole power of relational databases is that you can apply whatever restrictions you might be interested in to allow you to avoid pulling unnecessary rows from the db.
I suppose one contrived example where you might want that is if you have a table of employees and a table of jobs that need doing and want to see all possible assignments of one employee to one job.


q:
I am completely new to LINQ in C#/.NET.  I understand that I could use it to convert a DataSet into an Array/List, am I able to go in the opposite direction?

I'm using NPlot to generate a graph of captured prices, which are stored in a List, where PriceInformation is a class containing two public doubles and a DateTime.

Any suggestions very welcome.

[A]
There's a method called
CopyToDataTable
.  That method will only help if you already have a IEnumerable(DataRow)
Here's how I'd do this:
```
```
//extension method to convert my type to an object array.
public static object[] ToObjectArray(this MyClass theSource)
{
  object[] result = new object[3];
  result[0] = theSource.FirstDouble;
  result[1] = theSource.SecondDouble;
  result[2] = theSource.TheDateTime;

  return result;
}

//some time later, new up a dataTable, set it's columns, and then...

DataTable myTable = new DataTable()

DataColumn column1 = new DataColumn();
column1.DataType = GetType("System.Double");
column1.ColumnName = "FirstDouble";
myTable.Add(column1);

DataColumn column2 = new DataColumn();
column2.DataType = GetType("System.Double");
column2.ColumnName = "SecondDouble";
myTable.Add(column2);

DataColumn column3 = new DataColumn();
column3.DataType = GetType("System.DateTime");
column3.ColumnName = "TheDateTime";
myTable.Add(column3);

// ... Each Element becomes an array, and then a row
MyClassList.ForEach(x => myTable.Rows.Add(x.ToObjectArray());
```
```


q:
I am trying to fill a form in a php application from a C# client (Outlook addin). I used Fiddler to see the original request from within the php application and the form is transmitted as a multipart/form. Unfortunately .Net does not come with native support for this type of forms (WebClient has only a method for uploading a file).
Does anybody know a library or has some code to achieve this? I want to post different values and additionally (but only sometimes) a file.

Thanks for your help,
Sebastian

[A]
This is cut and pasted from some sample code I wrote, hopefully it should give the basics. It only supports File data and form-data at the moment.
```
```
public class PostData
{

    private List<PostDataParam> m_Params;

    public List<PostDataParam> Params
    {
        get { return m_Params; }
        set { m_Params = value; }
    }

    public PostData()
    {
        m_Params = new List<PostDataParam>();

        // Add sample param
        m_Params.Add(new PostDataParam("email", "MyEmail", PostDataParamType.Field));
    }

    /// <summary>
    /// Returns the parameters array formatted for multi-part/form data
    /// </summary>
    /// <returns></returns>
    public string GetPostData()
    {
        // Get boundary, default is --AaB03x
        string boundary = ConfigurationManager.AppSettings["ContentBoundary"].ToString();

        StringBuilder sb = new StringBuilder();
        foreach (PostDataParam p in m_Params)
        {
            sb.AppendLine(boundary);

            if (p.Type == PostDataParamType.File)
            {
                sb.AppendLine(string.Format("Content-Disposition: file; name=\"{0}\"; filename=\"{1}\"", p.Name, p.FileName));
                sb.AppendLine("Content-Type: text/plain");
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
            else
            {
                sb.AppendLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", p.Name));
                sb.AppendLine();
                sb.AppendLine(p.Value);
            }
        }

        sb.AppendLine(boundary);

        return sb.ToString();
    }
}

public enum PostDataParamType
{
    Field,
    File
}

public class PostDataParam
{

    public PostDataParam(string name, string value, PostDataParamType type)
    {
        Name = name;
        Value = value;
        Type = type;
    }

    public string Name;
    public string FileName;
    public string Value;
    public PostDataParamType Type;
}
```
```
To send the data you then need to:
```
```
HttpWebRequest oRequest = null;
oRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);
oRequest.ContentType = "multipart/form-data";
oRequest.Method = "POST";
PostData pData = new PostData();

byte[] buffer = encoding.GetBytes(pData.GetPostData());

// Set content length of our data
oRequest.ContentLength = buffer.Length;

// Dump our buffered postdata to the stream, booyah
oStream = oRequest.GetRequestStream();
oStream.Write(buffer, 0, buffer.Length);
oStream.Close();

// get the response
oResponse = (HttpWebResponse)oRequest.GetResponse();
```
```
Hope thats clear, i've cut and pasted from a few sources to get that tidier.


q:
I'm collecting metadata using the sys.* views, and according to the documentation, the sys.identity_columns view will return the seed and increment values like so.

CREATE TABLE ident_test (
  test_id int IDENTITY(1000,10),
  other int
)

SELECT name, seed_value, increment_value
  FROM sys.identity_columns
 WHERE object_id = OBJECT_ID( 'ident_test' )

However, the above query just returns one column.  Is it just me?

(Note: I've had to change this question somewhat from its earlier version.)

[A]
Are you sure you are running this in a database with tables with
```
IDENTITY
```
columns?
```
```
SELECT c.name, i.seed_value, i.increment_value
FROM sys.columns c
INNER JOIN sys.identity_columns i
    ON i.object_id = c.object_id
    AND i.column_id = c.column_id
```
```
Returns rows for me in a regular production database with a few identities.
Using a
```
LEFT JOIN
```
returns these rows as well as many which are not
```
IDENTITY
```
I ran this on another database, and I noticed some
```
NULL
```
s are returned (even in the
```
INNER JOIN
```
case).  This is because some of the columns are in
```
VIEW
```
s.
Try adding:
```
```
INNER JOIN sys.tables t
ON t.object_id = c.object_id
```
```
To filter only to actual
```
IDENTITY
```
columns in tables.


q:
If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:

private object m_myProp;
public object MyProp
{
    get { return m_myProp; }
}
protected void SetMyProp(object value)
{
    m_myProp = value;
}

Is there a better way?

[A]
```
```
private object m_myProp;
public object MyProp
{
    get { return m_myProp; }
    protected set { m_myProp = value; }
}
```
```
Or in C# 3.0
```
```
public object MyProp {get; protected set;}
```
```


q:
I have a POCO object that goes 4 levels deep contained objects (like Invoice has line items that have taxes that have gl entries), and I want to turn the entire thing into a DataSet. So there would be 4 tables, each with constraints being applied to the parent table.

Does anyone know of something that would automated this?

[A]
How do you populate this object? If it's from the database, there are two methods to structure your query such that the dataset is populated with separate, automatically related DataTable-s. Old and probably not supported anymore is the
SHAPE command
.
A better and more recent approach is to use
FOR XML
.
The later approach will also allow you to load a dataset from XML-serialized representation of your `POCO' (not FOR XML, but loading XML into DataSet)


q:
I've often used pointers to const objects, like so...

const int *p;

That simply means that you can't change the integer that p is pointing at through p. But I've also seen reference to const pointers, declared like this...

int* const p;

As I understand it, that means that the pointer variable itself is constant -- you can change the integer it points at all day long, but you can't make it point at something else.

What possible use would that have?

[A]
Same as a "const int" ... if the compiler knows it's not going to change, it can be optimization assumptions based on that.
```
```
struct MyClass
{
    char* const ptr;
    MyClass(char* str) :ptr(str) {}

    void SomeFunc(MyOtherClass moc)
    {
         for(int i=0; i < 100; ++i)
         {
                 printf("%c", ptr[i]);
                 moc.SomeOtherFunc(this);
         }
    }
}
```
```
Now, the compiler could do quite a bit to optimize that loop --- provided it knows that SomeOtherFunc() does not change the value of ptr.  With the const, the compiler knows that, and can make the assumptions.  Without it, the compiler has to assume that SomeOtherFunc will change ptr.


q: How secure are php Sessions?  I am planning to use the native PHP sessions to authenticate users.  Can users modify session data like they can $_POST and $_GET data?

[A]
PHP sessions are as secure as the session cookie given to the user.  All the data in the session is stored server-side, so users can't arbitrarily modify them except through whatever functionality your site provides.  However, PHP session cookies are a common target for cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.  Just the same, sessions are a good way to do user authentication as long as you're aware of the potential risks.
Some Wikipedia links:
CSRF
XSS


q:
e.g,

foo1
foo2
foo10
foo100

rather than

foo1
foo10
foo100
foo2

Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me.

[A]
You can use functions in your order-by clause.  In this case,
you can split the non-numeric and numeric portions of the
field and use them as two of the ordering criteria.
```
```
select * from t
 order by to_number(regexp_substr(a,'^[0-9]+')),
          to_number(regexp_substr(a,'[0-9]+$')),
          a;
```
```
You can also create a function-based index to support this:
```
```
create index t_ix1
    on t (to_number(regexp_substr(a, '^[0-9]+')),
          to_number(regexp_substr(a, '[0-9]+$')),
          a);
```
```


q:
Came across this:

http://www.eggheadcafe.com/articles/adonet_source_code_generator.asp

And wondering if this is the right solution as I am not that big of a fan of creating a class for every stored procedure or do I use Enterprise Library for ASP.net 2.0 project.

[A]
Is there any possibility of upgrading to framework 3.5? if so take a look at LINQ to SQL and Entity Framework as this will accomplish alot of this for you.
If not then as long as it generates standard code that doesnt tie you into 3rd party libraries then you could certainly use it. At my workplace we have our own generator similar to this and it works well although we will shortly be moving to LINQ to SQL.


q:
We have a dedicated godaddy server and it seemed to grind to a halt when we had users downloading only 3MB every 2 seconds (this was over about 20 http requests).

I want to look into database locking etc. to see if that is a problem - but first I'm curious as to what a dedicated server ought to be able to serve.

[A] A lot depends on what the 3MB is.  Serving up 1.5MBps of static data is way, way, way, within the bounds of even the weakest server.


q:
I do TDD on a daily basis for my C++ development on Solaris10. It has greatly reduced the time I have to spend using my debugger but sometime this is the only option.

DBX is pretty powerful but not that user friendly. Note that I'm talking about console DBX not the SunStudio GUI for DBX).

What are the best productivity tips you can give for dbx C++ debugging?

PS. Changing debugger is not an option.

[A]
I have bookmarked a few sites related to dbx. Here they are, in no particular order in case they might be useful to you:
Why Can't dbx Find My Function?
Online Help for the Dbx Debugger
Sun Studio: debugging a multi-threaded application w/ dbx
gdb vs. dbx: commands mapping and feature comparison
Importing debug information into dbx
command line dbx : See more source
Sun Studio C++ - Your .dbxrc
(NB: adapt the integer type used to cast pointers according to your pointer size)
Sun Studio: Investigating memory leaks with dbx
Sun Studio: Gathering memory allocations/leaks data, from a running process
EDIT on 2012 july 19th: I've tried to fix several link since Chris Quenelle's blog has moved. Some articles can still be accessed thanks to the wayback machine.


q: Which sorting algorithm works best on mostly sorted data?

[A]
Based on the highly scientific method of watching
animated gifs
I would say Insertion and Bubble sorts are good candidates.


q: I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!

[A]
You can read a file into an array of lines and do all the splitting with:
```
```
$lines = file("filename");
foreach($lines as $line) {
    $parts = explode("|", $line);
    // do the database inserts here
}
```
```
If you already have all the text in a variable as you said (e.g., with something like file_get_contents() ), you can explode on \n first and then do the same foreach statement as above.


q: Has anyone got much experience deploying applications to Amazons EC2? I am considering doing this in future and wonder about peoples experiences compared to shared hosting and dedicated server hosting are.

[A]
So far, so good. Being able to turn on 5/10/50/100+ machines at a time is awesome. It's even better being able to turn them off and forget about them. You need to change your mindset about how you store your persistent data, but once you have the sky is the limit.
Performance wise, small instances are slow. They're fine for load balancers and serving static content, etc, but if you are doing anything processor intensive, you need at least a m1.medium instance.
It's all pretty new, so there aren't many tools to help out yet. I'm using
Puppet
to configure my hosts and I have a set of PHP scripts for starting up clusters. I use LDAP as a host inventory database.
If you don't have the need/urge to build your own, see
Rightscale
for some really awesome tools for deploying/growing apps.


q:
Inspired by this question

The choice of which algorithm to use to sort a collection can be made better if we know ahead of time how well sorted a collection is. Is there a way we can measure (or maintain a measurement) of how well sorted the collection is? Can we do this in such a way that the cost of maintaining or measuring how well sorted something doesn't outweigh the benefit of choosing the best sort algorithm?

[A]
You could use sampling: Check N elements spaced evenly in the list and see how many are in order.  (Of course that only works in a random-access list, but usually that's the type you sort.)
Also have a threshold for small N.  If N is small (e.g.
```
10
```
) insertion sort is good even if the list isn't sorted.  Java makes this optimization for small N in what is otherwise a merge-sort.


q:
I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)

[A]
There's
a CodeProject article
for an ID3 reader.  And a
thread at kixtart.org
that has more information for other properties. Basically, you need to call the
```
GetDetailsOf()
```
method
on the
folder
shell object for
```
shell32.dll
```
.


q:
I'm looking for a Java library that is geared towards network math and already tested.  Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet.

Should I roll my own, or is there already a robust library for this?

[A]
org.apache.lenya.ac.IPRange
appears to have these features.
The Apache Lenya project is an open-source content management system.  It uses the Apache License, so you may be able to reuse just the code you need. (But as always, read the
license
yourself; don't trust legal advice from some guy on the internet! :-)


q: I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don't want to have to ask the user where to backup their data to, I just want to search for and use the first USB hard drive connected to the computer. Obtaining the unique ID of the hard drive would probably be a good idea too, just as a double check for next time the backup runs.

[A]
A few pieces of information can be gathered without too much trouble:
Use GetDriveType to find the first removeable drive, test if writeable media exists (which will largely rule out CD drives).  May also want to look at further strings that are available when you query the drive information via win32.
Use libusb to see where the first storage class USB device is (will likely be a flash or hard drive)
This
C# article
points towards win32 disk drive classes you might be able to tap into.
Post your answer here when you find it!
-Adam


q:
Let's say I have the following code:

@sites = Site.find(session[:sites]) # will be an array of Site ids
@languages = Language.for_sites(@sites)

for_sites is a named_scope in the Language model that returns the languages associated with those sites, and languages are associated with sites using has_many through. The goal is for @languages to have a distinct array of the languages associated with the sites.

Instead of calling the Language object on the second line, I'd ideally like to say

@sites.languages

and have the same list returned to me. Is there any way to do that cleanly in Rails 2.1 (or edge)? I know associations and named scopes can extend the array object to have attributes, but unless I'm missing something that doesn't apply here. Any plugins that do this would be welcome, it doesn't have to be in core.

[A]
Your instance variable @sites is an Array object and not Site so I don't think named_scope can be used. You can open up Array class to achieve this effect though (yikes)
```
```
class Array

  def languages
    ...
  end

end
```
```


q:
I need to output the contents of a text field using MS Query Analyzer. I have tried this:

select top 1 text from myTable

(where text is a text field)

and

DECLARE @data VarChar(8000)
select top 1 @data = text from myTable
PRINT @data

The first one prints only the first 2000 or so characters and the second only prints the first 8000 characters. Is there any way to get all of the text?

Notes:

must work with SQL Server 7

[A]
I don't think you can use varchar(MAX) in MSSQL7, so here's something that will give you all the data (note, what I'm understanding is you just want to visually see the data, and you aren't going put it in a variable or return it).
So, this will print off the entire string so you can visually see what's in the field:
```
```
DECLARE @limit as int,
        @charLen as int,
        @current as int,
        @chars as varchar(8000)

SET @limit = 8000

SELECT  TOP 1 @charLen = LEN(text)
FROM    myTable

SET @current = 1

WHILE @current < @charLen
BEGIN
    SELECT  TOP 1 @chars = SUBSTRING(text,@current,@limit)
    FROM    myTable
    PRINT @chars

    SET @current = @current + @limit
END
```
```


q:
I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript.  How may I access them?

Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.

Related:

  Accessing the web page's HTTP Headers in JavaScript

[A]
If you want to access referrer and user-agent, those are available to client-side Javascript, but not by accessing the headers directly.
To retrieve the referrer, use
```
document.referrer
```
.
To access the user-agent, use
```
navigator.userAgent
```
.
As others have indicated, the HTTP headers are not available, but you specifically asked about the referer and user-agent, which are available via Javascript.


q: I'd like to log the call trace during certain points, like failed assertions, or uncaught exceptions.

[A]
This
pretty much tells you what to do.
Essentially you need to set up the applications exception handling to log, something like:
```
```
#import <ExceptionHandling/NSExceptionHandler.h>

[[NSExceptionHandler defaultExceptionHandler]
                  setExceptionHandlingMask: NSLogUncaughtExceptionMask |
                                            NSLogUncaughtSystemExceptionMask |
                                            NSLogUncaughtRuntimeErrorMask]
```
```


q:
I'm trying to learn GNUMake for a small project I'm working on. So far, even the "basic" tutorials seem pretty rough and I've yet to make sense of the makefile syntax.

Does anyone have some good resources for an absolute beginner to get familiar with GNUMake?

[A]
The definitive guide is
http://www.gnu.org/software/make/manual/make.html
There is an o'reilly book "Managing Projects with GNU Make" which has more explanation.
You can also uses the earlier editions, they don't cover GnuMake specifically but are a lot thinner.
Make is a dirty secret among developers - none of us understand it, we just borrow a make script from somebody else and change it. I imagine only one script was ever written from scratch (probably by the creator of the tool).
When you need to do more than the simple example most people either switch to a more modern build system like Ant or roll their own in Perl/Python/etc.


q: If I download a .gem file to a folder in my computer, can I install it later using gem install?

[A]
Yup, when you do
```
gem install
```
, it will search the current directory first, so if your .gem file is there, it will pick it up. I found it on the
gem reference
, which you may find handy as well:
gem install will install the named
  gem. It will attempt a local
  installation (i.e. a .gem file in the
  current directory), and if that fails,
  it will attempt to download and
  install the most recent version of the
  gem you want.


q:
Or if any body knows of an alternative control that does?

It would be handy to serve up content to the WebBrowser control that has embedded images & other resources from a database without having a dependency on these resources being hosted on a webserver or to create temporary files on the local file system.

Mhtml supports this but doesn't seem to work in a WebBrowser control when using the DocumentText property?

[A]
Seems to be working for me.
example:
```
```
this.webBrowser1.Url = new System.Uri(@"C:\TempFiles\MyTest.mht");
```
```
what in particular is not working correctly?


q:
I'm looking for Ruby's Active record for PHP. Something that is so simple that I just define my fields, extend the base ORM class, and I get ACID operations for free. I should get default getters and setters without writing any code, but overriding a default getter or setter is as easy as declaring get$fieldName or set$fieldName functions with the behavior I want.  Symphony makes you create about 5 files per object, and all defined objects always load as far as I can tell. What is a better alternative? Why is it better? Can you put simple examples in your answers please?

Doctrine is another ORM I've looked at besides symphony . There also you need to create yaml files that describe your data structures. The database already defines this stuff. What will just read my table defs without having to generate and store config files everywhere?

[A]
Zend_Db_Table
and
Zend_Db_Table_Row
are fairly good at what you're describing.  You don't need any configuration file, most metadata is "discovered" from the database itself.
Technically these classes don't implement the ActiveRecord pattern.  Instead, they implement the
Table Data Gateway
and
Row Data Gateway
patterns.  Together, these offer similar value as ActiveRecord, and in some ways are more flexible than ActiveRecord.
But as with any ORM, there are inevitably some SQL queries and operations that you can't do through the OO interface.  No ORM can serve as one-stop shopping.
Footnote:  I worked on the Zend Framework project for a little over a year, especially on the Zend_Db component.  But I don't work for them anymore.


q:
How do I access a page's HTTP response headers via JavaScript?

Related to this question, which was modified to ask about accessing two specific HTTP headers.

Related:

  How do I access the HTTP request header fields via JavaScript?

[A]
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request. That was the original question posted here. It has been
repeatedly asked
, too, because some people would like to get the actual response headers of the original page request without issuing another one.
For AJAX Requests:
If an HTTP request is made over AJAX, it is possible to get the response headers with the
```
getAllResponseHeaders()
```
method. It's part of the XMLHttpRequest API. To see how this can be applied, check out the
```
fetchSimilarHeaders()
```
function below. Note that this is a work-around to the problem that won't be reliable for some applications.
```
```
myXMLHttpRequest.getAllResponseHeaders();
```
```
The API was specified in the following candidate recommendation for XMLHttpRequest:
XMLHttpRequest - W3C Candidate Recommendation 3 August 2010
Specifically, the
```
getAllResponseHeaders()
```
method was specified in the following section:
w3.org:
```
XMLHttpRequest
```
: the
```
getallresponseheaders()
```
method
The MDN documentation is good, too:
developer.mozilla.org:
```
XMLHttpRequest
```
.
This will not give you information about the original page request's HTTP response headers, but it could be used to make educated guesses about what those headers were. More on that is described next.
Getting header values from the Initial Page Request:
This question was first asked several years ago, asking specifically about how to get at the original HTTP response headers for the
current page
(i.e. the same page inside of which the javascript was running). This is quite a different question than simply getting the response headers for any HTTP request. For the initial page request, the headers aren't readily available to javascript. Whether the header values you need will be reliably and sufficiently consistent if you request the same page again via AJAX will depend on your particular application.
The following are a few suggestions for getting around that problem.
1. Requests on Resources which are largely static
If the response is largely static and the headers are not expected to change much between requests, you could make an AJAX request for the same page you're currently on and assume that they're they are the same values which were part of the page's HTTP response. This could allow you to access the headers you need using the nice XMLHttpRequest API described above.
```
```
function fetchSimilarHeaders (callback) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === XMLHttpRequest.DONE) {
            //
            // The following headers may often be similar
            // to those of the original page request...
            //
            if (callback && typeof callback === 'function') {
                callback(request.getAllResponseHeaders());
            }
        }
    };

    //
    // Re-request the same page (document.location)
    // We hope to get the same or similar response headers to those which
    // came with the current page, but we have no guarantee.
    // Since we are only after the headers, a HEAD request may be sufficient.
    //
    request.open('HEAD', document.location, true);
    request.send(null);
}
```
```
This approach will be problematic if you truly have to rely on the values being consistent between requests, since you can't fully guarantee that they are the same. It's going to depend on your specific application and whether you know that the value you need is something that won't be changing from one request to the next.
2. Make Inferences
There are
some BOM properties
(Browser Object Model) which the browser determines by looking at the headers. Some of these properties reflect HTTP headers directly (e.g.
```
navigator.userAgent
```
is set to the value of the HTTP
```
User-Agent
```
header field). By sniffing around the available properties you might be able to find what you need, or some clues to indicate what the HTTP response contained.
3. Stash them
If you control the server side, you can access any header you like as you construct the full response. Values could be passed to the client with the page, stashed in some markup or perhaps in an inlined JSON structure. If you wanted to have every HTTP request header available to your javascript, you could iterate through them on the server and send them back as hidden values in the markup. It's probably not ideal to send header values this way, but you could certainly do it for the specific value you need. This solution is arguably inefficient, too, but it would do the job if you needed it.


q:
In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?

using (MyWrapper wrapper = new MyWrapper())
{
    throw new Exception("Bad error.");
}

If an exception is thrown in the using statement I want to know about it when the IDisposable object is disposed.

[A]
Instead of the syntactic sugar of the using statement, why not just implement your own logic for this.  Something like:
```
```
try
{
  MyWrapper wrapper = new MyWrapper();

}
catch (Exception e)
{
  wrapper.CaughtException = true;
}
finally
{
   if (wrapper != null)
   {
      wrapper.Dispose();
   }
}
```
```


q:
I'm trying to figure out a decent solution (especially from the SEO side) for embedding fonts in web pages. So far I have seen the W3C solution, which doesn't even work on Firefox, and this pretty cool solution. The second solution is for titles only. Is there a solution available for full text? I'm tired of the standard fonts for web pages.

Thanks!

[A]
And it's unlikely too -- EOT is a fairly restrictive format that is supported only by IE.  Both Safari 3.1 and Firefox 3.1 (well the current alpha) and possibly Opera 9.6 support true type font (ttf) embedding, and at least Safari supports SVG fonts through the same mechanism.  A list apart had a good discussion about this a while
back
.


q:
How can I comment a JSP expression like: <%= map.size() %>

Is there something like <%= // map.size() %>?

[A]
One of:
In html
```
```
<!-- map.size here because -->
<%= map.size() %>
```
```
theoretically the following should work, but i never used it this way.
```
```
<%= map.size() // map.size here because %>
```
```


q:
I am curious as to why an implicit cast fails in...

int? someValue = SomeCondition ? ResultOfSomeCalc() : null;

and why I have to perform an explicit cast instead

int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;

It seems to me that the compiler has all the information it need to make an implicit casting decision, no?

[A]
The relevant section of the C# 3.0 spec is 7.13, the conditional operator:
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
If X and Y are the same type, then this is the type of the conditional
Otherwise, if an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.
Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.
Otherwise, no expression type can be determined, and a compile-time error occurs.


q:
So after installing NUnit, the assemblies (nunit.framework, etc.) now appear in the References > Add Reference dialog, but they're not in the %WINDIR%\Microsoft.NET\Framework\v2.0.50727 dir and there is no NUnit registry entry for the Assembly Path (i.e. HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramewokr\AssemblyFolder).

There's also no automatic entries created in the project properties Reference Paths for the NUnit install directory.  How the heck are they appearing in the "Add Dialog"?!?!  I thought the mentioned way were the only ways assemblies could appear in "Add Reference".

[A]
Strange, [HKEY_CURRENT_USER\SOFTWARE\Microsoft.NETFramework\AssemblyFolders] should be the only thing driving this.
Perhaps this snippet from
this page
is relevant?
If you install the .NET Framework 3.0 Service Pack 1 (SP1), the following registry subkey is added:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\v3.0
```
```
If you install the .NET Framework 3.5, the following registry subkey is added:
```
```
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\v3.5
```
```


q: I would like to have my warnings set to the highest level using Microsoft Visual C++ compiler. Similar to using -pedantic on gcc. What compiler switches do you use to have the most warnings enabled?

[A]
```
/W4 /Wall
```
should do the trick.


q:
I need to apply some xml templates to various streams of xml data (and files, on occasion) and there seem to be a large number of xml libraries for java out there -- enough that it's difficult to quickly determine which libraries are still active, how they differ from the other options that are also active, and what criteria should be considered when choosing one.

What libraries do you use for manipulating xml in java, and why is it better than the alternatives?

[A]
You should decide if you want/are able to load the whole document into memory.  If it is a large document, you may want to look at the sax
parser
.  This works well for large documents.  Otherwise you may want to look into a dom parser.


q: Are the .net classes relating to DbProviderFactory thread safe?

[A]
When you say "These instances are generated once at run time, and used for the rest of the service's life", do you mean the connection object? Also, do you mean you're keeping the connection object open through out the life of your service?  If your service is multi-threaded and you only have one instance of the connection (say for example a singleton or static class), you have to make sure the connection is only used by one thread at a time.
Without seeing much code, it sounds like a problem with how you treat the IDbConnection you get from the factory, instead of the factory itself.
We use the DbProviderFactory very heavily for our multithreaded applications, which connect to Oracle, FoxPro and SqlServer and I haven't seen this issue.
Good luck!
Ricardo.


q:
I have just started migrating my homegrown persistence framework to JPA.

Given that the persistence frameworks hide a lot of the plumbing, I'm interested in knowing if NOT closing EntityManagers will create a resource leak, or if the frameworks will collect and close them for me.

I intend in all places to close them, but do I HAVE to?

At the moment using TopLink, just because it works with NetBeans easily, but am happy to investigate other JPA providers.

[A]
You should.
Frameworks have no idea how you intend to use the EM, so they cannot close it (except, may be, on finalization, which is not guaranteed). Yes, not closing them would create a resource leak.
The idea is the same as "always close java.sql.Connection" (despite some data sources have settings to close them automatically by inactivity) or "always close Hibernate session".
Besides, if you plan to write portable code, you shouldn't rely on specific JPA provider "being smart" -- other may fail to close the EM in time.


q: I need to write robust code in .NET to enable a windows service (server 2003) to restart itself. What is the best way to so this? Is there some .NET API to do it?

[A]
I don't think you can in a self-contained service (when you call Restart, it will stop the service, which will interrupt the Restart command, and it won't ever get started again). If you can add a second .exe (a Console app that uses the ServiceManager class), then you can kick off the standalone .exe and have it restart the service and then exit.
On second thought, you could probably have the service register a Scheduled Task (using the command-line 'at' command, for example) to start the service and then have it stop itself; that would probably work.


q:
This article here suggests to use -XX:+UseParNewGC "To enable a parallel young generation GC with the concurrent GC".

My confusion is that in order to enable both parallel and concurrent GC, should I

use -XX:+UseParNewGC or

use both -XX:+UseParNewGC and -XX:+UseConcMarkSweepGC ?

PS

I am using JVM 6.

[A]
Since the document you linked was for a 1.4.2 VM that's what I'll assume you're using (JVMs 5 and 6 behave differently).
From
http://java.sun.com/docs/hotspot/gc1.4.2/
if -XX:+UseConcMarkSweepGC is used on
  the command line then the flag
  UseParNewGC is also set to true if it
  is not otherwise explicitly set on the
  command line
So the answer is you only need to use -XX:+UseConcMarkSweepGC and it will enable the concurrent collector with the parallel young generation collector.
Edit: for Java 6, the same flag (-XX:+UseConcMarkSweepGC) enables the concurrent collector. The choice of collector you want depends on a few things, and you should test different configurations. But there are some very general guidelines. If you have a single processor, single thread machine then you should use the serial collector (default for some configurations, can be enabled explicitly for with -XX:+UseSerialGC). For multiprocessor machines where your workload is basically CPU bound, use the parallel collector. This is enabled by default if you use the -server flag, or you can enable it explicitly with -XX:+UseParallelGC. If you'd rather keep the GC pauses shorter at the expense of using more total CPU time for GC, and you have more than one CPU, you can use the concurrent collector (-XX:+UseConcMarkSweepGC). Note that the concurrent collector tends to require more RAM allocated to the JVM than the serial or parallel collectors for a given workload because some memory fragmentation can occur.


q:
This is the exception that I'm getting when I'm trying to bind to a System.Type.Name.

Here is what I'm doing:

this.propertyTypeBindingSource.DataSource = typeof(System.Type);

/* snip */

this.nameTextBox1.DataBindings.Add(
    new System.Windows.Forms.Binding(
        "Text",
        this.propertyTypeBindingSource,
        "Name", true));

Is there some trick with binding to System.Type, is it not allowed or is there any workaround? Have no problems with binding to other types.

[A]
Found a workaround. Made a class
```
```
public class StubPropertyType
{
    public StubPropertyType(Type type)
    {
        this.StubPropertyTypeName = type.Name;
    }

    public string StubPropertyTypeName = string.Empty;
}
```
```
created a binding source
```
```
this.propertyStubBindingSource.DataSource = typeof(StubPropertyType);
```
```
created an instance of the class and bound the textbox to it.
```
```
this.nameTextBox.DataBindings.Add(
    new System.Windows.Forms.Binding(
        "Text",
        this.propertyStubBindingSource,
        "StubPropertyTypeName",
        true));
```
```
works exactly as required.


q: In one of the stackoverflow podcasts (#18 I think) Jeff and Joel were talking about multi vs single tenant databases. Joel mentioned that "FogBugz on Demand" used a database per customer architecture and I was wondering if there is a point beyond which you'll need to have multiple database servers to distribute the load?

[A]
Technically the limit of databases per instance in SQL Server is 32,767, but I doubt that you could use a SQL Server instance that has more than 2,000 databases, at that point the server would probably be not responsive.
You may be able to have close to 30,000 databases if they were all auto-closed and not being used. you can find more information about capacity limits here:
Maximum Capacity Specifications for SQL Server


q:
According to the PHP manual, in order to make code more portable, they recommend using something like the following for escaping data:

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

I have other validation checks that I will be performing, but how secure is the above strictly in terms of escaping data? I also saw that magic quotes will be deprecated in PHP 6. How will that affect the above code? I would prefer not to have to rely on a database-specific escaping function like mysql_real_escape_string().

[A]
Magic quotes are inherently broken. They were meant to sanitize input to the PHP script, but without knowing how that input will be used it's impossible to sanitize correctly. If anything, you're better off checking if magic quotes are enabled, then calling stripslashes() on $_GET/$_POST/$_COOKIES/$_REQUEST, and then sanitizing your variables at the point where you're using it somewhere. E.g. urlencode() if you're using it in a URL, htmlentities() if you're printing it back to a web page, or using your database driver's escaping function if you're storing it to a database. Note those input arrays could contain sub-arrays so you might need to write a function can recurse into the sub-arrays to strip those slashes too.
The PHP
man page on magic quotes
agrees:
"This feature has been DEPRECATED as
  of PHP 5.3.0 and REMOVED as of PHP
  5.4.0. Relying on this feature is highly discouraged. Magic Quotes is a
  process that automagically escapes
  incoming data to the PHP script. It's
  preferred to code with magic quotes
  off and to instead escape the data at
  runtime, as needed."


q:
I'm trying to make a triangle (isosceles triangle) to move around the screen and at the same time slightly rotate it when a user presses a directional key (like right or left).

I would like the nose (top point) of the triangle to lead the triangle at all times. (Like that old asteroids game).

My problem is with the maths behind this. At every X time interval, I want the triangle to move in "some direction", I need help finding this direction (x and y increments/decrements).

I can find the center point (Centroid) of the triangle, and I have the top most x an y points, so I have a line vector to work with, but not a clue as to "how" to work with it.

I think it has something to do with the old Sin and Cos methods and the amount (angle) that the triangle has been rotated, but I'm a bit rusty on that stuff.

Any help is greatly appreciated.

[A]
The arctangent (inverse tangent) of vy/vx, where vx and vy are the components of your (centroid->tip) vector, gives you the angle the vector is facing.
The classical arctangent gives you an angle normalized to -90° < r < +90° degrees, however, so you have to add or subtract 90 degrees from the result depending on the sign of the result and the sign of vx.
Luckily, your standard library should proive an atan2() function that takes vx and vy seperately as parameters, and returns you an angle between 0° and 360°, or -180° and +180° degrees. It will also deal with the special case where vx=0, which would result in a division by zero if you were not careful.
See
http://www.arctangent.net/atan.html
or just search for "arctangent".
Edit: I've used degrees in my post for clarity, but Java and many other languages/libraries work in radians where 180° = π.
You can also just add vx and vy to the triangle's points to make it move in the "forward" direction, but make sure that the vector is normalized (vx² + vy² = 1), else the speed will depend on your triangle's size.


q: How would I be able to programmatically search and replace some text in a large number of PDF files?  I would like to remove a URL that has been added to a set of files.  I have been able to remove the link using javascript under Batch Processing in Adobe Pro, but the link text remains.  I have seen recommendations to use text touchup, which works manually, but I don't want to modify 1300 files manually.

[A]
Finding text in a PDF can be inherently hard because of the graphical nature of the document format -- the letters you are searching for may not be contiguous in the file.  That said,
CAM::PDF
has some search-replace capabilities and heuristics.  Give
changepagestring.pl
a try and see if it works on your PDFs.
To install:
```
```
$ cpan install CAM::PDF
 # start a new terminal if this is your first cpan module
 $ changepagestring.pl input.pdf oldtext newtext output.pdf
```
```


q:
I have an application which I have made a 256 x 256 Windows Vista icon for.

I was wondering how I would be able to use a 256x256 PNG file in the ico file used as the application icon and show it in a picture box on a form.

I am using VB.NET, but answers in C# are fine. I'm thinking I may have to use reflection.

I am not sure if this is even possible in Windows XP and may need Windows Vista APIs

[A]
Found info
here
.  To get the large Vista icon, you need to use Shell32's SHGetFileInfo method.  I've copied the relevant text below, of course you'll want to replace the filename variable with "Assembly.GetExecutingAssembly().Location".
```
```
using System.Runtime.InteropServices;
```
```
A bunch of constants we will use in the call to SHGetFileInfo() to specify the size of the icon we wish to retrieve:
```
```
// Constants that we need in the function call
private const int SHGFI_ICON = 0x100;
private const int SHGFI_SMALLICON = 0x1;
private const int SHGFI_LARGEICON = 0x0;
```
```
The SHFILEINFO structure is very important as it will be our handle to various file information, among which is the graphic icon.
```
```
// This structure will contain information about the file
public struct SHFILEINFO
{
    // Handle to the icon representing the file
    public IntPtr hIcon;
    // Index of the icon within the image list
    public int iIcon;
    // Various attributes of the file
    public uint dwAttributes;
    // Path to the file
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
    public string szDisplayName;
    // File type
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
    public string szTypeName;
};
```
```
The final preparation for the unmanaged code is to define the signature of SHGetFileInfo, which is located inside the popular Shell32.dll:
```
```
// The signature of SHGetFileInfo (located in Shell32.dll)
[DllImport("Shell32.dll")]
public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, int cbFileInfo, uint uFlags);
```
```
Now that we have everything prepared, it's time to make the call to the function and display the icon that we retrieved. The object that will be retrieved is an Icon type (System.Drawing.Icon) but we want to display it in a PictureBox so we'll convert the Icon to a Bitmap using the ToBitmap() method.
But first of all there are 3 controls you need to add to the form, a Button btnExtract that has "Extract Icon" for its Text property, picIconSmall which is a PictureBox and a picIconLarge which is also a PictureBox. That's because we will get two icons sizes. Now double click btnExtract in Visual Studio's Design view and you'll get to its Click event. Inside it is the rest of the code:
```
```
private void btnExtract_Click(object sender, EventArgs e)
{
    // Will store a handle to the small icon
    IntPtr hImgSmall;
    // Will store a handle to the large icon
    IntPtr hImgLarge;

    SHFILEINFO shinfo = new SHFILEINFO();

    // Open the file that we wish to extract the icon from
    if(openFile.ShowDialog() == DialogResult.OK)
    {
        // Store the file name
        string FileName = openFile.FileName;
        // Sore the icon in this myIcon object
        System.Drawing.Icon myIcon;

        // Get a handle to the small icon
        hImgSmall = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_SMALLICON);
        // Get the small icon from the handle
        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
        // Display the small icon
        picIconSmall.Image = myIcon.ToBitmap();

        // Get a handle to the large icon
        hImgLarge = SHGetFileInfo(FileName, 0, ref shinfo, Marshal.SizeOf(shinfo), SHGFI_ICON | SHGFI_LARGEICON);
        // Get the large icon from the handle
        myIcon = System.Drawing.Icon.FromHandle(shinfo.hIcon);
        // Display the large icon
        picIconLarge.Image = myIcon.ToBitmap();

    }
}
```
```
UPDATE: found even more info
here
.


q:
Does anyone knows how to detect printable characters in java?

After a while ( trial/error ) I get to this method:

    public boolean isPrintableChar( char c ) {
        Character.UnicodeBlock block = Character.UnicodeBlock.of( c );
        return (!Character.isISOControl(c)) &&
                c != KeyEvent.CHAR_UNDEFINED &&
                block != null &&
                block != Character.UnicodeBlock.SPECIALS;
    }

I'm getting the input via KeyListener and come Ctr-'key' printed an square. With this function seems fairly enough.

Am I missing some char here?

[A]
I'm not perfectly sure whether I understand your problem. But if you want detect if character can be drawn to Graphics object, and if not print some placeholder char you might find usefull:
```
```
Font.canDisplay(int)
```
```
It will check whether font can display specific codepoint (it is more that check whether font is displayable at all -- since there are chars that are displayable - like ą - but some fonts cant display them.


q:
I am changing document template macros. The one thing I can't find out how to do is to customize error messages. For example an error message in a document is

"Error! No table of figures entries found"

I would like to change this to display something else. Is it possible to do this with Word VBA or VBScript?

[A]
If you want to trap a specific error type in VBA, one method is to use On Error Resume Next then test for an error message on the line following the action to trap, e.g.:
```
```
On Error Resume Next
' try action
If Err.Number <> 0 Then
  ' handle w/ custom message
  Err.Clear
End If
```
```
If you know the exact error number (
```
If Err.Number = N Then
```
), that would be better of course.


q: As above. Usually at work someone else does the database design, and when I do personal projects they're small enough to not really require more than five or six tables, but I'm about to start a personal project that I think will probably require around eleven or twelve tables and I'd like something to help me design it neatly and keep track of it.

[A]
MySQL Workbench
, while a little buggy, has been invaluable to me since I discovered it.
Visio
has a good visual database designer, but it can't export the result to a MySQL database and is windows only.
phpMyAdmin
also has a
designer tool
which can be used if you correctly configure the
pma database
.


q:
I'm calling a web service that returns an array of objects in JSON.  I want to take those objects and populate a div with HTML.  Let's say each object contains a url and a name.

If I wanted to generate the following HTML for each object:

<div><img src="the url" />the name</div>

Is there a best practice for this? I can see a few ways of doing it:

Concatenate strings

Create elements

Use a templating plugin

Generate the html on the server, then serve up via JSON.

[A]
Either of the first two options is both common and acceptable.
I'll give examples of each one in
Prototype
.
```
```
// assuming JSON looks like this:
// { 'src': 'foo/bar.jpg', 'name': 'Lorem ipsum' }
```
```
Approach #1:
```
```
var html = "
 #{name}
".interpolate(json);
$('container').insert(html); // inserts at bottom
```
```
Approach #2:
```
```
var div = new Element('div');
div.insert( new Element('img', { src: json.src }) );
div.insert(" " + json.name);
$('container').insert(div); // inserts at bottom
```
```


q:
How do I write the getDB() function and use it properly?

Here is a code snippet of my App Object:

public class MyApp extends UiApplication {

    private static PersistentObject m_oStore;
    private static MyBigObjectOfStorage m_oDB;

    static {
        store = PersistentStore.getPersistentObject(0xa1a569278238dad2L);
    }

    public static void main(String[] args) {
        MyApp theApp = new MyApp();
        theApp.enterEventDispatcher();
    }
    public MyApp() {
        pushScreen(new MyMainScreen());
    }

    // Is this correct?  Will it return a copy of m_oDB or a reference of m_oDB?
    public MyBigObjectOfStorage getDB() {
        return m_oDB;  // returns a reference
    }

}

[A]
```
```
public MyBigObjectOfStorage getDB() {
    Object o = store.getContents();
    if ( o instanceof MyBigObjectOfStorage ) {
        return (MyBigObjectOfStorage) o;
    } else {
        return null;
    }
}
```
```


q:
If I make two iPhone applications, how can/should I share custom data (not contacts and stuff like that) among them?

Thanks!

[A]
There are two different ways you might go about this.
1) The data you need to share is non-persistent. In other words you need to launch one application with a piece of data that it can do something with. In this case you would register a special URL scheme per application.
You can find out more information about URL schemes via Craig Hockenberry in his
[redacted] blog post
.
2) The data you need to share is persistent. In other words you need something like a data file that both applications can read and write too. As far as I know there isn't a safe way to do this other than storing your data on a remote server. If you need the data accessible without a data connection then you would need to figure out a way to sync data between the individual apps and the remote server.


q: I teach a C++ course using Visual Studio.  One of my students has a Mac and was looking for an IDE to use on his machine. What would be good to recommend?

[A]
Xcode
which is part of the MacOS Developer Tools is a great IDE. There's also
NetBeans
and
Eclipse
that can be configured to build and compile C++ projects.
Clion
from JetBrains, also is available now, and uses Cmake as project model.