Question:
I have a working copy of my project, checked out using Subversion 1.5.1. When I attempt to run StatSVN against it, I get the following error:

Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info
  INFO: StatSVN - SVN statistics generation

Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger info
  INFO: svn: '.' is not a working copy
  Sep 18, 2008 12:25:22 PM net.sf.statsvn.util.JavaUtilTaskLogger error
  SEVERE: Repository root not available - verify that the project was checked out with svn version 1.3.0 or above.

Has anyone experienced this? I've seen suggestions it might be related to using a locale other than en_US, but I am using en_US.

Answer: Just guessing here, but are you sure that statSVN is compatible with working copies created with version 1.5 of the client? The format changed with svn 1.5...


Question:
I have 4 versions of file A.txt in my subversion repository, say: A.txt.r1, A.txt.r2, A.txt.r3 and A.txt.r4. My working copy of the file is r4 and I want to switch back to r2. I don't want to use "svn update -r 2 A.txt" because this will delete all the revisions after r2, namely r3 and r4.

So is there any way that I update my working copy to r2 and still having the option to switch to r3 and r4 later? Put it another way, I want to still be able to see all 4 revisions by using "svn log A.txt" after doing the update.

Answer:
updating to an older rev will not delete your newer revs.
so you could do
```
svn up -r2 file
```
, then
```
svn up -r4 file
```
.
also, you wouldn't be able to commit the r2 file this way, because you'd have to update before committing, and you'd end up with r4 again.


Question: I'm looking to have a couple of plugins in a Flex project I'm working on. I know I can load a SWF using the SWFLoader, but I thought in Flex3 you can now have Runtime Shared Libraries or something. Does anyone have any good documentation on loading a plugin at runtime? Ideally I'd like to be able to load a plugin from a URL, then execute some code from within the plugin (e.g. add a control to the page).

Answer:
You can use either Modules or RSL.
RSLs have the advantage of getting cached by flash rather than the browser so they stick around longer.
Modules are easier to create and use. I have used modules and had issues with modules failing to load (code needs to handle that case). I haven't tried RSLs yet.
Here is some documentation on creating RSLs
http://labs.adobe.com/wiki/index.php/Flex_3:Feature_Introductions:Flex_3_RSLs


Question: I want to change the Text of the browse button in the FileUpload Control (System.Web.UI.WebControls), instead of the [Browse...] text I want to use [...]

Answer:
This isn't technically possible for security purposes, so the user cannot be misled.
However, there are a couple of workarounds, although these require working with the raw HTML rather than the .NET server control - take a look at
http://www.quirksmode.org/dom/inputfile.html
for one example.


Question:
I am building a quiz and i need to calculate the total time taken to do the quiz.
and i need to display the time taken  in  HH::MM::SS..any pointers?

Answer:
new Date().time returns the time in milliseconds.
```
```
var nStart:Number = new Date().time;

// Some time passes

var nMillisElapsed:Number = new Date().time - nStart;

var strTime:String = Math.floor(nMillisElapsed / (1000 * 60 * 60)) + "::" +
   (Math.floor(nMillisElapsed / (1000 * 60)) % 60) + "::" +
   (Math.floor(nMillisElapsed / (1000)) % 60);
```
```


Question: Is there a method for controlling the Balance of the Wave output that will work on both XP and Vista?

Answer:
Vista has a new api for everything related to mixers and audio, per process legacy api's should still work, but to change global volume, you would have to look at the new COM interfaces added to Vista
This
should get you started


Question:
I'm generating a self-signed SSL certificate to protect my server's admin section, and I keep getting this message from OpenSSL:

unable to write 'random state'

What does this mean?

This is on an Ubuntu server. I have upgraded libssl to fix the recent security vulnerability.

Answer:
In practice, the most common reason for this happening seems to be that the .rnd file in your home directory is owned by root rather than your account.  The quick fix:
```
```
sudo rm ~/.rnd
```
```
For more information, here's the entry from the
OpenSSL FAQ
:
Sometimes the openssl command line utility does not abort with a "PRNG not seeded" error message, but complains that it is "unable to write 'random state'". This message refers to the default seeding file (see previous answer). A possible reason is that no default filename is known because neither RANDFILE nor HOME is set. (Versions up to 0.9.6 used file ".rnd" in the current directory in this case, but this has changed with 0.9.6a.)
So I would check RANDFILE, HOME, and permissions to write to those places in the filesystem.
If everything seems to be in order, you could try running with
strace
and see what exactly is going on.


Question:
I'd like to install Gentoo. I need it to develop GUI C++ applications using wxWidgets, so I need:

build tools: make, automake, autoconf, etc.

C++ compiler (GCC)

X Window System for testing (Fluxbox or something minimal would be enough)

Now, I have two options:

download the small network installer (57MB) do a network install

download the 600MB CD

I'd like to download as less as possible and still have all the tools above.

I also don't understand whether the network installer will first prompt me for the packages I want, or it will fetch 600 MB of data anyway?

I might want to install it on other computers later, so I'd go with 'full' install from CD if the network install does not save me anything.

Answer:
Gentoo is ultraminimalist by default.
The install CD gets you a basic working system, a basic compile environment ( Some version of the GCC suite ), and package management.
Its up to you then to install what you want to use.
Its not like many other distributions where theres a big set of "default" packages to have installed.
You have to know what you want, and install what you want.
The "Live" Cd will make things a bit quicker  by having a few precompiled binaries available, but besides that, you still have to choose what you want to install.
I also don't understand whether the
  network installer will first prompt me
  for the packages I want, or it will
  fetch 600 MB of data anyway?
it will only install what you want to. If you use NetInstall and install nothing except GCC, it will only download enough to have GCC.
Welcome to gentoo.
It can be a little daunting for first timers, but once you've gotten past the steep learning curve you'll love it :)


Question:
I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory).

I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.

Answer:
Here's how I did it (grabbing all files ending in ".ranks"):
```
```
import urllib2, cStringIO, zipfile

try:
    remotezip = urllib2.urlopen(url)
    zipinmemory = cStringIO.StringIO(remotezip.read())
    zip = zipfile.ZipFile(zipinmemory)
    for fn in zip.namelist():
        if fn.endswith(".ranks"):
            ranks_data = zip.read(fn)
            for line in ranks_data.split("\n"):
                # do something with each line
except urllib2.HTTPError:
    # handle exception
```
```


Question:
I have a handful of projects that all use one project for the data model.  Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it.

I'd like to have a modelContext.xml file and another for my ui.xml, etc.

Can I do this?

Answer:
Yes, you can do this via the import element.
```
```
<import resource="services.xml"/>
```
```
Each element's resource attribute is a valid path (e.g. classpath:foo.xml)


Question: I can never remember the number. I need a memory rule.

Answer:
Well, it has 32 bits and hence can store 2^32 different values. Half of those are negative.
The solution is 2,147,483,647
And the lowest is −2,147,483,648.
(Notice that there is one more negative value.)


Question:
I'm implementing a simple service using datagrams over unix local sockets (AF_UNIX address family, i.e. not UDP).  The server is bound to a public address, and it receives requests just fine.  Unfortunately, when it comes to answering back, sendto fails unless the client is bound too.  (the common error is Transport endpoint is not connected).

Binding to some random name (filesystem-based or abstract) works.  But I'd like to avoid that: who am I to guarantee the names I picked won't collide?

The unix sockets' stream mode documentation tell us that an abstract name will be assigned to them at connect time if they don't have one already.  Is such a feature available for datagram oriented sockets?

Answer:
I'm not so sure I understand your question completely, but here is a datagram implementation of an echo server I just wrote. You can see the server is responding to the client on the same IP/PORT it was sent from.
Here's the code
First, the server (listener)
```
```
from socket import *
import time
class Listener:
    def __init__(self, port):
        self.port = port
        self.buffer = 102400

    def listen(self):

        sock = socket(AF_INET, SOCK_DGRAM)
        sock.bind(('', self.port))

        while 1:
            data, addr = sock.recvfrom(self.buffer)
            print "Received: " + data
            print "sending to %s" % addr[0]
            print "sending data %s" % data
            time.sleep(0.25)
            #print addr # will tell you what IP address the request came from and port
            sock.sendto(data, (addr[0], addr[1]))
            print "sent"
        sock.close()

if __name__ == "__main__":
    l = Listener(1975)
    l.listen()
```
```
And now, the Client (sender) which receives the response from the Listener
```
```
from socket import *
from time import sleep
class Sender:
    def __init__(self, server):
       self.port = 1975
       self.server = server
       self.buffer = 102400

    def sendPacket(self, packet):
        sock = socket(AF_INET, SOCK_DGRAM)
        sock.settimeout(10.75)

        sock.sendto(packet, (self.server, int(self.port)))

        while 1:
            print "waiting for response"
            data, addr = sock.recvfrom(self.buffer)
            sock.close()
            return data

if __name__ == "__main__":
        s = Sender("127.0.0.1")
        response = s.sendPacket("Hello, world!")
        print response
```
```


Question:
How can I bind an array parameter in the HQL editor of the HibernateTools plugin?
The query parameter type list does not include arrays or collections.

For example:

     Select * from Foo f where f.a in (:listOfValues).

How can I bind an array to that listOfValues?

Answer:
You probably cannot. Hibernate replaces the objects it gets out of the database with it's own objects (kind of proxies). I would strongly assume Hibernate cannot do that with an array. So if you want to bind the array-data put it into a List on access by Hibernate.
As an example one could do:
```
```
select * from Foo f where f.a in f.list
```
```


Question:
We are trying to integrate tests in our daily builds using TestComplete, so far we have a machine dedicated for testing and our build script copies to this machine everything TestComplete needs for its tests (Application, Database, Test script project and source files, etc).

Basically we can open the TestComplete project manually and run the tests.

Now we want to automate that process, so how do you do it? Or how do you think would be the simplest and best way to make this automation?

Keeping it short, we want to automate the process of opening TestComplete after each build, run all the tests and send an email with the test results.

Anyone can share some experience about this?

Thanks.

Answer:
Well, although I have not used TestComplete I have used a competing package called QA Wizard Pro. Since you are asking this question I am assuming that it isn't something that is natively supported by TestComplete. QA Wizard is the same way and they expect it to be run manually instead of automatically, though there are test run files that can be run. For QA Wizard I created a batch file that was run nightly from the task scheduler. The account to run the software must be able to interact with the desktop and a user must be logged in
with
a display. I used a free piece of software called
AutoHotKey
to automate the running of the tests and then some
Cygwin
tools to parse the results and trigger an email through
Blat
with the results. It isn't a perfect solution but it does work.


Question:
I am new to asp and have a deadline in the next few days.
i receive the following xml from within a webservice response.

print("<?xml version="1.0" encoding="UTF-8"?>
<user_data>
<execution_status>0</execution_status>
<row_count>1</row_count>
<txn_id>stuetd678</txn_id>
<person_info>
    <attribute name="firstname">john</attribute>
    <attribute name="lastname">doe</attribute>
    <attribute name="emailaddress">john.doe@johnmail.com</attribute>
</person_info>
</user_data>");

How can i parse this xml into asp attributes?

Any help is greatly appreciated

Thanks
Damien

On more analysis, some soap stuff is also returned as the aboce response is from a web service call. can i still use lukes code below?

Answer:
You need to read about MSXML parser. Here is a link to a good all-in-one example
http://oreilly.com/pub/h/466
Some reading on XPath will help as well. You could get all the information you need in MSDN.
Stealing the code from
Luke
excellent reply for aggregation purposes:
```
```
Dim oXML, oNode, sKey, sValue

Set oXML = Server.CreateObject("MSXML2.DomDocument.6.0") 'creating the parser object
oXML.LoadXML(sXML) 'loading the XML from the string

For Each oNode In oXML.SelectNodes("/user_data/person_info/attribute")
  sKey = oNode.GetAttribute("name")
  sValue = oNode.Text
  Select Case sKey
    Case "execution_status"
    ... 'do something with the tag value
    Case else
    ... 'unknown tag
  End Select
Next

Set oXML = Nothing
```
```


Question: I know it happens sometime before Load, but during what event exactly?

Answer:
It's loaded into memory between init and load. See t
his article
for a full break down of the page lifecycle.


Question:
I have a web application where there are number of Ajax components which refresh themselves every so often inside a page (it's a dashboard of sorts).

Now, I want to add functionality to the page so that when there is no Internet connectivity, the current content of the page doesn't change and a message appears on the page saying that the page is offline (currently, as these various gadgets on the page try to refresh themselves and find that there is no connectivity, their old data vanishes).

So, what is the best way to go about this?

Answer:
```
```
navigator.onLine
```
```
That should do what you're asking.
You probably want to check that in whatever code you have that updates the page. Eg:
```
```
if (navigator.onLine) {
    updatePage();
} else {
    displayOfflineWarning();
}
```
```


Question: I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?

Answer:
There is actually a wonderful
Python Imaging Library (PIL)
.  It gives you the ability to alter existing images, including anti-aliasing capabilities, and create new images with text and such.  You can also find a
decent introductory tutorial
in the PIL handbook provided on the aforementioned site.


Question:
I'm running a SQL query on SQL Server 2005, and in addition to 2 columns being queried from the database, I'd also like to return 1 column of random numbers along with them. I tried this:

select column1, column2, floor(rand() * 10000) as column3
from table1

Which kinda works, but the problem is that this query returns the same random number on every row. It's a different number each time you run the query, but it doesn't vary from row to row. How can I do this and get a new random number for each row?

Answer:
You need to use a UDF
first:
```
```
CREATE VIEW vRandNumber
AS
SELECT RAND() as RandNumber
```
```
second:
```
```
CREATE FUNCTION RandNumber()
RETURNS float
AS
  BEGIN
  RETURN (SELECT RandNumber FROM vRandNumber)
  END
```
```
test:
```
```
SELECT dbo.RandNumber(), *
FROM <table>
```
```
Above borrowed from
Jeff's SQL Server Blog


Question:
I have a table with game scores, allowing multiple rows per account id: scores (id, score, accountid). I want a list of the top 10 scorer ids and their scores.

Can you provide an sql statement to select the top 10 scores, but only one score per account id?

Thanks!

Answer:
Try this:
```
```
select top 10 username,
              max(score)
from usertable
group by username
order by max(score) desc
```
```


Question:
Apparently xrange is faster but I have no idea why it's faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

for i in range(0, 20):
for i in xrange(0, 20):

Answer:
See this
post
to find difference between range and xrange:
To quote:
```
range
```
returns exactly what you think: a list of consecutive
  integers, of a defined length beginning with 0.
```
xrange
```
, however,
  returns an
"xrange object"
, which acts a great deal like an iterator


Question:
I have a couple of triggers on a table that I want to keep separate and would like to priortize them.

I could have just one trigger and do the logic there, but I was wondering if there was an easier/logical way of accomplishing this of having it in a pre-defined order ?

Answer:
Use sp_settriggerorder.  You can specify the first and last trigger to fire depending on the operation.
sp_settriggerorder on MSDN
From the above link:
A. Setting the firing order for a DML trigger
The following example specifies that trigger uSalesOrderHeader be the first trigger to fire after an UPDATE operation occurs on the Sales.SalesOrderHeader table.
```
USE AdventureWorks;
GO
sp_settriggerorder
    @triggername= 'Sales.uSalesOrderHeader',
    @order='First',
    @stmttype = 'UPDATE';
```
B. Setting the firing order for a DDL trigger
The following example specifies that trigger ddlDatabaseTriggerLog be the first trigger to fire after an ALTER_TABLE event occurs in the AdventureWorks database.
```
USE AdventureWorks;
GO
sp_settriggerorder
    @triggername= 'ddlDatabaseTriggerLog',
    @order='First',
    @stmttype = 'ALTER_TABLE',
    @namespace = 'DATABASE';
```


Question: Suppose you have a program which reads from a socket. How do you keep the download rate below a certain given threshold?

Answer:
Assuming a network transport, a TCP/IP based one, Packets are sent in response to ACK/NACK packets going the other way.
By limiting the rate of packets acknowledging receipt of the incoming packets, you will in turn reduce the rate at which new packets are sent.
It can be a bit imprecise, so its possibly optimal to monitor the downstream rate and adjust the response rate adaptively untill it falls inside a comfortable threshold. ( This will happen really quick however, you send dosens of acks a second )


Question:
I've started figuring out drupal, and so far most of the results are just ugly.
May be I need to learn it in something similar to a real-life project.
I thought — to reproduce this site's functionality might be a good learning project. But I need help. :)

Without assuming this site is based on drupal (it most likely is not — too quick, I think) is there a way to build something similar in functionality (yes, slower, OK if not as fancy as this one, but close) with existing drupal modules and schemes (or with minimal tweaking)?

Or drupal is not good enough for that?
Or — is it too complicated project for a student?

Which existing modules and schemes might help to build something similar?

(No competition is intended with stackoverflow.)

Answer:
Firstly, Drupal is by no means a slow system, actually it works quite well.
Secondly, this has been already asked and answered
here
.
By the way Drupal has a medium learning curve but, once you learn how to use you'll find it simple and you'll find it will satisfy almost everything you want to do with it. Its plugin system is just great and it's very SEO friendly (I don't get paid from Drupal I swear, I just happen to like it a lot)
My
website
is made in drupal if you wanna take a look (is in spanish though).


Question:
It is a real pain to deploy my InfoPath 2007 Forms from the designer into our development environment's SharePoint server.  All of our forms require "full trust" since they include business logic written in C#.  Here are the manual steps:

1) Run the "Publish Form" wizard in InfoPath, specifying the target site to publish to and location to save the xsn file.

2) De-activate the existing version of the form from the site collection features (if an older version exists).

3) Log into Central Admin on the development server.  Navigate to Application Management -> Manage Form Templates and upload the xsn file.

4) Activate the form as a site collection feature.

Does anyone have an idea how this can be automated?  Maybe via stsadm?

Answer:
You can package InfoPath forms in SharePoint solutions (WSP files). These can be deployed by making use of STSADM. For more information:
http://blogs.importchaos.com/alonsorobles/2008/06/04/creating-a-sharepoint-solution-for-an-infopath-form-template-deployment/#comments
http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=37
http://blah.winsmarts.com/2008-8-Deploying_InfoPath_2007_Forms_to_Forms_Server_-and-ndash_Properly.aspx


Question: How can I tell Activerecord to not load blob columns unless explicitly asked for? There are some pretty large blobs in my legacy DB that must be excluded for 'normal' Objects.

Answer:
I believe you can ask AR to load specific columns in your invocation to find:
```
```
MyModel.find(id, :select => 'every, attribute, except, the, blobs')
```
```
However, this would need to be updated as you add columns, so it's not ideal.  I don't think there is any way to specifically exclude one column in rails (nor in a single SQL select).
I guess you could write it like this:
```
```
MyModel.find(id, :select => (MyModel.column_names - ['column_to_exclude']).join(', '))
```
```
Test these out before you take my word for it though. :)


Question:
Using the method Application.Restart() in C# should restart the current application: but it seems that this is not always working.

Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?

Answer:
Try locking before dumping. Here's how I initiate a full app-dump. Might work for you, might not.
```
```
Context.Application.Lock();
Context.Session.Abandon();
Context.Application.RemoveAll();
Context.Application.Restart();
Context.Application.UnLock();
```
```


Question: Convert.ToString() only allows base values of 2, 8, 10, and 16 for some odd reason; is there some obscure way of providing any base between 2 and 16?

Answer:
```
```
string foo = Convert.ToString(myint,base);
```
```
http://msdn.microsoft.com/en-us/library/14kwkz77.aspx
EDIT
: My bad, this will throw an argument exception unless you pass in the specified bases (2, 8, 10, and 16)
Your probably SOL if you want to use a different base (but why???).


Question:
Is there a Vim shortcut for jumping to the argument list of the current function?  I often find myself needing to mess with the argument list of a function, and it's kind of annoying to have to do ?def or ?function or 10k or what-have-you until I finally get to it, then /( or t( or 5e to get to the right position in the argument list, and so on.  It would be great if I could just hit ,a for example and instantly get put into insert mode at the end/beginning of the argument list.

Possible approaches:

Folding

Tag support (ctags)

Also, I'm using Python, so solutions based on curly braces unfortunately won't work.

If no such shortcut exists, I'll just write one and post it here as an answer.  :-)

Answer:
map ,a ma[{F(a
Hit ,a to go to the argument list, then `a to return to where you were when you invoked ,a. Caveat: [{ jumps back to the last unmatched { character, so if you're inside a loop or other control structure, it will take you to the beginning of that, instead.
I don't know of a way to get to the beginning of the function in a fool-proof way. If you're consistent about your tabbing, you may be able to do something like this:
map ,a ma?function :nohlf(a
where, if you don't use a single tab before you define your functions, you'd change  to appropriate value.


Question:
I'm using the following code to query a database from my jsp, but I'd like to know more about what's happening behind the scenes.

These are my two primary questions.

Does the tag access the ResultSet directly, or is the query result being stored in a datastructure in memory?

When is the connection closed?

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>

<sql:query var="query" dataSource="${ds}" sql="${listQuery}"></sql:query>
<c:forEach var="row" items="${query.rows}" begin="0">
    ${row.data }
    ${row.more_data }
</c:forEach>

Note: I've always been against running queries in the jsp, but my result set is too large to store in memory between my action and my jsp. Using this tag library looks like the easiest solution.

Answer:
The key thing here is this: javax.servlet.jsp.jstl.sql.Result
That's what JSTL uses as the result of a SQL Query. If you look at the interface, it has this method:
public java.util.SortedMap[] getRows()
c:forEach "knows" about javax.servlet.jsp.jstl.sql.Result, since Result isn't anything else that forEach knows about (Collections, arrays, iterators, etc).
So, all of that implies that the SQL query will suck the entire result set in to RAM.
If you moved your query in to the JSP because you didn't want to load the entire result set in to a collection, then it doesn't look like the SQL tag will solve that problem for you.
In truth you should look up Value List Pattern.
But a "simple" solution to your problem would be to create a custom Iterator that "knows" about your ResultSet. This one wraps a result set and closes everything if it encounters an exception or if the result runs its course (like it would in a forEach). Kind of a special purpose thing.
```
public class ResultSetIterator implements Iterator {
```
```
```
Connection con;
Statement s;
ResultSet rs;
Object curObject;
boolean closed;

public ResultSetIterator(Connection con, Statement s, ResultSet rs) {
    this.con = con;
    this.s = s;
    this.rs = rs;
    closed = false;
}

public boolean hasNext() {
    advance();
    return curObject != null;
}

public Object next() {
    advance();
    if (curObject == null) {
        throw new NoSuchElementException();
    } else {
        Object result = curObject;
        curObject = null;
        return result;
    }
}

public void remove() {
    throw new UnsupportedOperationException("Not supported yet.");
}

private void advance() {
    if (closed) {
        curObject = null;
        return;
    }
    if (curObject == null) {
        try {
            if (rs.next()) {
                curObject = bindObject(rs);
            }
        } catch (SQLException ex) {
            shutDown();
            throw new RuntimeException(ex);
        }
    }
    if (curObject == null) {
        // Still no object, must be at the end of the result set
        shutDown();
    }
}

protected Object bindObject(ResultSet rs) throws SQLException {
    // Bind result set row to an object, replace or override this method
    String name = rs.getString(1);
    return name;
}

public void shutDown() {
    closed = true;
    try {
        rs.close();
    } catch (SQLException ex) {
        // Ignored
    }
    try {
        s.close();
    } catch (SQLException ex) {
        // Ignored
    }
    try {
        con.close();
    } catch (SQLException ex) {
        // Ignored
    }
}
```
```
}
This is, naturally, untested. But since JSTLs forEach can work with an Iterator, it's the simplest object you could really pass to it. This will prevent you from loading the entire result set in to memory. (As an interesting aside, it's notable how almost, but not quite, completely unlike Iterator a ResultSets behavior is.)


Question: I'm new to .Net and I'm trying to understand the basics first. What is the difference between MSIL and Java bytecode?

Answer:
There are not that much differences. Both are intermediate formats of the code you wrote. When executed, the Virtual machines will execute the intermediate language managed that means that the Virtual Machine controls the variables and calls. There is even a language which I don't remeber right now that can run at .Net and Java the same way.
Basicly, it's just another format for the same thing
Edit: Found the language (besides Scala): It's FAN (
http://www.fandev.org/
), looks very interesting, but no time yet to evaluate


Question:
I have:

class MyClass extends MyClass2 implements Serializable {
  //...
}

In MyClass2 is a property that is not serializable. How can I serialize (and de-serialize) this object?

Correction: MyClass2 is, of course, not an interface but a class.

Answer:
MyClass2 is just an interface so techinicaly it has no properties, only methods.  That being said if you have instance variables that are themselves not serializeable the only way I know of to get around it is to declare those fields transient.
ex:
```
```
private transient Foo foo;
```
```
When you declare a field transient it will be ignored during the serialization and deserialization process.  Keep in mind that when you deserialize an object with a transient field that field's value will always be it's default (usually null.)
Note you can also override the readResolve() method of your class in order to initialize transient fields based on other system state.


Question:
Our CruiseControl system checks out from starteam. I've noticed that it is sometimes not checking out new versions of files, only added files.

Does anyone know why this is?

Answer:
I cannot say
why
this happens, but for what it's worth, we avoid the problem entirely by having StarTeam delete all of the local files before checking-out. We get
all
of the files that way. We use the following StarTeam arguments in our NAnt script:
```
```
delete-local -q -p "${starteam_project_root}" -is -filter "N" -cfgd "${exec_time}"
```
```
Which translates to something like:
```
```
delete-local -q -p "user:passwd@SERVER:49201/ProjectName/" -is -filter "N"-cfgd "09/18/2008 14:33:22"
```
```


Question:
I want to generate a Makefile from an existing Xcode project on the Mac. Specifically, an existing iPhone, Objective-C program on the Mac.

I found PBToMake, but it looks like it is for Xcode 2.1 and when I tried using it, it did not work for an Xcode 3.1 project.

Answer:
Xcode does not support generating a Makefile from a project. If you just want to build your project outside of the IDE, check out the
```
xcodebuild
```
command-line tool.


Question:
I found this link http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/, but there isn't a lot of description around it, aside that it's "simple".

Ideally, I'd like an extension to CcMode that can do it, or at least a mode that can handle auto-styling and has similar shortcuts to CcMode.

If there isn't one, any good elisp references to help me get started writing it myself would be greatly appreciated.

EDIT: David's response prompted me to take a closer look at glsl-mode.el, and it is in fact based on cc-mode, so it's exactly what I was looking for in the first place.

Answer:
Add the following code to your ~/.emacs file.
```
```
(autoload 'glsl-mode "glsl-mode" nil t)
(add-to-list 'auto-mode-alist '("\\.vert\\'" . glsl-mode))
(add-to-list 'auto-mode-alist '("\\.frag\\'" . glsl-mode))
```
```
Put the file
http://artis.imag.fr/~Xavier.Decoret/resources/glsl-mode/glsl-mode.el
somewhere on your emacs path.  You can eval (print load-path) in your
scratch
buffer to get the list of possible locations.  If you don't have write access to any of those, you can append another location to load-paths by adding
```
```
(setq load-path (cons "~/.emacs.d" load-path))
```
```
to your ~/.emacs file.


Question: I'd like to be able to create a parameterized query in MS Access 2003 and feed the values of certain form elements to that query and then get the corresponding resultset back and do some basic calculations with them. I'm coming up short in figuring out how to get the parameters of the query to be populated by the form elements. If I have to use VBA, that's fine.

Answer:
Here is a snippet of code. It updates a table using the parameter txtHospital:
```
```
Set db = CurrentDb

Set qdf = db.QueryDefs("AddHospital")
qdf.Parameters!txtHospital = Trim(Me.HospName)
qdf.ReturnsRecords = False

qdf.Execute dbFailOnError

intResult = qdf.RecordsAffected
```
```
Here is a sample of the SQL:
```
```
PARAMETERS txtHospital Text(255);

INSERT INTO tblHospitals (
[Hospital] )

VALUES (
[txtHospital] )
```
```


Question:
I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style.  I know that you can do this with size rolling style by using the maxSizeRollBackups.

<appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="mylog.log" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <rollingStyle value="Date" />
    <datePattern value=".yyMMdd.'log'" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d %-5p %c - %m%n"  />
    </layout>
</appender>

Answer:
Not sure exactly what you need.  Below is an extract from one of my lo4net.config files:
```
```
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="App_Data\log"/>
    <param name="DatePattern" value=".yyyy-MM-dd-tt".log""/>
    <param name="AppendToFile" value="true"/>
    <param name="RollingStyle" value="Date"/>
    <param name="StaticLogFileName" value="false"/>
    <param name="maxSizeRollBackups" value="60" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%r %d [%t] %-5p %c - %m%n"/>
    </layout>
  </appender>
```
```


Question:
Some programming languages such as Java and C# include encryption packages in their standard libraries.  Others such as Python and Ruby make you download third-party modules to do strong encryption.  I assume that this is for legal reasons; perhaps Sun Microsystems has enough lawyers that they aren't afraid of getting sued, while Guido van Rossum feels more vulnerable.

But what does the law actually say about this?  At this point, would open source authors have anything to fear if they included strong encryption in their programming languages' standard libraries?  If so, then why don't they?  If not, then how do Sun and Microsoft get away with it.

Answer:
IANAL, But...
Java and C# are closed-source, and thus have terms in the EULA that say more-or-less "It's not our fault if you use this somewhere you're not supposed to". They also have teams of lawyers to protect themselves and enforce that clause.
Most open-source licenses do not have similar langauge, and even the ones that do, they don't have teams of lawyers on their side, as the OP said.
Also, Python and PERL are older than Java and C#, from the days when it was illegal to export cryptographic software from the US. Not adding cryptography since the law was changed is perhaps simply a "consistency-is-good" decision.


Question:
I am trying to fix memory leaks in IE 7. Using Drip for investigations but it is not helping much when most dynamically generated DOM elements do not have unique ids.

Tips?

Answer:
Just remember that memory leaks are really about you not cleaning up after yourself. All you need is a little organization.
In the past, I have created my own proxy object for attaching events to DOM elements. It uses my javascript library's api to actually set and remove events. The proxy itself just keeps track of all of the references so that I can call a method on it to have it clean up all of my potential memory leaks.
For my purposes, I was able to just call a single deconstructor on the page that would clean up the leaks for the entire page when the user was leaving the page.
You may have to be more granular but the technique is the same.


Question:
I have a LINQ to SQL generated class with a readonly property:

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
Public ReadOnly Property TotalLogins() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
End Property

This prevents it from being changed externally, but I would like to update the property from within my class like below:

Partial Public Class User

...

    Public Shared Sub Login(Username, Password)
        ValidateCredentials(UserName, Password)

        Dim dc As New MyDataContext()
        Dim user As User = (from u in dc.Users select u where u.UserName = Username)).FirstOrDefault()
        user._TotalLogins += 1
        dc.SubmitChanges()
    End Sub

...

End Class

But the call to user._TotalLogins += 1 is not being written to the database? Any thoughts on how to get LINQ to see my changes?

Answer:
```
```
Make a second property that is protected or internal(?)

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
protected Property TotalLogins2() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
    Set(byval value as System.Nullable(Of Integer))
        Return Me._TotalLogins
    End Get
End Property
```
```
and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.


Question:
What is a tool or technique that can be used to perform spell checks upon a whole source code base and its associated resource files?

The spell check should be source code aware meaning that it would stick to checking string literals in the code and not the code itself.  Bonus points if the spell checker understands common resource file formats, for example text files containing name-value pairs (only check the values).  Super-bonus points if you can tell it which parts of an XML DTD or Schema should be checked and which should be ignored.

Many IDEs can do this for the file you are currently working with.  The difference in what I am looking for is something that can operate upon a whole source code base at once.

Something like a Findbugs or PMD type tool for mis-spellings would be ideal.

Answer:
```
```
Make a second property that is protected or internal(?)

<Column(Name:="totalLogins", Storage:="_TotalLogins", DbType:="Int", UpdateCheck:=UpdateCheck.Never)>  _
protected Property TotalLogins2() As System.Nullable(Of Integer)
    Get
        Return Me._TotalLogins
    End Get
    Set(byval value as System.Nullable(Of Integer))
        Return Me._TotalLogins
    End Get
End Property
```
```
and then update that . I think it won't save readonly properties by default. And why should it anyway. I now it's a hack but hey that's life.


Question:
I want to override the JSON MIME type ("application/json") in Rails to ("text/x-json").  I tried to register the MIME type again in mime_types.rb but that didn't work.  Any suggestions?

Thanks.

Answer:
Try:
```
```
render :json => var_containing_my_json, :content_type => 'text/x-json'
```
```


Question:
There's a diagram depicting the difference between traditional MVC and Cocoa MVC here:

Cocoa Design Patterns: The Model-View-Controller Design Pattern

Are there any benefits of doing it the "Cocoa" way in .NET using Visual Studio?

Answer:
There's no reason
not
to do it that way, if it makes more sense to you. Be aware that a lot of things in the Cocoa framework are the way they are due to higher-level design decisions, for example favoring composition and delegation over subclassing.
If you want, you can design C# software that looks like Objective-C software, but people with no Cocoa experience will have to have it explained to them, because the loosely-coupled design will just seem "weird" to them.
Oh, right - the advantages of that design include greater re-usability of the UI view and model classes (since they won't have any knowledge of each other), slightly simpler code in the view classes, and more of the "application logic" in a single place (the controller classes).


Question: In XNA, how do I load in a texture or mesh from a file without using the content pipeline?

Answer:
I believe Texture2D.FromFile(); is what you are looking for.
It does not look like you can do this with a Model though.
http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.graphics.texture2d.fromfile.aspx


Question: Basically, we have a rule setup to run a script when a code word is detected in the body of an incoming message. The script will append the current subject header with a word in front. For example, Before: "Test Message", After: "Dept - Test Message". Any ideas?

Answer:
Not tested:
```
```
mailItem.Subject = "Dept - " & mailItem.Subject
mailItem.Save
```
```


Question:
Suppose I want to open a file in an existing Emacs session using su or sudo, without dropping down to a shell and doing sudoedit or sudo emacs. One way to do this is

C-x C-f /sudo::/path/to/file

but this requires an expensive round-trip through SSH. Is there a more direct way?

[EDIT] @JBB is right. I want to be able to invoke su/sudo to save as well as open. It would be OK (but not ideal) to re-authorize when saving. What I'm looking for is variations of find-file and save-buffer that can be "piped" through su/sudo.

Answer:
Ugh. Perhaps you could open a shell in Emacs and exec sudo emacs.
The problem is that you presumably don't just want to open the file. You want to be able to save it later. Thus you need your root privs to persist, not just exist for opening the file.
Sounds like you want Emacs to become your window manager. It's bloated enough without that. :)


Question: What does a JIT compiler specifically do as opposed to a non-JIT compiler? Can someone give a succinct and easy to understand description?

Answer:
A JIT compiler runs
after
the program has started and compiles the code (usually bytecode or some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime information whereas a standard compiler doesn't and can make better optimizations like inlining functions that are used frequently.
This is in contrast to a traditional compiler that compiles
all
the code to machine language
before
the program is first run.
To paraphrase, conventional compilers build the whole program as an EXE file BEFORE the first time you run it. For newer style programs, an assembly is generated with pseudocode (p-code). Only AFTER you execute the program on the OS (e.g., by double-clicking on its icon) will the (JIT) compiler kick in and generate machine code (m-code) that the Intel-based processor or whatever will understand.


Question:
I once was asked to increase thread priority to fix a problem.  I refused, saying that changing it was dangerous and was not the root cause of the problem.

My question is, under what circumstannces should I conider changing priority of threads?

Answer:
Not many.  The only time I've ever had to change thread priorities in a
positive
direction was with a user interface thread.  UIs must be extremely snappy in order for the app to feel right, so a lot of times it is best to prioritize painting threads higher than others.  For example, the Swing Event Dispatch Thread runs at priority 6 by default (1 higher than the default).
I do push threads down in priority quite a bit.  Again, this is usually to keep the UI responsive while some long-running background process does its thing.  However, this also will sometimes apply to polling daemons and the like which I
know
that I don't want to be interfering with anything, regardless of how minimal the interference.


Question:
I have a .NET 3.5 (target framework) web application.  I have some code that looks like this:

public string LogPath { get; private set; }
public string ErrorMsg { get; private set; }

It's giving me this compilation error for these lines:

"must declare a body because it is not marked abstract or extern."

Any ideas?  My understanding was that this style of property was valid as of .NET 3.0.

Thanks!

The problem turned out to be in my .sln file itself.  Although I was changing the target version in my build options, in the .sln file, I found this:

TargetFramework = "3.0"

Changing that to "3.5" solved it.  Thanks, guys!

Answer:
It is, as long as you put
abstract
in front, or implement the methods.
```
```
public abstract string LogPath { get; private set; }
public abstract string ErrorMsg { get; private set; }
```
```
See
http://forums.asp.net/t/1031651.aspx


Question:
I am looking to build a multi-threaded text import  facility (generally CSV into SQL Server 2005) and would like to do this in VB.NET but I am not against C#.  I have VS 2008 trial and just dont know where to begin.  Can anyone point me in the direction of where I can look at and play with the source of a VERY simple multi-threaded application for VS 2008?

Thanks!

Answer:
This is a great article:
http://www.devx.com/DevX/10MinuteSolution/20365
In particular:
```
```
Dim t As Thread
t = New Thread(AddressOf Me.BackgroundProcess)
t.Start()

Private Sub BackgroundProcess()
   Dim i As Integer = 1
   Do While True
        ListBox1.Items.Add("Iterations: " + i)
        i += 1
        Thread.CurrentThread.Sleep(2000)
   Loop
End Sub
```
```


Question:
I am a .Net developer that has been tasked with upgrading a classic asp website to asp.net. The website is currently running on luck and bubble gum but there is not enough time or money to stop progress and do a full rewrite. Of course I will still need to be able to deliver new features while I am upgrading.

What strategies should I use to make a smooth gradual change to asp.net? Should I convert to a single tier .net solution and then refactor to a proper multi-tier solution or should I design my business and data layers now? Should I go straight to 3.5 or is it easier to just get to 1.1 and upgrade to 2.0 or 3.5 after?

A full conversion would probably take 3-5 months. There is also some existing 1.1 code, which is why I am considering using that as a jumping off point.

Answer:
How long would a complete conversion/rewrite take? It's also going to depend on how you've structured your original project.
I
can
answer that you should just target v2.0 (3.5 if you want/need it's features) from the beginning. There's no need to subject yourself to 1.1 of the framework.


Question:
Let's say we have 0.33, we need to output 1/3.

If we have 0.4, we need to output 2/5.

The idea is to make it human-readable to make the user understand "x parts out of y" as a better way of understanding data.

I know that percentages is a good substitute but I was wondering if there was a simple way to do this?

Answer:
You might want to read
What Every Computer Scientist Should Know about Floating Point Arithmetic
.
You'll have to specify some precision by multiplying by a large number:
```
```
3.141592 * 1000000 = 3141592
```
```
then you can make a fraction:
```
```
3 + (141592 / 1000000)
```
```
and reduce via GCD...
```
```
3 + (17699 / 125000)
```
```
but there is no way to get the
intended
fraction out. You might want to
always
use fractions throughout your code instead --just remember to reduce fractions when you can to avoid overflow!


Question:
In order to distribute a function I've written that depends on other functions I've written that have their own dependencies and so on without distributing every m-file I have ever written, I need to figure out what the full list of dependencies is for a given m-file. Is there a built-in/freely downloadable way to do this?

Specifically I am interested in solutions for MATLAB 7.4.0 (R2007a), but if there is a different way to do it in older versions, by all means please add them here.

Answer:
For newer releases of Matlab (eg 2007 or 2008) you could use the built in functions:
mlint
dependency report and
coverage report
Another option is to use Matlab's profiler. The command is profile, it can also be used to track dependencies.  To use profile, you could do
```
```
>> profile on   % turn profiling on
>> foo;         % entry point to your matlab function or script
>> profile off  % turn profiling off
>> profview     % view the report
```
```
If profiler is not available, then perhaps the following two functions are (for pre-MATLAB 2015a):
depfun
depdir
For example,
```
```
>> deps = depfun('foo');
```
```
gives a structure, deps, that contains all the dependencies of foo.m.
From answers
2
, and
3
, newer versions of MATLAB (post 2015a) use
```
matlab.codetools.requiredFilesAndProducts
```
instead.
See answers
EDIT:
Caveats thanks to @Mike Katz comments
Remember that the Profiler will only
  show you files that were actually used
  in those runs, so if you don't go
  through every branch, you may have
  additional dependencies. The
  dependency report is a good tool, but
  only resolves static dependencies on
  the path and just for the files in a
  single directory.
Depfun is more reliable but gives you
  every possible thing it can think of,
  and still misses LOAD's and EVAL's.


Question: We'd like a trace in our application logs of these exceptions - by default Java just outputs them to the console.

Answer:
There are two ways:
/* Install a Thread.UncaughtExceptionHandler on the EDT */
Set a system property:
System.setProperty("sun.awt.exception.handler",MyExceptionHandler.class.getName());
I don't know if the latter works on non-SUN jvms.
--
Indeed, the first is not correct, it's only a mechanism for detecting a crashed thread.


Question: I'm using Eclipse PHP Development Tools.  What would be the easiest way to access a file or maybe create a remote project trough FTP and maybe SSH and SFTP?.

Answer:
have you checked
RSE
(
R
emote
S
ystem
E
xplorer) ? I think it's pretty close to what you want to achieve.
a blog post about it, with screenshots


Question:
Let's say I have an array, and I know I'm going to be doing a lot of "Does the array contain X?" checks. The efficient way to do this is to turn that array into a hash, where the keys are the array's elements, and then you can just say
if($hash{X}) { ... }

Is there an easy way to do this array-to-hash conversion? Ideally, it should be versatile enough to take an anonymous array and return an anonymous hash.

Answer:
```
```
%hash = map { $_ => 1 } @array;
```
```
It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.
What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.


Question:
I have been playing with Haml recently and really like the way the resulting code looks to me...the developer. I'm also not too worried about a designer being able to consume or change it...we're a small team.

That said, beginning work on a project we believe will generate quite a bit of traffic (who doesn't?). I'm concerned that there are things I just don't know about haml. Is there anything erb can do that haml can't? Does haml have a negative effect as a project grows? Are there other things that should be considered?

And finally...how does Haml compare speedwise to erubis? I see that it supposedly beats erb and eruby now...

Thanks!

Answer:
I would personally recommend us erubis in precompiled templates.
Especially if there's no need for dynamic templating. Then your biggest slowdown will be limited by the speed at which ruby can parse ruby.
I'd probably set up a small cron job that just monitors for changed source templates and autocompiles them on-change that you can turn off when not in use.
Compile once, use many.
Oh, and if you're really concerned about speed, Tenjin may be worth a look too ( same creators as erubis )
http://www.kuwata-lab.com/tenjin/rbtenjin-examples.html


Question:
I have a Windows Workflow application that uses classes I've written for COM automation. I'm opening Word and Excel from my classes using COM.

I'm currently implementing IDisposable in my COM helper and using Marshal.ReleaseComObject(). However, if my Workflow fails, the Dispose() method isn't being called and the Word or Excel handles stay open and my application hangs.

The solution to this problem is pretty straightforward, but rather than just solve it, I'd like to learn something and gain insight into the right way to work with COM. I'm looking for the "best" or most efficient and safest way to handle the lifecycle of the classes that own the COM handles. Patterns, best practices, or sample code would be helpful.

Answer:
I can not see what failure you have that does not calls the Dispose() method. I made a test with a sequential workflow that contains only a code activity which just throws an exception and the Dispose() method of my workflow is called twice (this is because of the standard WorkflowTerminated event handler). Check the following code:
Program.cs
```
```
class Program
    {
        static void Main(string[] args)
        {
            using(WorkflowRuntime workflowRuntime = new WorkflowRuntime())
            {
                AutoResetEvent waitHandle = new AutoResetEvent(false);
                workflowRuntime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs e)
                {
                    waitHandle.Set();
                };
                workflowRuntime.WorkflowTerminated += delegate(object sender, WorkflowTerminatedEventArgs e)
                {
                    Console.WriteLine(e.Exception.Message);
                    waitHandle.Set();
                };

                WorkflowInstance instance = workflowRuntime.CreateWorkflow(typeof(WorkflowConsoleApplication1.Workflow1));
                instance.Start();

                waitHandle.WaitOne();
            }
            Console.ReadKey();
        }
    }
```
```
Workflow1.cs
```
```
public sealed partial class Workflow1: SequentialWorkflowActivity
    {
        public Workflow1()
        {
            InitializeComponent();
            this.codeActivity1.ExecuteCode += new System.EventHandler(this.codeActivity1_ExecuteCode);
        }

        [DebuggerStepThrough()]
        private void codeActivity1_ExecuteCode(object sender, EventArgs e)
        {
            Console.WriteLine("Throw ApplicationException.");
            throw new ApplicationException();
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Here you must free your resources
                // by calling your COM helper Dispose() method
                Console.WriteLine("Object disposed.");
            }
        }
    }
```
```
Am I missing something? Concerning the lifecycle-related methods of an Activity (and consequently of a Workflow) object, please check this post:
Activity "Lifetime" Methods
. If you just want a generic article about disposing, check
this
.


Question: I'm looking for the total commit charge.

Answer:
Here's an example using WMI:
```
```
strComputer = "."

Set objSWbemServices = GetObject("winmgmts:\\" & strComputer)
Set colSWbemObjectSet = _
 objSWbemServices.InstancesOf("Win32_LogicalMemoryConfiguration")

For Each objSWbemObject In colSWbemObjectSet
 Wscript.Echo "Total Physical Memory (kb): " & _
 objSWbemObject.TotalPhysicalMemory
 WScript.Echo "Total Virtual Memory (kb): " & _
 objSWbemObject.TotalVirtualMemory
 WScript.Echo "Total Page File Space (kb): " & _
 objSWbemObject.TotalPageFileSpace
Next
```
```
If you run this script under CScript, you should see the number of kilobytes of physical memory installed on the target computer displayed in the command window. The following is typical output from the script:
Total Physical Memory (kb): 261676
Edit:
Included total page file size property also
taken from:
http://www.microsoft.com/technet/scriptcenter/guide/sas_wmi_dieu.mspx?mfr=true


Question:
I have a web application that is dynamically loading PDF files for viewing in the browser.
Currently, it uses "innerHTML" to replace a div with the PDF Object.  This works.

But, is there a better way to get the ID of the element and set the "src" or "data"  parameter for the Object / Embed and have it instantly load up a new document?
I'm hoping the instance of Adobe Acrobat Reader will stay on the screen, but the new document will load into it.

Here is a JavaScript example of the object:

document.getElementById(`divPDF`).innerHTML = `<OBJECT id='objPDF' DATA="'+strFilename+'" TYPE="application/pdf" TITLE="IMAGING" WIDTH="100%" HEIGHT="100%"></object>`;

Any insight is appreciated.

Answer:
I am not sure if this will work, as I have not tried this out in my projects.
(Looking at your JS, I believe you are using jQuery. If not, please correct me)
Once you have populated the divPDF with the object you might try the code below:
```
```
$("objPDF").attr({
    data: "dir/to/newPDF"
});
```
```
Again, I am not sure if this will work for your particular needs but if you attach this code to an event handler you can switch out the data of the object.
You could also wrap it in a function to be used over and over again:
```
```
function pdfLoad(dirToPDF) {
    $("objPDF").attr({
        data: dirToPDF
    });
}
```
```


Question:
I have a simple table  comments (id INT, revision INT, comment VARCHAR(140)) with some content like this:

1|1|hallo1|
1|2|hallo2|
1|3|hallo3|
2|1|hallo1|
2|2|hallo2|

I'm searching for an SQL statement which will return each comment with the highest revision:

1|3|hallo3|
2|2|hallo2|

I've come up with this solution:

select id, revision, comment
  from comments
  where revision = (
      select max(revision)
        from comments as f
        where f.id = comments.id
  );

but it is very slow on large data sets. Are there any better queries to accomplish this?

Answer:
Make sure you have your indexes set up appropriately.  Indexing on id, revision would be good.
Here's a different take on your query. Haven't checked its execution plan, but if you set up the index well it should help:
```
```
SELECT c.*
  FROM comments c
  INNER JOIN (
        SELECT id,max(revision) AS maxrev
          FROM comments
          GROUP BY id
  ) b
    ON c.id=b.id AND c.revision=b.maxrev
```
```
Editted to add:
If you're on SQL Server, you might want to check out Indexed Views as well:
http://www.microsoft.com/technet/prodtechnol/sql/2005/impprfiv.mspx
Editted again to add info:
```
```
Subquery:
25157 records
2 seconds
Execution plan includes an Index Seek (82%) base and a Segment (17%)

Left Outer Join:
25160 records
3 seconds
Execution plan includes two Index Scans @ 22% each with a Right Outer Merge at 45% and a Filter at 11%
```
```
I'd still go with the sub query.


Question:
How do I see if a certain object has been loaded, and if not, how can it be loaded, like the following?

if (!isObjectLoaded(someVar)) {
    someVar= loadObject();
}

Answer:
```
typeof(obj)
```
would return "object" for an object of a class among other possible values.


Question:
When someone talks about a variables storage class specifier, what are they talking about?

They also often talk about variable linkage in the same context, what is that?

Answer:
The storage class specifier controls the
storage
and the
linkage
of your variables. These are two concepts that are different.
C specifies the following specifiers for variables: auto, extern, register, static.
Storage
The storage duration determines how long your variable will live in ram.
There are three types of storage duration: static, automatic and dynamic.
static
If your variable is declared at file scope, or with an extern or static specifier, it will have static storage. The variable will exist for as long as the program is executing. No execution time is spent to create these variables.
automatic
If the variable is declared in a function, but
without
the extern or static specifier, it has automatic storage. The variable will exist only while you are executing the function.  Once you return, the variable no longer exist.  Automatic storage is typically done on the stack.  It is a very fast operation to create these variables (simply increment the stack pointer by the size).
dynamic
If you use malloc (or new in C++) you are using dynamic storage.  This storage will exist until you call free (or delete). This is the most expensive way to create storage, as the system must manage allocation and deallocation dynamically.
Linkage
Linkage specifies who can see and reference the variable. There are three types of linkage: internal linkage, external linkage and no linkage.
no linkage
This variable is only visible where it was declared. Typically applies to variables declared in a function.
internal linkage
This variable will be visible to all the functions within the file (called a
translation unit
), but other files will not know it exists.
external linkage
The variable will be visible to other translation units.  These are often thought of as "global variables".
Here is a table describing the storage and linkage characteristics based on the specifiers
```
Storage Class   Function            File
  Specifier        Scope              Scope
-----------------------------------------------------
  none           automatic         static
                 no linkage        external linkage

 extern          static            static
                 external linkage  external linkage

 static          static            static
                 no linkage        internal linkage

  auto           automatic         invalid
                 no linkage

register         automatic         invalid
                 no linkage
```


Question: I have two DateTime objects: StartDate and EndDate. I want to make sure StartDate is before EndDate. How is this done in C#?

Answer:
```
```
if(StartDate < EndDate)
{}
```
```
DateTime supports normal comparision operators.


Question: My Vista application needs to know whether the user has launched it "as administrator" (elevated) or as a standard user (non-elevated). How can I detect that at run time?

Answer:
The following C++ function can do that:
```
```
HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet );

/*
Parameters:

ptet
    [out] Pointer to a variable that receives the elevation type of the current process.

    The possible values are:

    TokenElevationTypeDefault - This value indicates that either UAC is disabled,
        or the process is started by a standard user (not a member of the Administrators group).

    The following two values can be returned only if both the UAC is enabled
    and the user is a member of the Administrator's group:

    TokenElevationTypeFull - the process is running elevated.

    TokenElevationTypeLimited - the process is not running elevated.

Return Values:

    If the function succeeds, the return value is S_OK.
    If the function fails, the return value is E_FAIL. To get extended error information, call GetLastError().

Implementation:
*/

HRESULT GetElevationType( __out TOKEN_ELEVATION_TYPE * ptet )
{
    if ( !IsVista() )
        return E_FAIL;

    HRESULT hResult = E_FAIL; // assume an error occurred
    HANDLE hToken   = NULL;

    if ( !::OpenProcessToken(
                ::GetCurrentProcess(),
                TOKEN_QUERY,
                &hToken ) )
    {
        return hResult;
    }

    DWORD dwReturnLength = 0;

    if ( ::GetTokenInformation(
                hToken,
                TokenElevationType,
                ptet,
                sizeof( *ptet ),
                &dwReturnLength ) )
    {
            ASSERT( dwReturnLength == sizeof( *ptet ) );
            hResult = S_OK;
    }

    ::CloseHandle( hToken );

    return hResult;
}
```
```


Question:
On my desktop I have written a small Pylons app that connects to Oracle.   I'm now trying to deploy it to my server which is running Win2k3 x64. (My desktop is 32-bit XP) The Oracle installation on the server is also 64-bit.

I was getting errors about loading the OCI dll, so I installed the 32 bit client into C:\oracle32.

If I add this to the PATH environment variable, it works great.   But I also want to run the Pylons app as a service (using this recipe) and don't want to put this 32-bit library on the path for all other applications.

I tried using sys.path.append("C:\\oracle32\\bin") but that doesn't seem to work.

Answer:
sys.path is python's internal representation of the PYTHONPATH, it sounds to me like you want to modify the PATH.
I'm not sure that this will work, but you can try:
```
```
import os
os.environ['PATH'] += os.pathsep + "C:\\oracle32\\bin"
```
```


Question:
Suppose we have:

interface Foo
{
 bool Func(int x);
}

class Bar: Foo
{
  bool Func(int x)
  {
   return (x>0);
  }
}

class Baz: Foo
{
  bool Func(int x)
  {
   return (x<0);
  }
}

Now we can toss around Bar and Baz as a Foos and call their Func methods.

Delegates simplify this a little bit:

delegate bool Foo(int x);

bool Bar(int x)
{
 return (x<0);
}

bool Baz(int x)
{
 return (x>0);
}

Now we can toss around Bar and Baz as Foo delegates.

What is the real benefit of delegates, except for getting shorter code?

Answer:
No, delegates are for method pointers. Then you can make sure that the signature of the method associated w/ the delegate is correct.
Also, then you don't need to know the structure of the class. This way, you can use a method that you have written to pass into a method in another class, and define the functionality you want to have happen.
Take a look at the
List<> class with the Find method
. Now you get to define what determines if something is a match or not, without requiring items contained in the class to implement IListFindable or something similar.


Question: Simple question, how do you list the primary key of a table with T-SQL? I know how to get indexes on a table, but can't remember how to get the PK.

Answer:
The system stored procedure
```
sp_help
```
will give you the information. Execute the following statement:
```
```
execute sp_help table_name
```
```


Question:
Let's say I have two models, Classes and People. A Class might have one or two People as instructors, and twenty people as students. So, I need to have multiple relationships between the models -- one where it's 1->M for instructors, and one where it's 1->M for students.

Edit: Instructors and Students must be the same; instructors could be students in other classes, and vice versa.

I'm sure this is quite easy, but Google isn't pulling up anything relevant and I'm just not finding it in my books.

Answer:
There are many options here, but assuming instructors are always instructors and students are always students, you can use inheritance:
```
```
class Person < ActiveRecord::Base; end  # btw, model names are singular in rails
class Student < Person; end
class Instructor < Person; end
```
```
then
```
```
class Course < ActiveRecord::Base  # renamed here because class Class already exists in ruby
  has_many :students
  has_many :instructors
end
```
```
Just remember that for single table inheritance to work, you need a
```
type
```
column in the
```
people
```
table.
using an association model might solve your issue
```
```
class Course < ActiveRecord::Base
  has_many :studentships
  has_many :instructorships
  has_many :students,    :through => :studentships
  has_many :instructors, :through => :instructorships
end

class Studentship < ActiveRecord::Base
  belongs_to :course
  belongs_to :student, :class_name => "Person", :foreign_key => "student_id"
end

class Instructorship < ActiveRecord::Base
  belongs_to :course
  belongs_to :instructor, :class_name => "Person", :foreign_key => "instructor_id"
end
```
```


Question:
For example, given a type param method i'm looking for something like the part in bold

void MyMethod< T >() {

  if ( typeof(T).Implements( IMyInterface ) )
  {

  //Do something

else

  //Do something else

}

Anwers using C# 3.0 are also welcome, but first drop the .NET 2.0 ones please ;)

Answer:
Type.IsAssignableFrom
```
```
if(typeof(IMyInterface).IsAssignableFrom(typeof(T)))
{
  // something
}
else
{
  // something else
}
```
```


Question:
I have the feeling that is easy to find samples, tutorials and simple examples on Flex.

It seems harder to find tips and good practices based on real-life projects.

Any tips on how to :

How to write maintainable actionscript code

How to ensure a clean separation of concern. Has anybody used an MVC framework such as cairngorm, puremvc or easymvc on a real Flex project ?

How to fetch data from a server with blazeds/amfphp ?

How to reduce latency for the end-user ?

...

Answer:
I work often with Flex in my job, and I will be happy to help.. but your questions deserve an article for each one :) I'll try some short answer.
Maintenable code: I think that the same rules of any other OO languages apply. Some flex-specific rules I'm use to follow: use strong typed variables, always consider dispatching events as the way for your UI components talk each other (a little more initial work, very flexible and decoupled later).
Frameworks: looked at it, read the documentation.. very nice, but I still feel that their complications are not balanced by the benefits they provide. Anyway I'd like to change my mind on this point..
Talking with server: Right now I'm using BlazeDS, it works very well.. there are many tutorials on the subject out there, if you find any trouble setting up it I would be happy to help.
Latency: Do you mean in client/server comunications? If so, you should explore the various type of channels BlazeDS implements.. pull-only, two-way http polling, near real-time on http (comet).. if you need more, LiveCycle Data Services ES, the commrcial implementation from which BlazeDS is born, among other things offer another protocol called RTMP, it isn't http-tunnelled so there can be problem with firewalls and proxies, but it offers better performance (there is a free closed-source version of LCDS). I use the standard http channels in intranet environments, and found no real performance problems even with large datasets.
Well.. quite a lot of stuff, can't be more specific now on each of this points, ask you if need :)


Question:
Suppose I want to store many small configuration objects in XML, and I don't care too much about the format. The XMLDecoder class built into the JDK would work, and from what I hear, XStream works in a similar way.

What are the advantages to each library?

Answer:
If you are planning on storing all those configuration objects in a single file, and that file will be quite large, both the options you've outlined above could be quite memory intensive, as they both require the entire file to be read into memory to be deserialized.
If memory usage is a concern (the file containing the XML will be very large), I recommend
SAX
.
If memory usage is not a concern (the file containing the XML will not be very large), I'd use whatever is included with the default JRE (in this case XMLDecoder) just to remove 3rd party dependencies.


Question:
I'm working with an mpeg stream that uses a IBBP... GOP sequence. The (DTS,PTS) values returned for the first 4 AVPackets are as follows: I=(0,3) B=(1,1) B=(2,2) P=(3,6)

The PTS on the I frame looks like it is legit, but then the PTS on the B frames cannot be right, since the B frames shouldn't be displayed before the I frame as their PTS values indicate. I've also tried decoding the packets and using the pts value in the resulting AVFrame, put that PTS is always set to zero.

Is there any way to get an accurate PTS out of ffmpeg? If not, what's the best way to sync audio then?

Answer:
Ok, scratch my previous confused reply.
For a IBBPBBI movie, you'd expect the PTSes to look like this (in decoding order)
```
```
0, 3, 1, 2, 6, 4, 5, ...
```
```
corresponding to the frames
```
```
I, P, B, B, I, B, B, ...
```
```
So you appear to be missing an I at the start of your sequence but otherwise the timestamps look correct.


Question:
I'm currently modifying a Java script in Rational Functional Tester and I'm trying to tell RFT to wait for an object with a specified set of properties to appear. Specifically, I want to wait until a table with X number of rows appear. The only way I have been able to do it so far is to add a verification point that just verifies that the table has X number of rows, but I have not been able to utilize the wait for object type of VP, so this seems a little bit hacky. Is there a better way to do this?

Jeff

Answer:
No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty("rowCount", x);
Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method.
The
```
find()
```
codesample below assumes that
```
doc
```
is an html document.  Adjust this to be your parent java window.
```
```
TestObject[] tables = doc.find(atDescendant(".rowCount", x), false);
```
```
If you are not familiar with
```
find()
```
, do a search in the RFT API reference in the help menu.
```
find()
```
will be your best friend in RFT scripting.


Question:
Shell ("explorer.exe www.google.com")

is how I'm currently opening my products ad page after successful install. However I think it would look much nicer if I could do it more like Avira does, or even a popup where there are no address bar links etc.  Doing this via an inbrowser link is easy enough

<a href="http://page.com"
onClick="javascript:window.open('http://page.com','windows','width=650,height=350,toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,directories=no,status=no');    return false")">Link text</a>

But how would I go about adding this functionality in VB?

Answer:
No, there is not a built-in waitForProperty() type of method, so you cannot do something simple like tableObject.waitForProperty("rowCount", x);
Your options are to use a verification point as you already are doing (if it ain't broke...) or to roll your own synchronization point using a do/while loop and the find() method.
The
```
find()
```
codesample below assumes that
```
doc
```
is an html document.  Adjust this to be your parent java window.
```
```
TestObject[] tables = doc.find(atDescendant(".rowCount", x), false);
```
```
If you are not familiar with
```
find()
```
, do a search in the RFT API reference in the help menu.
```
find()
```
will be your best friend in RFT scripting.


Question:
I have uncovered another problem in the effort that we are making to port several hundreds of ksh scripts from AIX, Solaris and HPUX to Linux. See here for the previous problem.

This code:

#!/bin/ksh
if [ -a k* ]; then
    echo "Oh yeah!"
else
    echo "No way!"
fi
exit 0

(when run in a directory with several files whose name starts with k) produces "Oh yeah!" when called with the AT&T ksh variants (ksh88 and ksh93). On the other hand it produces and error message followed by "No way!" on the other ksh variants (pdksh, MKS ksh and bash).

Again, my question are:

Is there an environment variable that will cause pdksh to behave like ksh93? Failing that:

Is there an option on pdksh to get the required behavior?

Answer:
You do realize that [ is an alias (often a link, symbolic or hard) for
```
/usr/bin/test
```
, right?  So perhaps the actual problem is different versions of
```
/usr/bin/test
```
?
OTOH, ksh overrides it with a builtin.  Maybe there's a way to get it to not do that?  or maybe you can explicitly alias [ to
```
/usr/bin/test
```
, if
```
/usr/bin/test
```
on all platforms is compatible?


Question:
Is it possible to use chapters in videos for the iPhone in an application?

For example:
I have a 3 minutes video to play. I have chapter 1 starting at 0s, chapter 2 at 50s, chapter 3 at 95s.

Can I start plating the video at 50s (chapter 2) until the end? Can I make it play just the chapter 2 from 50s to 95s?

My question is not about how to add chapters to a video. I want to know if this behaviour is available on the iphone.

Answer:
This is definitely possible sending the non-documented message
setCurrentTime
to MPMoviePlayerController. It takes one parameter of type double which specifies the playback position in seconds. Find below a short example:
Extend the MPMoviePlayerController to avoid compiler warnings:
```
```
@interface MPMoviePlayerController (extended)
-(void)setCurrentTime:(double)seconds;
@end
```
```
Then you can call it wherever you need it - before start or during playback.
```
```
MPMoviePlayerController* player = [[ MPMoviePlayerController alloc] initWithContentURL:url ];
[ player setCurrentTime:95.0 ];
[ player play ];
```
```


Question:
I'm attempting to convert a home-grown login system to the standard asp.net login control included in .net.  I want all communication on the website for a user not logged in to be in clear text, but lock everything in SSL once the user logs in - including the transmission of the username and password.

I had this working before by loading a second page - "loginaction.aspx" - with a https: prefix, then pulling out the username and password by looking for the proper textbox controls in Request.Form.Keys.  Is there a way to do something similar using the .net login controls?  I dont want to have a seperate login page, but rather include this control (within a loginview) on every page on the site.

Answer:
You aren't going to be able to have your site as non-SSL, with a login box on every page, and then submit the username and password via SSL.
The only way to really accomplish this is to use frames of some sort. This way your entire page could be non-SSL, but the login frame would have to be SSL.
The usual ways of doing this is to either lock down the entire site with SSL, don't worry about having the username and password SSL encrypted and go to SSL after they log in, or go the frame route I mentioned above.


Question: I believe the question says it all ... (I'll update if needed)

Answer:
You aren't going to be able to have your site as non-SSL, with a login box on every page, and then submit the username and password via SSL.
The only way to really accomplish this is to use frames of some sort. This way your entire page could be non-SSL, but the login frame would have to be SSL.
The usual ways of doing this is to either lock down the entire site with SSL, don't worry about having the username and password SSL encrypted and go to SSL after they log in, or go the frame route I mentioned above.


Question:
The C preprocessor is justifiably feared and shunned by the C++ community. In-lined functions, consts and templates are usually a safer and superior alternative to a #define.

The following macro:

#define SUCCEEDED(hr) ((HRESULT)(hr) >= 0)

is in no way superior to the type safe:

inline bool succeeded(int hr) { return hr >= 0; }

But macros do have their place, please list the uses you find for macros that you can't do without the preprocessor.

Please put each use-cases in a seperate answer so it can be voted up and if you know of how to achieve one of the answers without the preprosessor point out how in that answer's comments.

Answer:
When you want to change the program flow (
```
return
```
,
```
break
```
and
```
continue
```
) code in a function behaves differently than code that is actually inlined in the function.
```
```
#define ASSERT_RETURN(condition, ret_val) \
if (!(condition)) { \
    assert(false && #condition); \
    return ret_val; }

// should really be in a do { } while(false) but that's another discussion.
```
```


Question:
I have two code bases of an application.  I need to copy all the files in all the directories with .java from the newer code base, to the older (so I can commit it to svn).

How can I write a batch files to do this?

Answer:
XCOPY /D ?
```
```
xcopy c:\olddir\*.java c:\newdir /D /E /Q /Y
```
```


Question:
I am programming a game on the iPhone.  I am currently using NSTimer to trigger my game update/render.  The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer.

So my question is what is the best alternative to using NSTimer?

One alternative per answer please.

Answer:
I don't know about the iPhone in particular, but I may still be able to help:
Instead of simply plugging in a fixed delay at the end of the loop, use the following:
Determine a refresh interval that you would be happy with and that is larger than a single pass through your main loop.
At the start of the loop, take a current timestamp of whatever resolution you have available and store it.
At the end of the loop, take another timestamp, and determine the elapsed time since the last timestamp (initialize this before the loop).
sleep/delay for the difference between your ideal frame time and the already elapsed time this for the frame.
At the next frame, you can even try to compensate for inaccuracies in the sleep interval by comparing to the timestamp at the start of the previous loop. Store the difference and add/subtract it from the sleep interval at the end of this loop (sleep/delay can go too long OR too short).
You might want to have an alert mechanism that lets you know if you're timing is too tight(i,e, if your sleep time after all the compensating is less than 0, which would mean you're taking more time to process than your frame rate allows). The effect will be that your game slows down. For extra points, you may want to simplify rendering for a while, if you detect this happening, until you have enough spare capacity again.


Question:
I am using the WebBrowser control to add a WebInterface to C# app. My desire is to verify that only such app is able to connect to our Web server using SSL client certificates.

My idea was to embed the client certificate in the app and just use when connecting via my app. Anybody have a sugestion on how to do this? Or the only way to make it work is to load the key in the X509Store.

If I put it in X509Store, will it make my key available for general Internet Explorer Usage?

Answer:
Are you sure this is what you want to do? If you embed the private key in your application (as your approach entails), an attacker can extract it and use it to authenticate their rogue software.
A server cannot authenticate client software. It can only test whether a client possesses some secret. When you embed a private key in your client and distribute it, it will not be a secret anymore.
I'd recommend authenticating
users
of your software, rather than the software itself. You need to let users generate their own secret, whether it is a password or a private key, and give them an incentive to protect it.


Question:
I'm fresh out of college and have been working in C++ for some time now.  I understand all the basics of C++ and use them, but I'm having a hard time grasping more advanced topics like pointers and classes.  I've read some books and tutorials and I understand the examples in them, but then when I look at some advanced real life examples I cannot figure them out.  This is killing me because I feel like its keeping me from bring my C++ programming to the next level.  Did anybody else have this problem? If so, how did you break through it?
Does anyone know of any books or tutorials that really describe pointers and class concepts well?
or maybe some example code with good descriptive comments using advanced pointers and class techniques?
any help would be greatly appreciated.

Answer:
Pretend a pointer is an array address.
```
```
x = 500; // memory address for hello;
MEMORY[x] = "hello";
print  MEMORY[x];
```
```
its a graphic oversimplification, but for the most part as long as you never want to know what that number is or set it by hand you should be fine.
Back when I understood C I had a few macros I had which more or less permitted you to use pointers just like they
were
an array index in memory. But I've long since lost that code and long since forgotten.
I recall it started with
```
```
#define MEMORY 0;
#define MEMORYADDRESS( a ) *a;
```
```
and that on its own is hardly useful.  Hopefully somebody else can expand on that logic.


Question: Given an instance of System.Reflection.Assembly.

Answer: Not possible. Nothing specifies a "Root" namespace. The default namespace in the options is a visual studio thing, not a .net thing


Question:
I need to attach a file with mailx but at the moment I am not having success.

Here's my code:

subject="Something happened"
to="somebody@somewhere.com"
body="Attachment Test"
attachment=/path/to/somefile.csv

uuencode $attachment | mailx -s "$subject" "$to" << EOF

The message is ready to be sent with the following file or link attachments:

somefile.csv

Note: To protect against computer viruses, e-mail programs may prevent
sending or receiving certain types of file attachments.  Check your
e-mail security settings to determine how attachments are handled.

EOF

Any feedback would be highly appreciated.

Update
I have added the attachment var to avoid having to use the path every time.

Answer:
Well, here are the first few problems you've got.
You appear to be assuming that a mail client is going to handle uuencoded attachment without any headers.  That won't happen.
You're misusing I/O redirection:  uuencode's output and the here-document are both being fed to mailx, which can't happen.
You're misusing uuencode:  if one path is given, it's just a name to give the decoded file, not an input file name.  Giving the file twice will assign the same name to the decoded file as that which was read.  The -m flag forces base64 encode.  But this still isn't going to provide attachment headers for mailx.
You're way better getting a copy of mpack, which will do what you want.
If you must do it, you could do something like this:
```
```
cat <<EOF | ( cat -; uuencode -m /path/to/somefile.csv /path/to/somefile.csv; ) | mailx -s "$subject" "$to"
place your message from the here block in your example here
EOF
```
```
There are lots of other possibilities... but this one still has the here document
as in your example and was easy off the top of my head, and there's no temp file involved.


Question:
I am trying to write a servlet that will send a XML file (xml formatted string) to another servlet via a POST.
(Non essential xml generating code replaced with "Hello there")

   StringBuilder sb=  new StringBuilder();
    sb.append("Hello there");

    URL url = new URL("theservlet's URL");
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Length", "" + sb.length());

    OutputStreamWriter outputWriter = new OutputStreamWriter(connection.getOutputStream());
    outputWriter.write(sb.toString());
    outputWriter.flush();
    outputWriter.close();

This is causing a server error, and the second servlet is never invoked.

Answer:
Don't forget to use:
```
```
connection.setDoOutput( true)
```
```
if you intend on sending output.


Question:
I have a SQL statement that looks like:

SELECT [Phone]
FROM [Table]
WHERE
(
    [Phone] LIKE '[A-Z][a-z]'
    OR [Phone] = 'N/A'
    OR [Phone] LIKE '[0]'
)

The part I'm having trouble with is the where statement with the "LIKEs". I've seen SQL statements where authors used like statements in the way I'm using them above. At first, I thought this might be a version of Regular Expressions but I've since learned.

Is anyone familiar with using like statements in such a way. Note: the "N/A" is working fine.

What I need to match is phone numbers that have characters. Or phone numbers which contain nothing but zero.

Answer:
Check
here
.
[] matches a range of characters.
I think you want something like this:
```
```
SELECT [Phone]
FROM [Table]
WHERE
(
    [Phone] LIKE '%[A-Z]%'
    OR [Phone] LIKE '%[a-z]%'
    OR [Phone] = 'N/A'
    OR [Phone] LIKE '0'
)
```
```


Question:
I have this string

'john smith~123 Street~Apt 4~New York~NY~12345'

Using JavaScript, what is the fastest way to parse this into

var name = "john smith";
var street= "123 Street";
//etc...

Answer:
With JavaScript’s
```
String.prototype.split
```
function:
```
```
var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.
```
```


Question: Sessions in PHP seemed to have changed since the last time I used them, so I'm looking for a simple way of using sessions but at the same time for it to be relatively secure and a good common practice.

Answer:
First off, use cookie based only unless you have a very specific good business reason not to. I had a client that insisted on url based sessions only for a project. very insecure and a pain to work with.
One good idea is to regenerate the session on each request. this makes hijack much less likely. For example.
```
```
session_start();
$old_sessionid = session_id();
session_regenerate_id();
$new_sessionid = session_id();
```
```
Another thing that is good practice is if you are doing some kind of user login as part of the system, completely invalidate and empty the session data on a logout to insure that the user is truly logged out of the system. I have seen systems where logout is just accomplished by removing the session cookie.


Question:
We have multiple MFC apps, which use CMutex( false, "blah" ), where "blah" allows the mutex to work across process boundaries.

One of these apps was re-written without MFC (using Qt instead).  How can I simulate the CMutex using Win32 calls? (Qt's QMutex is not inter-process.)  I prefer not to modify the MFC apps.

Answer:
The following funcs will probably be what you want, they are all documented on MSDN.
```
```
CreateMutex(...)
WaitForSingleObject(...)
ReleaseMutex(...)
```
```


Question:
This isn't legal:

public class MyBaseClass
{
  public MyBaseClass() {}
  public MyBaseClass(object arg) {}
}

public void ThisIsANoNo<T>() where T : MyBaseClass
{
  T foo = new T("whoops!");
}

In order to do this, you have to do some reflection on the type object for T or you have to use Activator.CreateInstance.  Both are pretty nasty.  Is there a better way?

Answer:
```
```
where T : MyBaseClass, new()
```
```
only works w/ parameterless public constructor. beyond that, back to activator.CreateInstance (which really isn't THAT bad).


Question:
My development server (CentOS 5) is running Subversion 1.4.2, and I wish to upgrade it to 1.5.  I have read in various blogs and documents scattered around the web that this may be done by using RPMForge.  I have followed the instructions found on CentOS Wiki, including installing yum-priorities and setting my priorities as indicated (1 and 2 for core repo sources, and 20 for RPMForge).

However, when I attempt to run:

$ yum info subversion

the version number given to me is still 1.4.2, with a status of Installed.  My other option at this point is compiling from source, but I would like to find a package-managed solution for ease of future upgrades.

Any thoughts?

Answer:
If you install
RPMForge
's repos, you should then be able to get a newer package - this isn't working for you?
You should see rpmforge.list in /etc/apt/sources.list.d with a line like:
```
```
repomd http://apt.sw.be redhat/el$(VERSION)/en/$(ARCH)/dag
```
```
I just tested on a clean CentOS 5 install, and
```
yum check-update
```
shows
```
```
subversion.i386                          1.5.2-0.1.el5.rf       rpmforge
subversion-perl.i386                     1.5.2-0.1.el5.rf       rpmforge
```
```
So check your sources list and run check-update again.
Edit: Whoops, lost part of my answer.  Added it back above.


Question:
Let's say I have data structures that're something like this:

Public Class AttendenceRecord
  Public CourseDate As Date
  Public StudentsInAttendence As Integer
End Class

Public Class Course
  Public Name As String
  Public CourseID As String
  Public Attendance As List(Of AttendenceRecord)
End Class

And I want a table that looks something like this:

| Course Name | Course ID | [Attendence(0).CourseDate] | [Attendence(1).CourseDate]| ...
| Intro to CS |  CS-1000  |             23             |              24           | ...
| Data Struct |  CS-2103  |             15             |              14           | ...

How would I, in the general case, get everything to the right of Course ID to be horizontally scrollable, while holding Course Name and Course ID in place? Ideally using a table, listview, or datagrid inside ASP.NET and/or WinForms.

Answer:
In pure .Net I don't know of anything.  There are
CSS Solutions
for a fixed header.  But a fixed left column, in my experience, requires some javascript finangling.
Took me a minute to find the old example.  Host has since gone down.
http://web.archive.org/web/20080215013647/http://www.litotes.demon.co.uk/example_scripts/tableScroll.html
This is the mechanism I used to get it to work:  Take a normal table, and separate it out into 4 other tables.  Get the column widths and row heights to match up using business constraints, and then link the onscroll event to scroll the other tables.


Question: I have a flash app (SWF) running Flash 8 embedded in an HTML page. How do I get flash to reload the parent HTML page it is embedded in? I've tried using ExternalInterface to call a JavaScript function to reload the page but that doesn't seem to work.

Answer:
Try something like this:
```
getURL("javascript:location.reload(true)");
```


Question:
How do you organize your Extension Methods? Say if I had extensions for the object class and string class I'm tempted to separate these extension methods into classes IE:

public class ObjectExtensions
{
    ...
}

public class StringExtensions
{
    ...
}

am I making this too complicated or does this make sense?

Answer:
There are two ways that I organize the extension methods which I use,
1) If the extension is specific to the project I am working on, then I keep it in the same project/assembly, but in its own namespace.
2) If the extension is of a kind so that I may or is using it in other projects too, then I separate them in a common assembly for extensions.
The most important thing to keep in mind is, what is the scope which I will be using these in? Organizing them isn't hard if I just keep this in mind.


Question:
Is there any way to use a constant as a hash key?

For example:

use constant X => 1;

my %x = (X => 'X');

The above code will create a hash with "X" as key and not 1 as key. Whereas, I want to use the value of constant X as key.

Answer:
```
use constant
```
actually makes constant subroutines.
To do what you want, you need to explicitly call the sub:
```
```
use constant X => 1;

my %x = ( &X => 'X');
```
```
or
```
```
use constant X => 1;

my %x = ( X() => 'X');
```
```


Question: Every so often I get an error saying one of my tables "is marked as crashed and should be repaired". I then do a REPAIR TABLE and repair it. What causes them to be marked as crashed and how can I prevent it? I am using MyISAM tables with MySQL 5.0.45.

Answer:
It could be many things, but
MySQL Performance Blog
mentions bad memory, OS or MySQL bugs that could cause hidden corruption. Also, that and
another article
mention several things to keep in mind when doing crash recovery.


Question:
I'd like to make status icons for a C# WinForms TreeList control.  The statuses are combinations of other statuses (eg. a user node might be inactive or banned or inactive and banned), and the status icon is comprised of non-overlapping, smaller glyphs.

I'd really like to avoid having to hand-generate all the possibly permutations of status icons if I can avoid it.

Is it possible to create an image list (or just a bunch of bitmap resources or something) that I can use to generate the ImageList programmatically?

I'm poking around the System.Drawing classes and nothing's jumping out at me.  Also, I'm stuck with .Net 2.0.

Answer:
```
```
Bitmap image1 = ...
Bitmap image2 = ...

Bitmap combined = new Bitmap(image1.Width, image1.Height);
using (Graphics g = Graphics.FromImage(combined)) {
  g.DrawImage(image1, new Point(0, 0));
  g.DrawImage(image2, new Point(0, 0);
}

imageList.Add(combined);
```
```


Question:
What would the differences be in implementing remote business logic?

Currently we are planning on using ADF to develop front-end web applications (moving from Struts). What are the differences between the front end calling EJBs using TopLink vs ADF Business Components through RMI in terms of scalability as the migration from Struts to ADF will also encompass PL/SQL and Oracle Forms, thus increasing the user count drastically?

Answer:
I'm going through a similar situation right now. I'm am not an expert, but here what I've gathered from my experience. Whether EJB's using Toplink or ADF scales better depends quite a bit on the particulars of your situation. In some cases one might be better than the other, but I get the feeling that they are both pretty good solutions.
However since you mention that the project also involves the migration of Oracle Forms, then it seems that ADF would be the best choice since Oracle seems to be positioning JDeveloper and ADF as the successor for Forms and Reports (see the
ADF Documentation targeting Forms and Designer Developers
).