q:
I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.

For example, let's say I have three files. Using execfile:

script_1.py calls script_2.py.

In turn, script_2.py calls script_3.py.

How can I get the file name and path of script_3.py, from code within script_3.py, without having to pass that information as arguments from script_2.py?

(Executing os.getcwd() returns the original starting script's filepath not the current file's.)

[A]
It's not entirely clear what you mean by "the filepath of the file that is currently running within the process".
```
sys.argv[0]
```
usually contains the location of the script that was invoked by the Python interpreter.
Check the
sys documentation
for more details.
As @Tim and @Pat Notz have pointed out, the __file__ attribute provides access to
the file from which the module was
  loaded, if it was loaded from a file


q:
I'm working on moving a client/server application created with C# and WinForms into the SOA/WPF/Silverlight world. One of the big hurdles is the design of the UI. My current UI is MDI driven and users rely heavily on child windows, having many open at the same time and toggling back and forth between them.

What might be the best way to recreate the UI functionality in an MDI-less environment? (I've no desire to create MDI functionality on my own in WPF). Tabs? A list panel that toggles different controls?

[A]
I think the answer is really going to be up to your users -- I'd set up some prototypes with multiple paradigms and let them provide some input.  The last thing you want to do is introduce a new UI paradigm without having any end-user input.
Tabs are really popular now, but don't allow side-by-side viewing, so if that is a requirement you may want to go with more of an outlook-style setup, with multiple panels that can be activated, hidden and resized.
One thing that you might want to do is to code your app as a composite UI, where each view is built independently from its container (be it a child window, tab or accordion, etc.), and is just "dropped in" in the designer.  That will protect you from when the users change their minds about the navigation paradigm in the future.

s: huggingface

c: devops

d: intermediate


q:
How do I format a number in Java?

What are the "Best Practices"?

Will I need to round a number before I format it?

32.302342342342343 => 32.30

.7323 => 0.73

etc.

[A]
From
this thread
, there are different ways to do this:
```
```
double r = 5.1234;
System.out.println(r); // r is 5.1234

int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);

// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();

System.out.println(r); // r is 5.12
```
```
```
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
```
```
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();

// The value of dd2dec will be 100.24
```
```
The
DecimalFormat()
seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code.


q:
One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover

does anyone have any ideas or have created such a thing before

we have a couple ideas but they involve to much database usage

We prefer that it be FREE!!!


q:
I have a two dimensional array that I need to load data into.  I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).

I have it declared as follows:

float[,] _calibrationSet;
    ....
int calibrationRow = 0;
While (recordsToRead)
{
  for (int i = 0; i < SensorCount; i++)
   {
     _calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
   }
   calibrationRow++;
}

This causes a NullReferenceException, so when I try to initialize it like this:

_calibrationSet = new float[,];

I get an "Array creation must have array size or array initializer."

Thank you,
Keith

[A]
You can't use an array.
Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...)
Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage).
Example:
```
```
List<float[]> _calibrationSet = new List<float[]>();

// ...

while (recordsToRead)
{
    float[] record = new float[SensorCount];
    for (int i = 0; i < SensorCount; i++)
    {
        record[i] = calibrationArrayView.ReadFloat();
    }
    _calibrationSet.Add(record);
}

// access later: _calibrationSet[record][sensor]
```
```
Oh, and it's worth noting (as
Grauenwolf
did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records.


q: Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?

[A]
You can only tell whether the current thread holds a normal lock (
```
Thread.holdsLock(Object)
```
). You can't get a reference to the thread that has the lock without native code.
However, if you're doing anything complicated with threading, you probably want to familiarize yourself with the java.util.concurrent packages. The
```
ReentrantLock
```
does allow you to get its owner (but its a protected method, so you'd have to extend this). Depending on your application, it may well be that by using the concurrency packages, you'll find that you don't need to get the lock's owner after all.
There are non-programmatic methods to find the lock owners, such as signaling the JVM to issue a thread dump to stderr, that are useful to determine the cause of deadlocks.


q: I'm looking at sessions in Django, and by default they are stored in the database.  What are the benefits of filesystem and cache sessions and when should I use them?

[A]
The filesystem backend is only worth looking at if you're not going to use a database for any other part of your system. If you are using a database then the filesystem backend has nothing to recommend it.
The memcache backend is much quicker than the database backend, but you run the risk of a session being purged and some of your session data being lost.
If you're a really, really high traffic website and code carefully so you can cope with losing a session then use memcache. If you're not using a database use the file system cache, but the default database backend is the best, safest and simplest option in almost all cases.


q:
I'm looking at developing a device which will need to support Ethernet over USB (hosted in Linux, XP, and Vista). As I understand it, Vista and Linux support the industry standard USB CDC. However, in classic Windows style, XP only supports it's own Remote NDIS. So, now I'm thinking of just bowing down and doing it over RNDIS, as opposed to rolling my own CDC driver for XP.

I've been reading some older documentation that says even XP is pretty buggy with NDIS (suprise!). Does anyone have experience with XP's RNDIS drivers? Are they safe for product development? Any insight would be much appreciated.


q:
I'm having a strange problem.

I have to use GetPostBackEventRefence to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?

This is what I'm missing after the postback:

<script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
    var theform;
    if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
        theform = document.Main;
    }
    else {
        theform = document.forms["Main"];
    }
    theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
    theform.__EVENTARGUMENT.value = eventArgument;
    theform.submit();
}
// -->
</script>

[A]
The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally generate a submit but requre a postback) being displayed on the page.
The __doPostback function will only be put into the page if ASP thinks that one of your controls requires it.
If you aren't using one of those you can use:
```
```
Page.ClientScript.GetPostBackClientHyperlink(controlName, "")
```
```
to add the function to your page


q:
Suppose I have the following C code.

unsigned int u = 1234;
int i = -5678;

unsigned int result = u + i;

What implicit conversions are going on here, and is this code safe for all values of u and i? (Safe, in the sense that even though result in this example will overflow to some huge positive number, I could cast it back to an int and get the real result.)

[A]
Short Answer
Your
```
i
```
will be
converted
to an unsigned integer by adding
```
UINT_MAX + 1
```
, then the addition will be carried out with the unsigned values, resulting in a large
```
result
```
(depending on the values of
```
u
```
and
```
i
```
).
Long Answer
According to the C99 Standard:
6.3.1.8 Usual arithmetic conversions
If both operands have the same type, then no further conversion is needed.
Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
In your case, we have one unsigned int (
```
u
```
) and signed int (
```
i
```
). Referring to (3) above, since both operands have the same rank, your
```
i
```
will need to be
converted
to an unsigned integer.
6.3.1.3 Signed and unsigned integers
When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
Now we need to refer to (2) above. Your
```
i
```
will be converted to an unsigned value by adding
```
UINT_MAX + 1
```
. So the result will depend on how
```
UINT_MAX
```
is defined on your implementation. It will be large, but it will not overflow, because:
6.2.5 (9)
A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
Bonus: Arithmetic Conversion Semi-WTF
```
```
#include <stdio.h>

int main(void)
{
  unsigned int plus_one = 1;
  int minus_one = -1;

  if(plus_one < minus_one)
    printf("1 < -1");
  else
    printf("boring");

  return 0;
}
```
```
You can use this link to try this online:
https://repl.it/repls/QuickWhimsicalBytes
Bonus: Arithmetic Conversion Side Effect
Arithmetic conversion rules can be used to get the value of
```
UINT_MAX
```
by initializing an unsigned value to
```
-1
```
, ie:
```
```
unsigned int umax = -1; // umax set to UINT_MAX
```
```
This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information:
Is it safe to use -1 to set all bits to true?


q:
If I have 2 query sources how do I find ones that are in one that are not in the other?

example of join to find items in both:

var results = from item1 in qs1.Items
   join item2 in qs2 on item1.field1 equals item2.field2
   select item1;

So what would the linq code be to return the items in qs1 that are not in qs2?

[A]
From
Marco Russo
```
```
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
    from c in dc.Customers
    where !(from o in dc.Orders
            select o.CustomerID)
           .Contains(c.CustomerID)
    select c;
foreach (var c in query) Console.WriteLine( c );
```
```


q:
I was browsing this thread, which has good recommendation but a bit too general for me.

So, if anyone has a collection of nice game programming feeds,please share them. :)

(both general and specific topics are welcome)

[A]
If you are catpuring logging information for future searching and anaylsis perhaps a database would be a better answer.
As for your solution.  Flat files do not scale well at all where as a database scale much better.  I wouldn't split the files either, that just compounds the scalability issue.  If you have to use a flat file I would probably try keeping the meta data in a csv (less over head) and the data in a series of files indexed by the csv file.  That way all the data doesn't impact your index file.  Just my thoughts.


q:
How does unix handle full path name with space and arguments ?

In windows we quote the path and add the command-line arguments after, how is it in unix?

 "c:\foo folder with space\foo.exe" -help

update:

I meant how do I recognize a path from the command line arguments.

[A]
You can quote if you like, or you can escape the spaces with a preceding \, but most UNIX paths (Mac OS X aside) don't have spaces in them.
```
```
/Applications/Image\ Capture.app/Contents/MacOS/Image\ Capture

"/Applications/Image Capture.app/Contents/MacOS/Image Capture"

/Applications/"Image Capture.app"/Contents/MacOS/"Image Capture"
```
```
All refer to the same executable under Mac OS X.
I'm not sure what you mean about recognizing a path - if any of the above paths are passed as a parameter to a program the shell will put the entire string in one variable - you don't have to parse multiple arguments to get the entire path.


q: My drupal site (internal) will not display the TinyMCE editor when using Google Chrome browser. Has anyone gotten TinyMCE to work with Chrome in Drupal 5?

[A]
There are a number of known incompatibilities between TinyMCE and WebKit (the rendering engine used by Chrome).  If you're using TinyMCE 2.x, you might want to try the
Safari plug-in to TinyMCE
; Safari also uses WebKit.  I gather also that
TinyMCE 3.x has better support for Safari/WebKit
than TinyMCE 2.x, so you might want to try upgrading to the latest 3.x version.
HTH
Alastair


q:
How would you find the fractional part of a floating point number in PHP?

For example, if I have the value 1.25, I want to return 0.25.


q:
Do any editors honer C #line directives with regards to goto line features?

Context:
I'm working on a code generator and need to jump to a line of the output but the line is specified relative to the the #line directives I'm adding.
I can drop them but then finding the input line is even a worse pain

[A]
```
#line
```
directives are normally inserted by the precompiler, not into source code, so editors won't usually honor that if the file extension is
```
.c
```
.
However, the normal file extension for post-compiled files is
```
.i
```
or
```
.gch
```
, so you might try using that and see what happens.


q:
Any ideas what the average user's download speed is? I'm working on a site that streams video and am trying to figure out what an average download speed as to determine quality.

I know i might be comparing apples with oranges but I'm just looking for something to get a basis for where to start.

[A]
You could try looking at the lower tier offerings from AT&T and Comcast.  Probably 1.5 Mbps for the basic level (which I imagine most people get).
The "test your bandwidth" sites may have some stats on this, too.


q: I have a scenario wherein, for example, I need to repeat a list of US states and display a table of cities and city populations after the name of each state. The design requirement dictates that every outer repetition must be the name of a state followed by a table of cities, and that requirement cannot be changed at this time. Are there disadvantages to nesting a GridView within a Repeater and then binding each repeated GridView during the Repeater's ItemDataBound event? What are some alternative solutions?

[A]
If it were me, I'd reverse the question and ask why
I should
use a GridView,  If you need a bunch of built-in features like paging and sorting, then the GridView might be a good fit.  If you just want tabular data, I'd reconsider.  Why?  Because with GridView you're getting a whole bunch of stuff you won't use, your ViewState will be potentially huge, and your page performance will be slower.
I'm not a bigot when it comes to GridView, but I only use them when there is a damn good reason.


q:
So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this

if(Debug.Mode){

<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}

I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.

[A]
I should had used google.
```
```
#if DEBUG
    Console.WriteLine("Debug mode.")
#else
    Console.WriteLine("Release mode.")
#endif
```
```
Make sure that the option "Configuration settings" -> "Build" "Define DEBUG
constant" in the project properties is checked.


q:
I'm using Helicon's ISAPI Rewrite 3, which basically enables .htaccess in IIS.  I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com.  I used the following rule from the examples but it affects subdomains:

RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]

This works for most part, but is also redirect sub.example.com to www.sub.example.com.  How can I rewrite the above rule so that subdomains do not get redirected?

[A]
Can't you adjust the RewriteCond to only operate on example.com?
```
```
RewriteCond %{HTTP:Host} ^example\.com(.*) [NC]
```
```


q:
One of the things I miss the most in ActionScript is the lack of operator overloading, in particular ==. I kind of work around this issue by adding a "Compare" method to my classes, but that doesn't help in many cases, like when you want to use things like the built in Dictionary.

Is there a good way to work around this problem?

[A]
Nope.
But it doesn't hurt to add
```
equals
```
methods to your own classes. I try to never use
```
==
```
when comparing objects (the same goes for
```
===
```
, which is the same thing for objects) since it only checks
identity
.
Sadly all the collections in Flash and Flex assume that identity is the only measure of equality that is needed.
There are hints in Flex that someone wanted to alleviate this problem at one time, but it seems like it was abandoned: there is an interface called
IUID
, and it is mentioned in the
Flex Developer's Guide
, but it is not used anywhere. Not even the collections in Flex use it to determine equality. And since you are asking for a solution for Flash, it may not have helped you anyway.
I've written some more about this (in the context of Flex) on my blog:
Is there no equality?
.


q:
I have some HTML that is generated via a Rich Text Editor outside of my Flex application but would like to display it inside Flex.

The HTML is simple HTML tags, things like styles, anchors, and possibly image tags, is there a control that would let me render this HTML in flex or am I going to have to roll up my sleeves and roll my own?

Any ideas appreciated...Thanks.

[A]
If the HTML is
really
simple, you can display it in a normal label or textarea component, If it is more complex, I'll quote what I answered
in this question
. The discussion there also has a little more info.
If it is complex HTML and Javascript, one possible way is
HTMLComponent
, a method that uses an iframe over your flash to make it appear like the HTML is in your app. There are a few downsides to this method however - most of them described in detail
at Deitte.com
.
If this can move offline, you could use Air (it has an mx:HTML component built in).
Deitte.com
has a detail of this technique as well.


q:
What does it mean when a PostgreSQL process is "idle in transaction"?

On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:

postgres: user db 127.0.0.1(55658) idle in transaction

Does this mean that some of the processes are hung, waiting for a transaction to be committed?  Any pointers to relevant documentation are appreciated.

[A]
The
PostgreSQL manual
indicates that this means the transaction is open (inside BEGIN) and idle.  It's most likely a user connected using the monitor who is thinking or typing.  I have plenty of those on my system, too.
If you're using Slony for replication, however, the
Slony-I FAQ
suggests
```
idle in transaction
```
may mean that the network connection was terminated abruptly.  Check out the discussion in that FAQ for more details.


q:
Ruby has two different exceptions mechanisms: Throw/Catch and Raise/Rescue.

Why do we have two?

When should you use one and not the other?

[A]
I think
http://hasno.info/ruby-gotchas-and-caveats
has a decent explanation of the difference:
catch/throw are not the same as raise/rescue. catch/throw allows you to quickly exit blocks back to a point where a catch is defined for a specific symbol, raise rescue is the real exception handling stuff involving the Exception object.


q:
I am looking for a way to delete all files older than 7 days in a batch file.  I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.

Similar things can be done in BASH in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.

[A]
Enjoy:
```
```
forfiles -p "C:\what\ever" -s -m *.* -d <number of days> -c "cmd /c del @path"
```
```
See
```
forfiles
```
documentation
for more details.
For more goodies, refer to
An A-Z Index of the Windows XP command line
.
If you don't have
```
forfiles
```
installed on your machine, copy it from any
Windows Server 2003
to your Windows XP machine at
```
%WinDir%\system32\
```
. This is possible since the EXE is fully compatible between Windows Server 2003 and Windows XP.
Later versions of Windows and Windows Server have it installed by default.
For Windows 7 and newer (including Windows 10):
The syntax has changed a little. Therefore the updated command is:
```
```
forfiles /p "C:\what\ever" /s /m *.* /D -<number of days> /C "cmd /c del @path"
```
```


q: See here http://www.hanselman.com/blog/InSearchOfThePerfectMonospacedProgrammersFontInconsolata.aspx - for want of a better description - the statement block highlighting - eg in the pics on the link the "statement blocks" are grouped with a vertical line. I understand this is a feature of CodeRush - does R# have either anything similar, or a plugin to do the same?

[A]
R# has a feature called Highlight current line, which you have to enable in the ReSharper options.  This looks like crap on dark background, high contrast themes, so if you use one I'd suggest going into the Visual Studio options, under Fonts & Colors and going to "ReSharper - current Line" and making the background color a darker shade that doesn't have as much contrast with the background.
R# also has matching brace highlighting, which is color-configurable as well under the same VS option dialog.
Does that answer you question?


q:
Consider the Oracle emp table. I'd like to get the employees with the top salary with department = 20 and job = clerk. Also assume that there is no "empno" column, and that the primary key involves a number of columns. You can do this with:

select * from scott.emp
where deptno = 20 and job = 'CLERK'
and sal =  (select max(sal) from scott.emp
            where deptno = 20 and job = 'CLERK')

This works, but I have to duplicate the test deptno = 20 and job = 'CLERK', which I would like to avoid. Is there a more elegant way to write this, maybe using a group by? BTW, if this matters, I am using Oracle.

[A]
The following is slightly over-engineered, but is a good SQL pattern for "top x" queries.
```
```
SELECT
 *
FROM
 scott.emp
WHERE
 (deptno,job,sal) IN
 (SELECT
   deptno,
   job,
   max(sal)
  FROM
   scott.emp
  WHERE
   deptno = 20
   and job = 'CLERK'
  GROUP BY
   deptno,
   job
  )
```
```
Also note that this will work in Oracle and Postgress (i think) but not MS SQL. For something similar in MS SQL see question
SQL Query to get latest price


q:
Jeff covered this a while back on his blog in terms of 32 bit Vista.

Does the same 32 bit 4 GB memory cap that applies in 32 bit Vista apply to 32 bit Ubuntu? Are there any 32 bit operating systems that have creatively solved this problem?

[A]
In theory, all 32-bit OSes have that problem. You have 32 bits to do addressing.
```
```
2^32 bits / 2^10 (bits per kb) / 2^10 (kb per mb) / 2^10 (mb per gb) = 2^2 = 4gb.
```
```
Although there are some ways around it. (Look up the jump from 16-bit computing to 32-bit computing. They hit the same problem.)


q:
I have two spreadsheets... when one gets modified in a certain way I want to have a macro run that modifies the second in an appropriate manner.  I've already isolated the event I need to act on (the modification of any cell in a particular column), I just can't seem to find any concrete information on accessing and modifying another spreadsheet (this spreadsheet is located on a different LAN share also... the user has access to both, though).

Any help would be great.  References on how to do this or something similar are just as good as concrete code samples.

[A]
In Excel, you would likely just write code to open the other worksheet, modify it and then save the data.
See
this tutorial
for more info.
I'll have to edit my VBA later, so pretend this is pseudocode, but it should look something like:
```
```
Dim xl: Set xl = CreateObject("Excel.Application")
xl.Open "\\the\share\file.xls"

Dim ws: Set ws = xl.Worksheets(1)
ws.Cells(0,1).Value = "New Value"
ws.Save

xl.Quit constSilent
```
```


q: It seems like IDataReader.Read() is always true at least one time (If I'm wrong about this let me know.)  So how do you tell if it has no records without just wrapping it in a try/catch?

[A]
```
```
if(dr.Read())
{
   //do stuff
}
else
{
 //it's empty
}
```
```
usually you'll do this though:
```
```
while(dr.Read())
{
}
```
```


q:
I'm trying to create an SSIS package that takes data from an XML data source and for each row inserts another row with some preset values.  Any ideas?  I'm thinking I could use a DataReader source to generate the preset values by doing the following:

SELECT 'foo' as 'attribute1', 'bar' as 'attribute2'

The question is, how would I insert one row of this type for every row in the XML data source?

[A]
I've never tried it, but it looks like you might be able to use a
Derived Column transformation
to do it: set the expression for attribute1 to
```
"foo"
```
and the expression for attribute2 to
```
"bar"
```
.
You'd then transform the original data source, then only use the derived columns in your destination.  If you still need the original source, you can Multicast it to create a duplicate.
At least I think this will work, based on the documentation.  YMMV.


q:
Say I have a list as follows:

item1

item2

item3

Is there a CSS selector that will allow me to directly select the last item of a list? In this case item 3.

Cheers!

[A]
Not that i'm aware of.  The traditional solution is to tag the first & last items with class="first" & class="last" so you can identify them.
The CSS psudo-class
first-child
will get you the first item but not all browsers support it. CSS3 will have
last-child too
(this is currently supported by Firefox, Safari but not IE 6/7/beta 8)


q:
I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    return a.attr - b.attr
})

but found that - doesn't appear to work with strings in JavaScript. How can I sort a list of objects based on an attribute with type string?

[A]
Use
```
String.prototype.localeCompare
```
a per your example:
```
```
list.sort(function (a, b) {
    return ('' + a.attr).localeCompare(b.attr);
})
```
```
We force a.attr to be a string to avoid exceptions.
```
localeCompare
```
has been supported
since Internet Explorer 6
and Firefox 1. You may also see the following code used that doesn't respect a locale:
```
```
if (item1.attr < item2.attr)
  return -1;
if ( item1.attr > item2.attr)
  return 1;
return 0;
```
```


q: I'm tearing my hair out with this one. If I start a block comment /* in VS.NET 2005+ then carriage return, Visual Studio insists that I have another asterisk *. I know there's an option to turn this off but I just can't find it. Anyone know how to turn this feature off?

[A]
Update: this setting was changed in VS 2015 update 2. See
this answer
.
This post
addresses your question. The gist of it is:
```
```
Text Editor > C# > Advanced > Generate XML documentation comments for ///
```
```


q: When a template is added using the add-template stsadm command, it becomes available to everyone when creating a subsite. Is there any way to make it only available when a site collection is being created?

[A]
go to site actions -> Site Settings -> view all site settings -> site templates and page layouts and remove the site template from the list of allowed items.
Gary Lapointe may also have made an stsadm extenstion for it; check
stsadm.blogspot.com
Mauro Masucci
http://www.brantas.co.uk


q:
I work for a company whose primary business is not software related. Most documentation for using source control is written with a development team writing for commercial or open source projects in mind. As someone who writes in house software I can say that work is done differently then it would be in a commercial or open source setting. In addition there are stored procedures and database scripts that need to be kept in sync with the code.

In particular I am looking to get suggestions on how best to structure the repository with in house software in mind. Most documentation suggests trunk, branches, tags etc. And procedures for keeping production, test and development environments in sync with their respective sections in the repository etc.

[A]
You could use a service like www.unfuddle.com to set up a free SVN or GIT repository.
We use Unfuddle and it's really great. There are free and paid versions (depending on your needs).
Or, you could of course set up a local copy. There are plenty of tutorials to be found via Google for that:
http://www.google.com/search?rlz=1C1GGLS_enUS291&aq=f&sourceid=chrome&ie=UTF-8&q=set+up+svn


q: How can I retrieve the page title of a webpage (title html tag) using Python?

[A]
I'll always use
lxml
for such tasks. You could use
beautifulsoup
as well.
```
```
import lxml.html
t = lxml.html.parse(url)
print(t.find(".//title").text)
```
```
EDIT based on comment:
```
```
from urllib2 import urlopen
from lxml.html import parse

url = "https://www.google.com"
page = urlopen(url)
p = parse(page)
print(p.find(".//title").text)
```
```


q:
I have a table in a MySql database that stores user accounts. One of the columns, expires, stores an expiration date but defaults to NULL. I need to be able to remove an expiration date and set it back to the default value.

Currently, all of my CRUD routines are written using MySqlCommand with parameters. Can this be done directly with a MySqlParameter, or do I have to create an alternate command object to handle this eventuality?

[A]
It's not clear what conditions you're talking about. If you want to set column to default value, you can use
DbNull.Value
;
```
```
command.AddWithValue("@param", DbNull.Value);

or

command.Parameters.Add("@param", <data type>).Value = DBNull.Value;
```
```


q: How can you find out what are the long running queries are on Informix database server? I have a query that is using up the CPU and want to find out what the query is.

[A]
```
```
SELECT ELAPSED_TIME_MIN,SUBSTR(AUTHID,1,10) AS AUTH_ID,
AGENT_ID, APPL_STATUS,SUBSTR(STMT_TEXT,1,20) AS SQL_TEXT
FROM SYSIBMADM.LONG_RUNNING_SQL
WHERE ELAPSED_TIME_MIN > 0
ORDER BY ELAPSED_TIME_MIN DESC
```
```
Credit:
SQL to View Long Running Queries


q: What object do you query against to select all the table names in a schema in Oracle?

[A]
You may use:
```
```
select tabname from tabs
```
```
to get the name of tables present in schema.


q: Is there any performance to be gained these days from compiling java to native code, or do modern hotspot compilers end up doing this over time anyway?

[A]
Memory performance or CPU performance? Or are they the same these days?
My only evidence is anecdotal and on a different platform: after porting a bunch of CPU-hungry apps to C# (.NET 2.0), I did not notice substantial loss in performance (I do not consider 10% substantial). Well written code seems to perform well on a variety of architectures.
Most apps spend/waste time with:
IO operations that will not benefit from static (compile-time) analysis.
Bad Algorithms that will not benefit from static analysis.
Bad Memory layouts in critical CPU inner loops. While it is technically possible that compilers help us here, I have yet to see a real compiler do anything interesting.
So based upon my experience, unless you are writing a video codec, there is no benefit to compiling Java apps vs. just relying upon the hotspot compilers.


q:
I'm wondering what strategies people use for reduced sign on with legacy applications and how effective they have found them?

We have an ASP.Net based intranet and own a lot of the legacy applications, but not all.  We also have BizTalk and are considering the use of it's SSO engine too.

[A]
A good compromise between effort/rework and the convenience of single sign on is to continue to maintain a list of users, privileges, roles etc in the legacy app.  Make the changes necessary to automatically log the user into your application based on their user account (usually their Windows or network account).
I'm currently running a couple of applications that use this method of sign on, and it makes them seem more integrated even though they aren't.
Another advantage we've found is that it stops people from sharing passwords to legacy applications.  They're much less likely to hand out an admin password that also gives others access to their email or payroll details!


q: How do you get around this Ajax cross site scripting problem on FireFox 3?

[A]
If you're using jQuery it has a callback function to overcome this:
http://docs.jquery.com/Ajax/jQuery.ajax#options
As of jQuery 1.2, you can load JSON
  data located on another domain if you
  specify a JSONP callback, which can be
  done like so: "myurl?callback=?".
  jQuery automatically replaces the ?
  with the correct method name to call,
  calling your specified callback. Or,
  if you set the dataType to "jsonp" a
  callback will be automatically added
  to your Ajax request.
Alternatively you could make your ajax request to a server-side script which does the cross-domain call for you, then passes the data back to your script


q:
So I'm running PPP under linux with a cellular modem.  The program I'm writing needs to know if the link is active before sending any data.

What are my options to check

if the link is available

if it routes to a server I control (it doesn't go to the internet as I said earlier)

Also, what is the best way to restart it - I'd like to have program control over when it starts and stops, so I assume an init.d isn't appropriate.  Using system() doesn't seem to give a PID, are there other options besides fork() and the gaggle of exec??() calls?

C on Linux on ARM (custom distribution using buildroot).

[A]
You could parse
```
/proc/net/route
```
.


q:
For a project I'm working on. I need to look for an executable on the filesystem. For UNIX derivatives, I assume the user has the file in the mighty $PATH variable, but there is no such thing on Windows.

I can safely assume the file is at most 2 levels deep into the filesystem, but I don't know on what drive it will be. I have to try all drives, but I can't figure out how to list all available drives (which have a letter assigned to it).

Any help?

EDIT: I know there is a %PATH% variable, but it is not as integrated as in UNIX systems. For instance, the application I'm looking for is OpenOffice. Such software would not be in %PATH%, typically.

[A]
Of course there is a
```
PATH
```
environment variable
in Windows
.
```
%PATH%
```
This variable contains a semicolon-delimited list of directories in which the command interpreter will search for executable files. Equivalent to the UNIX $PATH variable.


q:
I'm a bit stuck on this. Basically I want to do something like the following SQL query in LINQ to SQL:

SELECT f.*
FROM Foo f
WHERE f.FooId IN (
    SELECT fb.FooId
    FROM FooBar fb
    WHERE fb.BarId = 1000
)

Any help would be gratefully received.

[A]
Try using two separate steps:
```
```
// create a Dictionary / Set / Collection fids first
var fids = (from fb in FooBar
            where fb.BarID = 1000
            select new { fooID = fb.FooID, barID = fb.BarID })
            .ToDictionary(x => x.fooID, x => x.barID);

from f in Foo
where fids.HasKey(f.FooId)
select f
```
```


q:
The Sun Documentation for DataInput.skipBytes states that it "makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes. However, it may skip over some smaller number of bytes, possibly zero. This may result from any of a number of conditions; reaching end of file before n bytes have been skipped is only one possibility."

Other than reaching end of file, why might skipBytes() not skip the right number of bytes? (The DataInputStream I am using will either be wrapping a FileInputStream or a PipedInputStream.)

If I definitely want to skip n bytes and throw an EOFException if this causes me to go to the end of the file, should I use readFully() and ignore the resulting byte array? Or is there a better way?

[A]
1) There might not be that much data available to read (the other end of the pipe might not have sent that much data yet), and the implementing class might be non-blocking (i.e. it will just return what it can, rather than waiting for enough data to fulfil the request).
I don't know if any implementations actually behave in this way, however, but the interface is designed to permit it.
Another option is simply that the file gets closed part-way through the read.
2) Either readFully() (which will always wait for enough input or else fail) or call skipBytes() in a loop.  I think the former is probably better, unless the array is truly vast.


q:
I want to get the base 10 logarithm of a Fixnum using Ruby, but found that n.log or n.log10 are not defined. Math::log is defined but uses a different base than 10.

What is the easiest way to get the base 10 logarithm of a Fixnum?

[A]
Reading the documentation for module Math the answer is really obvious:
```
```
Math::log10(n)
```
```
This gives the base 10 logarithm of n.


q:
How do you get a Media Type (MIME type) from a file using Java?  So far I've tried JMimeMagic & Mime-Util. The first gave me memory exceptions, the second doesn't close its streams properly.

How would you probe the file to determine its actual type (not merely based on the extension)?

[A]
Unfortunately,
```
```
mimeType = file.toURL().openConnection().getContentType();
```
```
does not work, since this use of URL leaves a file locked, so that, for example, it is undeletable.
However, you have this:
```
```
mimeType= URLConnection.guessContentTypeFromName(file.getName());
```
```
and also the following, which has the advantage of going beyond mere use of file extension, and takes  a peek at content
```
```
InputStream is = new BufferedInputStream(new FileInputStream(file));
mimeType = URLConnection.guessContentTypeFromStream(is);
 //...close stream
```
```
However, as suggested by the comment above, the built-in table of mime-types is quite limited, not including, for example, MSWord and PDF. So, if you want to generalize, you'll need to go beyond the built-in libraries, using, e.g., Mime-Util (which is a great library, using both file extension and content).


q:
what is the best method for inter process communication in a multithreaded java app.

It should be performant (so no JMS please) easy to implement and reliable,so that
objects & data can be bound to one thread only?

Any ideas welcome!

[A]
Could you clarify a bit?  Do you mean IPC in a single JVM? (Multiple threads, yes, but at an OS-level only one process.)  Or do you mean multiple JVMs?  (And truly OS-level inter process communications.)
If it is the first, then maybe something out of
java.util.concurrent
, like
ConcurrentLinkedQueue
would do the trick.  (I pass message around inbetween my threads with classes from java.util.concurrent with success.)
If the later, then I'm going to just guess and suggest taking a look at
RMI
, although I don' think it qualifies as fully reliable--you'd have to manage that a bit more 'hands on' like.


q:
In PostgreSQL, I can do something like this:

ALTER SEQUENCE serial RESTART WITH 0;

Is there an Oracle equivalent?

[A]
A true restart is not possible
AFAIK
. (Please correct me if I'm wrong!).
However, if you want to set it to 0, you can just delete and recreate it.
If you want to set it to a specific value, you can set the INCREMENT to a negative value and get the next value.
That is, if your sequence is at 500, you can set it to 100 via
```
```
ALTER SEQUENCE serial INCREMENT BY -400;
SELECT serial.NEXTVAL FROM dual;
ALTER SEQUENCE serial INCREMENT BY 1;
```
```


q:
Given a path such as "mydir/myfile.txt", how do I find the file's absolute path in Python? E.g. on Windows, I might end up with:

"C:/example/cwd/mydir/myfile.txt"

[A]
```
```
>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
```
```
Also works if it is already an absolute path:
```
```
>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
```
```


q:
I have a list of structs and I want to change one element. For example :

MyList.Add(new MyStruct("john");
MyList.Add(new MyStruct("peter");

Now I want to change one element:

MyList[1].Name = "bob"

However, whenever I try and do this I get the following error:

Cannot modify the return value of
  System.Collections.Generic.List.this[int]‘ because it is not
  a variable

If I use a list of classes, the problem doesn't occur.

I guess the answer has to do with structs being a value type.

So, if I have a list of structs should I treat them as read-only? If I need to change elements in a list then I should use classes and not structs?

[A]
```
```
MyList[1] = new MyStruct("bob");
```
```
structs in C# should almost always be designed to be immutable (that is, have no way to change their internal state once they have been created).
In your case, what you want to do is to replace the entire struct in specified array index, not to try to change just a single property or field.


q:
Typically when writing new code you discover that you are missing a #include because the file doesn't compile. Simple enough, you add the required #include. But later you refactor the code somehow and now a couple of #include directives are no longer needed. How do I discover which ones are no longer needed?

Of course I can manually remove some or all #include lines and add them back until the file compiles again, but this isn't really feasible in a large project with thousands of files. Are there any tools available that will help automating task?

[A]
You can use
PC-Lint/FlexeLint
to do that.
Unusually there isn't a free OS version of the tool available.
You can remove #includes by passing by reference instead of passing by value and forward declaring. This is because the compiler doesn't need to know the size of the object at compile time. This will require a large amount of manual work on your behalf however. The good thing is it will reduce your compile times.


q: How can i format currency related data in a manner that is culture aware in JavaScript?

[A]
Dojo has a
currency formatter
that's locale aware.
If you don't want to include Dojo in your project just for this function, then perhaps you can localize the currency in your back-end?


q:
Has anyone had good experiences with any Java libraries for Graph algorithms. I've tried JGraph and found it ok, and there are a lot of different ones in google. Are there any that people are actually using successfully in production code or would recommend?

To clarify, I'm not looking for a library that produces graphs/charts, I'm looking for one that helps with Graph algorithms, eg minimum spanning tree, Kruskal's algorithm Nodes, Edges, etc. Ideally one with some good algorithms/data structures in a nice Java OO API.

[A]
For visualization our group had some success with
prefuse
.  We extended it to handle architectural floorplates and bubble diagraming, and it didn't complain too much.  They have a new Flex toolkit out too called Flare that uses a very similar API.
UPDATE:
I'd have to agree with the comment, we ended up writing a lot of custom functionality/working around prefuse limitations.  I  can't say that starting from scratch would have been better though as we were able to demonstrate progress from day 1 by using prefuse.  On the other hand if we were doing a second implementation of the same stuff, I might skip prefuse since we'd understand the requirements a lot better.


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

public class Test<E> {
    public boolean sameClassAs(Object o) {
        // TODO help!
    }
}

How would I check that o is the same class as E?

Test<String> test = new Test<String>();
test.sameClassAs("a string"); // returns true;
test.sameClassAs(4); // returns false;

I can't change the method signature from (Object o) as I'm overridding a superclass and so don't get to choose my method signature.

I would also rather not go down the road of attempting a cast and then catching the resulting exception if it fails.

[A]
I could only make it working like this:
```
```
public class Test<E> {

    private E e;

    public void setE(E e) {
        this.e = e;
    }

    public boolean sameClassAs(Object o) {

        return (o.getClass().equals(e.getClass()));
    }

    public boolean sameClassAs2(Object o) {
        return e.getClass().isInstance(o);
    }
}
```
```


q: I assume that char* = "string" is the same to char* = new char[6]. I believe these strings are created on the heap instead of the stack. So do I need to destroy them or free their memory when I'm done using them or do they get destroyed by themselves?

[A]
You don't know where the string literals are stored. It may even be read-only memory, so your code should read:
```
```
const char* c = "string";
```
```
And a
new
char array should be
delete
d just like any other dynamically allocated memory area.


q: What is the easiest way to extract the original exception from an exception returned via Apache's implementation of XML-RPC?

[A]
According to the
XML-RPC Spec
it returns the "fault" in the xml.
Is this the "Exception" you are referring to or are you refering to a Java Exception generated while making the XML-RPC call?
Fault example
```
```
HTTP/1.1 200 OK
Connection: close
Content-Length: 426
Content-Type: text/xml
Date: Fri, 17 Jul 1998 19:55:02 GMT
Server: UserLand Frontier/5.1.2-WinNT

<?xml version="1.0"?>
<methodResponse>
  <fault>
    <value>
      <struct>
      <member>
        <name>faultCode</name>
        <value><int>4</int></value>
      </member>
      <member>
        <name>faultString</name>
        <value>
          <string>Too many parameters.</string>
        </value>
      </member>
      </struct>
    </value>
  </fault>
</methodResponse>
```
```


q:
The rich presentational capabilities of WPF and Silverlight mean developers like me will be working closely with graphic designers more often these days, as is the case in my next project.

Does anyone out there have any tips and experience (from both points of view) on making this go more smoothly?

For example, when I mentioned source control to a designer recently, I was quickly told you can't source control graphics, images etc, so it is a waste of time.  So I responded: ok but, what about XAML files in WPF/Silverlight?

Scott Hanselman spoke about this topic in a podcast, but he focused more on the tools, while I'm more interested in the communication issues/aspects.

[A]
This may be a bit off topic (I'm replying specifically to your question about source control and graphics), but you
can
put binary data (images etc.) into source control (and in my opinion in a lot of cases should) -- they just take up more disk space and you can't use a diff view to analyze what has changed in any meaningful way, but what you do gain is a history of commit messages documenting each revision, rollback ability and the ability to easily archive (
tagging a revision
in SVN terms) all files (be they visual assets, documentation, source code, whatever) belonging to a specific release/version together. It's also easier for your build system to just fetch everything required for building a specific version of your software from the source control.


q:
How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0).

I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.

[A]
this is VB.NET code to check for any removable drives or CDRom drives attached to the computer:
```
```
Me.lstDrives.Items.Clear()
For Each item As DriveInfo In My.Computer.FileSystem.Drives
    If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then
        Me.lstDrives.Items.Add(item.Name)
    End If
Next
```
```
it won't be that hard to modify this code into a c# equivalent, and more
driveType
's are available.
From MSDN:
Unknown:
The type of drive is unknown.
NoRootDirectory:
The drive does not have a root directory.
Removable:
The drive is a removable storage device, such as a floppy disk drive or a USB flash drive.
Fixed:
The drive is a fixed disk.
Network:
The drive is a network drive.
CDRom:
The drive is an optical disc device, such as a CD or DVD-ROM.
Ram:
The drive is a RAM disk.


q:
This is not specific to any language, it´s just about best practices. I am using JPA/Hibernate (but it could be any other ORM solution) and I would like to know how do you guys deal with this situation:
Let´s suppose that you have a query returning something that is not represented by any of your domain classes.
Do you create a specific class to represent that specific query?
Do you return the query in some other kind of object (array, map...)
Some other solutions?
I would like to know about your experiences and best practices.

P.S.
Actually I am creating specific objetcs for specific queries.

[A]
I typically write a function that performs a query using SQL and then puts the results into either a list or dictionary (in Java, I'd use either an ArrayList or a HashMap).
If I found myself doing this a lot, I'd probably create a new file to hold all of these queries.  Otherwise I'd just make them functions in whatever file they were needed/used.
Since we're talking Java specifically, I would certainly not create a new class in a separate file.  However, for queries needed in only one class, you could create a private static inner class with only the function(s) needed to generate the query(s) needed by that class.


q:
The source database is quite large. The target database doesn't grow automatically. They are on different machines.

I'm coming from a MS SQL Server, MySQL background and IDS11 seems overly complex (I am sure, with good reason).

[A]
have you used the export tool ?  There used to be a way if you first put the db's into quiescent mode and then you could actually copy the DBSpaces across (dbspaces tool I think... its been a few years now).
Because with informix you used to be able to specify the DBSpaces(s) to used for the table (maybe even in the alter table ?).
Check - dbaccess tool - there is an export command.
Put the DB's into quiesent mode or shut down, copy the dbspaces and then attach table telling it to point to the new dbspaces file.  (the dbspaces tool could be worth while looking at.. I have manuals around here.  they are 9.2, but it shouldn't have changed too much).


q:
Is it possible to deploy a native Delphi application with ClickOnce without a stub C# exe that would be used to launch the Delphi application?

The same question applies to VB6, C++ and other native Windows applications.

[A]
I'm not 100% sure if this can be accomplished without the stub, but this article may provide some insight:
How To: ClickOnce deployment for unmanaged app with COM component in managed assembly


q:
I have a ASP.Net website that is failing on AJAX postbacks (both with ASP.Net AJAX and a 3rd part control) in IE.    FireFox works fine.  If I install the website on another machine without .Net 3.5 SP1, it works as expected.

When it fails, Fiddler shows that I'm getting a 405 "Method Not Allowed".  The form seems to be posting to pages other than page I'm viewing.

The form's action is "#" for the page on the broken website (with SP1).  The form's action is "Default.aspx" for the same page on a website without SP1.

Any ideas?

[A]
These are my observations rather than a full answer:
My guess (without trying to re-produce it myself) is that a couple of things may be happening as the DataSet tries to 'flatten' a hierarchical structure to a relational data structure.
1) thinking about the data from a relational database perspective; there is no obvious primary key field for identifying each of the Foo elements in the collection so the DataSet has automatically used the ordinal position in the file as an auto-generated field called Foo-Id.
2) There are actually two elements called 'Foo' so that probably explains the generation of a strange name for the column 'Foo-Id-0' (it has auto-generated a unique name for the column - I guess you could think of this as a fault-tolerant behaviour in the DataSet).


q:
I have a variable of type Dynamic and I know for sure one of its fields, lets call it a, actually is an array. But when I'm writing

var d : Dynamic = getDynamic();
for (t in d.a) {
}

I get a compilation error on line two:

You can't iterate on a Dynamic value, please specify Iterator or Iterable

How can I make this compilable?

[A]
Haxe can't iterate over
```
Dynamic
```
variables (as the compiler says).
You can make it work in several ways, where this one is probably easiest (depending on your situation):
```
```
var d : {a:Array<Dynamic>} = getDynamic();
for (t in d.a) { ... }
```
```
You could also change
```
Dynamic
```
to the type of the contents of the array.


q:
Flat files and relational databases give us a mechanism to serialize structured data. XML is superb for serializing un-structured tree-like data.

But many problems are best represented by graphs. A thermal simulation program will, for instance, work with temperature nodes connected to each others through resistive edges.

So what is the best way to serialize a graph structure? I know XML can, to some extent, do it---in the same way that a relational database can serialize a complex web of objects: it usually works but can easily get ugly.

I know about the dot language used by the graphviz program, but I'm not sure this is the best way to do it. This question is probably the sort of thing academia might be working on and I'd love to have references to any papers discussing this.

[A]
XML is very verbose.  Whenever I do it, I roll my own.  Here's an example of a 3 node directed acyclic graph.  It's pretty compact and does everything I need it to do:
```
```
0: foo
1: bar
2: bat
----
0 1
0 2
1 2
```
```


q: How can I generate UML diagrams (especially sequence diagrams) from existing Java code?

[A]
What is your codebase? Java or C++?
eUML2 for Java is a powerful UML modeler designed for Java developper
  in Eclipse. The free edition can be used for commercial use. It
  supports the following features:
CVS and Team Support
Designed for large project with multiple and customizable model views
Helios Compliant
Real-time code/model synchronization
UML2.1 compliant and support of OMG XMI
JDK 1.4 and 1.5 support
The commercial edition provides:
Advanced reversed engineering
Powerful true dependency analyze tools
UML Profile and MDD
Database tools
Customizable template support


q:
When you send an email using C# and the System.Net.Mail namespace, you can set the "From" and "Sender" properties on the MailMessage object, but neither of these allows you to make the MAIL FROM and the from address that goes into the DATA section different from each other.  MAIL FROM gets set to the "From" property value, and if you set "Sender" it only adds another header field in the DATA section.  This results in "From X@Y.COM on behalf of A@B.COM", which is not what you want.  Am I missing something?

The use case is controlling the NDR destination for newsletters, etc., that are sent on behalf of someone else.

I am currently using aspNetEmail instead of System.Net.Mail, since it allows me to do this properly (like most other SMTP libraries).  With aspNetEmail, this is accomplished using the EmailMessage.ReversePath property.

[A]
Do you mean this?:
```
```
//create the mail message
 MailMessage mail = new MailMessage();

 //set the addresses
 mail.From = new MailAddress("me@mycompany.com");
 mail.To.Add("you@yourcompany.com");

 //set the content
 mail.Subject = "This is an email";
 mail.Body = "this is a sample body with html in it. This is bold This is blue";
 mail.IsBodyHtml = true;

 //send the message
 SmtpClient smtp = new SmtpClient("127.0.0.1");
 smtp.Send(mail);
```
```
From
http://www.systemnetmail.com/faq/3.1.2.aspx


q:
Is the edit control I'm typing in now, with all its buttons and rules freely available for use?

My web project is also .Net based.

[A]
It's the
WMD
Markdown editor which is free and seems to be pretty easy to use.  Just include the javascript for it and (in the easiest case), it just attaches to the first textarea it finds.
Here's some info about the
Perl implementation of Markdown
which, according to the site, WMD is 100% compatible with.
@Chris Upchurch
Technically the current release isn't open-source, just free to use.  The next version is supposed to be released with an MIT license though.
"now completely free to use. The next release will be open source under an MIT-style license."


q: Is it any compilator option of flag?

[A]
You can if you setup an external tool pointing to MsBuild to build the solution with the multiple process flag /m.
Scott Hanselman wrote a
nice post
on how to accomplish this, so I won't repeat what he has already done.


q:
In a C# Windows Forms application I want to detect if another instance of the application is already running.
If so, activate the main form of the running instance and exit this instance.

What is the best way to achieve this?

[A]
Here is what I'm currently doing in the application's Program.cs file.
```
```
// Sets the window to be foreground
[DllImport("User32")]
private static extern int SetForegroundWindow(IntPtr hwnd);

// Activate or minimize a window
[DllImportAttribute("User32.DLL")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
private const int SW_RESTORE = 9;

static void Main()
{
    try
    {
        // If another instance is already running, activate it and exit
        Process currentProc = Process.GetCurrentProcess();
        foreach (Process proc in Process.GetProcessesByName(currentProc.ProcessName))
        {
            if (proc.Id != currentProc.Id)
            {
                ShowWindow(proc.MainWindowHandle, SW_RESTORE);
                SetForegroundWindow(proc.MainWindowHandle);
                return;   // Exit application
            }
        }

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MainForm());
    }
    catch (Exception ex)
    {
    }
}
```
```


q:
How do I figure out if an array contains an element?
I thought there might be something like [1, 2, 3].includes(1) which would evaluate as true.


q:
I'm having a problem running a T4 template using TextTransform.exe on my build server. On my dev machine the template works perfectly. The error message is as follows.

error : Running transformation: System.TypeLoadException: Could not instantiate type System.Xml.Linq.XDocument

The build server has the windows 2008 SDK on it, my machine has VS 2008. I thought mayve it couldn't find System.Data.Xml so I ensure the dll was present in the same directory, but no luck. Any ideas?


q:
Given a string "filename.conf", how to I verify the extension part?

I need a cross platform solution.

[A]
```
```
_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w
```
```
This is Windows (Platform SDK) only


q: I would like my Core assembly to not expose a certain class and I would still like to be able to test it. How can I do that ?

[A]
InternalsVisibleTo
attribute to the rescue!
Just add:
```
```
[assembly:InternalsVisibleToAttribute("UnitTestAssemblyName")]
```
```
to your Core classes AssemblyInfo.cs file
See
Friend Assemblies (C# Programming Guide)
for best practices.


q:
In my base page I need to remove an item from the query string and redirect. I can't use

Request.QueryString.Remove("foo")

because the collection is read-only. Is there any way to get the query string (except for that one item) without iterating through the collection and re-building it?

[A]
```
```
Response.Redirect(String.Format("nextpage.aspx?{0}", Request.QueryString.ToString().Replace("foo", "mangledfoo")));
```
```
I quick hack, saves you little. But foo will not be present for the code awaiting it in nextpge.aspx :)


q:
In Microsoft SQL Server, is there a way to detect whether a database has had its isolation level set via the T-SQL command ALTER DATABASE <database> SET READ_COMMITTED_SNAPSHOT ON;?

I cannot find a simple way to detect this in either T-SQL or via the Management Studio's GUI.

[A]
```
```
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
```
```
Return value:
1
:
```
READ_COMMITTED_SNAPSHOT
```
option is
ON
. Read operations under the
```
READ COMMITTED
```
isolation level are based on snapshot scans and do not acquire locks.
0
(default):
```
READ_COMMITTED_SNAPSHOT
```
option is
OFF
. Read operations under the
```
READ COMMITTED
```
isolation level use
Shared (S) locks
.


q:
Have any well-documented or open source projects targeted iPhone, Blackberry, and Android ? Are there other platforms which are better-suited to such an endeavor ?
Note that I am particularly asking about client-side software, not web apps, though any information about the difficulties of using web apps across multiple mobile platforms is also interesting.

[A]
The iPhone uses Objective C, the Blackberry Java SE with RIM functionality and Android another custom version of Java. I could possibly see how you could combine the latter two but there is no functionality (without jailbreaking) of running Java applications on an iPhone.
The best bet I've seen so far is something like
Qt
that will run on Windows CE, almost certainly shortly Symbian, some Java platforms and the three major desktop OSs.


q:
Definition:

A palindrome is a word, phrase, number or other sequence of units that has the property of reading the same in either direction

How to check if the given string is a palindrome?

This was one of the FAIQ [Frequently Asked Interview Question] a while ago but that mostly using C.

Looking for solutions in any and all languages possible.

[A]
```
```
boolean isPalindrome(String str1) {
  //first strip out punctuation and spaces
  String stripped = str1.replaceAll("[^a-zA-Z0-9]", "");
  return stripped.equalsIgnoreCase((new StringBuilder(stripped)).reverse().toString());
}
```
```
Java version


q:
I need to design a small project for generating excel reports in .NET, which will be sent to users to use.

The excel reports will contain PivotTables.

I don't have much experience with them, but I can think of three implementation alternatives:

Set a query for it, populate it, send it disconnected. This way the user will be able to group values and play a little, but he will not be able to refresh the data.

Generate a small access database and send it along with the excel file, connect to it.

Copy the data to the excel (perhaps in some other sheet) and connect to the data there. This will make the excel file very large I think.

What would be the best alternative in regards to performance vs usability? Is there another alternative I don't know about?


q:
Is there an existing solution to create a regular expressions dynamically out of a given date-time format pattern? The supported date-time format pattern does not matter (Joda DateTimeFormat, java.text.SimpleDateTimeFormat or others).

As a specific example, for a given date-time format like dd/MM/yyyy hh:mm, it should generate the corresponding regular expression to match the date-times within the specified formats.

[A]
```
SimpleDateFormat
```
already does this with the
```
parse()
```
method.
If you need to parse multiple dates from a single string, start with a regex (even if it matches too leniently), and use
```
parse()
```
on all the potential matches found by the regex.


q:
I am trying to code TDD style in PHP and one of my biggest stumbling blocks (other than lack of a decent IDE) is that I have to make my own hacked together IoC container just to inject all my mock objects properly.

Has anyone used an Ioc container in PHP?  All I've been able to find is PHP IOC on the ever-annoying phpclasses.org and it seems to have almost no documentation and not much of a following.

[A]
I played with some DI Frameworks for PHP, but I haven't used one in production. Have some links:
http://www.stubbles.net/
which
I think is the oldest I tried
http://php.xjconf.net/
FLOW3
- I belive this one will
become a very nice framework (its
beta right now)
You mentioned you would use it for TDD - so maybe have a look at
Dependency Injection for Unit Tests in PHP


q: How can I build a loop in JavaScript?

[A]
A loop in JavaScript looks like this:
```
```
for (var = startvalue; var <= endvalue; var = var + increment) {
    // code to be executed
}
```
```


q:
How can you obtain the Type (the name as a string is sufficient) of an Object in VB6 at runtime?

i.e. something like:

If Typeof(foobar) = "CommandButton" Then ...

/EDIT: to clarify, I need to check on Dynamically Typed objects. An example:

Dim y As Object

Set y = CreateObject("SomeType")

Debug.Print( <The type name of> y)

Where the output would be "CommandButton"

[A]
This should prove difficult, since in VB6 all objects are COM (
```
IDispatch
```
) things. Thus they are only an interface.
```
TypeOf(object) is class
```
probably only does a COM get_interface call (I forgot the exact method name, sorry).


q: Does anyone have any experience with a tool that generates test strings from a BNF grammar that could then be fed into a unit test?

[A]
I don't have an answer to the tool question, but I will say it is fairly easy in any text processing language (perl/python/etc) to randomly generate sentences from a BNF grammar, and slightly more verbose in a bigger language (Java/C/etc), but it shouldn't be too hard to roll your own.
The problem with this, of course, is that it can only generate strings in the grammar, and unless your grammar is very simple, the test space is infinitely large.


q:
I've noticed that SQL Server 2005 x64 does not seem to lock pages into memory the same way SQL Server 2000 did.  In 2000 I could easily see from task manager that SQL had locked 8GB of ram with AWE.  I'm fairly certain I've got 2005 setup in an equivalent way.

Is this a normal x64 difference or am I forgetting a crucial setup option?

[A]
SQL Server 2005 x64 certainly doesn't need, or use, AWE; AWE is only to allow it to use > 4GB on 32 bit systems.
You
can
use the old lock-pages-in-memory trick, but as this KB shows (
http://support.microsoft.com/kb/918483
): "Note For 64-bit editions of SQL Server 2005, only SQL Server 2005 Enterprise Edition can use the Lock pages in memory user right."


q:
Since Graduating from a very small school in 2006 with a badly shaped & outdated program (I'm a foreigner & didn't know any better school at the time) I've come to realize that I missed a lot of basic concepts from a mathematical & software perspective that are mostly the foundations of other higher concepts.

I.e. I tried to listen/watch the open courseware from MIT on Introduction to Algorithms but quickly realized I was missing several mathematical concepts to better understand the course.

So what are the core mathematical concepts a good software engineer should know? And what are the possible books/sites you will recommend me?

[A] Start with what we CS folks call "discrete math".  Calculus and linear algebra can come in quite handy too because they get your foot in the door to a lot of application domains.  Once you've mastered those three, go for probability theory.  Those 4 will get you to competency in 95% (I made that up) of application domains.


q:
Creating a patch is very easy in SubVersion, With Tortoise, you right-click and select Create Patch. But for the life of me, I can't find this functionality in TFS. Is this possible?

If not, what's the standard way to submit patches in open source TFS hosted projects (a la CodePlex)?

[A]
```
```
tf diff /shelveset:shelveset /format:unified
```
```
Edit:
This writes to standard output.  You can pipe the output to a file.
For more options, see
Difference Command
.


q:
How can I use the Prototype library and create unobtrusive javascript to inject the onmouseover and onmouseout events to each row, rather than putting the javascript in each table row tag?

An answer utilizing the Prototype library (instead of mootools, jQuery, etc) would be most helpful.

[A]
You can use Prototype's
```
addClassName
```
and
```
removeClassName
```
methods.
Create a CSS class "hilight" that you'll apply to the hilighted
```
<tr>
```
's.  Then run this code on page load:
```
```
var rows = $$('tbody tr');
for (var i = 0; i < rows.length; i++) {
    rows[i].onmouseover = function() { $(this).addClassName('hilight'); }
    rows[i].onmouseout = function() { $(this).removeClassName('hilight'); }
}
```
```


q:
I need to check programmatically (in .NET) whether a given user (domain account) is a member of the built-in Administrators group on a current computer (the one where the application gets executed).

Is it possible?

[A]
You could loop the groups like i did in this answer:
Determining members of local groups via C#
After reading some more, the easiest thing would be to use the
```
System.DirectoryServices.AccountManagement
```
namespace. Here is how it can be used:
http://www.leastprivilege.com/SystemDirectoryServicesAccountManagement.aspx
Sample:
```
```
public static bool IsUserInGroup(string username, string groupname, ContextType type)
{
    PrincipalContext context = new PrincipalContext(type);

    UserPrincipal user = UserPrincipal.FindByIdentity(
        context,
        IdentityType.SamAccountName,
        username);
    GroupPrincipal group = GroupPrincipal.FindByIdentity(
        context, groupname);

    return user.IsMemberOf(group);
}
```
```


q:
Wrote the following in PowersHell as a quick iTunes demonstration:

$iTunes = New-Object -ComObject iTunes.Application
$LibrarySource = $iTunes.LibrarySource
foreach ($PList in $LibrarySource.Playlists)
{
  write-host $PList.name
}

This works well and pulls back a list of playlist names.
However on trying to close iTunes a warning appears

One or more applications are using the iTunes scripting interface. Are you sure you want to quit?

Obviously I can just ignore the message and press [Quit] or just wait the 20 seconds or so, but is there a clean way to tell iTunes that I've finished working with it?

Itunes 7.7.1, Windows XP

[A]
Here is one thing that I did on my a Powershell script that adds podcasts to iTunes. I use Juice on a server to download all the podcasts that I listen to.  The script uses .Net methods to release the COM objects.  When I wrote my iTunes script I had read a couple of articles that stated you should release your COM objects using .NET.
```
```
[void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$LibrarySource)
    [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$iTunes)
```
```
I also run my scripts the majority of time from a shortcut, not from the powershell prompt.
Based on your comments, I did some testing and I determined that I would get the message when running against iTunes, if I ran my script in a way that leaves powershell running.  iTunes seems to keep track of that.  Running the script in a manner that exits it's process after running, eliminated the message.
One method of running your script from powershell, is to prefix your script with powershell.
```
```
powershell .\scriptname.ps1
```
```
The above command will launch your script and then exit the process that was used to run it, but still leaving you at the powershell prompt.


q: So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact?

[A]
I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace.  I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time an exception is thrown... so it's not like you are just jumping from one place in the code to another, there is a lot going on.
I don't think it's a problem as long as you are using exceptions for EXCEPTIONAL behavior (so not your typical, expected path through the program).


q:
We have some input data that sometimes appears with &nbsp characters on the end.

The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.

Ltrim and Rtrim don't remove the characters, so we're forced to do something like:

UPDATE myTable
SET myColumn = replace(myColumn,char(160),'')
WHERE charindex(char(160),myColumn) > 0

This works for the &nbsp, but is there a good way to do this for any non-alphanumeric (or in this case numeric) characters?

[A]
This page
has a sample of how you can remove non-alphanumeric chars:
```
```
-- Put something like this into a user function:
DECLARE @cString    VARCHAR(32)
DECLARE @nPos    INTEGER
SELECT  @cString = '90$%45623 *6%}~:@'
SELECT  @nPos = PATINDEX('%[^0-9]%', @cString)

WHILE @nPos > 0
BEGIN
SELECT @cString = STUFF(@cString, @nPos, 1, '')
SELECT  @nPos = PATINDEX('%[^0-9]%', @cString)
END

SELECT @cString
```
```


q:
I'm thinking this might be a quick and easy way to lower the form spam on our site just a little bit. The idea being that (I have read) spammers aren't running with javascript enabled. (Or at least they are accessing your website without running javascript. I.e., they aren't browsing up to it in IE or FF.

I can use .asp or .aspx.

[A]
The simplest way is to set a cookie via javascript and check for it on postback.However, if you're looking to minimize spam you should actually have the browser perform a simple task which requires javascript execution. See Phil Haack's "Invisibile Captcha Validator" control, which has since been included in his Subkismet library:
http://haacked.com/archive/2006/09/26/Lightweight_Invisible_CAPTCHA_Validator_Control.aspx


q:
I have an application that reads a CSV file with piles of data rows.  I give the user a summary of the number of rows based on types of data, but I want to make sure that I don't read in too many rows of data and cause OutOfMemoryErrors.  Each row translates into an object.  Is there an easy way to find out the size of that object programmatically?  Is there a reference that defines how large primitive types and object references are for a VM?

Right now, I have code that says read up to 32,000 rows, but I'd also like to have code that says read as many rows as possible until I've used 32MB of memory.  Maybe that is a different question, but I'd still like to know.

[A]
I doubt you want to do it programmatically unless you just want to do it once and store it for future use.  It's a costly thing to do.  There's no sizeof() operator in Java, and even if there was, it would only count the cost of the references to other objects and the size of the primitives.
One way you could do it is to serialize the thing to a File and look at the size of the file, like this:
```
```
Serializable myObject;
ObjectOutputStream oos = new ObjectOutputStream (new FileOutputStream ("obj.ser"));
oos.write (myObject);
oos.close ();
```
```
Of course, this assumes that each object is distinct and doesn't contain non-transient references to anything else.
Another strategy would be to take each object and examine its members by reflection and add up the sizes (boolean & byte = 1 byte, short & char = 2 bytes, etc.), working your way down the membership hierarchy.  But that's tedious and expensive and ends up doing the same thing the serialization strategy would do.


q:
I've been doing c# for a long time, and have never come across an easy way to just new up a hash.

I've recently become acquainted with the ruby syntax of hashes and wonder, does anyone know of a simple way to declare a hash as a literal, without doing all the add calls.

{ "whatever" => {i => 1}; "and then something else" => {j => 2}};

[A]
If you're using C# 3.0 (.NET 3.5) then you can use collection initializers. They're not quite as terse as in Ruby but still an improvement.
This example is based on the
MSDN Example
```
```
var students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}
};
```
```


q: I don't ever recall coming across anything for C that's as extensive as C++'s Boost library.

[A] I've never seen anything. Really, C++ templates are the enabling technology for STL and much of boost, and C doesn't have them. I've seen many C-interface libraries for things like image processing, 3D graphics, networking, etc., but never a real general-purpose library like boost. You can find pieces though - threading libraries, string libraries, etc. - that are similar to sections of boost.


q:
Can I return it as an object if I am doing a

Select OneItem from Table Where OtherItem = "blah"?

Is there a better way to do this?

I am building a constructor to return an object based on its name rather than its ID.

[A]
```
query.UniqueResult<T>()
```
returns just one
T


q:
I'm coming from the open source world, and interested in giving ASP.NET a spin. But I'm having a little trouble separating the tools from the platform itself in regards to the licensing. I've downloaded Visual Web Developer 2008 Express, but not sure how different this is from one of the full-featured Visual Studio licenses -- and whether or not my Express license will prevent me from using all the features of ASP.NET.

Is a Visual Studio license just an IDE, or does it include pieces of .NET not available to the Express license?  What about the other tools like IIS and SQL Server?

Thanks.

[A]
All of .net is available in the .net SDK, so in theory you will not need Visual Studio at all.
Now, there are some things that Express will not do. For example, the Database Designer is not very comprehensive and adding different remote databases is not or only very hardly possible. Still, in code you can connect to everything.
There is also no Remote Debugger, no support for creating Setup Files (well, that does not apply to ASP.net anyway), no real Publish Web Site Feature (although that can be
added manually
as it's just a Frontend for a SDK tool), no integrated Unit testing (and Microsoft
loves to threaten people
who add it), etc.
For a full comparison, see here:
Visual Studio 2008 Editions
But as said: Functionality of .net is all in the SDK, Visual Studio is just making it a bit easier to work with.


q: What does the , operator do in C?

[A]
The expression:
```
```
(expression1,  expression2)
```
```
First
```
expression1
```
is evaluated, then
```
expression2
```
is evaluated, and the value of
```
expression2
```
is returned for the whole expression.


q:
Anyone know this compiler feature? It seems GCC support that. How does it work? What is the potential gain? In which case it's good? Inner loops?

(this question is specific, not about optimization in general, thanks)

[A]
The fun thing about optimization is that speed gains are found in the unlikeliest of places.
It's also the reason you need a profiler, rather than guessing where the speed problems are.
I recommend starting with a profiler (
```
gperf
```
if you're using GCC) and just start poking around the results of running your application through some normal operations.


q:
What is iPhone's browser tag and how iPhone optimized web site is different from a usual mobile web site?

Thanks!

[A]
Nettuts has a great introduction to web-developement for iPhone. You find it
here
This is the specific code you asked for (taken from that article):
```
```
<!--#if expr="(${HTTP_USER_AGENT} = /iPhone/)"-->

<!--
place iPhone code in here
-->

<!--#else -->

<!--
    place standard code to be used by non iphone browser.
-->
<!--#endif -->
```
```


q: I'm on a little quest of merging the structure of two MySql databases. Is there a tool for this with the might of Red-Gate's SQL Compare? Are there any free alternatives?

[A]
although i dont have any experience with it, i hear that navicat would be the tool to use:
https://www.navicat.com/en/products/navicat-for-mysql
also toad for mysql i hear isnt bad:
http://www.quest.com/toad-for-mysql/


q:
A requirement for an ASP.Net 2.0 project I'm working on limits a certain field to a max of 10 words (not characters). I'm currently using a CustomValidator control with the following ServerValidate method:

Protected Sub TenWordsTextBoxValidator_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TenWordsTextBoxValidator.ServerValidate
    '' 10 words
    args.IsValid = args.Value.Split(" ").Length <= 10
End Sub

Does anyone have a more thorough/accurate method of getting a word count?

[A]
You can use one of the builtin validators with a regex that counts the words.
I'm a little rusty with regex so go easy on me:
```
```
(\b.*\b){0,10}
```
```


q:
I'm looking for some "Best Practices" for automating the deployment of Stored Procedures/Views/Functions/Table changes from source control. I'm using StarTeam & ANT so the labeling is taken care of; what I am looking for is how some of you have approached automating the pull of these objects from source - not necessarily StarTeam.

I'd like to end up with one script that can then be executed, checked in, and labeled.

I'm NOT asking for anyone to write that - just some ideas or approaches that have (or haven't) worked in the past.

I'm trying to clean up a mess and want to make sure I get this as close to "right" as I can.

We are storing the tables/views/functions etc. in individual files in StarTeam and our DB is SQL 2K5.

[A]
I prefer to separate views, procedures, and triggers (objects that can be re-created at will) from tables.  For views, procedures, and triggers, just write a job that will check them out and re-create the latest.
For tables, I prefer to have a database version table with one row.  Use that table to determine what new updates have not been applied.  Then each update is applied and the version number is updated.  If an update fails, you have only that update to check and you can re-run know that the earlier updates will not happen again.


q: What are the available libraries for creating pretty charts and graphs in a Python application?

[A]
Have you looked into
ChartDirector for Python
?
I can't speak about this one, but I've used ChartDirector for PHP and it's pretty good.


q: How are people unit testing code that uses Linq to SQL?

[A]
Normally, you don't need to test the part of the code that uses LINQ to SQL but if you really want to, you can use the same data sets that you're querying against the server and turn them into in-memory objects and run the LINQ queries against that (which would use the Enumerable methods instead of Queryable).
Another option is to use Matt Warren's
mockable version of the DataContext
.
You can also get the SQL statements that LINQ to SQL uses by getting them via the debugger (from the IQueryable object), check those manually, and then include them in the automated tests.


q:
There are many ASP.MVC blog post bits and pieces scattered over different web sites, as well as couple of resource questions here - ASP.NET Model-view-controller (MVC) - where do I start from? and MVC Learning Resources

I wonder if there was a one-stop tutorial posted yet on getting started with ASP.NET MVC?

Thank you!

Edit: I probably need to clarify - a one-stop tutorial that'd help to get started within and hour or two and learn more as I go... Reading books is a non starter for me personally - takes more time I can afford and starts with basics...

[A]
http://www.asp.net/mvc
Whoops, submitted before I was done.  The ASP.NET MVC site has tons of videos/screencast on getting started with ASP.NET MVC.  Definitely watch the Scott Hanselman ones first.
Edit
The Rob Conery screencasts that
@David provided
are provided on the
ASP.NET MVC site
also, under videos.  That would constitute one spot to get those resources and also the ones the ASP.NET MVC team put out.
One note on any resource you use.  You could run into functionality that is no longer available in the framework due to it being in development.  If you use the resources provided that you already found along with the tutorials, you will find the replacements or how to get around it.


q:
Let's say you have a variable in a makefile fragment like the following:

MY_LIST=a b c d

How do I then reverse the order of that list?  I need:

$(warning MY_LIST=${MY_LIST})

to show

MY_LIST=d c b a

Edit:  the real problem is that

ld -r some_object.o ${MY_LIST}

produces an a.out with undefined symbols because the items in MY_LIST are actually archives, but in the wrong order.  If the order of MY_LIST is reversed, it will link correctly (I think).  If you know a smarter way to get the link order right, clue me in.

[A]
Doh!  I could have just used a shell script-let:
```
(for d in ${MY_LIST}; do echo $$d; done) | tac
```


q: I know RIM has their own IDE (BlackBerry JDE) for building BlackBerry apps, but does anyone know how to configure IntelliJ IDEA to build/debug BlackBerry apps?

[A]
Not really an answer, but more asking for clarification what is different for Blackberry dev versus other J2ME devices...
I see its a
MIDP J2ME
device, and so the standard
Intellij J2ME
support would seem to give most of what is needed.
I guess the emulator side of things might be different... but maybe you can call the jde emulator from IDEA...
Regards,
Chris


q:
Here is the full error: SqlException: A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider, error: 1 - I/O Error detected in read/write operation)

I've started seeing this message intermittently for a few of the unit tests in my application (there are over 1100 unit & system tests).  I'm using the test runner in ReSharper 4.1.

One other thing: my development machine is a VMWare virtual machine.

[A]
I ran into this many moons ago.  Bottom line is you are running out of available ports.
First make sure your calling application has connection pooling on.
If that does then check the number of available ports for the SQL Server.
What is happening is that if pooling is off then every call takes a port and it takes by default 4 minutes to have the port expire, and you are running out of ports.
If pooling is on then you need to profile all the ports of SQL Server and make sure you have enough and expand them if necessary.
When I came across this error, connection pooling was off and it caused this issue whenever a decent load was put on the website.  We did not see it in development because the load was 2 or 3 people at max, but once the number grew over 10 we kept seeing this error.  We turned pooling on, and it fixed it.


q:
Is there a good way to see what format an image is, without having to read the entire file into memory?

Obviously this would vary from format to format (I'm particularly interested in TIFF files) but what sort of procedure would be useful to determine what kind of image format a file is without having to read through the entire file?

BONUS: What if the image is a Base64-encoded string? Any reliable way to infer it before decoding it?

[A]
Most image file formats have unique bytes at the start. The unix
```
file
```
command looks at the start of the file to see what type of data it contains. See the Wikipedia article on
Magic numbers in files
and
magicdb.org
.


q: What is best practice when creating your exception classes in a .NET solution: To derive from System.Exception or from System.ApplicationException?

[A]
```
ApplicationException
```
considered useless
is a strong, and critical, argument against
```
ApplicationException
```
.
Upshot: don't use it. Derive from
```
Exception
```
.


q:
I am using Windows, and I have two monitors.

Some applications will always start on my primary monitor, no matter where they were when I closed them.

Others will always start on the secondary monitor, no matter where they were when I closed them.

Is there a registry setting buried somewhere, which I can manipulate to control which monitor applications launch into by default?

@rp: I have Ultramon, and I agree that it is indispensable, to the point that Microsoft should buy it and incorporate it into their OS.  But as you said, it doesn't let you control the default monitor a program launches into.

[A]
I'm fairly sure the primary monitor is the default.  If the app was coded decently, when it's closed, it'll remember where it was last at and will reopen there, but -- as you've noticed -- it isn't a default behavior.
EDIT: The way I usually do it is to have the location stored in the app's settings.  On load, if there is no value for them, it defaults to the center of the screen.  On closing of the form, it records its position.  That way, whenever it opens, it's where it was last.  I don't know of a simple way to tell it to launch onto the second monitor the first time automatically, however.
-- Kevin Fairchild


q:
Does any one know how the event handler manages the posted events?

In my app i have two threads (guiThread and computationThread). After an exception is thrown I call postEvent(..) to an existing dialog. The Qt-Event-Handler holds this one back until the dialog is closed.

Sorry my question is a bit cloudy. I will write it more exactly, if I have time left. I found a work around. But for me the problem is still interesting.

[A]
As mentionned in the Qt documentation about
QCoreApplication::postEvent
:
When control returns to the main event loop, all events that are stored in the queue will be sent using the notify() function.
...which explains why the Qt Event Handler holds the event until the dialog is closed.
If I understand correctly what you want to do, I would try using
sendEvent
.


q:
I think this is specific to IE 6.0 but...

In JavaScript I add a div to the DOM. I assign an id attribute. When I later try to pick up the div by the id all I get is null.

Any suggestions?

Example:

var newDiv = document.createElement("DIV");
newDiv.setAttribute("ID", "obj_1000");
document.appendChild(newDiv);

alert("Added:" + newDiv.getAttribute("ID") + ":" + newDiv.id + ":" + document.getElementById("obj_1000") );

Alert prints "::null"

Seems to work fine in Firefox 2.0+

[A]
You have to add the div to the dom.
```
```
// Create the Div
var oDiv = document.createElement('div');
document.body.appendChild(oDiv);
```
```


q:
How do I create a branch in subversion that is deeper' than just the 'branches' directory?

I have the standard trunk, tags and branches structure and I want to create a branch that is several directories deeper than the 'branches' tag.

Using the standard svn move method, it gives me a folder not found error. I also tried copying it into the branches folder, checked it out, and the 'svn move' it into the tree structure I wanted, but also got a 'working copy admin area is missing' error.

What do I need to do to create this?

For the sake of illustration, let us suppose I want to create a branch to go directly into 'branches/version_1/project/subproject' (which does not exist yet)?

[A]
```
```
svn copy --parents http://url/to/subproject http://url/to/repository/branches/version_1/project/subproject
```
```
That should create the directory you want to put the subproject in (
```
--parents
```
means "create the intermediate directories for me").


q:
As part of a larger web-app (using CakePHP), I'm putting together a simple blog system. The relationships are exceedingly simple: each User has a Blog, which has many Entries, which have many Comments.

An element I'd like to incorporate is a list of "Popular Entries." Popular Entries have been defined as those with the most Comments in the last month, and ultimately they need to be ordered by the number of recent Comments.

Ideally, I'd like the solution to stay within Cake's Model data-retrieval apparatus (Model->find(), etc.), but I'm not sanguine about this.

Anyone have a clever/elegant solution? I'm steeling myself for some wild SQL hacking to make this work...

[A]
Shouldn't be too bad, you just need a group by (this is off the type of my head, so forgive syntax errors):
```
```
SELECT entry-id, count(id) AS c
FROM comment
WHERE comment.createdate >= DATE_SUB(CURDATE(), INTERVAL 1 MONTH)
GROUP BY entry-id
ORDER BY c DESC
```
```


q:
var e1 = new E1();
e1.e2s.Add(new e2()); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.imsertonsubmit(e1);
context.submitchanges();

[A]
Well - I don't know if your initial code block would work, but I'm guessing you have to mark your new e2 as insert on submit. Thus:
```
```
var e1 = new E1();
var e2 = new e2();
e1.e2s.Add(e2); //e2s is null until e1 is saved, i want to save them all at the same time
context.e1s.insertonsubmit(e1);
context.e2s.insertonsubmit(e2);
context.submitchanges();
```
```


q: How can you import a foxpro DBF file in SQL Server?

[A]
Use a linked server or use openrowset, example
```
```
SELECT * into SomeTable
FROM OPENROWSET('MSDASQL', 'Driver=Microsoft Visual FoxPro Driver;
SourceDB=\\SomeServer\SomePath\;
SourceType=DBF',
'SELECT * FROM SomeDBF')
```
```


q:
System.IO.Directory.GetFiles() returns a string[].  What is the default sort order for the returned values?  I'm assuming by name, but if so how much does the current culture effect it?  Can you change it to something like creation date?

Update: MSDN points out that the sort order is not guaranteed for .Net 3.5, but the 2.0 version of the page doesn't say anything at all and neither page will help you sort by things like creation or modification time.  That information is lost once you have the array (it contains only strings).  I could build a comparer that would check for each file it gets, but that means accessing the file system repeatedly when presumably the .GetFiles() method already does this.  Seems very inefficient.

[A]
```
```
Dim Files() As String
Files = System.IO.Directory.GetFiles("C:\")
Array.Sort(Files)
```
```