Question:
I have a WPF ListView which currently scrolls everytime I click on an item which is only partially visible.  How can I keep the control from scrolling that item into view (instead simply selecting the partially visible one)?  This behavior is very annoying when doing a drag from this control.

Thanks.

Added:  I am looking for a solution to keep the control itself from scrolling when contents are clicked that the control believes are not fully visible.  Often this is by a few pixels and the scroll is not necessary.

Answer:
have you tried
this approach
?
just as an addon, I don't know how much you know about the subject, but
here is a good place
to read more about it.
added:
I just found that you can
prevent the mouse wheel of scrolling
as well.


Question:
I have installed CherryPy 3.1.0,. Here is what happens when I try to run tutorial 9:

$ cd /Library/Python/2.5/site-packages/cherrypy/tutorial/
$ python tut09_files.py
Traceback (most recent call last):
  File "tut09_files.py", line 48, in <module>
    from cherrypy.lib import static
ImportError: cannot import name static

The previous line in the file:

import cherrypy

passes without error, so it appears that it can find cherrypy on the path. What am I missing?

Answer:
I am a big fan of the proposed HTML 5 solution (
```
data-
```
prefixed attributes). Edit: I'd add that there are probably better examples for the use of custom attributes. For instance, data that a custom application will use that have no analogue in standard attributes (eg. customization for event handlers based on something that can't necessarily be expressed in a className or id).


Question:
Hopefully I haven't misunderstood the meaning of "duck typing", but from what I've read, it means that I should write code based on how an object responds to methods rather than what type/class it is.

Here's the code:

def convert_hash(hash)
  if hash.keys.all? { |k| k.is_a?(Integer) }
    return hash
  elsif hash.keys.all? { |k| k.is_a?(Property) }
    new_hash = {}
    hash.each_pair {|k,v| new_hash[k.id] = v}
    return new_hash
  else
    raise "Custom attribute keys should be ID's or Property objects"
  end
end

What I want is to make sure that I end up with a hash where the keys are an integer representing the ID of an ActiveRecord object. I don't particularly enjoy having to iterate through the hash keys twice with all? to determine if I need to grab the ID's out.

Of course, I'll accept any other suggestions to improve this code as well :)

Answer:
How you write this method should depend on whether you expect an exception to be thrown during the course of normal program execution.  If you want a readable exception message because an end-user might see it, then throwing one manually makes sense.  Otherwise, I'd just do something like this:
```
```
def convert(hash)
    new_hash = {}
    hash.each_pair { |k,v| new_hash[ k.is_a?(Integer) ? k : k.id ] = v }
    return new_hash
end
```
```
This will accomplish exactly the same thing, and you'll still get an exception if an array key doesn't have an id field.  Even better, this uses a little more duck typing because now anything that has an id field will be acceptable, which is better than explicitly checking for something being a Property.  This makes your code more flexible, especially when unit testing.
We still have an explicit check for integer objects, but this kind of occasional special case is usually acceptable, especially when checking for built-in data types.


Question:
I have a form using multiple <cfinput type="datefield" ...>. They are positioned in such a way that the pop-up CSS calendar should appear over the field for others. However, the text fields for the other dates end up in front of the calendar.

This is only an IE issue as Firefox and Safari work just fine.

Is there a simple CSS hack or some other simple thing I can do to get the calendar to act as it should? Re-arranging the form is not very helpful.

Answer:
My first inclination is to attempt to add a style for the text fields with a negative z-index.  Alternately, you could attempt to apply a positive z-index to the popup.
The first would probably be easier, given the way that the popups are written dynamically -- CF passes any unrecognized or unused attributes through to the browser, so you could just add a style.  Something like:
```
```
<cfinput type="datefiled" name="bob" value="" style="z-index: -1;">
```
```
Not tested, YYMV.


Question:
I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding ActionForms. Some of them have only String properties (even for numbers), some of them use the seemingly appropriate types (Integer, Date, String, etc). What's the best practice here?

Also, it seems that if a property is of type Integer, and the value the user entered is not an integer value, Struts silently swallows this and just doesn't set the property. What's up with this?

Answer: For Struts 1.2x, properties where the user enters or selects values on the HTML form and that are populated on the ActionForm instance automatically by the Struts HTML tags must be Strings or booleans. However, there's no reason why your ActionForm can't have getter methods that return the properties as more meaningful types for your application e.g. Date.


Question:
I am looking for a concise way to check a value to see if it is nil or zero.  Currently I am doing something like:

if (!val || val == 0)
  # Is nil or zero
end

But this seems very clumsy.

Answer:
I believe your code is incorrect; it will in fact test for three values:
```
nil
```
,
```
false
```
, and zero. This is because the
```
!val
```
expression is true for all values that are false, which in Ruby is
```
nil
```
and
```
false
```
.
The best I can come up with right now is
```
```
if val == nil || val == 0
  # do stuff
end
```
```
Which of course is not very clever, but (very) clear.


Question:
How do I convert a hex string to an integer?

"0xffff"   ⟶   65535
"ffff"     ⟶   65535

Answer:
```
int(hexstring, 16)
```
does the trick, and works with and without the 0x prefix:
```
```
>>> int("a", 16)
10
>>> int("0xa", 16)
10
```
```


Question:
I inherited this gigantic legacy Java web app using Struts 1.2.4. I have a specific question regarding Actions. Most of the pages have exactly one Action, and the processExecute() methods are hideous monsters (very long and tons of nested if statements based on request parameters).

Given that Actions are an implementation of the command pattern, I'm thinking to split these Actions into one Action per user gesture. This will be a large refactoring though, and I'm wondering:

Is this the right direction?

Is there an intermediate step I could take, a pattern that deals with the mess inside the monolithic actions? Maybe another command pattern inside the Action?

Answer:
My way of dealing with this would be:
dont do 'everything at once'
whenever you change anything, leave it better than you found it
replacing conditionals with separate Action implementations is one step.
Better yet: Make your implementations separate from the Action classes so that you can use it when you change frameworks
Keep your new Command implementation
absolutely
without references to Struts, use your new Actions as Wrapper around these implementations.
You might need to provide interfaces to your Struts ActionForms in order to pass them around without copying all the data. On the other hand - you might want to pass around other objects than ActionForms that are usually a bunch of Strings (see your other question about
Struts 1.2 ActionForms
)
start migrating parts to newer & better technology. Struts 1.2 was great when it came out, but is definitely not what you want to support in eternity. There are some generations of better frameworks now.
There's definitely more - Sorry, I'm running out of time here...


Question: How would I drag and drop something into a static control?  It looks like I need to create a sub class of COleDropTarget and include that as a member variable in a custom CStatic.  That doesn't appear to be working though.  When I try and drag something onto the Static control I get the drop denied cursor.

Answer:
The static control's
```
m_hWnd
```
must be valid when you call
```
COleDropTarget::Register
```
, which is why it doesn't work from within your
```
CMyStatic
```
constructor. What you can do is override
```
CWnd::PreSubclassWindow
```
within your
```
CMyStatic
```
class:
```
```
class CMyStatic : public CStatic {
    ...
    virtual void PreSubclassWindow();
};

void CMyStatic::PreSubclassWindow()
{
    CStatic::PreSubclassWindow();

    m_MyDropTarget.Register(this);
}
```
```
There's a really good article
here
on CodeProject that you may find helpful.


Question: Please don't reply I should use ddd, nemiver, emacs, vim, or any other front-end, I just prefer gdb as it is, but would like to see its output with some terminal colors.

Answer:
It's not colours, but consider gdb's
text gui
. It makes a vast difference to how usable gdb is.
You can launch it with:
```
```
gdb -tui executable.out
```
```
Screenshot:
As you can see, the main features are:
shows what line of the source we are on and surrounding lines
shows breakpoints


Question:
Why would you choose java over others? Why did you choose java to program your application?

Please include what you are using java for (desktop application/ web application/ mobile).

Answer:
Java provides a very rich API right out of the box and hands-down produces the most portable applications since there is a Java VM for almost every platform.
BTW: I haven't used Java since I left college since I work for a Microsoft shop, but I can't think of a single thing I can do in C# that I can't do in Java, whether it be enterprise applications, web applications, or desktop applications.


Question:
I'd like to have comments in my code, but I want them to be removed before deploying.
Yes, it's not hard to write such a thing, but if it already exists…
And how about comments in ASP pages?

Answer:
Sounds like you are looking for a JSMin tool or similar.
There are many tools which you can purchase, but there are also some online tools you can use:
http://www.askapache.com/tools/online-compression-tool-compares-packer-jsmin-dojo-and-yui-compressor.html
http://www.askapache.com/online-tools/js-compress/
Good Luck!


Question:
I have a footer that is a 1 x 70px, which is set as the background and tiles horizonally.

In cases when the web page does not contain a lot of content on it, it will display the footer above where the footer should be. I want it to fill in with a solid color, so if they scroll down, it won't show the footer, then the white under the footer.

Here is the style I have for the footer.

.footer{
    background:#055830 url('/images/footer_tile.gif') repeat-x top left;
    color:#fff;
    font-size:12px;
    height: 70px;
    margin-top: 10px;
    font-family: Arial, Verdana, sans-serif;
    width:100%;
}

I want the footer to look like this:

Answer:
You can use
```
```
position:absolute;
bottom: 0;
```
```
to put the footer at the bottom always...


Question:
I'm trying to order items based on an attribute value:

<xsl:apply-templates select="Question">
    <xsl:sort order="ascending" select="@Value"></xsl:sort>
</xsl:apply-templates>

This does order them, but I could have values like 1,2,3, ... 10, 11, ... 20 and it will order them 1,10,11, ... 2,20... 3. etc.

I could also have values like 1.A, 1.B, 2.A, 2.B etc.

How can I order these values to take into account the numeric content and the alphabetic, in that priority?

Answer:
You can sort in numeric order using the
```
data-type
```
attribute:
```
```
<xsl:sort order="ascending" select="@Value" data-type="number"></xsl:sort>
```
```
The built-in sort function does not have support for more complex ordering (such as the multipart keys you mention).


Question: I'm asking in generalities - why would any server not set and return headers and/or status codes? I can't think of a good reason for this. Perhaps I'm overlooking something.

Answer:
The Status-Code is a required part of a HTTP Response.
By definition, the only reason for a server not to provide a Status-Line is that it is not a HTTP server.
RFC 2616, section 6: Response
.
Or said in a slightly less pedant way: if it does this, the server is hopelessly buggy and you should run away from it screaming.


Question:
I'm using a column of checkboxes in a YUI DataTable, I works fine. But I haven't found a way to put a name and value attribute so I can use when the form is submitted.

Thanks in advance.

Answer:
In order to get a name and value attribute, you use a checkbox like this:
```
```
<input type="checkbox" name="the_name" value="the_value" />
```
```
In your server-side code, you would look into the POST or GET data for the name of the checkbox. If it is there, the checkbox was checked. If it isn't there, the checkbox was not checked.
http://www.w3schools.com/HTMLDOM/dom_obj_checkbox.asp


Question:
I'm doing a personal organizer for learning purposes, and i've never worked with XML so i'm not sure if my solution is the best. Here's the basic structure for the XML file i came with:

<calendar>
    <year value="2008">
        <month value="october">
            <day value="16">
                <activity name="mike's birthday" time="21:00" address="mike's apartment" urgency="10">
                     activity description.
                </activity>
            </day>
        </month>
    </year>
</calendar>

The urgency attribute should be on a scale of 1 to 10.

I did a quick search on google and couldn't find a good example. Maybe that's not the best solution, and i'd like to know if its adequate. I'm doing the application in PHP if that has any relevance.

Answer:
Your way is quite adequate to me. However, I prefer child tags to attributes, so my way would be more like:
```
```
<activity>
  <name>Mike's Birthday</name>
  <time>2100</time>
  <address>Mike's Place</address>
  <urgency>10</urgency>
  <description>activity description</description>
</activity>
```
```
But like I said, your way is just fine.
Quick question, though - why not a database?


Question:
I have code similar to this filtering entries in an Array of Objects:

var filterRegex = new RegExp(".*blah.*","ig");
if (filterRegex.test(events[i].thing) && events[i].show) {
    console.log("SUCCESS: filtering thing " + i + " " + events[i].thing);
    events[i].show = false;
    numevents--;
}

I get inconsistent results with this if condition (checking with Firebug, both conditions are true individually, but sometimes the whole expression evaluates to false). HOWEVER, if I actually put an alert() called inside this if statement (like line 4), it becomes consistent and I get the result I want.

Can you see anything wrong with this logic and tell me why it's not always producing what is expected?

Answer:
I just can't imagine there is any situation where two JavaScript expressions evaluate to true individually, but not when combined.
Are you sure both expressions actually produce a boolean value every time? (Okay, to make
```
regex.test()
```
not produce a boolean value is difficult, but how about
```
event.show
```
. Might that be undefined at times?
Do you refer to the correct index when saying
```
event[0].show
```
, wouldn't you mean
```
event[i].show
```
?


Question: I need that my Apache require authentication only to external access but free in my local network. I have mod_user in my Apache.

Answer:
Not much into apache authentication, i just use tomcat from time to time to test some jsp.
Have you tried reading this?
http://httpd.apache.org/docs/1.3/howto/auth.html#basicconfig


Question:
I have an error handling method in my ApplicationController:

rescue_from ActiveRecord::RecordNotFound, :with => :not_found

def not_found(exception)
  @exception = exception
  render :template => '/errors/not_found', :status => 404
end

In RAILS_ROOT/app/views/errors/not_found.html.erb, I have this:

<h1>Error 404: Not Found</h1>
<%= debug @exception %>

But @exception is always nil there.  I've tried debug assigns, but that's always {}.  Do assigns not get copied when calling render :template?  If so, how can I get them?

I'm on edge Rails.

Answer:
That's odd, and I don't know why.  As an alternative, have you tried passing the exception as an explicit local?
```
```
def not_found(exception)
  render :template => '/errors/not_found',
         :status   => 404,
         :locals   => {:exception => exception}
end
```
```
and the view:
```
```

Error 404: Not Found

<%= debug exception %>
```
```


Question:
In the following one to many

CREATE TABLE source(id int, name varchar(10), PRIMARY KEY(id));
CREATE TABLE params(id int, source int, value int);

where params.source is a foreign key to source.id

INSERT INTO source values(1, 'yes');
INSERT INTO source values(2, 'no');

INSERT INTO params VALUES(1,1,1);
INSERT INTO params VALUES(2,1,2);
INSERT INTO params VALUES(3,1,3);

INSERT INTO params VALUES(4,2,1);
INSERT INTO params VALUES(5,2,3);
INSERT INTO params VALUES(6,2,4);

If i have a list of param values (say [1,2,3]), how do I find all the sources that have ALL of the values in the list (source 1, "yes") in SQL?

Thanks

Answer:
Edit
Modified to handle case where there can be multiple occurances of the value for a given source.
Try this:
```
```
SELECT
    *
FROM
    source
WHERE
    (
        SELECT COUNT(DISTINCT value)
        FROM params
        WHERE params.source = source.id
          AND params.value IN (1, 2, 3)
    ) = 3
```
```
You can rewrite it to a GROUP BY as well:
```
```
SELECT
    source.*
FROM
    source
    INNER JOIN params ON params.source = source.id
WHERE
    params.value IN (1, 2, 3)
GROUP BY
    source.id,
    source.name
HAVING
    COUNT(DISTINCT params.value) = 3
```
```


Question:
Is there a way to start an instance of eclipse, passing it some sort of parameter telling it to use a specific workspace?

The problem I'm trying to solve is that I have a workspace for work projects and one for personal projects. I'd like to be able to tie these to workspaces to separate shortcuts that I could launch independently.

Answer:
From
http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm
:
Use the following command-line argument:
```
```
-data your_workspace_location
```
```
For example,
```
```
-data c:\users\robert\myworkspace
```
```
you can also use UNIX-style relative path names such as
```
```
-data ../workspace
```
```
even under Windows, in case something doesnt like colons or backslashes in parameters, like Jumplist Launcher


Question:
I would like to have the same editor available on all of the platforms I frequent.

Emacs and Vi are not desired solutions.

Answer:
From
http://help.eclipse.org/help21/topic/org.eclipse.platform.doc.user/tasks/running_eclipse.htm
:
Use the following command-line argument:
```
```
-data your_workspace_location
```
```
For example,
```
```
-data c:\users\robert\myworkspace
```
```
you can also use UNIX-style relative path names such as
```
```
-data ../workspace
```
```
even under Windows, in case something doesnt like colons or backslashes in parameters, like Jumplist Launcher


Question:
I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file.  I've found many different web pages that claim they have a solution, but so far none of them work.

Here's what I have at the moment (leaving out the try-catch block):

URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);

The class that contains this code is in the com.xyz package, if that makes any difference.  That class also extends JFrame.  This code is throwing a MalformedUrlException on the first line.

Anyone have a solution that works?

Answer:
```
```
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
```
```
May or may not require a '/' at the front of the path.


Question:
I want to be able to introduce new 'tag lines' into a database that are shown 'randomly' to users. (These tag lines are shown as an introduction as animated text.)

Based upon the number of sales that result from those taglines I'd like the good ones to trickle to the top, but still show the others less frequently.

I could come up with a basic algorithm quite easily but I want something thats a little more 'statistically accurate'.

I dont really know where to start. Its been a while since I've done anything more than basic statistics. My model would need to be sensitive to tolerances, but obviously it doesnt need to be worthy of a PHD.

Edit: I am currently tracking a 'conversion rate' - i.e. hits per order. This value would probably be best calculated as a cumulative 'all time' convertsion rate to be fed into the algorithm.

Answer:
I would suggest randomly choosing with a weighting factor based on previous sales. So let's say you had this:
tag1 = 1 sale
tag2 = 0 sales
tag3 = 1 sale
tag4 = 2 sales
tag5 = 3 sales
A simple weighting formula would be 1 + number of sales, so this would be the probability of selecting each tag:
tag1 = 2/12 = 16.7%
tag2 = 1/12 = 8.3%
tag3 = 2/12 = 16.6%
tag4 = 3/12 = 25%
tag5 = 4/12 = 33.3%
You could easily change the weighting formula to get just the distribution that you want.


Question:
I want to combine these:

keys = ['name', 'age', 'food']
values = ['Monty', 42, 'spam']

Into a single dictionary:

{'name': 'Monty', 'age': 42, 'food': 'spam'}

Answer:
Like this:
```
```
keys = ['a', 'b', 'c']
values = [1, 2, 3]
dictionary = dict(zip(keys, values))
print(dictionary) # {'a': 1, 'b': 2, 'c': 3}
```
```
Voila :-)  The pairwise
```
dict
```
constructor and
```
zip
```
function are awesomely useful.


Question:
I have a HTML page that scrolls up and down (not a lot, but it does scroll). How can I set the scroll position in the page after executing some JavaScript?

I'm using jQuery to inject some additional HTML at the bottom of the page and I'd like to programmatically scroll to the position of that new content after it's added.

Answer:
Try using
```
window.scroll
```
.
Example:
```
```
// put the 100th vertical pixel at the top of the window
<button onClick="scroll(0, 100);">click to scroll down 100 pixels</button>
```
```


Question:
This page displays beautifully in firefox but i get all kinds of problems when testing the site in opera or internet explorer, mostly with the menu. I would like to know what techniques have caused this and how to avoid them.

http://www.jkhbdesign.se/

Edit 2: Here are some screenshots of some specific problems

The dropdown as it should look:

alt text http://nibbo.se/slask/correct.png

The way it looks in IE 7:

alt text http://nibbo.se/slask/dropdownie.png

The way it looks in Opera:

alt text http://nibbo.se/slask/dropdownopera.png

Answer:
At the very least you are going to have to deal with the fact that the CSS :hover is not supported in IE for any tag except the anchor tag.  You'll need to use onmouseover, onmouseout in IE to accomplish the same thing.  Or change the li:hover to an a:hover but that would be a bigger overhaul of your design I think.
Specifically, CSS like this:
```
```
ul.menu li:hover ul.submenu {
background:white none repeat scroll 0 0;
border:1px solid #A6A6A6;
display:block;
margin-left:-25px;
margin-top:23px;
padding:2px 0;
position:absolute;
}
```
```
Is not going to work properly in Internet Explorer.  I don't know about Opera.


Question:
Python 3.0 is in beta with a final release coming shortly.  Obviously it will take some significant time for general adoption and for it to eventually replace 2.x.

I am writing a tutorial about certain aspects of programming Python.  I'm wondering if I should do it in Python 2.x or 3.0? (not that the difference is huge)

a 2.x tutorial is probably more useful now, but it would be nice to start producing 3.0 tutorials.

anyone have thoughts?

(of course I could do both, but I would prefer to do one or the other)

Answer: It depends on your audience.  If it's a general audience, and you plan to leave it posted for a long time, I'd suggest looking forward and going with 3.0.  On the other hand if it's for a project or group that's going to be doing work in the near future, Python 2 probably make more sense.


Question: Is there a way in PHP to compile a regular expression, so that it can then be compared to multiple strings without repeating the compilation process?  Other major languages can do this -- Java, C#, Python, Javascript, etc.

Answer:
I'm not positive that you can. If you check out
Mastering Regular Expressions
, some PHP specific optimization techniques are discussed in Chapter10: PHP. Specifically the use of the S pattern modifier to cause the regex engine to "Study" the regular expression before it applies it. Depending on your pattern and your text, this could give you some speed improvements.
Edit
: you can take a peek at the contents of the book using
books.google.com
.


Question:
My code for sql connection using linq is:

var query1 = from u in dc.Usage_Computers
          where u.DomainUser == s3
          select u; // selects all feilds from table

GridView1.DataSource = query1;
GridView1.DataBind();

I have a field called "Operation" in the table "Domainuser" which has values like "1, 2, 3". When I populate these values to data grid I wanted to convert them to meaningful values like if the value of Operation is 1 then display in datagrid as "logon", if 2 then "logoff" etc...

How do i assign values for them after retrieving from database?

Answer:
I've done something similar using TemplateFields.  Using an ASP:Label bound to the property and adding an OnPreRender event handler for the control.  In the event handler for the control I translate the text based on it's current value and set the new value:
```
```
protected void label_OnPreRender( object sender, EventArgs e )
{
   Label l = (Label)sender;
   switch (l.Text) {
      case "1":
         l.Text = "Logon";
         break;
       ...
      default:
         break;
   }
}
```
```
If the form is in edit mode, you'll need to handle it differently.  You'll also probably need to add handlers for Inserting and Updating to the View control you are using to translate the data supplied by the page into its database representation.


Question:
I've got a table of hardware and a table of incidents. Each hardware has a unique tag, and the incidents are tied to the tag.

How can I select all the hardware which has at least one incident listed as unresolved?

I can't just do a join, because then if one piece of hardware had multiple unresolved issues, it would show up multiple times.

Answer:
```
```
select distinct(hardware_name)
from hardware,incidents
where hardware.id = incidents.hardware_id and incidents.resolved=0;
```
```


Question:
I have some C++ source code with templates maybe like this - doxygen runs without errors but none of the documentation is added to the output, what is going on?

///
/// A class
///
class A
{
  ///
  /// A typedef
  ///
  typedef B<C<D>> SomeTypedefOfTemplates;
};

Answer:
Yeah, so what is going on is the template instantiation is bogus. The ">>" like that is ambiguous and is meant to be a compile time error. You couldn't see it because maybe your compiler (VC++) let it slip by but I guess doxygen was stricter on that. Add a space like shown.
```
```
///
/// A class
///
class A
{
  ///
  /// A typedef
  ///
  typedef B<C<D> > SomeTypedefOfTemplates;
};
```
```


Question:
In ASP.NET what's the best way to do the following:

Show certain controls based on your rights?

For a gridview control, how do you show certain columns based on your role?

I'm thinking for number 2, have the data come from a role specific view on the database.

Answer:
Instead of actually using roles to hide/show certain controls, I would suggest having another layer of permissions for each role and show/hide based on those instead.
That way you can redefine what permissions a role has and won't have to change your code.
Also, this allows you to make new roles in the future and just assign a set of permissions to the role.
As for controls, yes... I would just set the Visible property on the control based on the user.IsInRole("permissionname") value.
For grids I would do the same... set the Visibility of the columns to the IsInRole boolean value.
```
```
//Delete Icon Column
gridViewContacts.Columns[0].Visible = user.IsInRole("DeleteAnyContact");
```
```
I would make create your permissions in a very granular nature.. such as
ViewAnyContact
ViewOwnContact
EditOwnContact
EditAnyContact
AddAnyContact
DeleteOwnContact
DeleteAnyContact
Etc...


Question: I have a 10 second sound effect wave file. What I would like to do is take that file and repeat it n number of times and then save the longer WAV file to disk. This way I can create a much longer background effect rather than auto-repeat on the media player which is a bit stuttered between repeats. I am trying to do this in C#.

Answer:
That's reasonably easy to do, given the
WAV file format
- assuming it's uncompressed audio (most WAV files are - or at least, they were last time I had anything to do with them).
There may well be audio APIs you can use to do this without getting stuck into the binary format, but I suspect they'd take as long to learn as just doing it yourself as you're not doing anything particularly complicated.


Question:
I'm sure this one is easy but I've tried a ton of variations and still cant match what I need.  The thing is being too greedy and I cant get it to stop being greedy.

Given the text:

test=this=that=more text follows

I want to just select:

test=

I've tried the following regex

(\S+)=(\S.*)
(\S+)?=
[^=]{1}
...

Thanks all.

Answer:
here:
```
```
// matches "test=, test"
(\S+?)=

or

// matches "test=, test" too
(\S[^=]+)=
```
```
you should consider using the second version over the first. given your string
```
"test=this=that=more text follows"
```
, version 1 will match
```
test=this=that=
```
then continue parsing to the end of the string. it will then backtrack, and find
```
test=this=
```
, continue to backtrack, and find
```
test=
```
, continue to backtrack, and settle on
```
test=
```
as it's final answer.
version 2 will match
```
test=
```
then stop. you can see the efficiency gains in larger searches like multi-line or whole document matches.


Question: I have a website that is deployed between 3 different environments - Dev, Stage, and Prod. For Stage and Prod, the site can resolve local paths to images with just the base url to the file, such as /SiteImages/banner.png. However, on the Dev server I have to hard code the full URL of the image path for the image to be resolved, such as http://server/folder/SiteImages/banner.png. Is there a setting I can flip to make the Dev server behave in the same manner as the other 2? I am using IIS 6.0 on a Win 2003 server.

Answer:
here:
```
```
// matches "test=, test"
(\S+?)=

or

// matches "test=, test" too
(\S[^=]+)=
```
```
you should consider using the second version over the first. given your string
```
"test=this=that=more text follows"
```
, version 1 will match
```
test=this=that=
```
then continue parsing to the end of the string. it will then backtrack, and find
```
test=this=
```
, continue to backtrack, and find
```
test=
```
, continue to backtrack, and settle on
```
test=
```
as it's final answer.
version 2 will match
```
test=
```
then stop. you can see the efficiency gains in larger searches like multi-line or whole document matches.


Question:
I have a table that has an insert trigger on it. If I insert in 6000 records into this table in one insert statement from a stored procedure, will the stored procedure return before the insert trigger completes?

Just to make sure that I'm thinking correctly, the trigger should only be called (i know 'called' isn't the right word) once because there was only 1 insert statement, right?

My main question is: will the sproc finish even if the trigger hasn't completed?

Answer:
Your insert trigger will run once for the entire insert statement. This is why it is important to use the
```
inserted
```
temporary table to see what has actually been inserted, and not just select the most recent single record, or something like that.
I just tested an insert and update trigger and indeed, they are considered part of the insert by sql server. the process will not finish until the trigger finishes.


Question:
I recently downloaded the source tarball for a GTK application that I'd like to improve.  It uses the standard ./configure and make build sequence.

The first time through, configure reported a bunch of unmet build dependencies, such as libgnomeui-2.0.  As I usually do, I had to manually go through and find the Debian *-dev package names corresponding to these dependencies... of course the names never match up quite the same, so it gets to be a real hassle.

So what occurred to me is... are there any helper tools to automatically install the build dependencies listed by the automake/autoconf configuration files???

(I already know about the dpkg-buildpackage tools, but in this case I am interested in building from a raw distribution-independent source tarball, not from the Debian package source.)

Answer:
```
apt-get build-dep <package>
```


Question:
Possible Duplicate:

  Most Useful Attributes in C#

besides:

[DefaultValue(100)]
[Description("Some descriptive field here")]
public int MyProperty{get; set;}

What other C# Attributes are useful for Properties, after learning these I feel like I'm Missing out.

Related Questions

Most Useful Attributes in C#

Answer:
```
```
[Browsable]
```
```
is a favorite of mine. (
MSDN
)


Question:
What would be the best way to port an existing Drupal site to a Django application?
I have around 500 pages (mostly books module) and around 50 blog posts. I'm not using any 3rd party modules.
I would like to keep the current URLS (for SEO purposes) and migrate database to Django. I will create a simple blog application, so migrating blog posts should be ok. What would be the best way to serve 500+ pages with Django? I would like to use Admin to edit/add new pages.

Answer:
All Django development is similar, and yours will fit the pattern.
Define the Django model for your books and blog posts.
Unit test that model using Django's built-in testing capabilities.
Write some small utilities to load your legacy data into Django.  At this point, you'll realize that your Django model isn't perfect.  Good.  Fix it.  Fix the tests.  Redo the loads.
Configure the default admin interface to your model.  At this point, you'll spend time  tweaking the admin interface.  You'll realize your data model is wrong.  Which is a good thing.  Fix your model.  Fix your tests.  Fix your loads.
Now that your data is correct, you can create templates from your legacy pages.
Create URL mappings and view functions to populate the templates from the data model.
Take the time to get the data model right.  It really matters, because everything else is very simple if your data model is solid.


Question:
Given the Below Tables.  How do I get the Distinct name given the other ID of 76 in LINQ?

**Table S**
SID   OtherID
------------------------------
1     77
2     76

**Table Q**
QID   SID  HighLevelNAme      LoweLevelName
---------------------------------------
10     1       Name1              Engine
11     1       Name1              SparkPlus
12     1       Name2              Seat
13     1       Name2              Belt
14     1       Name1              Oil

I want to return a list of

Name1
  Name2

The SQL to do this is

SELECT DISTINCT
    Q.HighLevelNAme
FROM S
JOIN Q ON Q.SID = S.SID
WHERE
        S.OtherID = 76

I also have Objects that represents each table.

An answer in VB or C# is acceptable.

Answer:
If you have the foreign key relationships defined in your database, and generated the LINQ classes via the designer, then the joins should be represented in the object model, right? So each QItem has a property SItem? If not, I guess you can use the Join extension method for that part.
Anyhow, I didn't test this IRL, but wouldn't it just be this?
```
```
var results = (from QItem in dataContext.QItems
                where QItem.SItem.OtherID == 76
                select QItem.HighLevelName).Distinct();
```
```


Question: Can somebody remember what was the command to create an empty file in MSDOS using BAT file?

Answer:
```
```
echo. 2>EmptyFile.txt
```
```


Question:
What is the best way to convert between HTML, XML, and XSL-FO in C#?

I already have the HTML (piped in from FCKEditor) and I'd like to print a PDF (I have an XSL->PDF converter). I just can't seem to find a library that will convert from HTML into anything XSL friendly.

Answer:
I'd first try
XSLT
.  When you're talking about formatting XML documents (and that's pretty much what you're talking about), that's the tool designed to do it.
From
Wiki
:
"The general idea behind XSL-FO's use
  is that the user writes a document,
  not in FO, but in an XML language.
  XHTML, DocBook, and TEI are all
  possibilities, but it could be any XML
  language. Then, the user obtains an
  XSLT transform, either by writing one
  themselves or by finding one for the
  document type in question. This XSLT
  transform converts the XML into
  XSL-FO."
You need an XSLT transform for HTML to XSL-FO.  Not sure where to get one, but apparently the concept isn't alien.


Question:
I imagine there are many of you out there who have developed an application online which automates a lot of processes and saves people at your company time and money.

The question is, what are your experiences with developing that application, having it all set in place, then "spicing" it up with some Ajax, so it makes for a better user experience?

Also, what libraries would you suggest using when adding Ajax to an already-developed web application?

Lastly, what are some common processes you see in web applications that Ajax does well with? For example, auto-populating the search box as you type.

Answer:
If you are using ASP.NET to write your applications, adding AJAX using ASP.NET AJAX is very straightforward and in many places will not require you to change any code at all except add two controls to the pages you want to modify.
This works using partial page loads. The controls you have to add (off the top off my head) are called something like
```
```
<asp:ScriptManager
```
```
and
```
```
<asp:UpdatePanel
```
```


Question:
In the Java code I'm working with we have an interface to define our Data Access Objects(DAO). Most of the methods take a parameter of a Data Transfer Object (DTO). The problem occurs when an implementation of the DAO needs to refer to a specific type of DTO. The method then needs to do a (to me completely unnecessary cast of the DTO to SpecificDTO. Not only that but the compiler can't enforce any type of type checking for specific implementations of the DAO which should only take as parameters their specifc types of DTOs.
My question is: how do I fix this in the smallest possible manner?

Answer:
You could use generics:
```
```
DAO<SpecificDTO> dao = new SpecificDAO();
dao.save(new SpecificDTO());
etc.
```
```
Your DAO class would look like:
```
```
interface DAO<T extends DTO> {
    void save(T);
}

class SpecificDAO implements DAO<SpecificDTO> {
    void save(SpecificDTO) {
        // implementation.
    }
    // etc.
}
```
```
SpecificDTO would extend or implement DTO.


Question:
I am having a problem with FCKeditor reverting html entities entered in the source view back to their original unicode representations.
For example when I enter &euro; into the source view, switch to html and then back to source view, the entity is replaced by an actual € symbol.
The bigger problem, as a result, is that this unicode character is then sent back to the server on submit causing character encoding issues with the underlying database table.
Anyone else come across this?
I have tried many combinations of config settings but all to no avail.

Answer:
What version of FCKeditor are you using?  The current version is 2.6.3.  I tested the € symbol in their demo by copying
```
€
```
into source view, switched back to display and then back to HTML the ASCII
```
€
```
was retained correctly.  As such it sounds like there might be a configuration problem with your install of FCKEditor or you need to upgrade.
Edit:
Just found this gem in the FCKEditor documentation:
http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/Configuration/Configuration_Options/ProcessNumericEntities


Question:
I just installed the first release candidate of Python 3.0 and got this error after typing:

>>> help('modules foo')

[...]
LookupError: unknown encoding: uft-8

Notice that it says uft-8 and not utf-8

Is this a py3k specific bug or a misconfiguration on my part? I do not have any other versions of Python installed on this French locale Windows XP SP3 machine.

Edit

A bug has been filled by Alex Coventry on October 16th.

Answer:
Looks like a typo in a config file somewhere, whether in the Py3k package or on your machine.  You might try installing the stable final Python 2.6 (which supports 3.0 syntax changes with imports from
```
__future__
```
), and if that works you should probably file a bug report.


Question:
I changed the folder that my WordPress installation was in.

However, this worked fine, except now all my images are not showing up.

The problem is that each post has the full url of the image in it. (not my doing, this seems to be the default setting)

Is there a tool or a quick fix available for this?

Answer:
You need to update your settings to reflect the directory change on the settings page in your admin section.
Edit:
Since it seems to be a problem in the posts themselves, you'll probably have to write a quick fixme script that runs through your post table searches for
```
'="/'
```
or something similar and updates any hardcoded links.


Question:
I have a textbox whose input is being handled by jQuery.

$('input.Search').bind("keyup", updateSearchTextbox);

When I press Enter in the textbox, I get a postback, which messes everything up. How can I trap that Enter and ignore it?

(Just to preempt one possible suggestion: The textbox has to be an <asp:textbox ... /> - I can't replace it with an <input ... />.)

Answer:
Your browser is automatically submitting the form when you press enter. To cancel this, add return false to your updateSearchTextBox function.
if that doesn't work, try this:
```
```
<script language="JavaScript">

function disableEnterKey(e)
{
     var key;
     if(window.event)
          key = window.event.keyCode; //IE
     else
          key = e.which; //firefox

     return (key != 13);
}

</script>
```
```
And in your codebehind:
```
```
textbox.Attributes.Add("OnKeyPress","return disableEnterKey(event)");
```
```


Question:
Our application is well structured (well we did our best!) and we have split the Model from the View, Now, we need to let some information to our client with a web access. We would like to build something small with IIS and some webform.

Here some information you might think are useful:

Our controller have Thread of database queries

Our database is PostGresql

All is build with C#2.0

We used a lot of databinding between our View and Controller in Winform.

Winform will stay for internal purpose, only a small part will be available on the Internet.

What are your suggestions for this kind of move?

Update

We will host the web in our company server so the database will stay inside the business. No need to duplicate data or any synchronization.

Answer:
The biggest challenge is going to be synchronizing your database between the local Winforms application and the hosted Webforms application. Once you do that, creating the web app is easy.
If your web application is read only, then you can set up replication. Find a tool that you like. Three that I found through a quick search are:
Slony-I
Mamoth Replicator
Bucardo
If your web application is not read only, then the problem is more difficult. You might want to consider upgrading to .NET 3.0 or 3.5 so you can use WCF. If there is a significant overlap in functionality, you might want to move your data to the web exclusively and expose it through WCF services.


Question:
I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception:

An error was encountered when parsing a DateTime value in the XML.

This seems to occur whenever the RSS feed expresses the publish date in the following format:

Thu, 16 Oct 08 14:23:26 -0700

If the feed expresses the publish date as GMT, things go fine:

Thu, 16 Oct 08 21:23:26 GMT

If there's some way to work around this  with XMLReaderSettings, I have not found it.  Can anyone assist?

Answer:
Interesting. It would looks like the datetime formatting is not one of the ones naturally expected by the datetime parser. After looking at the feed classes it does not look like you can inject in your own formatting convention for the parser and they it likely uses a specific scheme for validating the feel.
You may be able to change how the datetime parser behaves by modifying the
culture
. I have never done it before so I can't say for sure it would work.
Another solution night be to first transform the feed you are trying to read. Likely not the greatest but it could get you around the issue.
Good luck.


Question:
What's the best way to get an array of all elements in an html document with a specific CSS class using javascript?

No javascript frameworks like jQuery allowed here right now, and I could loop all the elements and check them manually myself.  I'm hoping for something a little more elegant.

Answer:
You can include a
getElementsByClass
function, or you can use
a jQuery selector
.
UPDATE:
The
implementation
mentioned by @
Shog9
is probably better than that above.


Question:
If I have a VB.Net function that returns an Int32, but uses an unsigned int (UInt32) for calculations, etc.  How can I convert a variable "MyUintVar32" with a value of say "3392918397 into a standard Int32 in VB.Net?

In c# if I just do a "return (int)(MyUintVar32);", I get -902048899, not an error.

I've tried several different methods.  What is the difference in the way c# handles these conversions versus VB.Net?

Answer:
It's not an optimal solution, but you can use BitConverter to get a byte array from the uint and convert the byte array to int.
```
```
Dim myUInt32 As UInt32 = 3392918397
Dim myInt32 As Int32 = BitConverter.ToInt32(BitConverter.GetBytes(myUInt32), 0)
```
```


Question:
Is it possible to somehow mark a System.Array as immutable.  When put behind a public-get/private-set they can't be added to, since it requires re-allocation and re-assignment, but a consumer can still set any subscript they wish:

public class Immy
{
    public string[] { get; private set; }
}

I thought the readonly keyword might do the trick, but no such luck.

Answer:
I believe best practice is to use
```
IList<>
```
rather than arrays in public APIs for this exact reason.
readonly
will prevent a member variable from being set outside of the constructor, but as you discovered, won't prevent people from assigning elements in the array.
See Eric Lippert's article
Arrays Considered Somewhat Harmful
for more information.
Edit:
Arrays can't be read only, but they can be converted to read-only IList implementations via
```
Array.AsReadOnly()
```
as @shahkalpesh points out.


Question: I notice that there's frequently an aspnet_client folder under the standard IIS web folder structure. What is this used for? Is it needed?

Answer: In the .NET 1.1 days and before, this folder provided ASP.NET with its JavaScript support for the validation controls and other functionality.  If you don't have a .NET 1.1 site  or older running it should be safe to delete it.  I would rename it first to ensure it doesn't cause any problems.


Question:
How can polymorphism be described in an easy-to-understand way?

We can find a lot of information about the subject on the Internet and books, like in Type polymorphism. But let's try to make it as simple as we can.

Answer:
The way I try and think of it is something that looks the same but can have different functionality depending on the instance. So you can have a type
```
```
interface IJobLoader
```
```
but depending on how it is used can have different functionality while still looking the same. You may have instances for BatchJobLoader, NightlyJobLoader etc
Maybe I am way off.


Question: Anyone know a QR decoder that works on mac or that might be online? I just need to decode one single image.

Answer:
Unfortunately, the most used library
libdecodeqr
is depends on OpenCV (gtk2) and it is too hard to compile it on OS X. (Tried to compile it because it is needed by
```
Image::DecodeQR
```
perl module - but unsuccessful).
Fortunately, found this link:
http://macscripter.net/viewtopic.php?id=37404
from citing the next:
Download the
ZBar source code
.
Unpack the the tarball, and open the resulting directory in a Terminal window.
Type
```
./configure --disable-video --without-python --without-gtk --without-qt
```
to configure the build process, limiting dependencies to ImageMagick.
Type "make" to invoke the build process.
Type "sudo make install", and enter an administrator password when prompted.
You will need
```
ImageMagick
```
what can be installed from
macports
.
After installing the ZBar, you can nicely decode qrcode with a command
```
```
zbarimg qrcode_file.png
```
```
Tested on OS X Mavericks 10.9.2 (and Lion/10.7.5)- and works nicely. Becasue it only depends on ImageMagick (exists in macports)- should be easily "compilable" on other OS X versions too.


Question: I saw this question asked about C# I would like an answer for PHP. I have some old code that has 4 pages of foreach loops and conditions which just makes it hard to read and follow. How would I make this more OO? I was thinking of using SPL Functions but don't fully understand whats involved yet.

Answer:
Start slowly.  refactor it a piece at a time.
If you are looping over a lot of arrays, look at the array functions like
```
array_map
```
,
```
array_walk
```
, and friends.  This is more a functional refactoring then an OO refactoring, but it would carry you pretty far.
If
it made sense to go more OO, then you will have some functions that you could then push into the proper classes as needed.


Question:
I continue to get this error:

Object '%s' cannot be renamed because the object participates in enforced dependencies

I need to find a script that will help me to find all the dependencies that there is with this table. I will need to drop them, rename, then bring them back.

SQL Server 2005

Answer:
To disable all contraints
```
```
sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
go
sp_msforeachtable "ALTER TABLE ? DISABLE TRIGGER  all"
go
```
```
To Re-enable
```
```
sp_msforeachtable"ALTER TABLE ? CHECK CONSTRAINT all"
go
sp_msforeachtable "ALTER TABLE ? ENABLE TRIGGER  all"
go
```
```
You should easily be able to adapt this to just one table.


Question:
I have a bunch of records in several tables in a database that have a "process number" field, that's basically a number, but I have to store it as a string both because of some legacy data that has stuff like "89a" as a number and some numbering system that requires that process numbers be represented as number/year.

The problem arises when I try to order the processes by number. I get stuff like:

1

10

11

12

And the other problem is when I need to add a new process. The new process' number should be the biggest existing number incremented by one, and for that I would need a way to order the existing records by number.

Any suggestions?

Answer:
Maybe this will help.
Essentially:
```
```
SELECT process_order FROM your_table ORDER BY process_order + 0 ASC
```
```


Question:
Assume a table with the following columns:

pri_id, item_id, comment, date

What I want to have is a SQL query that will delete any records, for a specific item_id that are older than a given date, BUT only as long as there are more than 15 rows for that item_id.

This will be used to purge out comment records older than 1 year for the items but I still want to keep at least 15 records at any given time.  This way if I had one comment for 10 years it would never get deleted but if I had 100 comments over the last 5 days I'd only keep the newest 15 records.  These are of course arbitrary record counts and date timeframes for this example.

I'd like to find a very generic way of doing this that would work in mysql, oracle, postgres etc.  I'm using phps adodb library for DB abstraction so I'd like it to work well with that if possible.

Answer:
Something like this should work for you:
```
```
delete
from
  MyTable
where
  item_id in
  (
    select
      item_id
    from
      MyTable
    group by
      item_id
    having
      count(item_id) > 15
  )
  and
    Date < @tDate
```
```


Question: What do I use to search for multiple words in a string?  I would like the logical operation to be AND so that all the words are in the string somewhere.  I have a bunch of nonsense paragraphs and one plain English paragraph, and I'd like to narrow it down by specifying a couple common words like, "the" and "and", but would like it match all words I specify.

Answer: Assuming PCRE (Perl regexes), I am not sure that you can do it at all easily.  The AND operation is concatenation of regexes, but you want to be able to permute the order in which the words appear without having to formally generate the permutation.  For N words, when N = 2, it is bearable; with N = 3, it is barely OK; with N > 3, it is unlikely to be acceptable.  So, the simple iterative solution - N regexes, one for each word, and iterate ensuring each is satisfied - looks like the best choice to me.


Question:
I'm building a code in which I'd like to be able to generate an event when the user changes the focus of the cursor from an Entry widget to anywhere, for example another entry widget, a button...

So far i only came out with the idea to bind to TAB and mouse click, although if i bind the mouse click to the Entry widget i only get mouse events when inside the Entry widget.

How can I accomplish generate events for when a widget loses cursor focus?

Thanks in advance!

Answer:
This isn't specific to tkinter, and it's not focus based, but I got an answer to a similar question here:
Detecting Mouse clicks in windows using python
I haven't done any tkinter in quite a while, but there seems to be "FocusIn" and "FocusOut" events. You might be able to bind and track these to solve your issue.
From:
http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm


Question:
Whats the best practice for setting up package structures in a Java Web Application?

How would you setup your src, unit test code, etc?

Answer:
You could follow maven's
standard project layout
. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,


Question:
Why is it that scanf() needs the l in "%lf" when reading a double, when printf() can use "%f" regardless of whether its argument is a double or a float?

Example code:

double d;
scanf("%lf", &d);
printf("%f", d);

Answer:
Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using
```
%lf
```
,
```
%lg
```
or
```
%le
```
(or
```
%la
```
in C99) to read in doubles.


Question:
Has anybody got any suggestions for a custom tabcontrol implemented in C# and which adheres to these criteria:

Allows the tabs to be placed along the side of the control.

Tab text must read horizontally.

Allow custom colouring.

Open source or no cost.

I prefer not to get my hands dirty with ownerdrawing if a solution already exists.

Answer:
You probably don't have a need for this anymore but anyone else who stumbles upon it might find it useful.
I found this tabcontrol on CodeProject it is also very easy to Draw your own tabs with it, they even give you a example on the site.
Y(et)A(nother)TabControl
A couple more tab controls.
TabStrip Control
TabStrips: A TabControl in the Visual Studio 2005 way!


Question:
I would like to know many minutes between 2 dates?

Example : Now - tommorow at the exact time would return me 1440.

Answer:
Look at the TimeSpan class.
```
```
DateTime date1 = DateTime.Now;
        DateTime date2 = DateTime.Now.AddDays(1);

        TimeSpan diff = date2.Subtract(date1);
        Console.WriteLine(diff.Minutes);
```
```


Question:
I have created HTTP handlers.

How do I create global variables for these handlers like I can with ASP.net web pages in  global.asax?

Answer:
Add the variables to the Application instance:
```
```
System.Web.HttpContext.Current.Application["MyGlobalVariable"] = myValue;
```
```
Or, if the variable only need to live for the life of an individual request, use the Context object's Items collection:
```
```
System.Web.HttpContext.Current.Items["MyGlobalVariable"] = myValue;
```
```
Again, that will live for only the life of a single request.


Question:
Trying to answer to another post whose solution deals with IP addresses and netmasks, I got stuck with plain bitwise arithmetic.

Is there a standard way, in Python, to carry on bitwise AND, OR, XOR, NOT operations assuming that the inputs are "32 bit" (maybe negative) integers or longs, and that the result must be a long in the range [0, 2**32]?

In other words, I need a working Python counterpart to the C bitwise operations between  unsigned longs.

EDIT: the specific issue is this:

>>> m = 0xFFFFFF00   # netmask 255.255.255.0
>>> ~m
-4294967041L         # wtf?! I want 255

Answer:
```
```
from numpy import uint32
```
```


Question:
I'd like to make a click event fire on an <input type="file"> tag programmatically.

Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.

I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.

Answer:
You cannot do that in all browsers, supposedly IE
does
allow it, but Mozilla and Opera do not.
When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.
I don't know why you cannot do it, but one thing that
is
a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.


Question:
I'm loading an image from a file, and I want to know how to validate the image before it is fully read from the file.

string filePath = "image.jpg";
Image newImage = Image.FromFile(filePath);

The problem occurs when image.jpg isn't really a jpg.  For example, if I create an empty text file and rename it to image.jpg, an OutOfMemory Exception  will be thrown when image.jpg is loaded.

I'm looking for a function that will validate an image given a stream or a file path of the image.

Example function prototype

bool IsValidImage(string fileName);
bool IsValidImage(Stream imageStream);

Answer:
I would create a method like:
```
```
Image openImage(string filename);
```
```
in which I handle the exception. If the returned value is Null, there is an invalid file name / type.


Question:
our partners sites leverages our iframes in their own websites. I was wondering if there is a way to track the analytics on the iframes.

The problem is, if we also utilize these iframes on our own website, how do i avoid duplicate tracking where a visit is counted on our domain's analytics and also counted again in iframes? is there a way to get around it?

Answer:
Adding the Google Analytics code to the iframe should work just fine. The easiest way to avoid duplicate tracking is probably to add a query parameter like ?partner=foo to the URLs that your partners use. You can check for your own site's value and not run the Google Analytics code at all, and also pass the partner ID to Google so that you can break down the reports by partner.
EDIT
Use ?utm_source=foo as the partner parameter, and Google Analytics will pick it up without you doing anything. Filter out your own impressions with
```
```
if ( location.href.indexOf("utm_source=mysite") < 0 )
{
    // Google Analytics code here
}
```
```
or you can set up a filter on your Google Analytics profile to filter them out.


Question: Could anyone please introduce books/papers/articles that I should read If I want to write a high-performance RPC server in Java, which handles large number of concurrent connections(C10K or over), is fault-tolerant, can be scaled out, and maintains high throughput? Thanks!

Answer:
A few years ago Ebay reimplemented their platform in Java and there are a few white papers and presentations floating around that describe it. Here are some:
http://www.sun.com/2003-0624/feature/index.html
http://www.infoq.com/presentations/shoup-ebay-architectural-principles
http://www.infoq.com/articles/ebay-scalability-best-practices
Supposedly there is a link to a relevant white paper somewhere on this site, though I haven't found it yet:
http://www.corej2eepatterns.com/


Question:
We have a proprietry system that we develop scripting code in.
We currently do not have a developer environment (apart from Notepad++) and cannot debug or compile this code.  We have to submit it to the vendor to insert the code into the test or live system.
The language is essentially C like and has the same syntax.
Basically we want a tool to be able to simply check the syntax of chunks of code we send to the vendor.
Does a tool exist that will do this for me?

Answer:
If it's really  the same syntax as C you can use a C compiler.  Usually there's a syntax check only option (
```
/Zs
```
for MSVC).
I'm not sure how many problems you'll run into since C compilers are pretty picky, and being "like C" is not the same as being C.
It does seem odd that you're being asked to develop code without having any capability to run or even compile it.  Kind of like writing a book without being able to proof read it before publishing.  I have a hard time getting even "Hello World" programs to compile & run without some sort of goof-up on the very first go.


Question: How do I go about setting a <div> in the center of the screen using jQuery?

Answer:
I like adding functions to jQuery so this function would help:
```
```
jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) +
                                                $(window).scrollTop()) + "px");
    this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) +
                                                $(window).scrollLeft()) + "px");
    return this;
}
```
```
Now we can just write:
```
```
$(element).center();
```
```
Demo:
Fiddle
(with added parameter)


Question:
I am using log.properties to configure logging for a Java app. Each class gets its own logger named after itself (e.g. com.company.program.ClassX).

I want to set a custom formatter for just one log, and leave the handler with the SimpleFormatter. Is this possible?

I am not interested in using log4j or another of the other logging suites. I am well aware of them. Nor am I interested in configuring a customer formatter for the logger through code, although if that is the only way to do it, it would be nice to know. Google isn't helping, and I am having problems testing this myself.

Answer:
I believe this is a limitation of Java logging.
You should decide to become interested in log4j.  java.util.logging is only marginally better than
```
System.out.println
```


Question:
I have a drop down like this on my page:

<p>
     <%= f.label :episode_id %><br />
     <%= f.collection_select(:episode_id, @episodes, :id, :show) %>
</p>

An episode has an id and belongs_to to a show which has a name.  In the dropdown, I'd like to display the show name.  :show.name doesn't work to display the name.  How do I do this?

Answer:
One way to do this would be to create a method in your Episode class called
```
show_name
```
like so:
```
```
def show_name
  show.name
end
```
```
The last symbol you are passing into collection_select is the name of the method that you want to call to get the option text.


Question:
Could somebody please point me in the right direction for learning how to do networking in C#/.net 3.5? Code samples and explanations are welcome. Basically I am looking for how to do asynchronous/multithreaded server/client models.

I am fairly comfortable with the basics in how to accomplish this in C++ with WinSock but though all of my research cannot seem to grasp this concept in C#.

Thanks for any assistance you can provide :)

Answer:
In .NET 3.5 world you should definitely learn
Windows Communication Foundation
- .NET framework for networking.
Useful link:
Synchronous and Asynchronous Operations (in WCF)
You can find useful WCF information on StackOverflow browsing posts
tagged with WCF
tag


Question:
How can I modify the NSDatePickerElementFlags for the NSDatePicker in row templates for NSDate properties returned by [NSPredicateRowEditorTemplate templatesWithAttributeKeyPaths:inEntityDescription:]? I would like the NSDatePicker to show hrs:minutes as well as the date.

Update
I've added an answer below, gleaned from the cocoa-dev list.

Answer:
In .NET 3.5 world you should definitely learn
Windows Communication Foundation
- .NET framework for networking.
Useful link:
Synchronous and Asynchronous Operations (in WCF)
You can find useful WCF information on StackOverflow browsing posts
tagged with WCF
tag


Question: Upon page load I want to move the cursor to a particular field.  No problem.  But I also need to select and highlight the default value that is placed in that text field.

Answer:
From
http://www.codeave.com/javascript/code.asp?u_log=7004
:
```
```
var input = document.getElementById('myTextInput');
input.focus();
input.select();
```
```
```
```
<input id="myTextInput" value="Hello world!" />
```
```


Question:
I've read a number of posts touting the merits of migrating from VS 2005 to 2008. However, I'd love to hear what the various pitfalls are in actually doing the migration. We're about to migrate and I'd prefer knowing what speed bumps to anticipate and plan for instead of discovering them by surprise along the way. Any helpful guidance on this would be much appreciated so that the process is as painless as possible.

Oh, we're primarily a C++ development house, with a handful of moderate size products and a bunch of small ancilliary tools. We use external makefiles for everything so that all builds are readily automated. Specific insights about what to expect when migrating this type of development operation would be most helpful.

Thanks in advance for the help!

Answer:
The
only
issue I have had with Visual Studio 2008 is that it was quite slow until I tweaked it a bit.  I was running into a delay coming out of Debug mode on the order of 8-10 seconds or so - was
quite
annoying.  SP1 helped out as did modifying some IE settings.
But otherwise, I've been happy with it.


Question:
I have a xml which is max 3 levels deep. Now by using C# or Xpath what the best method to check the whether all the child nodes under a parent node are empty.

Thanks in Advance.

Answer:
Given a sample document of:
```
```
<foo>
  <bar>
    <baz/>
    <baz>Hello, world!</baz>
    <baz><qux/></baz>
  </bar>
</foo>
```
```
This expression tells you which children of
```
foo/bar
```
have any child elements:
```
```
foo/bar/*[count(*)>0]
```
```
This expression tells you which children of
```
foo/bar
```
have any child text nodes:
```
```
foo/bar/*[text()]
```
```
So to ensure that all children are empty (no child elements or text nodes), ensure that this expression returns true:
```
```
not(foo/bar/*[count(*)>0 or text()])
```
```


Question: What is an NP-complete problem? Why is it such an important topic in computer science?

Answer:
Honestly,
Wikipedia
might be the best place to look for an answer to this.
If NP = P, then we can solve very hard problems much faster than we thought we could before.  If we solve only one NP-Complete problem in P (polynomial) time, then it can be applied to all other problems in the NP-Complete category.


Question: What control type should I use - Image, MediaElement, etc.?

Answer:
I, too, did a search and found several different solution in just a thread on the old MSDN forums. (link no longer worked so I removed it)
The simplest to execute seems to be to use a WinForms
```
PictureBox
```
control, and went like this (changed a few things from the thread, most of it the same).
Add a reference to
```
System.Windows.Forms
```
,
```
WindowsFormsIntegration
```
, and
```
System.Drawing
```
to your project first.
```
```
<Window x:Class="GifExample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
    Loaded="Window_Loaded" >
    <Grid>
        <wfi:WindowsFormsHost>
            <winForms:PictureBox x:Name="pictureBoxLoading">
            </winForms:PictureBox>
        </wfi:WindowsFormsHost>
    </Grid>
</Window >
```
```
Then in the
```
Window_Loaded
```
handler, you would set the
```
pictureBoxLoading.ImageLocation
```
property to the image file path that you want to show.
```
```
private void Window_Loaded(object sender, RoutedEventArgs e)
{
    pictureBoxLoading.ImageLocation = "../Images/mygif.gif";
}
```
```
The
```
MediaElement
```
control was mentioned in that thread, but it is also mentioned that it is a rather heavy control, so there were a number of alternatives, including at least 2 homebrewed controls based on the
```
Image
```
control, so this is the simplest.


Question:
I'm quite new to programming, and I was wondering if there is a good source of well-programmed non-standard C code and libraries.

I Googled and didn't find anything.
I was a bit surprised by this, especially because I used to search for many Python examples and libraries and never had trouble finding anything.

I already use standard libraries such as stdio.c, stdlib.c, and math.c, but I want to use some more specific C modules. A graph processing library, for example. (I don't really need this one, just a collection of C, not C++ or C#, resources and examples)

Answer:
there is no "centralized" source for C libraries... at least nothing along the lines of CPAN for Perl or the Python Package Index for Python.
Since C is sort of the "default" language for systems programming, it's often unstated that libraries are written for C.  You may want to try Freshmeat.net's
Advanced Search
, since it's centered on Unix software, and there are a lot of C libraries posted there.  For example, here's what I come up with searching for "graph library":
http://freshmeat.net/search/?section=projects&q=%2Bgraph+%2Blibrary
, and you can filter those results by language, license, etc.
(And your English is quite fine!  Which I can't say about all the posters on here :-p)


Question: Looking for an example in linq about how to insert a row of a gridview into datacontext.

Answer:
That was asked
here
a couple of weeks ago. What it comes down to is, there are many legal addresses that an easy regex won't match. It takes a truly insane regex to match the majority of legal addresses. And even then, a syntactically legal address doesn't guarantee the existence of an account behind it - take foo@example.invalid, for example.


Question:
I have a question about using os.execvp in Python. I have the following bit of code that's used to create a list of arguments:

args = [ "java"
       , classpath
       , "-Djava.library.path=" + lib_path()
       , ea
       , "-Xmx1000m"
       , "-server"
       , "code_swarm"
       , params
       ]

When I output a string using " ".join(args) and paste that into my shell prompt, the JVM launches fine, and everything works. Everything works if I use os.system(" ".join(args)) in my Python script, too.

But the following bit of code does not work:

os.execvp("java", args)

I get the following error:

Unrecognized option: -classpath [and then the classpath I created, which looks okay]
Could not create the Java virtual machine.

So what gives? Why does copying/pasting into the shell or using os.system() work, but not os.execvp()?

Answer:
If your "classpath" variable contains for instance "-classpath foo.jar", it will not work, since it is thinking the option name is "-classpath foo.jar". Split it in two arguments: [..., "-classpath", classpath, ...].
The other ways (copy and paste and system()) work because the shell splits the command line at the spaces (unless they are escaped or quoted). The command line is in fact passed down to the called program as an array (unlike on Windows), and the JVM is expecting to find an element with only "-classpath" followed by another element with the classpath.
You can see the difference for yourself by calling the following small Python script instead of the JVM:
```
```
#!/usr/bin/python
import sys
print sys.argv
```
```


Question:
I'm doing some optimising for my site and am trying to figure out just how big some inline code can be before it can justify having it's own file instead of being written inline.

My guess on how to measure it would be that the amount of code (CSS or JS in this case) would need to be bigger than the HTTP packets sent and received to get a 304 response.

Please ignore the fact that it's a good practice to keep styles and javascript out of the HTML page and think only in terms of browser performance. :)

Answer:
Honestly, in terms of browser performance, separating your CSS & JS files out and properly setting expires headers so they are cached will
increase
performance, not degrade it. The browser will cache it and never request it again, which reduces the amount of data transferred during multiple page views.
Only if a majority of your audience is coming to your website with an empty cache
and
only viewing 1 page would inlining CSS & JS help.
See:
http://developer.yahoo.com/performance/
http://www.ryandoherty.net/2008/10/12/optimizing-openspacebook/


Question:
Newbie question...

If I have a file that is in the root of the web app.   How do I programmaticaly query the path of that file?  ie, what directory it is in?

Answer:
```
```
System.Web.HttpServerUtility.MapPath( "~/filename.ext" );
```
```
will give you the physical (disk) path, which you would use with System.IO methods and such.
```
```
System.Web.Hosting.VirtualPathUtility.ToAbsolute( "~/filename.ext" );
```
```
will give you the "absolute" virtual path.  This won't be the full url, but isn't necessarily the root of the domain, either.  It could be something like
```
/admin/filename.ext
```
if the application is rooted in a subdirectory.


Question:
In spring you can initialize a bean by having the applicationContext.xml invoke a constructor, or you can set properties on the bean.  What are the trade offs between the two approaches?  Is it better to have a constructor (which enforces the contract of having everything it needs in one method) or is it better to have all properties (which gives you flexibility to only inject selectively for example when unit testing.)

What are the trade offs (between writing a bean that uses a constructor to establish it's initial state, or using properties and perhaps an afterProperties() method) ?

Answer:
IMO the major advantage of constructor injection is that it is compatible with immutability. However, if a class has more than about 3 dependencies, this requires providing a constructor which takes a large number of parameters, which is unwieldy.
When using setter-injection, I prefer to use the
```
@PostConstruct
```
annotation to identify the initialization method. This involves looser coupling to the Spring framework than the
```
afterProperties()
```
method you mention (actually, I think it's
```
afterPropertiesSet()
```
). Another option is the init method attribute of the
```
<bean>
```
element.


Question:
I am attempting to insert a Canvas3D object inside a Swing JPanel, but the code doesn't seem to be working (i.e. nothing happens):

        Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
        SimpleUniverse universe = new SimpleUniverse(canvas);
        BranchGroup root = new BranchGroup();
        root.addChild(new ColorCube());
        universe.addBranchGraph(root);
        universe.getViewingPlatform().setNominalViewingTransform();
        canvasPanel.add(canvas);

What am I missing? The JPanel was created using NetBean's Visual Editor.

Answer:
Canvas3D needs a size passed to it; setting the preferred configuration from SimpleUniverse is not enough. In my case, that meant this code:
```
// 3D canvas initialization
        Canvas3D canvas = new Canvas3D(SimpleUniverse.getPreferredConfiguration());
        SimpleUniverse universe = new SimpleUniverse(canvas);
        BranchGroup root = new BranchGroup();
        root.addChild(new ColorCube());
        universe.addBranchGraph(root);
        universe.getViewingPlatform().setNominalViewingTransform();
canvas.setSize(100, 100);
canvasPanel.add(canvas);
```


Question:
Similar question as this one but for a Microsoft Environment.

Email --> Exchange Server -->[something]

For the [something] I was using Outlook 2003 & C# but it feels messy (A program is trying to access outlook, this could be a virus etc)

Microsoft.Office.Interop.Outlook.Application objOutlook = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace objNS = objOutlook.GetNamespace("MAPI");
objNS.Logon("MAPIProfile", "MAPIPassword", false, true);

Is this the best way to do it?  Is there a better way of retrieving and processing emails in a Microsoft environment???

Answer:
This
library provides you basic support for the POP3 protocol and MIME, you can use it to check specified mailboxes and retrieve emails and attachments, you can tweak it to your needs.
Here is
another library
, this one is for the IMAP protocol, it's very basic but also allows you to fetch complete messages, including attachments...


Question: Should I be writing Doc Comments for all of my java methods?

Answer:
I
thoroughly
document every public method in every API class.  Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc.  I also document every protected method in every API class, though to a lesser extent.  This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit.  Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.


Question: The IntelliJ IDEA short-cut to reformat source code is Ctrl+Alt+L.  This happens to lock the screen in KDE (Gnome too?).  How can I disable this so IntelliJ receives the key sequence?

Answer:
Under the K menu, go to the Control Center.
Regional & Accessibility |
Keyboard Shortcuts |
Shortcut Schemes tab,
Global Shortcuts tab.
In the search box, type "lock", which should narrow the visible shortcuts and show the
Ctrl
+
Alt
+
L
one ("Lock Session").
Underneath, click None.
Click the Apply button.
On KDE Plasma 5 go to System Settings | Desktop Behaviour | Screen Locking
Here you will find a "Keyboard Shortcut" option. Change it to something else or set to none


Question:
Does Linux/Unix/Posix provide an API to user-space applications to access a monotonically increasing clock, with centisecond to millisecond accuracy?

On Linux, /proc/uptime provides a string-based representation of a floating point number of the number of seconds the system has been up.

gettimeofday(2) does not provide a monotonically increasing clock.

I could use getitimer(2) in the ITIMER_REAL time domain, set the timer to start at the (platform dependent) maximum and ignore the signal generated, but according to the man page the longest the timer can run for is approximately 100 days, which is shorter than my expected run time.

Answer:
There is clock_gettime:
```
```
struct timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
```
```


Question: Are there any issues with running an asp.net 1.1 application under windows server 2008 64-bit web edition?

Answer:
I have never tried it myself, but I did find the following pages that you might find interesting:
This blog
has an in depth walk through of configuring ASP.NET 1.1 on Windows Server 2008. The author does not say if it is x86 or x64, so I would just assume its x86. But either way, it looks like the author had to jump through some hoops to get the ISAPI filter setup correctly.
I also found
this thread
on the IIS7 forums where someone discuses having poor performance from ASP.NET 1.1. on x64 Win2k8. So from poor performance I would assume it worked to some extent. Unfortunately towards the end of the thread the author mentions encounter 500 errors, and then the discuss stops :-(
So from what I've read I would guess that its possible, but I would also guess that you would have less hassle if you could find some alternative that didn't involve both II7 and x64.


Question: When using __import__ with a dotted name, something like: somepackage.somemodule, the module returned isn't somemodule, whatever is returned seems to be mostly empty! what's going on here?

Answer:
From the python docs on
```
__import__
```
:
```
```
__import__( name[, globals[, locals[, fromlist[, level]]]])
```
```
...
When the name variable is of the form
  package.module, normally, the
  top-level package (the name up till
  the first dot) is returned, not the
  module named by name. However, when a
  non-empty fromlist argument is given,
  the module named by name is returned.
  This is done for compatibility with
  the bytecode generated for the
  different kinds of import statement;
  when using "import spam.ham.eggs", the
  top-level package spam  must be placed
  in the importing namespace, but when
  using "from spam.ham import eggs", the
  spam.ham subpackage must be used to
  find the eggs variable. As a
  workaround for this behavior, use
  getattr() to extract the desired
  components. For example, you could
  define the following helper:
```
```
def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod
```
```
To paraphrase:
When you ask for
```
somepackage.somemodule
```
,
```
__import__
```
returns
```
somepackage.__init__.py
```
, which is often empty.
It will return
```
somemodule
```
if you provide
```
fromlist
```
(a list of the variable names inside
```
somemodule
```
you want, which are not actually returned)
You can also, as I did, use the function they suggest.
Note: I asked this question fully intending to answer it myself. There was a big bug in my code, and having misdiagnosed it, it took me a long time to figure it out, so I figured I'd help the SO community out and post the gotcha I ran into here.


Question:
I'm using the following view function to iterate over all items in the database (in order to find a tag), but I think the performance is very poor if the dataset is large.
Any other approach?

def by_tag(tag):
return  '''
        function(doc) {
            if (doc.tags.length > 0) {
                for (var tag in doc.tags) {
                    if (doc.tags[tag] == "%s") {
                        emit(doc.published, doc)
                    }
                }
            }
        };
        ''' % tag

Answer:
You are very much on the right track with the view. A list of thoughts though:
View generation is incremental. If you're read traffic is greater than you're write traffic, then your views won't cause an issue at all. People that are concerned about this generally shouldn't be. Frame of reference, you should be worried if you're dumping hundreds of records into the view without an update.
Emitting an entire document will slow things down. You should only emit what is necessary for use of the view.
Not sure what the val == "%s" performance would be, but you shouldn't over think things. If there's a tag array you should emit the tags. Granted if you expect a tags array that will contain non-strings, then ignore this.


Question:
I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:

class Enum<E extends Enum<E>>

Could someone explain how to interpret this type parameter? Bonus points for providing other examples of where a similar type parameter could be used.

Answer:
It means that the type argument for enum has to derive from an enum which itself has the same type argument. How can this happen? By making the type argument the new type itself. So if I've got an enum called StatusCode, it would be equivalent to:
```
```
public class StatusCode extends Enum<StatusCode>
```
```
Now if you check the constraints, we've got
```
Enum<StatusCode>
```
- so
```
E=StatusCode
```
. Let's check: does
```
E
```
extend
```
Enum<StatusCode>
```
? Yes! We're okay.
You may well be asking yourself what the point of this is :) Well, it means that the API for Enum can refer to itself - for instance, being able to say that
```
Enum<E>
```
implements
```
Comparable<E>
```
. The base class is able to do the comparisons (in the case of enums) but it can make sure that it only compares the right kind of enums with each other. (EDIT: Well, nearly - see the edit at the bottom.)
I've used something similar in my C# port of ProtocolBuffers. There are "messages" (immutable) and "builders" (mutable, used to build a message) - and they come as pairs of types. The interfaces involved are:
```
```
public interface IBuilder<TMessage, TBuilder>
  where TMessage : IMessage<TMessage, TBuilder>
  where TBuilder : IBuilder<TMessage, TBuilder>

public interface IMessage<TMessage, TBuilder>
  where TMessage : IMessage<TMessage, TBuilder>
  where TBuilder : IBuilder<TMessage, TBuilder>
```
```
This means that from a message you can get an appropriate builder (e.g. to take a copy of a message and change some bits) and from a builder you can get an appropriate message when you've finished building it. It's a good job users of the API don't need to actually care about this though - it's horrendously complicated, and took several iterations to get to where it is.
EDIT: Note that this doesn't stop you from creating odd types which use a type argument which itself is okay, but which isn't the same type. The purpose is to give benefits in the
right
case rather than protect you from the
wrong
case.
So if
```
Enum
```
weren't handled "specially" in Java anyway, you could (as noted in comments) create the following types:
```
```
public class First extends Enum<First> {}
public class Second extends Enum<First> {}
```
```
```
Second
```
would implement
```
Comparable<First>
```
rather than
```
Comparable<Second>
```
... but
```
First
```
itself would be fine.


Question: The published code for Palm OS applications doesn't include standard headers, but instead uses Palm OS APIs for things like StrCopy and MemMove.  Can I use standard headers and functions or do I need to convert my code to use the Palm OS versions?

Answer:
It depends on the compiler and what version of the tools you're using.  In general, if you can use Palm OS APIs, you'll probably work better on the platform, but both CodeWarrior and prc-tools had some library functions implemented.
In CW for Palm OS V9, there's a pretty full version of the Metrowerks Standard Library (MSL).  Most of MSL C++ is there giving you access to STL and other constructs.  On the C front, you've got most of the standard C headers for memory management and string functions.  However, it omits implementations for locales, math, signals, and standard I/O.
To use the library, you need to make sure you link with the MSL C/C++ libraries.  This can be set when you create your project in the wizard or added later by modifying the access paths and adding the appropriate static libraries for your targets.


Question: How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.

Answer:
You should have a look at
numpy
if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.
```
```
from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.
```
```
You can also have a look at the
array
module, which is a much more efficient implementation of lists when you have to deal with only one data type.


Question:
I am seeing following exception when I try to use dynamic proxy

 com.intellij.rt.execution.application.AppMain DynamicProxy.DynamicProxy
Exception in thread "main" java.lang.IllegalArgumentException: interface Interfaces.IPerson is not visible from class loader
    at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353)
    at java.lang.reflect.Proxy.newProxyInstance(Proxy.java:581)
    at DynamicProxy.Creator.getProxy(Creator.java:18)
    at DynamicProxy.DynamicProxy.main(DynamicProxy.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)

Any idea what I need to do to resolve it

Answer:
When your
```
DynamicProxy
```
tries to do
```
Class.forName(youInterfaceClass.getName())
```
the resulting
```
java.lang.Class
```
instance is different from the one you passed when you created the proxy. In other words you have two class objects with the same name and the proxy is not sure which one is the right one (doesn't matter whether they are the same).
Usually, this happens when the interface you are trying to proxy is in a library loaded through two different classloaders (i.e. Tomcat's 'common' and 'application').
If this doesn't help, please post more info on your application - especially if you are using any application server, Spring or OSGi.


Question:
Working with Mircosoft Office Sharepoint Server 2007 (standard edition) what is the best way to place a site collection being developed under version control?  We're using Subversion for all our other (non-sharepoint) projects but I'm just not sure how to approach MOSS.

What needs to be placed under version control to ensure we have everything we need to rebuild the Sharepoint Environment?

Answer:
The question is sort of vague has you do not mention how you develop it. If you're just doing out of the box modifications on a site collection via the interface you have available in sharepoint it sounds like you need to do some kind of "backup". I don't think you can export a site collection as a template :P
If you're doing actual development, coding features that do site provisioning, web parts for that, custom page layouts and whatnot, I would suggestion copying the structure you have in the /12/ hive on your sharepoint in your visual studio. Place all the artifacts you have in the right folders in your solution and that makes it very easy to deploy, either just by copying and calling some stsadm commands or by making a new manifest.xml file and a .ddf file which you can then add to your solution repository on your sharepoint installation.


Question:
What are the lesser-known but useful features of the Haskell programming language. (I understand the language itself is lesser-known, but work with me. Even explanations of the simple things in Haskell, like defining the Fibonacci sequence with one line of code, will get upvoted by me.)

Try to limit answers to the Haskell core

One feature per answer

Give an example and short description of the feature, not just a link to documentation

Label the feature using bold title as the first line

Answer:
Optional Layout
You can use explicit braces and semicolons instead of whitespace (aka layout) to delimit blocks.
```
```
let {
      x = 40;
      y = 2
     } in
 x + y
```
```
... or equivalently...
```
```
let { x = 40; y = 2 } in x + y
```
```
... instead of ...
```
```
let x = 40
    y = 2
 in x + y
```
```
Because layout is not required, Haskell programs can be straightforwardly produced by other programs.


Question:
Since we cannot setup Eclipse's RSE to use at the tool for remote editing, I have installed Unison. But how can I get Eclipse to automatically run unison on every file save? Is there an eclipse plugin available for this?

TIA

Answer:
Depending on the importance, I would write a simple plugin to handle this.
EDIT:
All you
really
need to do is this:
1) Create the plugin from the templates with the RCP\PDE Eclipse install
2) Add the following code to your activator...
```
```
@Override
public void start( final BundleContext context ) throws Exception {
    super.start( context );
    plugin = this;

    ICommandService commandService = (ICommandService)plugin.getWorkbench().getService( ICommandService.class );
    commandService.addExecutionListener( new IExecutionListener() {

        public void notHandled( final String commandId, final NotHandledException exception ) {}

        public void postExecuteFailure( final String commandId, final ExecutionException exception ) {}

        public void postExecuteSuccess( final String commandId, final Object returnValue ) {
            if ( commandId.equals( "org.eclipse.ui.file.save" ) ) {
                // add in your action here...
                // personally, I would use a custom preference page,
                // but hard coding would work ok too
            }
        }

        public void preExecute( final String commandId, final ExecutionEvent event ) {}

    } );
}
```
```


Question:
C++ guarantees that variables in a compilation unit (.cpp file) are initialised in order of declaration. For number of compilation units this rule works for each one separately (I mean static variables outside of classes).

But, the order of initialization of variables, is undefined across different compilation units.

Where can I see some explanations about this order for gcc and MSVC (I know that relying on that is a very bad idea - it is just to understand the problems that we may have with legacy code when moving to new GCC major and different OS)?

Answer:
As you say the order is undefined across different compilation units.
Within the same compilation unit the order is well defined: The same order as definition.
This is because this is not resolved at the language level but at the linker level. So you really need to check out the linker documentation. Though I really doubt this will help in any useful way.
For gcc: Check out
ld
I have found that even changing the order of objects files being linked can change the initialization order. So it is not just your linker that you need to worry about, but how the linker is invoked by your build system. Even try to solve the problem is practically a non starter.
This is generally only a problem when initializing globals that reference each other during their own initialization (so only affects objects with constructors).
There are techniques to get around the problem.
Lazy initialization.
Schwarz Counter
Put all complex global variables inside the same compilation unit.
Note 1: globals:
Used loosely to refer to static storage duration variables that are potentially initialized before
```
main()
```
.
Note 2: Potentially
In the general case we expect static storage duration variables to be initialized before main, but the compiler is allowed to defer initialization in some situations (the rules are complex see standard for details).


Question:
I have code looking something like this:

$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table
          SET BlobData = '" . mysql_real_escape_string($data) . "',
          BlobHash = '$hash'
          ";
mysql_query($query);

I know this isn't very efficient as each of the '.' operators will reallocate a bigger memory block and the 30MB string will be copied several times.

Is there anything more efficient than the following solution?

$data = file_get_contents($tempFile); // perhaps 30MB of file data, now in PHP's memory
$hash = md5($data);
$query = "INSERT INTO some_table SET BlobData = '%s', BlobHash = '$hash'";
mysql_query(sprintf($query, mysql_real_escape_string($data)));

Answer:
Have you benchmarked the output buffering trick?
```
```
ob_start();
echo 'INSERT INTO some_table SET BlobData = \'', mysql_real_escape_string( $data ), '\', BlobHash = \'', $hash, '\'';
mysql_query( ob_get_clean() );
```
```
Another thing you could do is convert to mysqli or MDB2, which support bound parameters.  That would allow you to skip the mysql_real_escape_string call
and
the string concatenations.