Question:
Perforce allows people to check in unchanged files. Why any version control system would allow this is beyond me, but that's a topic for another question.  I want to create a trigger that will deny the submission of unchanged files.  However, I have no experience with Perforce triggers.  From what I've read, I'm guessing this would be a "Change-content" trigger since the files being submitted would have to be diffed against the respective head revisions they are about to replace.  I would need to iterate over the incoming files and make sure they had all indeed changed.  The problem is, I have no idea how to go about it.

Can anyone with Perforce trigger experience offer an example or at least point me in the right direction?

Answer:
If you look at the Triggers table in Perforce, you will see that triggers are nothing but scripts that get invoked when some kind of event happens. In your case, the change-content event is triggered.
You have several options to write scripts that interact with Perforce. The
Perforce downloads page
has libraries and modules for many widely use languages. Any of this will help you and greatly simplify what you need to do. Also, check the
Perforce Documentation page
and download the administrator's guide. It will explain how to create the trigger, etc.
Basically, you need to write a script that will get the information from the change list that is being submitted and for each file in it run a "diff" command against the server. If you find a file that has not change, you need to invalidate the submission.
The Perforce module on you favorite language and the administrators guide will give you all the answers you need.


Question:
Our company is sending out a lot of emails per day and planning to send even more in future. (thousands) Also there are mass mailouts as well in the ten thousands every now and then.

Anybody has experience with hotmail, yahoo (web.de, gmx.net) and similar webmail companies blocking your emails because "too many from the same source in a period of time" have been sent to them?

What can be done about it? Spreading email mailouts over a whole day/night? At what rate?

(we are talking about legal emailing just to make sure...)

Answer:
If you want to do this you're getting into some of the same techniques spammers use. Spreading email mailouts over a day or night could be a way to do it. I don't think anyone  knows the 'right' rate to do this because varies per mail-provider and they probably adjust this over time. You could try spreading the emails sent to a single provider. If you've got a lot of mail for hotmail.com for example then don't send it all at the same time.
Maybe it would be a good idea to look at pull media instead of push media for your application. You could put the content of the mass mailings up on a website and notify interested readers with an rss feed for example. This has a lower risk of irritating potential customer. And your company has a lower risk of being sued for spamming.
You're right, rss is not really accessible for all users. But as you'll probably need to create a webpage-alternative to the mailings anyway for people who can't read html-mail. You might as well provide an rss feed to those pages as an alternative for the users who do want to use it. This might reduce the volumes for the mailings enough to make your job a bit easier.


Question:
I have been trying to determine a best case solution for registering a COM server using WiX to create a Windows Installer package and am struggling.

In this post Deployment Engineering Archive: HOWTO: Use Regsvr32.exe with WIX, there is an open request for the "Setup police" to crack down on using regsvr32 through an exe custom action.  I know the evils of using regsvr32 as it registers to the system rather than the user, but I also recall that OleSelfRegister can have issues from a microsoft support bulletin (sorry, can't find the link) - and I believe they recommended using regsvr32.

Any advice?

Answer:
Read "Do not use the SelfReg and TypeLib tables" at:
https://msdn.microsoft.com/en-us/library/bb204770#no_selfreg
For WiX, take a look at the
Component
element in the schema reference at:
http://wixtoolset.org/documentation/manual/v3/xsd/wix/component.html
Take notice of certain child elements such as
AppId
,
Class
,
ProgId
,
Registry
and so on.  The proper technique is to use
```
COM extraction
```
to reflect the registration information and emit it declaratively into your installer so MSI can take care of it for you without going out of process to some code (like
```
DllRegisterServer()
```
) that could fail and also not provides MSI insight into the footprint of the component from a repair and advertisement perspective.


Question:
When used like this:

import static com.showboy.Myclass;

public class Anotherclass{}

what's the difference between import static com.showboy.Myclass and import com.showboy.Myclass?

Answer:
See
Documentation
The static import declaration is
  analogous to the normal import
  declaration. Where the normal import
  declaration imports classes from
  packages, allowing them to be used
  without package qualification, the
  static import declaration imports
  static members from classes, allowing
  them to be used without class
  qualification.
So when should you use static import?
  Very sparingly! Only use it when you'd
  otherwise be tempted to declare local
  copies of constants, or to abuse
  inheritance (the Constant Interface
  Antipattern). In other words, use it
  when you require frequent access to
  static members from one or two
  classes. If you overuse the static
  import feature, it can make your
  program unreadable and unmaintainable,
  polluting its namespace with all the
  static members you import. Readers of
  your code (including you, a few months
  after you wrote it) will not know
  which class a static member comes
  from. Importing all of the static
  members from a class can be
  particularly harmful to readability;
  if you need only one or two members,
  import them individually. Used
  appropriately, static import can make
  your program more readable, by
  removing the boilerplate of repetition
  of class names.


Question:
I am looking for a Dataflow / Concurrent Programming API for Java.

I know there's DataRush, but it's not free. What I'm interested in specifically is multicore data processing, and not distributed, which rules out MapReduce or Hadoop.

Any thoughts?

Thanks,
Rollo

Answer:
Does the built in Java
concurrent
package meet your needs?  It's a very nice package, built in ThreadPools, CopyOnWriteCollections, Executors, Future.  We use it to process large volumns of data in thread pools.


Question: What level of CPU usage should be considered high for SQL Server? ie 80% 90% 100%?

Answer: It really depends on your machine.  The best thing is to monitor the server using perfmon and see when things start to run slowly.  It is normal for SQL to use a lot of CPU under load.


Question: What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used".

Answer:
I thought this would work, based on
this source
.
```
```
SELECT
  'Currently, '
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of '
  || DECODE(VL.SESSIONS_MAX,0,'unlimited',VL.SESSIONS_MAX)
  || ' connections are used.' AS USAGE_MESSAGE
FROM
  V$LICENSE VL
```
```
However, Justin Cave is right.  This query gives better results:
```
```
SELECT
  'Currently, '
  || (SELECT COUNT(*) FROM V$SESSION)
  || ' out of '
  || VP.VALUE
  || ' connections are used.' AS USAGE_MESSAGE
FROM
  V$PARAMETER VP
WHERE VP.NAME = 'sessions'
```
```


Question:
I am wanting to use the Facebox plugin for JQuery but am having a few issues getting it running how I want.  The div that houses the facebox content is created outside of the  tag so even though I am loading up some web controls none of them are firing back to the server.

Has anyone dealt with this that can give me some pointers?

Answer:
poking around the facebox.js I came across this line in the function init(settings)...
```
```
$('body').append($.facebox.settings.faceboxHtml)
```
```
I changed that to ...
```
```
$('#aspnetForm').append($.facebox.settings.faceboxHtml)
```
```
and it loads up in the form tag, not sure yet if there are any side effects


Question:
How can I check if an application is running from a batch (well cmd) file?

I need to not launch another instance if a program is already running. (I can't change the app to make it single instance only.)

Also the application could be running as any user.

Answer:
You should check the parent process name, see
The Code Project
article about a
.NET based solution**
.
A non-programmatic way to check:
Launch Cmd.exe
Launch an application (for instance,
```
c:\windows\notepad.exe
```
)
Check properties of the Notepad.exe process in
Process Explorer
Check for parent process (This shows cmd.exe)
The same can be checked by getting the parent process name.


Question:
I have a basic ActiveRecord model in which i have two fields that i would like to validate. The requirement is that at least one of the fields must have a value. Both can have values, but at least one needs a value.

How do i express this with

validates_presence_of

statements? For example:

validates_presence_of :main_file
validates_presence_of :alt_file

i don't want an error to be generated if only one of them is empty, only if both are empty.

Answer:
```
```
validates_presence_of :main_file, :if => Proc.new { |p| p.alt_file.blank? }
validates_presence_of :alt_file, :if => Proc.new { |p| p.main_file.blank? }
```
```


Question: How can I convert a Char[] (of any length) to a List  ?

Answer:
First you need to understand that chars aren't bytes in .NET. To convert between chars (a textual type) and bytes (a binary type) you need to use an encoding (see System.Text.Encoding).
Encoding will let you convert between string/char[] and byte[]. Once you've got a byte array, there are various ways of converting that into a List<byte> - although you may not even need to, as byte[] implements IList<byte>.
See
my article on Unicode
for more about the text conversion side of things (and links to more articles).


Question:
I've been using Remote Desktop Connection to get into a workstation. But in this environment, I cannot use the power options in Start Menu. I need an alternative way to shutdown or restart.

How do I control my computer's power state through the command line?

Answer:
The most common ways to use the
```
shutdown
```
command are:
```
shutdown -s
```
— Shuts down.
```
shutdown -r
```
— Restarts.
```
shutdown -l
```
— Logs off.
```
shutdown -h
```
— Hibernates.
Note:
There is a common pitfall wherein users think
```
-h
```
means "help" (which it does for every other command-line program... except
```
shutdown.exe
```
, where it means "hibernate"). They then run
```
shutdown -h
```
and accidentally turn off their computers. Watch out for that.
```
shutdown -i
```
— "Interactive mode". Instead of performing an action, it displays a GUI dialog.
```
shutdown -a
```
— Aborts a previous shutdown command.
The commands above can be combined with these additional options:
```
-f
```
— Forces programs to exit. Prevents the shutdown process from getting stuck.
```
-t <seconds>
```
— Sets the time until shutdown. Use
```
-t 0
```
to shutdown immediately.
```
-c <message>
```
— Adds a shutdown message. The message will end up in the Event Log.
```
-y
```
— Forces a "yes" answer to all shutdown queries.
Note:
This option is not documented in any official documentation. It was discovered by
these StackOverflow users
.
I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order.
The
```
-f
```
option
from
JosephStyons
Using
```
rundll32
```
from
VonC
The Run box
from
Dean
Remote shutdown
from
Kip


Question: What role is Spring taking in Struts + Spring + Hibernate?

Answer:
Spring provides many different "modules" and different programmers will use different parts of Spring.
However, commonly in this sort of stack, you will see Spring being used as a provider of
An inversion of control container for dependency injection
An abstraction to Hibernate called "HibernateTemplate"
Framework classes for simplifying Aspect Oriented Programming
Transaction support, often "declaratively" via the IoC container and AOP.


Question:
I use FB1.5.3 and need to eventually add some FK to the database.
It happens that if I try to do it while anyone else is connected to the DB I get an exception.

Is there a way to add an FK while the system is running?

Answer:
I believe this is a limitation on firebird 1.5 and earlier.
Try google for (firebird foreign key "object is in use").
hth


Question:
I was browsing Scott Hanselman's Developer Interview question list, and ran across this question:

What is wrong with
  DateTime.Parse(myString)?

While I know there are inherent risks in parsing a string of unknow format or origin, are there other reasons? Is it to use DateTime.ParseExact instead? Should it be myString.ToString() first?

Answer:
In addition the locale problem,
```
DateTime.Parse()
```
could also throw an exception which you would then have to catch.  Use
```
DateTime.TryParse()
```
or
```
DateTime.TryParseExact()
```
instead.


Question:
Hi why doesn't this work in SQL Server 2005?

select HALID, count(HALID) as CH from Outages.FaultsInOutages

where CH > 3

group by HALID

I get invalid column name 'CH'

i think having was the right way to go but still receive the error:
Invalid column name 'CH'.

When running:

select HALID, count(HALID) as CH from Outages.FaultsInOutages
group by HALID having CH > 3

Answer:
Try
```
```
select HALID, count(HALID) from Outages.FaultsInOutages
group by HALID having count(HALID) > 3
```
```
Your query has two errors:
Using where an aggregate when grouping by, solved by using having
Using an alias for an aggregate in the condition, not supported, solved by using the aggregate again


Question: Can someone explain what are the benefits of using the @import syntax comparing to just including css using the standard link method?

Answer: It allows you to keep your logic CSS file spread over multiple physical files. Helps in team development, for example. Also useful when you have a lot of CSS files that you want to separate by functional areas (one for grids, one for lists, etc), let have accessible in the same logical file.


Question:
I have 3 tables

Links

Link ID

Link Name

GroupID (FK into Groups)

SubGroupID (FK into Subgroups)

Groups

GroupID

GroupName

SubGroup

SubGroupID

SubGroupName

GroupID (FK into Groups)

Every link needs to have a GroupID but teh SubGroupID is optional.  How do i write a SQL query to show:

Links.LinkName, Groups.GroupName, SubGroup.SubGroupName

For the records with no subgroup just put a blank entry in that field.  If i have 250 link rows, i should get back 250 reecords from this query.

Is there a way to do this in one query or do i need to do multiple queries?

Answer:
```
```
SELECT
  links.linkname
  , groups.groupname
  , subgroup.groupname
FROM
  links
  JOIN groups ON links.groupid = groups.groupid
  LEFT OUTER JOIN subgroups ON links.subgroupid = subgroup.subgroupid
```
```
(re-added to address OP's question)
incidentally, why not keep groups and subgroups in the same table, and use a self-referential join?
Akantro:
You'd have something like this:
    create table groups(
    groupid integer primary key,
    parentgroupid integer foreign key references groups (groupid),
    groupname varchar(50))
your query would then be
```
```
SELECT
  links.linkname
  , groups.groupname
  , SUBGROUPS.groupname
FROM
  links
  JOIN groups ON links.groupid = groups.groupid
  LEFT OUTER JOIN groups SUBGROUPS ON links.subgroupid = subgroup.groupid
```
```
there's no functional difference to keeping the tables like this, but the benefit is you only have to go to one place to edit the groups/subgroups


Question:
Consider:

int testfunc1 (const int a)
{
  return a;
}

int testfunc2 (int const a)
{
  return a;
}

Are these two functions the same in every aspect or is there a difference?

I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well.

Answer:
Yes, they are same for just
```
int
```
and different for
```
int*
```


Question:
I just upgraded a VS 2005 project to VS 2008 and was examining the changes.  I noticed one of the .Designer.cs files had changed significantly.  The majority of the changes were simply replacements of System with global::System. For example,

protected override System.Data.DataTable CreateInstance()

became

protected override global::System.Data.DataTable CreateInstance()

What's going on here?

Answer:
The :: operator is called a Namespace Alias Qualifier.
```
```
global::System.Data.DataTable
```
```
is the same as:
```
```
System.Data.DataTable
```
```
Visual Studio 2008 added it to the designer generated code to avoid ambigious reference issues that occasionally happened when people created classes named System...For example:
```
```
class TestApp
{
    // Define a new class called 'System' to cause problems.
    public class System { }

    // Define a constant called 'Console' to cause more problems.
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // Error  Accesses TestApp.Console
        //Console.WriteLine(number);
    }
}
```
```
However:
```
```
global::System.Console.Writeline("This works");
```
```
For further reading:
http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx


Question:
How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work.

For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete.

Then I went into the routes.rb file and entered map.resources :employees, which gives you access to the URL helper functions.

In whatever I want to call the Ajax operation from, I should just have a line like:

<%= link_to_remote "Delete", employee_path(@employee), :method => :delete %>

When I click on the link, it is still is sending a POST operation, so it does nothing.

What am I missing or doing wrong?

Answer:
Try
```
```
:url => employee_url(@employee)
```
```
IIRC, *_path is a named route generated by the :resource directive which includes the method, thus overwriting your :method => :delete


Question:
I need a way to update the month value on a dateTime field in my db. I'm being past an int value for the month and need to use that for the update.
Is it possible to do this in the sql statement or would I be best doing it in c# in the webservice?

Answer:
Shift down and then up again:
```
```
UPDATE table
SET datecol = DATEADD(m, @newmonth, DATEADD(m, -MONTH(datecol), datecol))
WHERE id = @id
```
```
or, more simply:
```
```
UPDATE table
SET datecol = DATEADD(m, @newmonth - MONTH(datecol), datecol)
WHERE id = @id
```
```


Question:
I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance?

I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers.

Answer:
Short answer: you can't.
Long answer: you can't, partly because the database may be lazily evaluating the query, only returning rows as you ask for them.
EDIT: Using a scrollable ResultSet you can :)
Indeed, I asked this very question in the Java databases newsgroup a long time ago (back in 2001!) and had some
helpful responses
.


Question:
I am currently working on an asp.net application in Visual Studio 2005. I would like to upgrade to 2008 to take advantage of some of the new features, but my remote team won't be able to upgrade to it for a while.

Is it possible for only a few people on my team to upgrade to Visual Studio 2008, while the rest of the team continues to use 2005?

At this point, I don't plan on using any of the 3.0+ foundation stuff yet, so that isn't a concern.

Answer:
Yes, the project files between 2005 and 2008 are compatible.  The solutions are not, but those are easy to remake or copy.  There is one gotcha with the project files, if you're using Web Applications projects.  The two versions reference different MSBuild target files.  Steven Harman has
a blog with a fix to add to the project file
.
So long as you aren't using anything new from the 3.5 compiler, you should be good.  Note that even if you are targeting the 2.0 Framework, the compiler will still accept 3.5 syntax (var, object initializers, etc.) so you'll still need to be aware of those.


Question:
When creating a new file with vim, I would like to automatically add some skeleton code.

For example, when creating a new xml file, I would like to add the first line:

  <?xml version="1.0"?>

Or when creating an html file, I would like to add:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title></title>
  </head>
  <body>
  </body>
</html>

Answer:
Here are two examples using python scripting.
Add something like this in your .vimrc or another file sourced by your .vimrc:
```
```
augroup Xml
  au BufNewFile *.xml :python import vim
  au BufNewFile *.xml :python vim.current.buffer[0:0] = ['<?xml version="1.0"?>']
  au BufNewFile *.xml :python del vim
augroup END

fu s:InsertHtmlSkeleton()
  python import vim
  python vim.current.buffer[0:0] = ['<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', "", "", "  <title></title>", "", "", "", "", ""]
  python del vim
endfu

augroup Html
  au BufNewFile *.html call <SID>InsertHtmlSkeleton()
augroup END
```
```


Question:
Using C#

How do you remove a specific node from an XMLDocument using XPATH?

Answer:
Here you go.   ChildNodeName, could be just the node name or an XPath query.
```
```
XmlDocument doc = new XmlDocument();

// Load you XML Document

XmlNode childNode = doc.SelectSingleNode(childNodeName);

// Remove from the document
doc.RemoveChild(childNode);
```
```
There is a different way using Linq, but I guessed you were using .NET 2.0


Question:
What is the difference between these two pieces of code

type
  IInterface1 = interface
    procedure Proc1;
  end;

  IInterface2 = interface
    procedure Proc2;
  end;

  TMyClass = class(TInterfacedObject, IInterface1, IInterface2)
  protected
    procedure Proc1;
    procedure Proc2;
  end;

And the following :

type
  IInterface1 = interface
    procedure Proc1;
  end;

  IInterface2 = interface(Interface1)
    procedure Proc2;
  end;

  TMyClass = class(TInterfacedObject,  IInterface2)
  protected
    procedure Proc1;
    procedure Proc2;
  end;

If they are one and the same, are there any advantages, or readability issues with either.

I guess the second means you cannot write a class that implements IInterface2 without implementing IInterface1, whilst with the first you can.

Answer:
Assuming you meant
```
```
...
IInterface2 = interface(Interface1)
...
```
```
I interpret it the same as you,
the second form requires a class implementing Interface2 to implement Interface1 as well
, while the first form does not.


Question:
We don't exactly comply with the XML-RPC spec, but the concepts are nearly identical.  A client comes in over HTTP/HTTPS with an XML payload.  We respond with an XML payload answering the request.  This is primarily machine to machine, so no human to type a username/password.  Our construct runs within apache tomcat.  We would like to authenticate the request and since not every service is available to every client, we need to authorize the request as well.  We have both subscription and per use charging models so it is necessary to log everything.

What would you recommend for both server and client?

Answer:
HTTP BASIC/DIGEST works fine for most machine to machine tasks, and it handled by the server so your API is unaffected.
It doesn't work as well for interactive uses because it's difficult to "log out" the user without closing the browser.
Otherwise you'll most likely need to alter your APIs to include authentication information and have your methods authenticate that within your code.
Or you could use the classic "login", set a cookie, keep a session technique.
But, frankly, for machine to machine work, HTTP BASIC is the easiest.
edit, regarding comments.
HTTP BASIC is simply a protocol used to present the artifacts necessary for authentication, and it works well for machine to machine web services.
HOW IT IS IMPLEMENTED is dependent on you and your application. Using Java, you can use container authentication and that will provide authentication as well as role mapping. The user -> role mapping is handled in either a data file or database. The URLs protected, and what roles are valid for each URL, is managed by web.xml.
If you continue to add different roles to different URLs, then, yes, you'll need to redeploy that application.
However, if you're just adding new users, then you simply update your file or database. And if you're adding new logic, and this new URLs, then you have to redeploy anyway. If you have a ROLE structure with a fine enough granularity, you won't have to be messing with the web.xml until you actually add new methods. For example you could, at the extreme, create a role per method, and assign them individually to users. Most don't need to go that far.
If you don't want to use container authentication, then write a Servlet Filter to implement your vision of mapping user and roles to URLs. You can still use the HTTP BASIC protocol for your clients, even if you implement your own facility.
If you're looking for an overall generic Java security framework, I defer to google -- there are several, I've not used any of them. I've had good luck with container authentication and writing our own.


Question:
When using tooltips to show a detailed description of a TreeNode, the tooltip is drawn on top of the node, as if it was completing the node's text. Also, if the text is long, the tooltip is positioned in a way that the text exceeds the screen.

But what I need is the tooltip to show right below the mouse pointer and not on top of the TreeNode.

Any idea how to do this?

Show, don't tell:

How it is:

How I want:

Answer:
You need to define a ToolTip and write an MouseOverEventHandler for the TreeView. In the MouseOverEventHandler calculate the node above which mouse is positioned, then show the description ToolTip. Also make sure you are not setting the tooltip description more than once, otherwise the behavior is quite ugly.
A better way is to show the description in the StatusStrip - bottom left of the Form.
Update:
OK since you have clarified your question. You can use
```
ToolTip.Show
```
method where you can specify coordinates:
```
```
public void Show(
    string text,
    IWin32Window window,
    int x,
    int y,
    int duration
)
```
```
Obviously, you'll have to add offset to x and y.


Question:
Given the email address: "Jim" <jim@example.com>

If I try to pass this to MailAddress I get the exception:

The specified string is not in the form required for an e-mail address.

How do I parse this address into a display name (Jim) and email address (jim@example.com) in C#?

EDIT:  I'm looking for C# code to parse it.

EDIT2:  I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string.

Answer:
Try:
```
```
"Jimbo <jim@example.com>"
```
```


Question:
Using the default TWebBrowser makes things easy to embed a web browser. Unfortunately the one that comes in by default is IE<n>.

I'm wondering how does one integrate a Gecko or WebKit one.

Are there VCL examples somewhere?

If not, how would one go about doing it?

Where's the best place to find the core for Gecko and/or WebKit in an embeddable format?

Answer:
TWebBrowser
is
IE. It is not a plugable construction for browsers. You can have other browsers integrated in your application. See
http://www.adamlock.com/mozilla/
http://delphi.mozdev.org/articles/taming_the_lizard_with_delphi.html
http://ftp.newbielabs.com/Delphi%20Gecko%20SDK/
Time has moved on
This answer is from '08 and since then time has moved on. The links don't work anymore and there are probably better alternatives now.


Question:
I have a table column that needs to be limited to a certain width - say 100 pixels.  At times the text in that column is wider than this and contains no spaces. For example:

a_really_long_string_of_text_like_this_with_no_line_breaks_makes_the_table_unhappy

I would like to calculate the width of text server-side and add an ellipsis after the correct number of characters.  The problem is that I don't have data about the rendered size of the text.

For example, assuming the browser was Firefox 3 and the font was 12px Arial.  What would be the width of the letter "a", the width of the letter "b", etc.?

Do you have data showing the pixel width of each character?  Or a program to generate it?

I think a clever one-time javascript script could do the trick.  But I don't want to spend time re-inventing the wheel if someone else has already done this.  I am surely not the first person to come up against this problem.

Answer:
Very very hard to do server-side. You can never know what fonts users have installed, and there are many things that affect the display of text.
Try this instead:
```
```
table-layout: fixed;
```
```
That'll make sure the table is never larger than the size you specified.


Question: What do you think the next evolution of languages will look like?

Answer:
You might assume C and C++ are being "phased out" and that Java/.Net/Python/whatever is an "advance" or the "next stop".
They are all used heavily (see the number C or C++ of tags on this site). The difference is that neither one is the lingua-franca of the programming world anymore. It used to be that the majority of apps were desktop or DOS apps on systems with very limited resources, furthermore all the major desktop APIs were written in C or C++. So everyone learned these.
Now its more complex. Languages are becomming more application specific. C/C++ for when performance is important. Scripting languages for when your main performance hit is db reads/writes. Java and .Net for generic, non-performance-critical desktop apps.
Its the same thing with computer or electrical engineering. In the past these were huge fields at the highest level of abstraction available. Now we have all sorts of higher levels of abstraction. Still, we need people to do this lower-level kind of engineering. They are still in demand. In the same manner, C will continue to be used in many environments, as will C++. You'd be crazy, for instance, to think that you could write a device driver in Java, you'd also be mildly crazy (but perhaps less so) to write a full fledged GUI app in C if you had the choice and ability to do it in Java or .Net.
Each tool has its purpose. I expect C, C++, and Java to evolve and continue to be used for new and legacy development.


Question:
On a project I'm working on, we use subversion, with tortoiseSVN as a client, under windows XP.

As we enter in production and continue development in parallel, many branches are created.

Often, we have to backport modifications made on the branch to the trunk, or to older branches. Backporting is a very delicate task, as many errors can be introduced into the code.

What are your favorite tools to make backporting easier and more secure ? If possible, add only one tool per answer, and vote for your favorite ones.

Answer:
You might assume C and C++ are being "phased out" and that Java/.Net/Python/whatever is an "advance" or the "next stop".
They are all used heavily (see the number C or C++ of tags on this site). The difference is that neither one is the lingua-franca of the programming world anymore. It used to be that the majority of apps were desktop or DOS apps on systems with very limited resources, furthermore all the major desktop APIs were written in C or C++. So everyone learned these.
Now its more complex. Languages are becomming more application specific. C/C++ for when performance is important. Scripting languages for when your main performance hit is db reads/writes. Java and .Net for generic, non-performance-critical desktop apps.
Its the same thing with computer or electrical engineering. In the past these were huge fields at the highest level of abstraction available. Now we have all sorts of higher levels of abstraction. Still, we need people to do this lower-level kind of engineering. They are still in demand. In the same manner, C will continue to be used in many environments, as will C++. You'd be crazy, for instance, to think that you could write a device driver in Java, you'd also be mildly crazy (but perhaps less so) to write a full fledged GUI app in C if you had the choice and ability to do it in Java or .Net.
Each tool has its purpose. I expect C, C++, and Java to evolve and continue to be used for new and legacy development.


Question:
I am using a multi-dimensional dynamic array in delphi and am trying to figure this out:

I have 2 seperate values for the first index and second index that are totally seperate of each other.

As new values come I want to grow the array if that new value is outside of either bound.

For new values x, y

I check:

if Length(List) < (x + 1) then
   SetLength(List, x + 1);
if Length(List[0]) < (y + 1) then
   SetLength(List, Length(List), y + 1);

Is this the correct way to do this or is there a better way to grow the array as needed?

Answer:
It looks fine to me - if you change the last line to
```
```
SetLength(List, Length(List), y + 1);
```
```


Question:
I recently deploy one web application in one of my development servers. I'm using oracle, asp.net and c#. When I run the application in the server everything works fine, but when I try to run the application outside of the server (using my pc, for example) i get this error:

ORA-12154: TNS:could not resolve the connect identifier specified

If i run the application in my pc with visual studio it works fine.

Oracle is installed in Server "A" and the application is in server "B". Server "A" is in one domain and server "B" is in other domain.My pc is in the same domain has Server "A".

In my pc I can find the file tnsname.ora in C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN, but in Server "B" i can´t find it anywhere

any idea?
Thanks for the help.

Answer:
Have you tried this yet? (from
http://ora-12154.ora-code.com/
)
ORA-12154:  TNS:could not resolve the connect identifier specified
Cause:  A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.
Action:
- If you are using local naming (TNSNAMES.ORA file):
Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)
Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.
Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.
Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.
If you are using directory naming:
Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
Verify that the LDAP directory server is up and that it is accessible.
Verify that the net service name or database name used as the connect identifier is configured in the directory.
Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier
If you are using easy connect naming:
Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
Make sure the host, port and service name specified are correct.
Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.


Question: I have a database with user 'dbo' that has a login name "domain\xzy".  How do I change it from "domain\xzy" to "domain\abc".

Answer:
This is a Windows login, not a SQL Server login, so you cannot 'change' the login name since it is linked to the user account in Active Directory.
Create a new Server Login (Windows) mapped to the new windows user (and remove the old one if necessary). Then in login's Security > User Mapping, permission that login to the appropriate database as user 'dbo' (or assign to the db_owner role)


Question:
One of the really nice things about python is the simplicity with which you can name variables that have the same name as the accessor:

self.__value = 1

def value():
    return self.__value

Is there a simple way of providing access to the private members of a class that I wish to subclass? Often I wish to simply work with the raw data objects inside of a class without having to use accessors and mutators all the time.

I know this seems to go against the general idea of private and public, but usually the class I am trying to subclass is one of my own which I am quite happy to expose the members from to a subclass but not to an instance of that class. Is there a clean way of providing this distinction?

Answer:
Not conveniently, without further breaking encapsulation. The double-underscore attribute is name-mangled by prepending '_ClassName' for the class it is being accessed in. So, if you have a 'ContainerThing' class that has a '__value' attribute, the attribute is actually being stored as '
```
_ContainerThing__value
```
'. Changing the class name (or refactoring where the attribute is assigned to) would mean breaking all subclasses that try to access that attribute.
This is exactly why the double-underscore name-mangling (which is not really "private", just "inconvenient") is a bad idea to use. Just use a
single
leading underscore. Everyone will know not to touch your 'private' attribute and you will still be able to access it in subclasses and other situations where it's darned handy. The name-mangling of double-underscore attributes is useful only to avoid name-clashes for attributes that are truly specific to a particular class, which is extremely rare. It provides no extra 'security' since even the name-mangled attributes are trivially accessible.
For the record, '
```
__value
```
' and '
```
value
```
' (and '
```
_value
```
') are not the same name. The underscores are part of the name.


Question:
I have a char array in a C application that I have to split into parts of 250 so that I can send it along to another application that doesn't accept more at one time.

How would I do that? Platform: win32.

Answer:
From the MSDN documentation:
The strncpy function copies the initial count characters of strSource to strDest and returns strDest. If count is less than or equal to the length of strSource, a null character is not appended automatically to the copied string. If count is greater than the length of strSource, the destination string is padded with null characters up to length count. The behavior of strncpy is undefined if the source and destination strings overlap.
Note that
```
strncpy
```
doesn't check for valid destination space; that is left to the programmer.  Prototype:
```
char *strncpy(
   char *strDest,
   const char *strSource,
   size_t count
);
```
Extended example:
```
```
void send250(char *inMsg, int msgLen)
{
    char block[250];
    while (msgLen > 0)
    {
         int len = (msgLen>250) ? 250 : msgLen;
         strncpy(block, inMsg, 250);

         // send block to other entity

         msgLen -= len;
         inMsg  += len;
    }
}
```
```


Question:
I'm just starting to get into Django, and of course as of last night one of the two new Python versions went final (2.6 obviously ;)) so I'm wondering if 2.6 plus Django is ready for actual use or do the Django team need more time to finish with tweaks/cleanup?

All the google searches I did were inconclusive, I saw bits about some initial test runs on beta 2 but nothing more recent seemed to show up.

Edit: http://groups.google.com/group/django-developers/browse_thread/thread/a48f81d916f24a04

They've confirmed here 1.0 w/2.6 works fine as far as they know.

Answer:
The impression I get is that 2.6 should work fine with Django 1.0. As found here:
http://simonwillison.net/2008/Oct/2/whatus/


Question:
I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database.

I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated.

But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender.

Is there a way to log the machine name via log4net in this manner?

Answer:
you can create a parameter similar to the following:
```
```
<parameter>
  <parameterName value="@machine" />
  <dbType value="String" />
  <size value="255" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%X{machine}" />
  </layout>
</parameter>
```
```
Then add this line before writing to the log:
```
MDC.Set("machine", Environment.MachineName);
```


Question:
Can you package up the .Net framework in an installer created in Visual Studio? If so how?

I've seen this done with Install4J packaging a JVM but I think that was the JVM to run Install4J.

Answer:
Sucky, yeah - I created an installer just recently before realizing that the .Net Framework (which was one of the things I needed to install) was required.  I ended up making a c++ program that installed .Net before my installer was launched.
Seems kind of odd to me to offer the ability to create an installer and not have it offer to install what it needs to run.  Kinda pointless at that point, eh?  Unless you know that every machine you give the installer to will have the necessary components...
Oh well, live and learn


Question:
I'm quite new to NHibernate and starting to find my way around.

I have a domain model that is somewhat like a tree.

Funds have Periods have Selections have Audits

Now I would like to get all Audits for a specific Fund

Would look like this if I made it in SQL

SELECT A.*

FROM Audit A

JOIN Selection S ON A.fkSelectionID = S.pkID

JOIN Period P ON S.fkPeriodID = P.pkID

JOIN Fund F ON P.fkFundID = F.pkID

WHERE F.pkID = 1

All input appreciated!

Answer:
Try this
```
```
select elements(s.Audits)
from Fund as f inner join Period as p inner join Selection as s
where f = myFundInstance
```
```


Question:
How do you include a file that is more than 2 directories back. I know you can use ../index.php to include a file that is 2 directories back, but how do you do it for 3 directories back?
Does this make sense?
I tried .../index.php but it isn't working.

I have a file in /game/forum/files/index.php and it uses PHP include to include a file. Which is located in /includes/boot.inc.php; / being the root directory.

Answer:
```
```
../../index.php
```
```


Question:
I'm a Mac user and I've decided to learn Emacs. I've read that to reduce hand strain and improve accuracy the CTRL and CAPS LOCK keys should be swapped. How do I do this in Leopard?

Also, in Terminal I have to use the ESC key to invoke meta. Is there any way to get the alt/option key to invoke meta instead?

update: While the control key is much easier to hit now, the meta key is also used often enough that its position on my MacBook and Apple Keyboard also deserves attention. In fact, I find that the control key is actually easier to hit, so I've remapped my control key to act as a meta key. Does anyone have a better/more standard solution?

Answer:
Swapping CTRL and CAPS LOCK
Go into
System Preferences
Enter the
Keyboard & Mouse
preference pane
In the
Keyboard
tab, click
Modifier Keys...
Swap the actions for
Caps Lock
and
Control
.
Using ALT/OPTION as META
In the menu bar, click
Terminal
Click
Preferences...
Under the
Settings
tab, go to the
Keyboard
tab
Check the box labeled
Use option as meta key
That's it! You should be well on your way to becoming an Emacs master!


Question:
Given the following C function in a DLL:

char * GetDir(char* path );

How would you P/Invoke this function into C# and marshal the char * properly.
.NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function.

Answer:
Try
```
```
[DllImport("your.dll", CharSet = CharSet.Ansi)]
string GetDir(StringBuilder path);
```
```
string is automatically marshalled to a zero-terminated string, and with the CharSet property, you tell the Marshaller that it should use ANSI rather than Unicode.
Note: Use string (or System.String) for a const char*, but StringBuilder for a char*.
You can also try MarshalAs, as in
this example
.


Question: If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket.

Answer:
Assuming you mean JavaScript running on the client - you cause an HTTP redirect to be made to the server, and have your servlet react to the request for the given URL.
This is known as
Ajax
, and there are a
number
of
libraries
that help you do it..


Question: I have an HTTP server that returns large bodies in response to POST requests (it is a SOAP server). These bodies are "streamed" via chunking. If I encounter an error midway through streaming the response how can I report that error to the client and still keep the connection open? The implementation uses a proprietary HTTP/SOAP stack so I am interested in answers at the HTTP protocol level.

Answer:
Once the server has sent the status line (the very first line of the response) to the client, you can't change the status code of the response anymore. Many servers delay sending the response by buffering it internally until the buffer is full. While the buffer is filling up, you can still change your mind about the response.
If your client has access to the response headers, you could use the fact that chunked encoding allows the server to add a trailer with headers after the chunked-encoded body. So, your server, having encountered the error, could gracefully stop sending the body, and then send a trailer that sets some header to some value. Your client would then interpret the presence of this header as a sign that an error happened.


Question:
I'm trying to create a Crystal Reports formula field (to calculate the percentage change in a price) that will return "N/A" if a particular report field is null, but return a number to two decimal places using accounting format (negative numbers surrounded by parentheses) if it is not.

The closest I have been able to manage is this:

If IsNull({ValuationReport.YestPrice}) Then
    'N/A'
Else
    ToText({@Price}/{ValuationReport.YestPrice}*100-100, '###.00', 2)

However this represents negative numbers using a negative sign, not parentheses.

I tried format strings like '###.00;(###.00)' and '(###.00)' but these were rejected as invalid. How can I achieve my goal?

Answer:
I think you are looking for
```
ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))
```
You can use
```
CCur
```
to convert numbers or string to Curency formats.
```
CCur(number)
```
or
```
CCur(string)
```
I think this may be what you are looking for,
```
Replace (ToText(CCur({field})),"$" , "")
```
that will give the parentheses for negative numbers
It is a little hacky, but I'm not sure CR is very kind in the ways of formatting


Question:
I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages.

Basically I have three questions:

Why use pointers over normal variables?

When and where should I use pointers?

How do you use pointers with arrays?

Answer:
Pointers are one way of getting an indirect reference to another variable.  Instead of holding the
value
of a variable, they tell you its
address
.  This is particularly useful when dealing with arrays, since using a pointer to the first element in an array (its address) you can quickly find the next element by incrementing the pointer (to the next address location).
The best explanation of pointers and pointer arithmetic that I've read is in K & R's
The C Programming Language
.  A good book for beginning learning C++ is
C++ Primer
.


Question:
So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project.

From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files?

Answer:
Subversion can do this, but you have to do it with
```
```
svn move <oldfile> <newfile>
```
```
Edit: And in this decade, we do
```
git mv <oldfile> <newfile>
```
, or just use
```
mv
```
and git usually figures it out on its own.


Question:
How does one dynamically load a new report from an embedded resource? I have created a reporting project that contains a report as an embedded resource. I added a second report file and use the following code to switch reports:

this.reportViewer1.LocalReport.ReportEmbeddedResource = "ReportsApplication2.Report2.rdlc";
this.reportViewer1.LocalReport.Refresh();
this.reportViewer1.RefreshReport();

When this code executes, the original report remains visible in the report viewer.

I have also tried using

LocalReport.LoadReportDefinition

but had the same result.

Answer:
The answer: you have to call
```
```
<ReportViewer>.Reset();
```
```
prior to changing the value of ReportEmbeddedResource or calling LoadReportDefinition.
After you do so, you'll also have to call
```
```
<ReportViewer>.LocalReport.DataSources.Add( ... );
```
```
to re-establish the data sources.


Question:
If I open a file using urllib2, like so:

remotefile = urllib2.urlopen('http://example.com/somefile.zip')

Is there an easy way to get the file name other then parsing the original URL?

EDIT: changed openfile to urlopen... not sure how that happened.

EDIT2: I ended up using:

filename = url.split('/')[-1].split('#')[0].split('?')[0]

Unless I'm mistaken, this should strip out all potential queries as well.

Answer:
Do you mean
```
urllib2.urlopen
```
?  There is no function called
```
openfile
```
in the
```
urllib2
```
module.
Anyway, use the
```
urllib2.urlparse
```
functions:
```
```
>>> from urllib2 import urlparse
>>> print urlparse.urlsplit('http://example.com/somefile.zip')
('http', 'example.com', '/somefile.zip', '', '')
```
```
Voila.


Question:
In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture.

I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures?

Answer:
This works for MSVC++ and
```
g++
```
:
```
```
#if defined(_M_X64) || defined(__amd64__)
  // code...
#endif
```
```


Question: Thinking in regards to Sliverlight, I would like to know where would be good places to go to get a refresher on 3d space, transforms, matrix manipulation, and all that good stuff.

Answer:
Think I may have found it myself.  Was looking at:
http://msdn.microsoft.com/en-us/library/cc189037(VS.95).aspx
and
http://www.c-sharpcorner.com/UploadFile/mgold/TransformswithGDIplus09142005064919AM/TransformswithGDIplus.aspx


Question:
I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3's and jpg's.  I have tried both of the following with no luck:

Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories);
Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories);

Is there a way to do this in one call?

Answer:
Nope. Try the following:
```
```
List<string> _searchPatternList = new List<string>();
    ...
    List<string> fileList = new List<string>();
    foreach ( string ext in _searchPatternList )
    {
        foreach ( string subFile in Directory.GetFiles( folderName, ext  )
        {
            fileList.Add( subFile );
        }
    }

    // Sort alpabetically
    fileList.Sort();

    // Add files to the file browser control
    foreach ( string fileName in fileList )
    {
        ...;
    }
```
```
Taken from:
http://blogs.msdn.com/markda/archive/2006/04/20/580075.aspx


Question:
I have a polygon soup of triangles that I would like to construct a BSP tree for.  My current program simply constructs a BSP tree by inserting a random triangle from the model one at a time until all the triangles are consumed, then it checks the depth and breadth of the tree and remembers the best score it achieved (lowest depth, lowest breadth).

By definition, the best depth would be log2(n) (or less if co-planar triangles are grouped?) where n is the number of triangles in my model, and the best breadth would be n (meaning no splitting has occurred).  But, there are certain configurations of triangles for which this pinnacle would never be reached.

Is there an efficient test for checking the quality of my BSP tree?  Specifically, I'm trying to find a way for my program to know it should stop looking for a more optimal construction.

Answer:
Randomly building BSP trees until you chance upon a good one will be really, really inefficient.
Instead of choosing a tri at random to use as a split-plane, you want to try out several (maybe all of them, or maybe a random sampling) and pick one according to some heuristic. The heuristic is typically based on (a) how balanced the resulting child nodes would be, and (b) how many tris it would split.
You can trade off performance and quality by considering a smaller or larger sampling of tris as candidate split-planes.
But in the end, you can't hope to get a totally optimal tree for any real-world data so you might have to settle for 'good enough'.


Question:
In Oracle, I can re-create a view with a single statement, as shown here:

CREATE OR REPLACE VIEW MY_VIEW AS
SELECT SOME_FIELD
FROM SOME_TABLE
WHERE SOME_CONDITIONS

As the syntax implies, this will drop the old view and re-create it with whatever definition I've given.

Is there an equivalent in MSSQL (SQL Server 2005 or later) that will do the same thing?

Answer:
You can use 'IF EXISTS' to check if the view exists and drop if it does.
```
IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS
        WHERE TABLE_NAME = 'MyView')
    DROP VIEW MyView
GO

CREATE VIEW MyView
AS
     ....
GO
```


Question:
On a 32-bit CPU, an integer is 4 bytes and a short integer is 2 bytes.  If I am writing a C/C++ application that uses many numeric values that will always fit within the provided range of a short integer, is it more efficient to use 4 byte integers or 2 byte integers?

I have heard it suggested that 4 byte integers are more efficient as this fits the bandwidth of the bus from memory to the CPU.  However, if I am adding together two short integers, would the CPU package both values in a single pass in parallel (thus spanning the 4 byte bandwidth of the bus)?

Answer:
Yes, you should definitely use a 32 bit integer on a 32 bit CPU, otherwise it may end up masking off the unused bits (i.e., it will always do the maths in 32 bits, then convert the answer to 16 bits)
It won't do two 16 bit operations at once for you, but if you write the code yourself and you're sure it won't overflow, you can do it yourself.
Edit
: I should add that it also depends somewhat on your definition of "efficient".  While it will be able to do 32-bit operations more quickly, you will of course use twice as much memory.
If these are being used for intermediate calculations in an inner loop somewhere, then use 32-bit.  If, however, you're reading this from disk, or even if you just have to pay for a cache miss, it may still work out better to use 16-bit integers.  As with all optimizations, there's only one way to know:
profile it
.


Question:
I am just beginning to do research into the feasibility of using Amazon's SimpleDB service as the datastore for RoR application I am planning to build. We will be using EC2 for the web server, and had planned to also use EC2 for the MySQL servers. But now the question is, why not use SimpleDB?

The application will (if successful) need to be very scalable in terms of # of users supported, will need to maintain a simple and efficient code base, and will need to be reliable.

I'm curious as to what the SO communities thoughts are on this.

Answer:
Well, considering simple DB doesn't use SQL, or even have tables, means that it's a completely different beast than MySQL and other SQL-based things (
http://aws.amazon.com/simpledb/
). There are no constraints, triggers, or joins. Good luck.
Here's one way of getting it up and running:
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=1242
(via
http://rubyforge.org/projects/aws-sdb/
)
I suppose if you're never going to need to query the data outside of rails, then SimpleDB may prove to be OK. But as it's not a first-class supported DB, you're likely to run into bugs that are difficult to fix. I wouldn't want to run a production rails app in a semi-beta backend.


Question:
I'm trying to have the modrewrite rules skip the directory vip. I've tried a number of things as you can see below, but to no avail.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
#RewriteRule ^vip$ - [PT]
RewriteRule ^vip/.$ - [PT]
#RewriteCond %{REQUEST_URI} !/vip
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

How do I get modrewrite to entirely ignore the /vip/ directory so that all requests pass directly to the folder?

Update:

As points of clarity:

It's hosted on Dreamhost

The folders are within a wordpress directory

the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important

Answer:
I'm not sure if I understand your objective, but the following might do what you're after?
```
```
RewriteRule ^/vip/(.*)$   /$1?%{QUERY_STRING} [L]
```
```
This will cause a URL such as
http://www.example.com/vip/fred.html
to be rewritten without the /vip.


Question: I am using an asp:Calander and I have an object that has a beginning date and an ending date. I need to get all the dates between these two dates and place them in an array so i can then render corresponding dates on the calander with different CSS

Answer:
```
```
DateTime startDate;
DateTime endDate;

DateTime currentDate = startDate;
List<DateTime> dates = new List<DateTime> ();

while (true)
{
    dates.Add (currentDate);
    if (currentDate.Equals (endDate)) break;
    currentDate = currentDate.AddDays (1);
}
```
```
It assumes that startDate < than endDate, you get the results on the "dates" list


Question:
I want to read all items of a feed in C#. The solutions I've found are only for the latest items like just the last 10 days.

Anybody has a good solution for this?

Answer:
Libraries for reading feeds typically read all the data in the feed, but feeds typically only contain recent data - you need a source of data that includes older items, not a better library for reading the data you have.
Most entities publish feeds to allow people to track when new content is published, not to make all their data available in a more convenient machine readable format. For this purpose, publishing recent data only makes sense as it saves on bandwidth.


Question:
I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java String flavor and pasted it into Java code, it does not work. The following class prints false:

public class RegexFoo {

    public static void main(String[] args) {
        String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]";
        String text = "http://google.com";
        System.out.println(IsMatch(text,regex));
}

    private static boolean IsMatch(String s, String pattern) {
        try {
            Pattern patt = Pattern.compile(pattern);
            Matcher matcher = patt.matcher(s);
            return matcher.matches();
        } catch (RuntimeException e) {
        return false;
    }
}
}

Does anyone know what I am doing wrong?

Answer:
Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.
```
```
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
```
This works too:
```
```
String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
```
Note:
```
```
String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>

String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com>
```
```


Question:
I have monthly sales figures stored in separate sheets.  I would like to create a plot of sales for multiple products per month.  Each product would be represented in a different colored line on the same chart with each month running along the x axis.

What is the best way to create a single line chart that pulls from the same relative cells on multiple sheets?

Answer:
Use the Chart Wizard.
On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.
Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.
Select your new series.
There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.
Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.
Hope that helps.
EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.


Question:
Normally I program in C# but have been forced to do some work in C++. It seems that the integration with Visual Studio (2008) is really poor compared to C# but I was wondering if there are any good tools, plugins or configurations that can improve the situation.

Another post pointed out the program Visual Assist X, which at least helps with some things such as refactoring (though it is a bit expensive for me). My major problem is, though, that the compile errors give little clue about what is wrong and I spend most of my time figuring out what I did wrong. It just feels like it is possibly to statically check for a lot more errors than VS does out of the box. And why doesn't it provide the blue underlines as with C#, that shouldn't be too hard?!

I realize that half the problem is just the fact that I am new to C++ but I really feel that it can be unreasonably hard to get a program to compile. Are there any tools of this sort out there or are my demands too high?

Answer:
I think there are two possibilities: 1) either you're trying out C++ stuff that is waaay over your knowledge (and consequently, you don't know what you did wrong and how to interpret error messages), 2) you have too high expectations.
A hint: many subsequent errors are caused by the first error.  When I get a huge list of errors, I usually correct just the first error and recompile.  You'd be amazed how much garbage (in terms of error messages) a missing delimiter or type declaration could produce :)
It is difficult to syntactically analyze a C++ program before compilation mainly for two reasons: 1) the C++ grammar is context-dependent, 2) templates are Turing-complete (think of them as of a functional programming language with a weird syntax).


Question:
I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?

public class Test {
    public static void main(String args[]) {
        Test t = new Test();
        t.testT(null);
    }

    public <T extends Test> void testT(Class<T> type) {
        Class<T> testType = type == null ? Test.class : type; //Error here
        System.out.println(testType);
    }
}

Type mismatch: cannot convert from Class<capture#1-of ? extends Test> to Class<T>

By casting Test.class to Class<T> this compiles with an Unchecked cast warning and runs perfectly.

Answer:
Remove the conditional and the error is a little nicer...
```
```
public class Test {
    public static void main(String args[]) {
        Test t = new Test();
        t.testT(null);
    }

    public <T extends Test> void testT(Class<T> type) {
    Class<T> testClass = Test.class;
        System.out.println(testClass);
    }
}

Test.java:10: incompatible types
found   : java.lang.Class<Test>
required: java.lang.Class<T>
        Class<T> testClass = Test.class;
```
```


Question:
I have a web application where users enter arbitrary sql queries for later batch processing. We want to validate the syntax of the query without actually executing it. Some of the queries will take a long time, which is why we don't want to execute them. I'm using Oracle's dbms_sql.parse to do this.

However, I now have a situation where I need to know the number and type of the result set columns. Is there a way to do this without actually executing the query? That is, to have Oracle parse the query and tell me what the result datatypes/names will be returned when the query is actually executed? I'm using Oracle 10g and and it's a Java 1.5/Servlet 2.4 application.

Edit: The users who enter the queries are already users on the database. They authenticate to my app with their database credentials and the queries are executed using those credentials. Therefore they can't put in any query that they couldn't run by just connecting with sqlplus.

Answer:
You should be able to prepare a SQL query to validate the syntax and get result set metadata.  Preparing a query should not execute it.
```
```
import java.sql.*;
. . .
Connection conn;
. . .
PreparedStatement ps = conn.prepareStatement("SELECT * FROM foo");
ResultSetMetadata rsmd = ps.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
```
```
Then you can get metadata about each column of the result set.


Question: Does MS Access 2007 support internal foreign keys within the same table?

Answer:
Yes.  Create the table with the hierarchy.
id - autonumber - primary key
parent_id - number
value
Go to the relationships screen.  Add the hierarchy table twice.  Connect the id and the parent_id fields.  Enforce referential integrity.


Question:
Is there a way to use Enum values inside a JSP without using scriptlets.

e.g.

package com.example;

public enum Direction {
    ASC,
    DESC
}

so in the JSP I want to do something like this

<c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">...

Answer:
You could implement the web-friendly text for a direction within the enum as a field:
```
```
<%@ page import="com.example.Direction" %>
...

Direction is <%=foo.direction.getFriendlyName()%>

<% if (foo.direction == Direction.ASC) { %>

That means you're going to heaven!

<% } %>
```
```
but that mixes the view and the model, although for simple uses it can be view-independent ("Ascending", "Descending", etc).
Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons.


Question:
Any failed ASSERT statements on Windows cause the below debug message to appear and freeze the applications execution. I realise this is expected behaviour but it is running periodically on a headless machine so prevent the unit tests from failing, instead waiting on user input indefinitely.

Is there s a registry key or compiler flag I can use to prevent this message box from requesting user input whilst still allowing the test to fail under ASSERT?

Basically, I want to do this without modifying any code, just changing compiler or Windows options.

Thanks!

Microsoft Visual C++ Debug Library ASSERT http://img519.imageshack.us/img519/853/snapshotbu1.png

Answer:
From MSDN about the ASSERT macro:
In an MFC ISAPI application, an assertion in debug mode will bring up a modal dialog box (ASSERT dialog boxes are now modal by default); this will interrupt or hang the execution. To suppress modal assertion dialogs, add the following lines to your project source file (projectname.cpp):
```
```
// For custom assert and trace handling with WebDbg
#ifdef _DEBUG
CDebugReportHook g_ReportHook;
#endif
```
```
Once you have done this, you can use the WebDbg tool (WebDbg.exe) to see the assertions.


Question: I am creating an installer for an ASP.Net website using WiX.  How do you set the ASP.Net version in IIS using WiX?

Answer:
First find the correct .NET version folder. Use DirectorySearch/FileSearch to perform search.
Use the above path to call aspnet_regiis.exe and set the version for the webapp from a custom action.
```
aspnet_regiis.exe -s W3SVC/1/ROOT/SampleApp1
```


Question: I'm trying to debug an MSBuild task, and I know there is some way to write to the MSBuild log from within a custom task but I forget how.

Answer:
The base
Task
class has a
```
Log
```
property you can use:
```
```
Log.LogMessage("My message");
```
```


Question: I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert?

Answer:
In a debug compilation,
```
Assert
```
takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false.  The program proceeds without any interruption if the condition is true.
If you compile in Release, all
```
Debug.Assert
```
's are automatically left out.


Question:
If I do the following:

import subprocess
from cStringIO import StringIO
subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0]

I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__
    (p2cread, p2cwrite,
  File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles
    p2cread = stdin.fileno()
AttributeError: 'cStringIO.StringI' object has no attribute 'fileno'

Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen.  How do I work around this?

Answer:
I figured out this workaround:
```
```
>>> p = subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> p.stdin.write(b'one\ntwo\nthree\nfour\nfive\nsix\n') #expects a bytes type object
>>> p.communicate()[0]
'four\nfive\n'
>>> p.stdin.close()
```
```
Is there a better one?


Question:
I have a Flex application that calls a function which searches a large document collection. Depending on the search term, the user may want to stop the request from flex.

I’d like to not only stop the flex application from expecting the request, but also stop the CFC request. Is this possible? What’s the best approach for doing this?

Answer:
You can programmatically end requests with either
```
<cfabort/>
```
or
```
<cfsetting requesttimeout="0"/>
```
- but that's on the CF server side of things, which I don't think is what you're asking?
Ending it remotely... well, if you have FusionReactor it
might
be possible to contact that using Flex and have it interrupt the request for you.
(You can certainly try to end requests within FusionReactor, but whether or not Flex can actually ask FR to stop it... you'd have to ask that on the FR mailing list if there's a way to do that.)
Possibly an alternative solution is to try and architect the search so that it works over multiple requests, but how feasible that is will depend on exactly what you're searching.


Question:
In the GNOME Terminal, Bash does smart auto-completion. For example

apt-get in<TAB>

becomes

apt-get install

In Emacs shell-mode, this auto-completion doesn't work, even after I explicitly source /etc/bash_completion. The above example sticks as in or auto-completes with a filename in the current directory rather than a valid apt-get command option. Presumably, this is because Emacs is intercepting the Tab key-press. How do I enable smart auto-completion in shell-mode?

Answer:
I don't know the answer to this. But the reason that it doesn't work as you expect is probably because the completion in emacs shells is handled by emacs internally (by the comint-dynamic-complete function), and doesn't have those smart completion functions built-in.
I'm afraid it is not an easy thing to fix.
Edit: njsf's suggestion of using term-mode is probably as good as it gets. Start it with
```
M-x term
```
It is included in the standard emacs distribution (and in emacs21-common or emacs22-common on Ubuntu and Debian at least).


Question:
I frequently need to debug .NET binaries on test machines (by test-machine, I mean that the machine doesn't have Visual Studio installed on it, it's frequently re-imaged, It's not the same machine that I do my development on, etc).

I love the Visual Studio debugger, but it's not practical for me to install visual studios on a freshly imaged test-machine just to debug an assertion or crash (the install takes way too long, the footprint is too large, etc).

I'd really like a quickly installed program that could break into a running process, let me specify the location of symbols/source code, and let me jump right into debugging.  For native binaries, windbg works great, but I haven't found anything similiar for managed binaries. Any recommendations?

(as a side note, I am aware of visual studios remote debugging capabilities, but for some reason it never seems to work consistently for me...  I often have connection issues)

Answer:
There is always
mdbg
and
cordbg
, but I would suggest digging more into why remote debugging doesn't work consistently.
VS2005/8 seem a lot more reliable than earlier versions here (though I primarily do unmanaged) and it saves you from having to have the symbols accessible on the target machine.


Question: In light of how ajax is actually used by most sites today; why is ajax embraced while frames are still regarded as a bad idea?

Answer:
Ajax and frames are completely different from an accessibility standpoint (they're also completely different full stop).
Frames offer very little positive effect but bring with them a host of negative issues.
Ajax on the other hand makes the user interface more dynamic without compromising usability in most cases.


Question:
Which profiler is better for general purpose profiling and heap analysis? 90% of our apps are standalone command line programs with substantial database and numeric processing. The other 10% are webapps/servlet container apps (with very little JSP and NO SCRIPLETS!). Target user would be Sr Software Engineer with 5-10 years of industry experience. We need support only for Sun JDK 5 and.

As of writing this question (2008-10-02), JProfiler was at 5.1.4 and YourKit was 7.5. Looks like YourKit 8.0 will be released soon.

Answer: If you're on jdk >=1.6_07 you might also want to look at jvisualvm which comes bundled.


Question:
What would you recommend for class that needs to keep a list of unique integers?

I'm going to want to Add() integers to the collection and also check for existence e.g. Contains().

Would be nice to also get them in a list as a string for display, ie. "1, 5, 10, 21".

Answer:
HashSet
:
The
```
HashSet<T>
```
class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
The capacity of a
```
HashSet<T>
```
object is the number of elements that the object can hold. A
```
HashSet<T>
```
object's capacity automatically increases as elements are added to the object.
The
```
HashSet<T>
```
class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the
```
Dictionary<TKey, TValue>
```
or
```
Hashtable
```
collections. In simple terms, the
```
HashSet<T>
```
class can be thought of as a
```
Dictionary<TKey, TValue>
```
collection without values.
A
```
HashSet<T>
```
collection is not sorted and cannot contain duplicate elements...


Question:
I have a lot of XML files and I'd like to generate a report from them. The report should provide information such as:

root 100%
 a*1 90%
 b*1 80%
  c*5 40%

meaning that all documents have a root element, 90% have one a element in the root, 80% have one b element in the root, 40% have 5 c elements in b.

If for example some documents have 4 c elements, some 5 and some 6, it should say something like:

c*4.3 4 6 40%

meaning that 40% have between 4 and 6 c elements there, and the average is 4.3.

I am looking for free software, if it doesn't exist I'll write it. I was about to do it, but I thought about checking it. I may not be the first one to have to analyze and get an structural overview of thousand of XML files.

Answer:
Here's an XSLT 2.0 method.
Assuming that
```
$docs
```
contains a sequence of document nodes that you want to scan, you want to create one line for each element that appears in the documents. You can use
```
<xsl:for-each-group>
```
to do that:
```
```
<xsl:for-each-group select="$docs//*" group-by="name()">
  <xsl:sort select="current-group-key()" />
  <xsl:variable name="name" as="xs:string" select="current-grouping-key()" />
  <xsl:value-of select="$name" />
  ...
</xsl:for-each-group>
```
```
Then you want to find out the stats for that element amongst the documents. First, find the documents have an element of that name in them:
```
```
<xsl:variable name="docs-with" as="document-node()+"
  select="$docs[//*[name() = $name]" />
```
```
Second, you need a sequence of the number of elements of that name in each of the documents:
```
```
<xsl:variable name="elem-counts" as="xs:integer+"
  select="$docs-with/count(//*[name() = $name])" />
```
```
And now you can do the calculations. Average, minimum and maximum can be calculated with the
```
avg()
```
,
```
min()
```
and
```
max()
```
functions. The percentage is simply the number of documents that contain the element divided by the total number of documents, formatted.
Putting that together:
```
```
<xsl:for-each-group select="$docs//*" group-by="name()">
  <xsl:sort select="current-group-key()" />
  <xsl:variable name="name" as="xs:string" select="current-grouping-key()" />
  <xsl:variable name="docs-with" as="document-node()+"
    select="$docs[//*[name() = $name]" />
  <xsl:variable name="elem-counts" as="xs:integer+"
    select="$docs-with/count(//*[name() = $name])" />
  <xsl:value-of select="$name" />
  <xsl:text>* </xsl:text>
  <xsl:value-of select="format-number(avg($elem-counts), '#,##0.0')" />
  <xsl:text> </xsl:text>
  <xsl:value-of select="format-number(min($elem-counts), '#,##0')" />
  <xsl:text> </xsl:text>
  <xsl:value-of select="format-number(max($elem-counts), '#,##0')" />
  <xsl:text> </xsl:text>
  <xsl:value-of select="format-number((count($docs-with) div count($docs)) * 100, '#0')" />
  <xsl:text>%</xsl:text>
  <xsl:text>
</xsl:text>
</xsl:for-each-group>
```
```
What I haven't done here is indented the lines according to the depth of the element. I've just ordered the elements alphabetically to give you statistics. Two reasons for that: first, it's significantly harder (like too involved to write here) to display the element statistics in some kind of structure that reflects how they appear in the documents, not least because different documents may have different structures. Second, in many markup languages, the precise structure of the documents can't be known (because, for example, sections can nest within sections to any depth).
I hope it's useful none the less.
UPDATE:
Need the XSLT wrapper and some instructions for running XSLT? OK. First, get your hands on
Saxon 9B
.
You'll need to put all the files you want to analyse in a directory. Saxon allows you to access all the files in that directory (or its subdirectories) using a collection using a
special URI syntax
. It's worth having a look at that syntax if you want to search recursively or filter the files that you're looking at by their filename.
Now the full XSLT:
```
```
<xsl:stylesheet version="2.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="xs">

<xsl:param name="dir" as="xs:string"
  select="'file:///path/to/default/directory?select=*.xml'" />

<xsl:output method="text" />

<xsl:variable name="docs" as="document-node()*"
  select="collection($dir)" />

<xsl:template name="main">
  <xsl:for-each-group select="$docs//*" group-by="name()">
    <xsl:sort select="current-group-key()" />
    <xsl:variable name="name" as="xs:string" select="current-grouping-key()" />
    <xsl:variable name="docs-with" as="document-node()+"
      select="$docs[//*[name() = $name]" />
    <xsl:variable name="elem-counts" as="xs:integer+"
      select="$docs-with/count(//*[name() = $name])" />
    <xsl:value-of select="$name" />
    <xsl:text>* </xsl:text>
    <xsl:value-of select="format-number(avg($elem-counts), '#,##0.0')" />
    <xsl:text> </xsl:text>
    <xsl:value-of select="format-number(min($elem-counts), '#,##0')" />
    <xsl:text> </xsl:text>
    <xsl:value-of select="format-number(max($elem-counts), '#,##0')" />
    <xsl:text> </xsl:text>
    <xsl:value-of select="format-number((count($docs-with) div count($docs)) * 100, '#0')" />
    <xsl:text>%</xsl:text>
    <xsl:text>
</xsl:text>
  </xsl:for-each-group>
</xsl:template>

</xsl:stylesheet>
```
```
And to run it you would do something like:
```
> java -jar path/to/saxon.jar -it:main -o:report.txt dir=file:///path/to/your/directory?select=*.xml
```
This tells Saxon to start the process with the template named
```
main
```
, to set the
```
dir
```
parameter to
```
file:///path/to/your/directory?select=*.xml
```
and send the output to
```
report.txt
```
.


Question:
Where can I find a good Rails newbie-friendly reference about generating rails models with foreign key relationships?

I've found some pages indicating that you should add has_many and belongs_to to the relevant models to specify these relationships, but haven't seen any instructions for getting the scaffolds to generate the correct controller and view code that would reflect these relationships.

Answer:
There are a bunch of StackOverflow questions asking for newbie reference materials. I recommend that you start with the two Peepcode screencasts:
Rails From Scratch Part I
Rails From Scratch Part II
They do a great job of visually introducing you to Rails 2 development. Then, I'd recommend you pick up the Rails 2.1 PDF by Ryan Daigle, to get the hang of the 2.1 features not covered in the screencasts.
I'm not sure what you're driving at with your question. What are you expecting the scaffolding to do? Create multi-object relationship links automatically? That's something you have to start layering in yourself....and as you do so, the scaffolding starts to be replaced with a real application. The scaffolding is just a starting point: it's not meant to guess what your inter-object relationships are going to look like in the application.


Question:
I'm looking for an example algorithm of smart pagination. By smart, what I mean is that I only want to show, for example, 2 adjacent pages to the current page, so instead of ending up with a ridiculously long page list, I truncate it.

Here's a quick example to make it clearer... this is what I have now:

Pages: 1 2 3 4 [5] 6 7 8 9 10 11

This is what I want to end up with:

Pages: ... 3 4 [5] 6 7 ...

(In this example, I'm only showing 2 adjacent pages to the current page)

I'm implementing it in PHP/Mysql, and the "basic" pagination  (no trucating) is already coded, I'm just looking for an example to optimize it... It can be an example in any language, as long as it gives me an idea as to how to implement it...

Answer:
Here is some code based on original code from
this very old link
. It uses markup compatible with Bootstrap's pagination component, and outputs page links like this:
```
```
[1] 2 3 4 5 6 ... 100
1 [2] 3 4 5 6 ... 100
...
1 2 ... 14 15 [16] 17 18 ... 100
...
1 2 ... 97 [98] 99 100
```
```
```
```
<?php

// How many adjacent pages should be shown on each side?
$adjacents = 3;

//how many items to show per page
$limit = 5;

// if no page var is given, default to 1.
$page = (int)$_GET["page"] ?? 1;

//first item to display on this page
$start = ($page - 1) * $limit;

/* Get data. */
$data = $db
    ->query("SELECT * FROM mytable LIMIT $start, $limit")
    ->fetchAll();

$total_pages = count($data);

/* Setup page vars for display. */
$prev = $page - 1;
$next = $page + 1;
$lastpage = ceil($total_pages / $limit);
//last page minus 1
$lpm1 = $lastpage - 1;

$first_pages = "
1
" .
    "
2";

$ellipsis = "
...
";

$last_pages = "
$lpm1
" .
    "
$lastpage";

$pagination = "";
$pagincation .= "
";

//previous button

$disabled = ($page === 1) ? "disabled" : "";
$pagination.= "
« previous
";

//pages
//not enough pages to bother breaking it up
if ($lastpage < 7 + ($adjacents * 2)) {
    for ($i = 1; $i <= $lastpage; $i++) {
        $active = $i === $page ? "active" : "";
        $pagination .= "
$i
";
    }
} elseif($lastpage > 5 + ($adjacents * 2)) {
    //enough pages to hide some
    //close to beginning; only hide later pages
    if($page < 1 + ($adjacents * 2)) {
        for ($i = 1; $i < 4 + ($adjacents * 2); $i++) {
            $active = $i === $page ? "active" : "";
            $pagination .= "
$i
";
        }
        $pagination .= $ellipsis;
        $pagination .= $last_pages;
    } elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2)) {
        //in middle; hide some front and some back
        $pagination .= $first_pages;
        $pagination .= $ellipsis
        for ($i = $page - $adjacents; $i <= $page + $adjacents; $i++) {
            $active = $i === $page ? "active" : "";
            $pagination .= "
$i
";
        }
        $pagination .= $ellipsis;
        $pagination .= $last_pages;
    } else {
        //close to end; only hide early pages
        $pagination .= $first_pages;
        $pagination .= $ellipsis;
        $pagination .= "
...
";
        for ($i = $lastpage - (2 + ($adjacents * 2)); $i <= $lastpage; $i++) {
            $active = $i === $page ? "active" : "";
            $pagination .= "
$i
";
        }
    }
}

//next button
$disabled = ($page === $last) ? "disabled" : "";
$pagination.= "
next »
";

$pagination .= "
";

if($lastpage <= 1) {
    $pagination = "";
}

echo $pagination;

foreach ($data as $row) {
    // display your data
}

echo $pagination;
```
```


Question:
I have a Person model that has a foreign key relationship to Book, which has a number of fields, but I'm most concerned about author (a standard CharField).

With that being said, in my PersonAdmin model, I'd like to display book.author using list_display:

class PersonAdmin(admin.ModelAdmin):
    list_display = ['book.author',]

I've tried all of the obvious methods for doing so, but nothing seems to work.

Any suggestions?

Answer:
According to the documentation, you can only display the
```
__unicode__
```
representation of a ForeignKey:
http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display
Seems odd that it doesn't support the
```
'book__author'
```
style format which is used everywhere else in the DB API.
Turns out there's
a ticket for this feature
, which is marked as Won't Fix.


Question:
A co worker of mine asked me to review some of my code and he sent me a diff file.  I'm not new to diffs or version control in general but the diff file was very difficult to read because of the changes he made.  Specifically, he used the "extract method" feature and reordered some methods.  Conceptually, very easy to understand but looking at the diff, it was very hard to tell what he had done.  It was much easier for me to checkout the previous revision and use Eclipse's "compare" feature, but it was still quite clunky.

Is there any version control system that stores metadata related to refactoring.  Of course, it would be IDE and Programming Language specific, but we all use Eclipse and Java!  Perhaps there might be some standard on which IDEs and version control implementations can play nicely?

Answer:
Eclipse can
export refactoring history
(see
3.2 release notes
as well).  You could then view the refactoring changes via preview in Eclipse.


Question:
Is there any alternative for WPF (windows presentation foundation) in python?

http://msdn.microsoft.com/en-us/library/aa970268.aspx#Programming_with_WPF

Answer:
You might want to look at
pygtk
and
glade
.
Here
is a tutorial.
There is a long
list of alternatives
on the
Python Wiki
.


Question:
Suppose I have a "tags" table with two columns: tagid and contentid.  Each row represents a tag assigned to a piece of content.  I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342.

The "easy" way to do this would be (pseudocode):

select contentid from tags where tagid = 334 and contentid in (
    select contentid from tags where tagid = 338 and contentid in (
        select contentid from tags where tagid = 342
    )
)

However, my gut tells me that there's a better, faster, more extensible way to do this.  For example, what if I needed to find the intersection of 12 tags?  This could quickly get horrendous.  Any ideas?

EDIT: Turns out that this is also covered in this excellent blog post.

Answer:
The only alternative way i can think of is:
```
```
select a.contentid from tags a
inner join tags b on a.contentid = b.contentid and b.tagid=334
inner join tags c on a.contentid = c.contentid and c.tagid=342
where a.tagid=338
```
```


Question:
I'm putting together a little tool that some business people can run on their local filesystems, since we don't want to setup a host for it.

Basically, its just HTML + Javascript (using jQuery) to pull some reports using REST from a 3rd party.

The problem is, FF3 and IE don't allow the ajax call, I get:

Access to restricted URI denied" code: "1012

Obviously its an XSS issue...how do I work around it? The data returned is in XML format.

I was trying to do it this way:

$.get(productUrl, function (data){
    alert (data);
});

EDIT: To be clear...I'm not setting up an internal host for this(Way to much red tape), and we CANNOT host this externally due to the data being retrieved.

EDIT #2: A little testing shows that I can use an IFRAME to make the request. Does anyone know if there any downsides to using a hidden IFRAME?

Answer:
If you have Python installed, a webserver to serve files can be as simple as
```
```
python -c “import SimpleHTTPServer;SimpleHTTPServer.test()”
```
```
Edit:
Original poster can't use this approach, but in general I think this is the way to solve this particular problem for future users with this issue.


Question:
I have never clearly understood the usage of MAXDOP. I do know that it makes the query faster and that it is the last item that I can use for Query Optimization.

However, my question is, when and where it is best suited to use in a query?

Answer:
This is a general rambling on Parallelism in SQL Server, it might not answer your question directly.
From Books Online, on MAXDOP:
Sets the maximum number of processors
  the query processor can use to execute
  a single index statement. Fewer
  processors may be used depending on
  the current system workload.
See
Rickie Lee's blog
on parallelism and CXPACKET wait type. It's quite interesting.
Generally, in an OLTP database, my opinion is that if a query is so costly it needs to be executed on several processors, the query needs to be re-written into something more efficient.
Why you get better results adding MAXDOP(1)? Hard to tell without the actual execution plans, but it might be so simple as that the execution plan is totally different that without the OPTION, for instance using a different index (or more likely) JOINing differently, using MERGE or HASH joins.


Question:
What are some good algorithms for automatically labeling text with the city / region  or origin?  That is, if a blog is about New York, how can I tell programatically.  Are there packages / papers that claim to do this with any degree of certainty?

I have looked at some tfidf based approaches, proper noun intersections, but so far, no spectacular successes, and I'd appreciate ideas!

The more general question is about assigning texts to topics, given some list of topics.

Simple / naive approaches preferred to full on Bayesian approaches, but I'm open.

Answer:
You're looking for a
named entity recognition
system, or short NER. There are
several
good
toolkits
available to help you out. LingPipe in particular has a very
decent tutorial
.
CAGEclass
seems to be oriented around NER on geographical place names, but I haven't used it yet.
Here's
a nice blog entry about the difficulties of NER  with geographical places names.
If you're going with Java, I'd recommend using the LingPipe NER classes. OpenNLP also has some, but the former has a better documentation.
If you're looking for some theoretical background,
Chavez et al. (2005)
have constructed an interesting syntem and documented it.


Question: I know that you can do this in SQL Server 2005, but I'm at a loss for 2000.

Answer:
From all the research I've done on this in the past, I unfortunately have to say no. SQL Server 2000 simply does not store this information, and I've never seen any solution for retrieving it.
There are a few alternative methods, but they all involve user intervention. Besides keeping stored procedure scripts in a source control system, I think the next best approach is to use comments inside the stored procedure. Not ideal, but it's better than nothing if you want to track what gets updated.


Question:
Up until now I have been using std::string in my C++ applications for embedded system (routers, switches, telco gear, etc.).

For the next project, I am considering to switch from std::string to std::wstring for Unicode support. This would, for example, allow end-users to use Chinese characters in the command line interface (CLI).

What complications / headaches / surprises should I expect? What, for example, if I use a third-party library which still uses std::string?

Since support for international strings isn't that strong of a requirement for the type of embedded systems that I work on, I would only do it if it isn't going to cause major headaches.

Answer:
From all the research I've done on this in the past, I unfortunately have to say no. SQL Server 2000 simply does not store this information, and I've never seen any solution for retrieving it.
There are a few alternative methods, but they all involve user intervention. Besides keeping stored procedure scripts in a source control system, I think the next best approach is to use comments inside the stored procedure. Not ideal, but it's better than nothing if you want to track what gets updated.


Question: Is there a connection limit on Sql Server 2005 Developers Edition.  We have many threads grabbing connections, and I know ADO.NET does connection pooling, but I get OutOfMemory exceptions.  We take out the db connections and it works fine.

Answer:
You may not be closing or disposing of your connection objects correctly.  Make sure your code looks something like this:
```
```
using (SqlConnection conn = new SqlConnection("connectionstring"))
{
    conn.Open();

    // database access code goes here
}
```
```
The using block will automatically close and dispose of your connection object.


Question:
Should log classes open/close a log file stream on each write to the log file or should it keep the log file stream open throughout the application's lifetime until all logging is complete?

I'm asking in context of a desktop application.  I have seen people do it both ways and was wondering which approach yields the best all-around results for a logger.

Answer:
If you have frequent read/writes it is more efficient to keep the file open for the lifetime with a
single open/close
.
You might want to
flush periodically or after each write
though. If your application crashes you might not have all the data written to your file. Use fflush on Unix-based systems and FlushFileBuffers on Windows.
If you are running on Windows as well you can use the CreateFile API with FILE_FLAG_NO_BUFFERING to go direct to the file on each write.
It is also
better to keep the file open
for the lifetime,
because
each time you open/close you might have a failure if the file is in use.  For example, you might have
a backup application that runs and opens/closes your file
as it's backing it up.  And this
might cause your program to not be able to access your own file
.   Ideally, you would want to keep your file open always and specify sharing flags on Windows (FILE_SHARE_READ).  On Unix-based systems, sharing will be default.