q:
In a comment on a previous question, someone said that the following sql statement opens me up to sql injection:

select
    ss.*,
    se.name as engine,
    ss.last_run_at + interval ss.refresh_frequency day as next_run_at,
    se.logo_name
from
    searches ss join search_engines se on ss.engine_id = se.id
where
    ss.user_id='.$user_id.'
group by ss.id
order by ss.project_id, ss.domain, ss.keywords

Assuming that the $userid variable is properly escaped, how does this make me vulnerable, and what can I do to fix it?

[A]
Assuming it is properly escaped, it doesn't make you vulnerable. The thing is that escaping properly is harder than it looks at first sight, and you condemn yourself to escape properly every time you do a query like that. If possible, avoid all that trouble and use prepared statements (or binded parameters or parameterized queries). The idea is to allow the data access library to escape values properly.
For example, in PHP, using
mysqli
:
```
```
$db_connection = new mysqli("localhost", "user", "pass", "db");
$statement = $db_connection->prepare("SELECT thing FROM stuff WHERE id = ?");
$statement->bind_param("i", $user_id); //$user_id is an integer which goes
                                       //in place of ?
$statement->execute();
```
```


q: i need a C# library about strict HTML validation and filtering

s: huggingface

c: devops

d: intermediate


q:
I've never actually used greasemonkey, but I was considering using it.
Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites, how safe can it be?
Can they steal my passwords? Look at my private data? Do things I didn't want to do?
How safe is Greasemonkey?

Thanks

[A]
Considering that GreaseMonkey allows you to let random people on the Internet change the behavior of your favorite websites, how safe can it be?
It's as safe as you allow it to be - but you aren't very clear, so let's look at it from a few perspectives:
Web Developer
Greasemonkey can't do anything to your website that a person with telnet can't already do to your website.  It automates things a bit, but other than that if greasemonkey is a security hole, then your website design is flawed - not greasemonkey.
Internet user with Greasemonkey loaded
Like anything else you load on your system, greasemonkey can be used against you.  Don't load scripts onto your system unless you trust the source (in both meanings of the term 'source').  It's fairly limited and sandboxed, but that doesn't mean it's safe, merely that it's harder for someone to do something nefarious.
Internet user without Greasemonkey
If you do not load greasemonkey or any of its scripts, it cannot affect you in any way.  Greasemonkey does not alter the websites you visit unless you've loaded it on your system.
Greasemonkey developer
There's not much you can do beyond what can already be done with XUL and javascript, but it is possible to trash your mozilla and/or firefox profile, and possibly other parts of your system.  Unlikely, difficult to do on purpose or maliciously, but it's not a bulletproof utility.
Develop responsibly.
-Adam


q:
I'm trying out PHPTAL and I want to render a table with zebra stripes. I'm looping through a simple php assoc array ($_SERVER).

Note that I don't want to use jQuery or anything like that, I'm trying to learn PHPTAL usage!

Currently I have it working like this (too verbose for my liking):

<tr tal:repeat="item server">
  <td tal:condition="repeat/item/odd" tal:content="repeat/item/key" class="odd">item key</td>
  <td tal:condition="repeat/item/even" tal:content="repeat/item/key" class="even">item key</td>
  <td tal:condition="repeat/item/odd" tal:content="item" class="odd">item value</td>
  <td tal:condition="repeat/item/even" tal:content="item" class="even">item value</td>
</tr>

Basically I want some kind of conditional assignment on the fly, but I'm unsure of the syntax.

[A]
Well, it seems like I have my own answer, though I still think this is rather ugly:
```
```

  item key
  item value

```
```
Anyone got anything more graceful looking for PHPTAL?


q:
I've built a entity framework model against a 2008 database.  All works ok against the 2008 database.  When I try to update the entity on a 2005 database I get this error.

The version of SQL Server in use does not support datatype 'datetime2

I specifically did not use any 2008 features when I built the database.  I can't find any reference to datetime2 in the code.  And, yes the column is defined as "datetime" in the database.

[A]
A quick google points me to what looks like the
solution
.
Open your EDMX in a file editor (or “open with…” in Visual Studio and select XML Editor). At the top you will find the storage model and it has an attribute ProviderManifestToken. This has should have the value 2008. Change that to 2005, recompile and everything works.
NOTE: You'll have to do this every time you update the model from database.


q:
How do Window's programmers profile their native C++ code?
On Unix/Linux you have gprof [thanks Evan] & valgrind (I personally used this one, although it's not a real profiler), and recently I'm on Mac and Solaris, which means I moved to dTrace. Now when I've had the need to profile on Windows in the past, like at my previous job, I used Intel's vtune, which is great, however it's commercial, and I don't have a license for private use, so I'm left wondering what's the standard (free is better) tool windows programmers commonly use?

Thanks in advance

[A]
You should give
Xperf
a try - it's a new system wide performance tool that can drill down to a particular application and what exactly it's doing inside itself as well as what's it's asking of the OS.
It's freely available on the
Windows SDK for Windows Server 2008 and .NET Framework 3.5 ISO
:
Install the SDK by downloading the
ISO image
, or using the Web based
  installer.
Find the xperf MSI in the SDK's "bin" directory.   It will be named
  xperf_x86.msi, xperf_x64.msi, or
  xperf_ia64.msi, depending on the
  architecture for which you install the
  SDK.
You can then install the xperf tools from the MSI directly, or copy
  the xperf MSI file to another location
  and install it from there.  For
  example, you could keep the MSI files
  on a USB key.
Source: Pigs Can Fly blog on MSDN.com
Just verified that the xperf msi will not install except on windows Vista or Windows 2007.
-Adam


q:
I'm working on a project that currently has zero users but we would like to scale up to potentially hundreds.  Currently we are running on a MySQL database with AMFPHP interacting with Flex.  We used Flex because of its robust graphic features (important to this project) and because the initial developer (not me) already knew ActionScript.  We are currently using AIR but might switch to web-based Flash at some point.

My questions are:

Is Flex a good tool for a project like this?

What are the main limitations of Flex that we might encounter?

What are other development platforms we might want to consider?

Thanks.
- Dave

[A]
Flex has no inherent scalability problems, however if you have a graphic intensive application, proper serving of these resources might be a problem, but that has little to do with Flex.
The only note-worthy and likely platform you won't be able to run on is the iPhone (no flash) and some older non-flash mobile devices (although most support Flash-lite nowadays)
As for alternatives, if you are Graphics heavy, and don't mind the iPhone, then Flex is good if not best cross platform solution besides using pure HTML technologies, the trick here is HTML alone can do 99% of what Flex can do, but if your App requires the missing 1% then you're out of Luck, also Flex will reduce crossplatform and most browser compatibility issues. So it might make your work more productive.


q:
I have an ASP page which will query records from a DB Table and do some processing and then Render an HTML table in the browser.My table has more than 16000 rows in it. When i am running the prigram with select top 2500 StudId,StudName from StudentsTbl, It is working fine.But when i am Using select  "StudId,StudName from StudentsTbl",It is not showing any out put. I am using Response.flush() after every 50 records in the while loop.Can any one tell me how to solve this ? Thanks in advance

Actaully I would create an Excel file from this ASP page by adding Response..ContentType = "application/vnd.ms-excel" Thats y i need to generate the all data one time

[A]
Based on your description of the problem, I'm betting that you're using IE as your test browser. The Response.Flush()
is
outputting HTML, but it will not display right away because IE doesn't know how to render a table incrementally. Instead, IE waits for the entire table to output before it draws it to the browser window. Your script isn't the problem, IE is.
With that being said, I want to point out that your design is fundamentally flawed. Think about your script from a usability perspective: there is no sane reason why you need to output 16000 rows of data all at once.
Page your recordset in SQL
, or limit the recordset to first 1000 rows using a TOP clause.


q:
My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look

Image

Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?

I also would like to set the size of those buttons so they are not so huge (BorderLayout is being used for the buttons and TextField)

[A]
If you can
```
setResizeable( false )
```
on the top level frame you can then set your layout manager to null and hard code each location and size via setBounds. This is how I would do it (contingent on resizing of course).


q: How can I rename a schema using SQL Server?

[A]
You move individual objects from one schema to another via:
```
```
ALTER SCHEMA NewSchema TRANSFER OldSchema.Object;
```
```


q:
I have been looking at using TDD and implementing proper testing (only just started to learn how much better it makes your life) in any of my projects that I create in the future.  So for the last couple of days I have been floating around on SO trying to learn about how to design your application for testability, but I still seem to be struggling with some of the ideas.

I have read a lot that you should program against interfaces rather than classes. The main problem I'm having is, how many interfaces should you create? Should you have one for everything you want to test? or am I reading this wrong?

Another thing is use lots of dependency injection, so you can mock the parts that you are injecting rather than use the real things.  Is this correct? or am I way off here too?

[A]
You are right with the Mocking part, if you actually are doing what you said.
As for the interfaces, my personal method of development considering this point is that I first write what my application's main path should look like (using my ideal mock API that does nothing). Then after looking through my Mock implementation and refining it a few times, I start the actual class design. At this stage "know" how I can test each method, and write a test for it, and if for some reason I come across a method I can't easily figure out how to test, it means the method is not good, most likely it has too many responsibilities, and too many intermediary states I can't test, so I break the method up (interface wins over class design here). And keep on trickling down until I have a workable application.


q:
What is the best way to construct a bit mask in C with m set bits preceded by k unset bits, and followed by n unset bits:

00..0 11..1 00..0
  k     m     n

For example, k=1, m=4, n=3 would result in the bit mask:

01111000


q:
I saw this signature on the ListView class:

public ListView..::.ListViewItemCollection Items { get; }

When I saw that, "What?!"

I searched "dot dot colon colon dot" and "..::." on Google with no result.

[A]
That's not C#; that's JScript. In C#, it would be:
public ListView.ListViewItemCollection Items { get; }
It's a little different because ListViewItemCollection is an inner class of ListView.
I'm guessing that you saw this looking at
ListView.Items Property (System.Windows.Forms)
.
If you look at the listing for all the other languages, they're all listed with the JScript syntax. You've found a documentation bug.


q:
I wish to find all rows in a table where one column is a substring of another column.

In other words, suppose I have a table (called people) with two columns: firstname and lastname, and I want to find all people like "rob robinowitz" and "jill bajillion".

Is there a way to do something like "select * from people where lastname like %firstname%"?  (But something which actually works).

[A]
You were close
```
```
select * from people where lastname like '%' + firstname + '%'
```
```
Alternative way (may be even faster)
```
```
select * from people where charindex(firstname,lastname)>0
```
```


q: Sounds easy, but I can't find where this built in class and others exists in the documentation. I use functions but want to know what there is on the OO side.

[A]
It's not a URL or anything, but you can get a fair idea using Reflection:
```
```
Reflection::export(new ReflectionClass('DateTime'));

Class [  class DateTime ] {

  - Constants [11] {
    Constant [ string ATOM ] { Y-m-d\TH:i:sP }
    Constant [ string COOKIE ] { l, d-M-y H:i:s T }
    Constant [ string ISO8601 ] { Y-m-d\TH:i:sO }
    Constant [ string RFC822 ] { D, d M y H:i:s O }
    Constant [ string RFC850 ] { l, d-M-y H:i:s T }
    Constant [ string RFC1036 ] { D, d M y H:i:s O }
    Constant [ string RFC1123 ] { D, d M Y H:i:s O }
    Constant [ string RFC2822 ] { D, d M Y H:i:s O }
    Constant [ string RFC3339 ] { Y-m-d\TH:i:sP }
    Constant [ string RSS ] { D, d M Y H:i:s O }
    Constant [ string W3C ] { Y-m-d\TH:i:sP }
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [9] {
    Method [  public method __construct ] {
    }

    Method [  public method format ] {
    }

    Method [  public method modify ] {
    }

    Method [  public method getTimezone ] {
    }

    Method [  public method setTimezone ] {
    }

    Method [  public method getOffset ] {
    }

    Method [  public method setTime ] {
    }

    Method [  public method setDate ] {
    }

    Method [  public method setISODate ] {
    }
  }
}
```
```
Not perfect, as there are no arguments, but a starting point at least.  They should make this easier to find out, I agree!


q:
If I have code like this:

        public XALServiceConfiguration CreateInstance()
        {
            var config = ConfigurationManager.GetSection(ConfigurationSectionName) as XALServiceConfiguration;
            if (config == null)
                throw new ConfigurationErrorsException("Configuration element 'xalService' was not found or is not of correct type.");
            return config;
        }

How can I test that the exception is thrown if the section is missing from the configuration file ? For other tests, the configuration section needs to be in the config file, so I cannot actually remove it from the file.

I am using the Visual Studio 2008 Unit test framework.

[A]
You could just catch the exception in a
```
try catch
```
statment and do an
```
Assert
```
in the catch.


q:
I want add the new node as parent node of the old nodes in XML using C#. for example node have the following XMl file:

<bookstore>
   <books>
      <author>
      </author>
   </books>
</bookstore>

like that now I want add the new like below:

<bookstore>
 <newnode>
   <books>
      <author>
      </author>
   </books>
 </newnode>
</bookstore>

[A]
Don't have VS here so can't confirm that this works but something like this:
```
```
XmlDocument xd = new XmlDocument();
xd.Load("oldxmlfile.xml");
XmlNode oldNode = xd["nameOfRootNode"];
xd.RemoveAll();
XmlNode newParent = xd.CreateNode("nodename");
newParent.AppendChild(oldNode);
xd.AppendChild(newParent);
xd.Save("newXmlFile.xml");
```
```


q: Are there any command line interfaces to the DHCP settings in Mac OS X? I have found that inside System Profiler, the Network tab provides a lot of useful information, but I have not found any documentation about any command line equivalents.

[A]
You should look at:
```
```
ifconfig(8)
netstat(1)
netintro(4)
```
```
The most important of these (netintro isn't actually a utility but rather introductory information on unix networking) is ifconfig which is the command line tool used to configure the various network interfaces you may have installed on your machine (like your ethernet card and your airport card) as well as any virtual interfaces (like your loopback address and things like parallels).


q:
I want to pose a question such as:

What is your name? Joe

How would I accomplish this using Console.WriteLine to also wait for the response on that same line instead of it being broken into:

What is your name?

Joe

[A]
Use
```
Console.Write
```
instead, so there's no newline written:
```
```
Console.Write("What is your name? ");
var name = Console.ReadLine();
```
```


q:
Suppose I want to count the lines of code in a project. If all of the files are in the same directory I can execute:

cat * | wc -l

However, if there are sub-directories, this doesn't work. For this to work cat would have to have a recursive mode. I suspect this might be a job for xargs, but I wonder if there is a more elegant solution?

[A]
Try using the
```
find
```
command, which recurses directories by default:
```
find . -type f -execdir cat {} \; | wc -l
```


q:
I need an OpenSource API in Java, which can encode *.wav and *.au formats to MP3 and vice-versa.

I have evaluated Java Sound API and LameOnJ, but they do not meet my requirements and are not stable, respectively. Please suggest one that is free and platform independent.

[A]
Use the
Process API
to invoke
SoX
SoX comes with source or as precompiled binaries for Windows and Mac.


q: I have a version resource in my resources in a C++ project which contains version number, copyright and build details.  Is there an easy way to access this at run-time to populate my help/about dialog as I am currently maintaining seperate const values of this information.  Ideally, the solution should work for Windows/CE mobile and earlier versions of Visual C++ (6.0 upwards).

[A]
Something like this will give you raw access to the resource data and get you started:
```
```
HRSRC res = ::FindResource(NULL, MAKEINTRESOURCE(MY_VERSION_ID), RT_VERSION);
DWORD size = ::SizeofResource(NULL, res);
HGLOBAL mem = ::LoadResource(NULL, res);
LPVOID raw_data = ::LockResource(mem);
...
::FreeResource(mem);
```
```


q:
I am trying to use C# to parse CSV. I used regular expressions to find "," and read string if my header counts were equal to my match count.

Now this will not work if I have a value like:

"a",""b","x","y"","c"

then my output is:

'a'
'"b'
'x'
'y"'
'c'

but what I want is:

'a'
'"b","x","y"'
'c'

Is there any regex or any other logic I can use for this ?

[A]
In order to have a parseable CSV file, any double quotes inside a value need to be properly escaped somehow.  The two standard ways to do this are by representing a double quote either as two double quotes back to back, or a backslash double quote.  That is one of the following two forms:
""
\"
In the second form your initial string would look like this:
"a","\"b\",\"x\",\"y\"","c"
If your input string is not formatted against some rigorous format like this then you have very little chance of successfully parsing it in an automated environment.


q:
I have an app that is written in Swing, awt.
I want to prevent users from pasting values into the textfields.
is there any way to do this without using action listeners?

[A]
You may be able to override the
```
paste()
```
method in
```
JTextComponent
```
.


q: I have an exe that I know was written in java. I understand that java programs can be made into an exe and there are tools to convert jar files to exe but is it possible to convert back? AFAIK jar files can be run on any platform that can run java and I would like to use a windows compiled java program on mac without using any extra virtualisation (wine,vmware)

[A]
It depends how the exe has been built:
If it has simply wrapped, with a tool like
JSmooth
, the same tool can
extract the jar
If it it has been compiled, with for instance gcj (as illustrated by
this question
),... I am not sure.
If it has been compiled by a static compiler (or
AOT - Ahead-Of-Time
-), I believe it is not possible to extract the orignial jars.


q:
I always tell in c# a variable of type double is not suitable for money. All weird things could happen. But I can't seem to create an example to demonstrate some of these issues. Can anyone provide such an example?

(edit; this post was originally tagged C#; some replies refer to specific details of decimal, which therefore means System.Decimal).

(edit 2: I was specific asking for some c# code, so I don't think this is language agnostic only)

[A]
Very, very unsuitable. Use decimal.
```
```
double x = 3.65, y = 0.05, z = 3.7;
Console.WriteLine((x + y) == z); // false
```
```
(example from Jon's page
here
- recommended reading ;-p)


q:
I had this question earlier and it was concluded it was a bug in 5.2.5.  Well, it's still broken in 5.2.6, at least for me:

Please let me know if it is broken or works for you:

$obj = new stdClass();
$obj->{"foo"} = "bar";
$obj->{"0"} = "zero";
$arr = (array)$obj;

//foo -- bar
//0 --    {error: undefined index}
foreach ($arr as $key=>$value){
    echo "$key -- " . $arr[$key] . "\n";
}

Any ways to "fix" the array after it has been cast from a stdClass?

[A]
Definitely seems like a bug to me (PHP 5.2.6).
You can fix the array like this:
```
```
$arr = array_combine(array_keys($arr), array_values($arr));
```
```
It's been reported in
this bug report
but marked as bogus...
the documentation
says:
The keys are the member variable
  names, with a few notable exceptions:
  integer properties are unaccessible;


q: Can the iPhone use other databases besides SQLite, like MySQL?

[A] The iPhone can only use SQLite as a database, directly on the device. This means there is no MySQL server inside the iPhone. But you can, and are free to have (your own) MySQL Back-end server, to which iPhone applications connect to. But Apple doesn't provide the server, so you have to pay the maintenance costs


q:
I'm working with a Java program that has multiple components (with Eclipse & Ant at the moment).

Is there some way to start multiple programs with one launch configuration? I have an Ant target that does the job (launches multiple programs) but there are things I would like to  do:

I would like to debug the programs with Eclipse, hence the need for Eclipse launch.

I would like to see the outputs for the programs at separate consoles.

Also other ways to launch multiple Java programs "with one click" with separate consoles and/or debugging would be ok.

[A]
['multiple launch part':]
If you have an ant launch configuration which does what you want, you can always transform it into a java launcher calling ant.
```
```
Main Class: org.apache.tools.ant.Main

-Dant.home=${resource_loc:/myPath/apache_ant}
-f ${resource_loc:/myProject/config/myFile-ant.xml}
```
```
You can then launch this ant session as a regular java application, with all eclipse debugging facilities at your disposal.
Add to your classpath in the User Entries section (
before
your project and default path):
ant.jar
ant-launcher.jar
[Multiple console part]
May be a possible solution would be to make sure your ant launcher actually launches the different application in their own JVM process (one javaw.exe for each application)
That way, you could use the ability of the
native eclipse console to switch between different  process
.
The Console view clearly separates output from each distinct "process" and keeps them in several "buffers". The Console has a built-in "switch" feature that will automatically switch the view to display the buffer of the last process that performed output, however you can easily switch the display to any "process buffer" you want to look at.
To switch the Console "buffer" display, just click on the black "Down arrow" next to the 4th toolbar button from the right in the Console View's title bar (the button
that resembles a computer screen):
this will show a pop-down menu listing the "names" of all active process buffers, preceded by an "order number".
The one currently displayed will have a check-mark before its "order number". You can switch the view to another display buffer simply by clicking on its name.


q:
Just wondering if there is anything built-in to Javascript that can take a Form and return the query parameters, eg: "var1=value&var2=value2&arr[]=foo&arr[]=bar..."

I've been wondering this for years.

[A]
I'm not entirely certain myself, I recall seeing jQuery did it to an extent, but it doesn't handle hierarchical records at all, let alone in a php friendly way.
One thing I do know for certain, is when building URLs and sticking the product into the dom, don't just use string-glue to do it, or you'll be opening yourself to a handy page breaker.
For instance, certain advertising software in-lines the version string from whatever runs your flash. This is fine when its adobes generic simple string, but however, that's very naive, and blows up in an embarrasing mess for people whom have installed Gnash, as gnash'es version string happens to contain a full blown GPL copyright licences, complete with URLs and <a href> tags. Using this in your string-glue advertiser generator, results in the page blowing open and having imbalanced HTML turning up in the dom.
The moral of the story:
```
```
var foo = document.createElement("elementnamehere");
   foo.attribute = allUserSpecifiedDataConsideredDangerousHere;
   somenode.appendChild(foo);
```
```
Not:
```
```
document.write("<elementnamehere attribute=\""
        + ilovebrokenwebsites
        + "\">"
        + stringdata
        + "</elementnamehere>");
```
```
Google need to learn this trick. I tried to report the problem, they appear not to care.


q:
There are too many method for embedding flash in html, which way is the best?
Requirements are:

Cross-browser support

Support for alternative content (if flash is not supported by the browser)

Possibility to require a specific version of the flash player

I have been reading about SWFobject, has anyone used it/tested?

[A]
In a project I work on we use SWFobject which works like a charm, it allows you to check for a specific version and also display alternative content if flash is not supported.
```
```
var fn = function() {
    if(swfobject.hasFlashPlayerVersion("9.0.115"))
    {
        var att = { data:"flash.swf", width:"y", height:"x" };
        var par = { menu: "false", flashvars: "" };
        signUp = swfobject.createSWF(att, par);
    }
}
swfobject.addDomLoadEvent(fn);
```
```


q:
I need to launch a media file from a URL from within my c# .NET application. Is there any way to do this natively in .NET? I don't need an embedded player, I just need the default player to launch. I have tried

System.Diagnostics.Process.Start("File URL");

but it launches the default browser and downloads the file, instead of attempting to play it in WMP/VLC/whatever the default media player is. Any ideas?

[A]
If you enter an URL it will be handled with the program registered to that URL format, in your case the default web browser.
What format are the media in? You can get associated program for an extension and then run that program with the url as parameter.
See:
Windows: List and Launch applications associated with an extension
So if your media is for example .MP3, then find the assoicated program for .MP3 (using the code in the link above) and pass the url as a parameter to that program.


q:
Can we have a SQL query which will basically help in viewing table and index sizes in SQl Server.

How SQL server maintains memory usage for  tables/indexes?

[A]
```
```
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"
```
```


q:
I'm recoding an old site that contains a chart similar to this:

alt text http://dl.getdropbox.com/u/240752/rental-chart.gif

How would this chart be represented with pure HTML? I'm loathed to just include it as an image.

I'm thinking a table, just replaced with an image, or perhaps overlaid with absolutely positioned table rows, but I think that may be a bit fragile.

Any suggestions welcomed.

[A]
Whats wrong with the image?
Most times when you see chart information on the Web its a generated .jpg or .png.
Have all those designers got something wrong?
Any attempt to draw the chart using tables and backgroud colours will not be intelligable to a sight impaired person, and, in all probability will not render correctly on a browser that cannot handle images.
Use the image and have an "alt" text with a real English description "A chart showing ACME product costs only $49 compared with competitors: Rental Company 4 at $51 .......


q: How can I access the apache basic-auth username in a PHP script?

[A]
Simply access this variable:
```
```
$_SERVER['PHP_AUTH_USER']
```
```


q:
I have the following string:

<SEM>electric</SEM> cu <SEM>hello</SEM> rent <SEM>is<I>love</I>, <PARTITION />mind

I want to find the last "SEM" start tag before the "PARTITION" tag. not the SEM end tag but the start tag. The result should be:

<SEM>is <Im>love</Im>, <PARTITION />

I have tried this regular expression:

<SEM>[^<]*<PARTITION[ ]/>

but it only works if the final "SEM" and "PARTITION" tags do not have any other tag between them. Any ideas?

[A]
Have you tried this:
```
```
<EM>.*<PARTITION\s*/>
```
```
Your regular expression was matching anything but "<" after the "EM" tag. Therefore it would stop matching when it hit the closing "EM" tag.


q: How do I ping a website or IP address with Python?

[A]
Depending on what you want to achive, you are probably easiest calling the system ping command..
Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!
```
```
import subprocess

host = "www.google.com"

ping = subprocess.Popen(
    ["ping", "-c", "4", host],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out
```
```
You don't need to worry about shell-escape characters. For example..
```
```
host = "google.com; `echo test`
```
```
..will
not
execute the echo command.
Now, to actually get the ping results, you could parse the
```
out
```
variable. Example output:
```
```
round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
```
```
Example regex:
```
```
import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')
```
```
Again, remember the output will vary depending on operating system (and even the version of
```
ping
```
). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)


q:
I need to use JavaScript in a form for mobile web application.

I need some information about it, related to browser compatibility as well as way to use JavaScript in mobile web applications (syntax).

[A]
It's a nightmare. It's like working with web-browsers in the 90's but with the manager expectations of tomorrow.
I strongly recommend you determine your target platforms in terms of regions, software, and actual hardware since the market is much more fragmented than the web and a large number of mobile devices have issues with CSS, JS and even XHTML ranging from painful to not-on-this-platform.
The good news is that android and iphone are pushing the field rapidly. The bad news is that makes a lot of the sources you'll google badly out-of-date.
Some references:
http://www.w3.org/TR/mobileOK-basic10-tests/#test_objects_or_script
http://mobiforge.com/developing/story/getting-started-with-mobile-ajax
http://mobiforge.com/
Especially that last one :)


q:
I can't seem to retrieve an ID I'm sending in a html.ActionLink in my controller, here is what I'm trying to do

<li>
    <%= Html.ActionLink("Modify Villa", "Modify", "Villa", new { @id = "1" })%></li>

    public ActionResult Modify(string ID)
    {

        ViewData["Title"] =ID;
        return View();
    }

That's what a tutorial I followed recommended, but it's not working, it's also putting ?Length=5 at the end of the URL!

Here is the route I'm using, it's default

        routes.MapRoute(
            "Default",                                              // Route name
            "{controller}/{action}/{id}",                           // URL with parameters
            new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
        );

[A]
Don't put the @ before the id
```
```
new { id = "1" }
```
```
The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route


q:
I've got a dump of a .Net process that has hung due to a deadlock (the gui thread is no longer responding, and my logs show that some threads have stopped responding). I have taken a snapshot and am now looking through it in windbg, and all threads bar one are waiting for the last one. Looking at that one thread's stacktrace with !clrstack -p I can see that it is trying to aquire a write on a ReaderWriterLock

How do I tell which other thread holds that lock so I can start figuring out how the deadlock happened?

thanks

[edit] apparently there was a command !rwlocks in the .Net1.1 sos.dll to help with this, but it isn't there in the .Net2.0 version. The hunt continues

[A]
I'm not absolutely sure but you might be able to use !SyncBlk to look at the sync block objects, if you invoke it without any arguments I think you should see the sync blocks that are owned by a thread.
If you have a sync block deadlock, the extension
SOSEX
might be what you need. This extension offers the command !dlk that shows which threads are waiting for which locks. This only works for sync blocks though, deadlocks on other sync objects will not be detected, if you are using lock() (Monitor.Enter) this should not be a problem for you.


q:
I've been playing with ADO.NET Entity Framework lately, and I find that it suits my needs for a project I'm developing. I also find cool its non-invasive nature.

After generating a data model from an existing database you are faced with the task of integrating the generated model and your business logic. More specifically, I'm used to integration-test my classes that interact with the data store via mocks/stubs of the DAL interfaces. The problem is that you cannot do this using the ADO.NET Entity Framework because the entities it generates are simple classes with no interface.

The question is: how do I apply a TDD approach to the development of an application that uses ADO.NET Entity Framework? Is this even possible or should I migrate to another DAL-generation toolset?

[A]
"The tight coupling of the persistence
  infrastructure to the entity classes
  largely eliminates the ability to
  efficiently use very tight feedback
  cycles on the business logic with
  automated testing. In its current
  state, EF entity classes cannot be
  effectively unit tested independently
  of the database.
The efficiency of automated unit
  testing of behavioral objects is
  largely a matter of how easy the
  mechanics of test data setup are and
  how quickly the tests can be executed.
  Using the actual database will make
  test data setup more laborious,
  introduce data to satisfy relational
  constraints that are not germane to
  the test, and make test execution an
  order of magnitude slower.
A team’s ability to do evolutionary
  design and incremental delivery is
  damaged by the Entity Framework’s
  inattention to fundamental software
  design principles like Separation of
  Concerns."
Blatantly stolen from here:
http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/


q:
I need to know if I can create a file in a specific folder, but there are too many things to check such as permissions, duplicate files, etc.
I'm looking for something like File.CanCreate(@"C:\myfolder\myfile.aaa"), but haven't found such a method.
The only thing I thought is to try to create a dummy file and check for exceptions but this is an ungly solution that also affects performance.
Do you know a better solution?

[A]
In reality, creating a dummy file isn't going to have a huge performance impact in most applications. Of course, if you have advanced permissions with create but not destroy it might get a bit hairy...
Guids are always handy for random names (to avoid conflicts) - something like:
```
```
string file = Path.Combine(dir, Guid.NewGuid().ToString() + ".tmp");
// perhaps check File.Exists(file), but it would be a long-shot...
bool canCreate;
try
{
    using (File.Create(file)) { }
    File.Delete(file);
    canCreate = true;
}
catch
{
    canCreate = false;
}
```
```


q:
Aloha

I have a method with (pseudo) signature:

public static T Parse<T>(string datadictionary) where T : List<U>

This doesn't build. How can I restrict the  in the method to accept only generic List<> objects (which should of cource not contain T's but something else :)

I need to restrict the type of T because I need to call a method on it in this code. The type passed in is a custom collection (based on List).

public class MyCollection<T> : List<T> where T: MyClass, new()
{
    public void Foo();
}

public static T Parse<T>(string datadictionary) where T : MyCollection<U>
{
    T.Foo();
}

-Edoode

[A]
Well, you can have two type parameters:
```
```
public static T Parse<T, U>(string datadictionary) where T : List<U>
```
```
That way you'll also actually know what U is (in a compile-time manner)...
EDIT: Alternatively (and better), just specify the element type and change the return type:
```
```
public static List<T> Parse<T>(string datadictionary)
```
```
e.g.
```
```
List<int> data = Parse<int>(whatever);
```
```
Note that you may wish to change from
```
List<T>
```
to
```
IList<T>
```
or even a broader interface.


q:
If you have a route:

routes.MapRoute("search", "{controller}/{action}/{filter1}/{filter2}/{filter3}", _
  New With {.filter1 = "", .filter2 = "", .filter3 = ""})

then in a view satisfied by the route pattern with a url of /member/search/dev/phil/hoy, when you attempt to create another route url with only filter1 present i.e.

<%=Url.RouteUrl(New RouteValueDictionary(
  New With {.controller="member",.action="search", .filter1="dev"}))%>

the result is the current route /member/search/dev/phil/hoy, not the expected trimmed route /member/search/dev

I have managed to work round the issue by using RouteTable.Routes.GetVirtualPath method directly, but does anyone know why it works this way or is it perhaps a bug?

[A]
Some people use nested
```
StackPanel
```
s to "solve" this problem, but IMHO that just introduces another problem (code bloat). I think the best way to solve this is to write your own panel that lays out children consecutively in columns. I did this on a previous project and it has a number of advantages:
More readable and terse XAML
Easier to maintain XAML
Faster performance
The usage looked something like this:
```
```
<local:FieldPanel>
    Field 1:
    <TextBox/>

    Field 2:
    <TextBox/>

    Field 3:
    <TextBox/>
</local:FieldPanel>
```
```


q:
I autoformat a GridView in ASP.NET.

It looks nice but the headers all run together like this:

idfirstNamelastNameage

I set CellPadding="5" but it does nothing.

How can I set the cell padding of the headers and all cells?

A D D E N D U M :

Thanks Andrew, I fixed it with this. Works in Firefox and Explorer 7:

.gridview2 tr td
{
    padding: 5px;
    border: 1px solid #ddd;
}
.gridview2 tr th
{
    padding: 5px;
}

[A]
You should set a cssclass and use css to control it. The only property of a table you cant fully control cross browser with css is cellspacing.
```
```
.myTableClass tr th {
    padding: 5px;
}
```
```


q:
i've got a site with a lot of referenced .js-Files; those are rather small files, but I want to keep my methods separated by topic/functionality.

Is it better to keep all the methods in one .js-File or is it no problem to have many (~ 20 - 30) small files all including only some lines?

[A]
By all means keep them separate for development, but you should consider bundling them together into one file for production.
There is a nice discussion at
sitepoint.com
For each of these files, an HTTP
  request is sent to the server, and
  then the browser awaits a response
  before requesting the next file.
  Limits (or limitations) of the browser
  generally prevent parallel downloads.
  This means that for each file, you
  wait for the request to reach the
  server, the server to process the
  request, and the reply (including the
  file content itself) to reach you. Put
  end to end, a few of these can make a
  big difference to page load times.


q: I have a bunch of rows in Excel that I want to paste into a new table in MS SQL. Is there a simple way ?

[A]
The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement.
Then copy these insert into a text file and then execute on the SQL.
The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.


q:
What's better for DSL: TCL or Lisp?
What can you say about Java(C#)-TCL binding versus Lisp(Scheme)?
What DSL tool is applicable for .Net development? (excepting Microsoft DSL tools)

[A]
It really depends on who will use the DSL.
If you are expecting non-IT domain experts then something simple and straightforward like TCL would be recommended. Explaining the joys of LISP to a non IT graduate would be a serious problem as would debugging a large LISP program written by someone who hasnt grokked LISP.
Equally expaining to someone that b = a + 1 is written B = INCR(A) isnt such a good idea either.
I would recommend Python, you can embed the domain specific code in one or two specialist classes. You have a language where non-IT users can code simple readable programs, and, where there are no limits on what an IT specialist can code.


q:
I am developing an application and want to display a form that will be filled in if editing the form, but will not be if the form will be a new entry.  I believe the least verbose way of doing this is to have just one form and to suppress any errors for echoing my variables so that nothing will be printed if it is a new form (since the variables will not exist if it is a new form).  For example:

<?php
if ( ! $new_item) {
    $variable = 'Example';
}
?>
<form>
    <input type="text" name="inputbox" value="<?php echo @$variable; ?>" />
</form>

Is this a good practice, or is there a better way of doing it?  Should I make separate views for the new items and for the items to be edited?  What are the performance repercussions of doing this?

[A]
I think the best way is to always set the variable
```
```
if ( ! $new_item) {
    $variable = 'Example';
} else {
    $variable = 'Default value';
    //or
    $variable = '';
}
```
```
Using the
```
@
```
error suppression is slow.
edit
Note that when you print the variable into the input value attribute, you should first call
```
htmlentities()
```
or
```
htmlspecialchars()
```
on it.
2nd edit
You say in your comment you are fetching the data as on object, in that case you could also do:
```
```
class example {
    public $somefield = 'default value';
}
```
```
Then if it is an existing record you are editing do something like this, which will cause the returned object to be an instance of 'example':
```
```
$record = mysql_fetch_object($result, 'example');
```
```
or if it is a new record instanciate it yourself:
```
```
$record = new example();
```
```
Then you always know
```
$record->somefield
```
will be set and you can do :
```
```
<form>
    <input type="text" name="somefield" value="<?php echo htmlspecialchars($record->somefield); ?>" />
</form>
```
```


q: What are the other ways of achieving auto-increment in oracle other than use of triggers?

[A]
You can create and use oracle sequences. The syntax and details are at
http://www.techonthenet.com/oracle/sequences.php
Also read the article
http://rnyb2.blogspot.com/2006/02/potential-pitfall-with-oracle-sequence.html
to understand the limitations with respect to AUTONUMBER in other RDBMS


q: How can I validate a SOAP response against an XSD file that defines the response schema. the web service I'm calling has an XMLDocument as input and output, so can't use WSDL for response schema validation.

[A]
I case you still need this (valid for SOAP UI version 2.5.1):
File, Preferences, Editor Setting, Validate Response.


q:
Does anybody know why

  vector<int> test(10);
  int a=0;

  for_each(test.begin(),test.end(),(_1+=var(a),++var(a)));

  for_each(test.begin(),test.end(),(cout << _1 << " "));
  cout << "\n"

Gives :  "0 1 2 3 4 5 6 7 8 9"

but

  transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a)));
  ...(as before)

Gives : "1 2 3 4 5 6 7 8 9 10"

?

[A]
Comma operator evaluates left to right, so the result of the
```
```
_1+=var(a), ++var(a)
```
```
is ++var(a), which you'll store using the transform version.
for_each:
_1 += var(a) is evaluated, updating your sequence (via the lambda _1), then ++var(a) is evaluated, but this has no effect on your sequence.
transform:
_1+=var(a) is evaluated, updating your sequence (just like before), then ++var(a) is evaluated, this also gives the result of the whole expression, then that is used to update your sequence again (via the transform)


q:
As the question says, how do I add a new option to a DropDownList using jQuery?

Thanks

[A]
With the plugin:
jQuery Selection Box
. You can do this:
```
```
var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false);
```
```


q: Does the opening Window enhance an application's attractiveness? Should it be a picture or bland Blue and White?

[A]
Use the default OS theme colors.  Anything else will be attractive to certain groups of people, and ugly to others (who will complain
very loudly
about how ugly they find it).  If you stick with the OS theme colors, then at least your application's appearance will not be something you'll be criticized over.


q: There seem to be many options to create an XML document in .NET. What's the best approach?

[A]
I would personally use LINQ to XML if I possibly could. It's
much
nicer than the DOM API. Of course, it does rely on you using .NET 3.5...
Note that your String.Format solution breaks down if you have any text which would need escaping. Admittedly I can't think of any car makes and models including
```
&
```
or
```
<
```
etc, but in a more general case it's a real issue.


q:
For our school project, we are tasked to define a design document describing the architecture of a PHP application.

We are free te decide what to include in the document.

Our professor suggested, lots of (UML) diagrams.

He also asked us to consider class diagrams, but with care, as PHP is not fully object oriented.

My question: Is a Domain Driven Object Oriented Design feasible for a PHP application? What to consider when doing OO in PHP? What are the pro's and con's? Any helpful resources on OO in PHP and PHP best-practices?

[A]
IMHO it's pretty difficult to describe the architecture of any application without knowing what the application is supposed to do. All applications (PHP or otherwise) of any complexity look different.
Secondly, PHP5 gives you classes/objects and the usual plethora of OO gubbings - so to describe it as 'not fully object orientated' is misleading I think. If you mean you can take a procedural approach with out being restricted to objects then yes, but if you wanted everything to be an object then that's your choice.
Is DDD feasible for PHP? Yes, of course. A particular approach to architecture is not usually dependent on technology. Best practices, pros/cons of OO design apply to most languages - PHP leaves you pretty free to decide how to structure your code.
You may find this
Best Practices
talk from the PHP site useful ;)


q:
I would like to change all the names of the attributes where class="testingCase" throughout all my whole html document.

e.g. Change:

<a class="testingCase" href="#" title="name of testing case">Blabla</a>
<a class="testingCase" href="#" title="name of another testing case">Bloo</a>

To this:

<a class="testingCase" href="#" newTitleName="name of testing case">Blabla</a>`
<a class="testingCase" href="#" newTitleName="name of another testing case">Bloo</a>`

I was thinking of a find and replace but that seems a lot of code for something so easy. Is there a jQuery function for this or a simple method?

[A]
There is no built-in method/function to "rename" an attribute in javascript, but you can create new attributes and remove other ones...
```
```
$('a.testingCase[title]').each(function() {
  var $t = $(this);
  $t.attr({
      newTitleName: $t.attr('title')
    })
    .removeAttr('title');
});
```
```
```
```

Blabla
Bloo
```
```
Edit: added in the bit that makes it only select
```
a
```
elements with class="testingCase"


q:
On Apache/PHP sites if I want to put a senstive file within my website folders, I put a .htaccess file in that folder so users can't download the sensitive file.

Is there a similar practice for IIS/ASP.NET sites, i.e. if I have a shared hosting account and don't have access to IIS server. Can I do this in web.config for instance?

e.g. the ASPNETDB.MDF file that ASP.NET Configuration put in the App_Data directory. I would assume this is protected by default but where can I change the settings for this folder as I could with a .htaccess file?

[A]
There are some things you can do with web.config like defining security settings etc...
Other times you have to use HttpModules or HttpHandlers, look here:
http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx
If not, you can find different ISAPI, but in this case you need access to IIS.
For example, the ISAPI for emulating rewrite mod apache:
> http://www.codeplex.com/IIRF
The other question, yes ASPNETDB.MDF in APP_Data is protected normally (it depends on your administrator). To change the path, change the connectionstring.


q: I am looking for any tool which will allow the performance testing/tuning of Sybase nested stored procedures. There are many tools around and of course Sybase's own for performance tuning and testing SQL but none of these can handle nested stored procedures (i.e. a stored proc calling another stored proc). Does anyone have/know of such a tool?


q:
I'd like to know when i should and shouldn't be wrapping things in a USING block.

From what I understand, the compiler translates it into a try/finally, where the finally calls Dispose() on the object.

I always use a USING around database connections and file access, but its more out of habit rather than a 100% understanding. I know you should explicity (or with a using) Dispose() objects which control resources, to ensure they are released instantly rather than whenever the CLR feels like it, but thats where my understanding breaks down.

Are IDisposables not disposed of when they go out of scope?

Do I only need to use a USING when my object makes use of Dispose to tidy itself up?

Thanks

Edit: I know there are a couple of other posts on the USING keyword, but I'm more interested in answers relating the the CLR and exactly whats going on internally

Andrew

[A]
No,
```
IDisposable
```
items are not disposed when they go out of scope. It is for precisely this reason that we need
```
IDisposable
```
- for deterministic cleanup.
They will
eventually
get garbage collected, and if there is a finalizer it will (maybe) be called - but that could be a long time in the future (not good for connection pools etc). Garbage collection is dependent on memory pressure - if nothing wants extra memory, there is no need to run a GC cycle.
Interestingly (perhaps) there are some cases where "using" is a pain - when the offending class throws an exception on
```
Dispose()
```
sometimes. WCF is an offender of this. I have discussed this topic (with a simple workaround)
here
.
Basically - if the class implements
```
IDisposable
```
, and you
own
an instance (i.e. you created it or whatever), it is your job to ensure that it gets disposed. That might mean via "using", or it might mean passing it to another piece of code that assumes responsibility.
I've actually seen debug code of the type:
```
```
#if DEBUG
    ~Foo() {
        // complain loudly that smoebody forgot to dispose...
    }
#endif
```
```
(where the
```
Dispose
```
calls
```
GC.SuppressFinalize
```
)


q:
I mainly use the MySQL GUI tools. This allows me to easily see the results in a table as well as to quick edits and bookmark frequently run queries. This suits my needs far better than the command line.

I remember when I used to do this on Oracle DBs years ago I could put variables in the query itself, so that when running the query I got prompted for the variable.

e.g.

select email from users where login = [VAR]

And when you run the query the system prompts you for VAR and you can type in john_smith14 and it executes the query. This is really useful for adhoc queries which you run a lot.

Yes I know using shell scripts and the command line this could be done more easily, but for several reasons aside from this, shell scripts are not a good solution for me.

[A]
I'm not sure if there's a way to get the GUI tools to prompt you for a value, but you can certainly use variables in MySQL.
```
```
SET @myVar='john_smith14';
SELECT email FROM users WHERE login = @myVar;
```
```
That might even suit you better, since you don't have to keep typing in the variable value each time..?


q: I want to develop a mobile web application using asp.net 3.5 that can be viewed on an iPhone but there is no longer a template in VS2008 to enable mobile development. Can this be done ?

[A]
the iphone uses the "regular" version of your website so developing a "mobile" version would nto accomplish what you're looking for. You should check the browser headers and redirect people to the iPhone version of your site if you detect mobile safari.
http://iphone.facebook.com/
Another option (if you're using MVC) is to have your controller detect the browser and show a different view if it catches mobile safari. This way you wouldn't need a duplicate site, just two sets of views.


q:
Why not use partial class to build the ViewModel?

Since the definition of viewmodel classes have some definition of the data classes of datamodel, why not try to reduce some work, extending or making partial classes of the datamodel, completing them with command and etc.

[A]
In some cases this may be useful, but generally the ViewModel (or PresentationModel) has a different set of concerns that would muddle the rest of the model.
For example, imagine that you have an object model that represents an order processing workflow (everybody's favorite example.) This same model might be underlying a WPF, a web site, and perhaps even other services.
Within the WPF application there will be WPF-specific concerns for presentation. Adding these concerns to primary model (even as partial classes) results in a violation of SRP. Ultimately, it would obscure the intent of model and make it difficult for consumers of the model to know which parts of it where essential and which were incidental.


q:
I am using NetBeans for PHP 6.5.

In my code I frequently use the following type of command:

if (($row = $db->get_row($sql))) {
        return $row->folder;
    } else {
        return FALSE;
    }

Netbeans tells me that I should not be using assignments in the IF statement.

Why ?

[A]
It's probably trying to help you avoid the dreaded typo:
```
```
if(a = b)
   //logic error
```
```
Although I would expect an enviroment smart enough to warn you about that, to also be smart enough to have "oh, don't worry about that case" conditions.


q:
I'm currently having a problem with a ShoppingCart for my customer.

He wants to be able to add Text between the CartItems so I was wondering if there is some way to still only have one List.

My solution would be to have two lists, one of type IList that gets iterated over when calculating Weight and overall Price of the Cart while having another IList that only exposes the necessary fields for displaying it in the ListView and that is a SuperType of CartItem. (But how do I then access additional fields for the listView, defaulting weight and price to 0 in the Description-Text-Class would break LSP).

But having two lists somehow feels a bit odd (and still gives me problems), so I was wondering if I could do some sort of a TypedList where I specify the Type of each item.

Any suggestions are welcome, I'm not really happy with both options.

[A]
Use an interface:
```
```
ICartListItem
```
```
And make your list be:
```
```
List<ICartListItem>
```
```
Now, create several types, have all of them implement this interface, and you can store them all safely in your list.
Alternatively, if you want there to be some default logic in a CartItem, use a base class instead of an interface.


q:
I am trying to build a server control that, depending on a "QuestionTypeId" display either a text box, date picker or Yes-No radio buttons.

I have my control displaying how I want it to, but when the submit button is pressed on the form, the text box, date picker or radio buttons that were generated in the RenderContents method are all null.

I have attempted to store the generated controls in view state, that stopped them being null, but the user inputs were not being stored.

I will post code if it is needed. Just ask.

[A]
When you add controls dynamically, you need to make sure they are recreated before the viewstate is restored.
I haven't done this in a while, but from memory I think you should recreate your controls in the OnInit method. This happens before postback data has been loaded and before the controls have their values set from viewstate.
It may be worth doing some reading on the asp.net page lifecycle:
http://msdn.microsoft.com/en-us/library/ms178472.aspx


q: Is there any setting using which the iPhone keyboard won't appear for a particular textbox in web page? May be some css kind of setting?

[A]
Do you want the text box to be editable for any other browser other than the iPhone?  If not, have you attempted to disable the text box?  I haven't tried this, nor can I recall seeing a disabled text box on a site with my iPhone; however, it may do it.
If disabling the text box works
, but you still only want to restrict it to the iPhone, you'll need to look at the User Agent for the iPhone.  You can determine this through server side code or through JavaScript's
```
navigator.userAgent
```
.
To save a bit more time for you as well, the iPhone's user agent is as follows:
```
```
Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3
```
```


q: Which ftp client or which syntax allows easy chmod for sub-directories?

[A]
To chmod all subdirs from where you are (recursive):
```
```
chmod -R *
```
```


q:
How would you get tree-structured data from a database with the best performance? For example, say you have a folder-hierarchy in a database. Where the folder-database-row has ID, Name and ParentID columns.

Would you use a special algorithm to get all the data at once, minimizing the amount of database-calls and process it in code?

Or would you use do many calls to the database and sort of get the structure done from the database directly?

Maybe there are different answers based on x amount of database-rows, hierarchy-depth or whatever?

Edit: I use Microsoft SQL Server, but answers out of other perspectives are interesting too.

[A]
If you have many trees in the database, and you will only ever get the whole tree out, I would store a tree ID (or root node ID) and a parent node ID for each node in the database, get all the nodes for a particular tree ID, and process in memory.
However if you will be getting subtrees out, you can only get a subtree of a particular parent node ID, so you either need to store all parent nodes of each node to use the above method, or perform multiple SQL queries as you descend into the tree (hope there are no cycles in your tree!), although you can reuse the same Prepared Statement (assuming that nodes are of the same type and are all stored in a single table) to prevent re-compiling the SQL, so it might not be slower, indeed with database optimisations applied to the query it could be preferable. Might want to run some tests to find out.
If you are only storing one tree, your question becomes one of querying subtrees only, and the second answer applied.


q:
I understand that, if S is a child class of T, then a List<S> is not a child of List<T>. Fine. But interfaces have a different paradigm: if Foo implements IFoo, then why is a List<Foo> not (an example of) a List<IFoo>?

As there can be no actual class IFoo, does this mean that I would always have to cast each element of the list when exposing a List<IFoo>? Or is this simply bad design and I have to define my own collection class ListOfIFoos to be able to work with them? Neither seem reasonable to me...

What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my List<Foo> internally as a List<IFoo>.

[A]
MASSIVE EDIT
You'll be able to do it with C# 4.0, but
[thanks Jon]
You can get around it using
```
ConvertAll
```
:
```
```
public List<IFoo> IFoos()
{
    var x = new List<Foo>(); //Foo implements IFoo
    /* .. */
    return x.ConvertAll<IFoo>(f => f); //thanks Marc
}
```
```


q:
I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.

Is there a function that can do this easily?

For example:

$string1 = "I am looking for a way to pull the first 100 characters from a string variable to put in another variable for printing.";
$string2 = 100charfunction($string1);
print $string2

To get:

I am looking for a way to pull the first 100 characters from a string vari

[A]
```
```
$small = substr($big, 0, 100);
```
```
For
String Manipulation
here is a page with a lot of function that might help you in your future work.


q:
When the page is done loading I call a function which puts the hover event on $('a.tooltip'). When I want to unbind this event I do the following:

   $('a.tooltip').unbind('mouseover mouseout');

That works! However when I want rebind the hover event and I call the function that was first loaded at document ready again, it doesn't rebind the hover helper. How can I rebind it?

Thank you,

Ice

[A]
Are you sure the unbinding is working correctly? In my experience, .hover() does rebind properly, but I have had to use this unbind syntax:
```
```
$(this).unbind('mouseenter').unbind('mouseleave');
```
```
When I tried putting both events into one unbind(), it only unbound one of them.
I wonder if that's happening for you? (Or if the choice of
```
mouseover
```
vs
```
mouseenter
```
, etc, matters?)
Update
According to
quirksmode.org
,
```
mouseenter
```
and
```
mouseleave
```
are IE-specific events, but as Jimmy pointed out in the comments, jQuery implements them for other browsers as well.


q:
I'm testing the basics for exchanging rest messages between a asp.net mvc site and a WCF 3.5 service.
The service is built using the template found in the WCF REST Starter Kit found on codeplex.
I would like to exchange json messages using jquery.
The REST Singleton service is working properly and it also provide examples of all the possible calling adding the help parameter ad the end of the uri.
I arrive to perform GET requests with the built in jquery $.getJSON.
I have problems doing the PUT (for updating values) and POST.

$.ajax({
     type: "PUT",
     dataType: "json",
     url: "http://localhost:1045/Service.svc/?format=json",
     data: '{"Value":testvalue}'
 });

What is the best approach for this? Is it possible not to use Ms. Ajax at all and is it correct to bypass it?

[A]
"PUT" and "DELETE" are not supported by all browsers according to jQuery
The type of request to make ("POST" or
  "GET"), default is "GET". Note: Other
  HTTP request methods, such as PUT and
  DELETE, can also be used here, but
  they are not supported by all
  browsers.
http://docs.jquery.com/Ajax/jQuery.ajax#options
I didn't really understand your question though.  Are you having a problem doing a PUT and a POST or just a POST?  Does the GET work fine?
One error that I noticed was your data, notice I added it without quotes.
```
```
$.ajax({
     type: "PUT",
     dataType: "json",
     url: "http://localhost:1045/Service.svc/?format=json",
     data: { Value: "testvalue" }
});
```
```


q:
I am creating a GUI frontend for the Eve Online API in Python.

I have successfully pulled the XML data from their server.

I am trying to grab the value from a node called "name":

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')
print name

This seems to find the node, but the output is below:

[<DOM Element: name at 0x11e6d28>]

How could I get it to print the value of the node?

[A]
It should just be
```
```
name[0].firstChild.nodeValue
```
```


q: I'm interested in hearing people's thoughts about the pros and cons of database mirroring vs. log shipping in this scenario: we need to setup a database backup situation wherein there is exactly one secondary server that need not automatically pick up when the primary fails.  Recovering and starting with the secondary should not have to take too long though.

[A] Switching to the secondary database does take longer with log shipping, but it's not too bad.  You'll have to manually copy any uncopied backup files, apply the transaction log backups to the secondary database, recover the secondary database, and change its role to primary.  If the old primary databases accessible, you should back up its transaction log before beginning.  Failing over with mirroring is somewhat simpler, and can be done automatically if you are using High Availability mode.  Even when using High Performance mode, it's still a one statement operation.


q:
In the Boost Signals library, they are overloading the () operator.

Is this a convention in C++? For callbacks, etc.?

I have seen this in code of a co-worker (who happens to be a big Boost fan). Of all the Boost goodness out there, this has only led to confusion for me.

Any insight as to the reason for this overload?

[A]
Another co-worker pointed out that it could be a way to disguise functor objects as functions. For example, this:
```
```
my_functor();
```
```
Is really:
```
```
my_functor.operator()();
```
```
So does that mean this:
```
```
my_functor(int n, float f){ ... };
```
```
Can be used to overload this as well?
```
```
my_functor.operator()(int n, float f){ ... };
```
```


q:
I have a table, users, in an Oracle 9.2.0.6 database.  Two of the fields are varchar - last_name and first_name.

When rows are inserted into this table, the first name and last name fields are supposed to be in all upper case, but somehow some values in these two fields are mixed case.

I want to run a query that will show me all of the rows in the table that have first or last names with lowercase characters in it.

I searched the net and found REGEXP_LIKE, but that must be for newer versions of oracle - it doesn't seem to work for me.

Another thing I tried was to translate "abcde...z" to "$$$$$...$" and then search for a '$' in my field, but there has to be a better way?

Thanks in advance!

[A]
How about this:
```
```
select id, first, last from mytable
where first != upper(first) or last != upper(last);
```
```


q:
I'm looking for the best way to interpret the standard (well, standardish) Ethernet PHY registers, to determine the speed that an Ethernet link is actually running at.  (e.g. 10/100/1000 and full/half-duplex)

I daresay that this is to be found in the source of things like Linux, and I'm just off to look there now, but if anyone has a good reference I'd be interested.

What I'm interested in is if it actually linked and what it linked at, rather than the vast sea of possibilities that each end has advertised at the outset.


q:
The navigation on the left menu in the below site uses CSS for mouseover links.
PVH

When I take the code of the navigation and make it separate page. Then the mouseover links are not working. What could be the reason?

Test

[A]
Probably...
```
```
<script src="menu_1b.js" type="text/javascript">
</script>
<script src="menu_com.js" type="text/javascript">
```
```
have something to say on the matter. EDIT: A function called function CreateMenuStructureAgain() kind of gives it away.


q: Is it possible to get access to the spell checker that is incorporated in browsers for text areas from Javascript? I would like to be able to control spell checking from withing my code. Most browsers (apart from IE) seem to have some kind of a spell checker built in to them nowadays.

[A]
The most access that I know of is disabling or enabling spellchecking on a field:
Inline Disabling of Firefox Spellcheck?
I don't know of a way that you can directly access the spellchecker of a browser via javascript.  If you aren't particular to the spell checker of the browser, there are many open source spell checkers for javascript. Just try googling javascript spell checker.
If you really want to use the browsers spellcheck you might want to create a textbox and set the display to none.  You could then put each word in the textbox and then check to see if it's underlined or not.  I'm not sure of the feasability of this, just a thought.  My suggestion would be to use a javascript spellchecker instead of trying to hack up a way of using the browser's spellchecker.


q:
How can I select multiple elements using a WHERE...IN... type of clause as in

select * from orders where orderid in (1, 4, 5)

in LinqToSql? I'd prefer not to have a lambda expression since they scare me.

[A]
LINQ has "Contains" which is like "IN" but expressed the other way round - an element isn't "in" a set, a set "contains" an element.
```
```
int[] validIds = { 1, 4, 5 };
var query = from order in db.Orders
            where validIds.Contains(order.Id)
            select order
```
```
This is more simply expressed (IMO) with a lambda though:
```
```
int[] validIds = { 1, 4, 5 };
var query = db.Orders.Where(order => validIds.Contains(order.Id));
```
```
I realise lambdas are "new" and therefore scary to some extent, but it's really well worth grabbing hold of them with both hands. They're lovely.


q:
I have a view which contains a form, the form posts and the data gets processed etc, then I want to return the view Index, so return view("Index");

however this will then complain about my ViewData not existing, I get the feeling that the controller code under Index() isn't being processed which adds the list it requires to the ViewData, anyone know what's wrong?

Thanks

edit: Apparently it's done to prevent recursion.. in which case, I'm lost as to what to do without repeating all my ViewData stuff both Controllers

[A]
I think you should have two actions: one that processes the form submission, and another one that collects data for the view.
Once the form has been processed, you call
```
return RedirectToAction("Index")
```
and you are done.
I hope I understood what you meant by this.


q:
I would like to write a utility that will provide me with a relatively unique ID in Java.  Something pretty simple, like x bits from timestamp + y bits from random number.

So, how would I implement the following method:

long getUniqueID()
{
    long timestamp = System.currentTimeMillis();
    long random = some random long

    ...

    return id;
}

BONUS

Any suggestions for other easily obtainable information I could use to form my ID?

note: I am aware of GUIDs and I know Java has a UUID class, but I don't want something that is 128 bits long.

[A]
What you are trying to do is create a
hash function
that combines two long values into a single long value. In this case, the
uniformity
of the hash function will be of utmost importance since collisions in created unique ID values are unacceptable. However, if you can compare hash values to previously created identifiers, then collisions can be resolved by modifying the hash until no collision occurs.
For example, you could take the time stamp and perform an
exclusive-or
(using the caret ^ operator in Java) with the random value. If a collision is detected, then add one to the result.


q:
Up to now in my application, I've been supporting all flavors of Windows from Windows 98 to Windows NT/2000 to XP to Vista.

But because of adding Unicode in my next version, support of Windows 98 would still be possible, but very difficult.

I know there are still some of my users running Windows 98.

What are the pros and cons of me no longer supporting Windows 98?

[A]
If you still have users running Windows 98, then one obvious drawback to dropping support is that some of those will inevitably refuse to upgrade. They'll either stick with the version of your software they already have, or switch to something else.
On the other hand, the cost of developing for and supporting those users probably outweighs the additional revenue gained from it. So even though in principle you don't want any unhappy customers, in practice it may be more cost-effective to keep 99% of them happy.


q:
When ever I think I can use the yield keyword, I take a step back and look at how it will impact my project. I always end up returning a collection instead of yeilding because I feel the overhead of maintaining the state of the yeilding method doesn't buy me much. In almost all cases where I am returning a collection I feel that 90% of the time, the calling method will be iterating over all elements in the collection, or will be seeking a series of elements throughout the entire collection.

I do understand its usefulness in linq, but I feel that only the linq team is writing such complex queriable objects that yield is useful.

Has anyone written anything like or not like linq where yield was useful?

[A]
Note that with yield, you are iterating over the collection once, but when you build a list, you'll be iterating over it twice.
Take, for example, a filter iterator:
```
```
IEnumerator<T>  Filter(this IEnumerator<T> coll, Func<T, bool> func)
{
     foreach(T t in coll)
        if (func(t))  yield return t;
}
```
```
Now, you can chain this:
```
```
MyColl.Filter(x=> x.id > 100).Filter(x => x.val < 200).Filter (etc)
```
```
You method would be creating (and tossing) three lists.  My method iterates over it just once.
Also, when you return a collection, you are forcing a particular implementation on you users. An iterator is more generic.


q:
I have a ComboBox inside of a cell of a DataGridView Row on a Windows form.  I need the following to happen:

click on the ComboBox

pick a value

recalculate a total & display inside of a lable that is sitting
    outside of the DataGridView.

Currently, the following is happening:

Click on the ComboBox

Click it again to open the CB's Drop-down list

select a value

click outside of the cell to force a recalculation of the
    external label.

I want to avoid, first, having to click the combo twice (once to set focus, and again to select the value).  Second, I'd like for a live recalculation to happen after selecting a value.

Does anyone have a trick or two to solve any of these?

I've tried most of the events on the DGV without much luck.

[A]
Add a handler to the CellClick event of the DataGridView that looks a bit like:
```
```
private void vehicleTypeGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if ( e.RowIndex == - 1 ) return; //Header Cell clicked -> ignore it.
    vehicleTypeGridView.BeginEdit ( true );
    var control = vehicleTypeGridView.EditingControl as DataGridViewComboBoxEditingControl;
    if ( control != null ) control.DroppedDown = true;
}
```
```


q:
when i point my browser to http://localhost/phpmyadmin, instead of showing me its front page, it comes up with save as dialog.

I'm running:
Apache/2.2.3 (Debian) PHP/5.2.0-8+etch13 Server

I've reinstalled both apache2 and php5.
After re-install i don't have httpd.conf file, how can i get it back? Is there a standard file which i can just copy into /etc/apache2?

I did a locate httpd.conf and the only file i got was the empty file i have under /etc/apache2/ which i made.

[A]
Did you configure the php extension to send an http header?
In httpd.conf:
AddType application/x-httpd-php .php
EDIT
The file is not necessarily named
```
httpd.conf
```
, that's just the default name.  Try searching for other configuration files in the Apache directory -- the extension probably is
```
.conf
```
but it might be something else...
If you used apt-get on debian to install apache2, try
```
/etc/apache2/apche2.conf
```
/EDIT


q:
What is the best way to centralize and secure the connections strings used by applications?  In my environment we have many internal applications.  Each application requires one or more connection strings in order to access the database.  We have a goal of centralizing all these connection strings (particularly SQL logins and passwords) so we could change passwords in one place instead of in 35 different .config files, registry entries etc.

Currently we are using a home grown component which pulls the connection string information from an access database, this covers the centralization requirement but isn't particularly secure.  In addition we have applications written in languages from classic asp, vb6, delphi, c++, .net so the solution would need to be usable by all those applications.

Does anyone have an idea of how to do this better, or do we need to rework our whole approach to the way our applications access the database.

[A]
The company I work for has used a similar situation through a SQL Server database instead.  We ended up creating a COM-compliant .net dll to simplify and secure the API into the database and to ensure that the same logic is used between classic asp, .Net, and DTS packages.  It has worked out great for us for year and while there are some refactoring items a lot of us would like to do with it, it's been great to address issues like server migrations or renamings.
I think you are on the right path; however, I would recommend the following changes:
Try to move to a true database server.  Access is great for MS Office but not for something of this scale.
Build an administrative console that allows for auditing of who is adding and editing information (secure who has access to what settings too).
Build a COM-compliant DLL so that it can be consumed by other systems in a secure and consistent manner.
EDIT:
Something that I have noticed after working years in a system like this is that it ties your hands slightly on some solutions.  Many tools out there (i.e. nHibernate, Elmah, etc. in the .Net world) really are limited when the connection string is no longer in the config files.  Many can be easily modified to use your API; however, it is something that takes more time to investigate if you want to use it.  Just a FYI on that.


q:
I'd like to allow a user to open files in their own client applications via Silverlight. I'd like this to work similarly to WebDAV, in the sense that they could read/write the file back into Silverlight's isolated storage...

Is it possible to construct a file:// link to an isolated storage file?
Is there a uri scheme that is defined for silverlight in a browser that has the silverlight plugin?

Am I totally nuts?


q:
The scenario is:

svn cp or mv some file

modify that file

svn diff > mypatch

On other machine (same working copy, but no changes):

Try to apply mypatch.

Fail -> tries to modify unexistant file.

How can I make svn diff produce patch-appliable patch, or cleanly apply patch produced by svn diff in this case? I can't commit. I would like to preserve mergeinfo (because the obvious workaround is to add the file as totally new, without connection to the previous one).

[A]
With subversion, you can specify which diff binary to use, and parameters to pass to it.  See
the manual
on svn diff.
You'd want to produce a regular patch file from a svn diff, so you'd want the svn diff to look like a normal diff.  Try this:
```
```
svn diff --diff-cmd /usr/bin/diff -x "-i -b" > mypatch
...
patch -p0 < mypatch
```
```
Proof of concept:
```
```
echo "newline" >> README.txt
svn diff --diff-cmd /usr/bin/diff -x "-i -b" > mypatch
cp README.txt README.txt.patched
svn revert README.txt
patch -p0 < mypatch
diff README.txt README.txt.patched
```
```
No difference in the two files after patching.


q: I have a table with almost 800,000 records and I am currently using dynamic sql to generate the query on the back end.  The front end is a search page which takes about 20 parameters and depending on if a parameter was chosen, it adds an " AND ..." to the base query.  I'm curious as to if dynamic sql is the right way to go ( doesn't seem like it because it runs slow).  I am contemplating on just creating a denormalized table with all my data.  Is this a good idea or should I just build the query all together instead of building it piece by piece using the dynamic sql. Last thing, is there a way to speed up dynamic sql?

[A]
It is more likely that your indexing (or lack thereof) is causing the slowness than the dynamic SQL.
What does the execution plan look like?  Is the same query slow when executed in SSMS?  What about when it's in a stored procedure?
If your table is an unindexed heap, it will perform poorly as the number of records grows - this is regardless of the query, and a dynamic query can actually perform better as the table nature changes because a dynamic query is more likely to have its query plan re-evaluated when it's not in the cache.  This is not normally an issue (and I would not classify it as a design advantage of dynamic queries) except in the early stages of a system when SPs have not been recompiled, but statistics and query plans are out of date, but the volume of data has just drastically changed.
Not the static one yet. I have with the dynamic query, but it does not give any optimizations. If I ran it with the static query and it gave suggestions, would applying them affect the dynamic query? – Xaisoft (41 mins ago)
Yes, the dynamic query (EXEC (@sql)) is probably not going to be analyzed unless you analyzed a workload file. – Cade Roux (33 mins ago)
When you have a search query across multiple tables that are joined, the columns with indexes need to be the search columns as well as the primary key/foreign key columns - but it depends on the cardinality of the various tables. The tuning analyzer should show this. – Cade Roux (22 mins ago)


q:
I am developing a product with heavy 3D graphics computations, to a large extent closest point and range searches. Some hardware optimization would be useful. While I know little about this, my boss (who has no software experience) advocates FPGA (because it can be tailored), while our junior developer advocates GPGPU with CUDA, because its cheap, hot and open. While I feel I lack judgement in this question, I believe CUDA is the way to go also because I am worried about flexibility, our product is still under strong development.

So, rephrasing the question, are there any reasons to go for FPGA at all? Or is there a third option?

[A]
I investigated the same question a while back. After chatting to people who have worked on FPGAs, this is what I get:
FPGAs are great for realtime systems, where even 1ms of delay might be too long. This does not apply in your case;
FPGAs can be very fast, espeically for well-defined digital signal processing usages (e.g. radar data) but the good ones are much more expensive and specialised than even professional GPGPUs;
FPGAs are quite cumbersome to programme. Since there is a hardware configuration component to compiling, it could take hours. It seems to be more suited to electronic engineers (who are generally the ones who work on FPGAs) than software developers.
If you can make CUDA work for you, it's probably the best option at the moment. It will certainly be more flexible than a FPGA.
Other options include Brook from ATI, but until something big happens, it is simply not as well adopted as CUDA. After that, there's still all the traditional HPC options (clusters of x86/PowerPC/Cell), but they are all quite expensive.
Hope that helps.


q:
I'm trying to redirect the java compiler output to a file.
I thought it's supposed to be:

javac file.java > log.txt

or something. Instead, I see all the output on the terminal and nothing in log.txt!

Also, if I want to log errors too, do I do

javac file.java 2>&1 > log.txt

?

[A]
```
```
javac file.java 2> log.txt
```
```
The reason is that you have
two
output file descriptors instead of one. The usual one is stdout, which you can redirect with > and it's supposed to be used for resulting output. The second one, stderr, is meant for human readable output like warnings, errors, current status etc., this one is redirected with 2>.
Your second line, using 2>&1, redirects stderr to stdout and finally stdout into log.txt.


q: What is the best way to make the SSRS reporr fit in to PDF page.

[A]
Next time please indicate what version of SSRS you are working with...
If you are careful to design your canvas to certain constraints your should be fine. Typically the PDF is going to emulate a 8.5" by 11" piece of paper - considering margins you should keep the width of your report to less than 7" but I think 6.5" is best.
You can do this by selecting the report itself, the menu in BIDS (VS) should now have a report item which you can select to reveal Report Properties. In the report properties you can select the orientation as well as standard paper sizes and margins. Based on your paper size and your left and right margins you should be able to calculate the maximum width for the body of your report. Back in the report designer select the report body and look at the properties. The object drop down list should specifically say BODY, in this you want to ensure the size of your body (width) is not greater than the Report width minus the margins.


q:
I get this error during checkout:

cvs checkout: warning: new-born file.java has disappeared
cvs [checkout aborted]: cannot make directory : No such file or directory
cvs status: cannot rewrite CVS/Entries.Backup: Permission denied

I'm sure I have the proper permissions to this folder and it happens even when I try to check out to a new one. I'm also sure that these files exist in cvs..

my checkout command is:

cvs co -d dir -N -r(num) -r(num)... file file... and so on

What does this new-born thing mean?

[A]
```
new-born
```
refers to a file that has been
```
add
```
-ed but not
```
commit
```
-ted yet, or that
```
CVS
```
is having trouble getting the file written locally.
My guess would be that there is a
```
.cvs
```
directory present that records an
```
add
```
but the file has since been deleted.
The additional errors you're seeing relate to permissions in the checkout directory - maybe you don't have write access to the checkout directory,
```
umask
```
is set incorrectly or there is a directory permission inheritance problem.


q:
I am iterating though a TreeSet and printing it out:

while (it.hasNext()) {
  System.out.println(it.next());
}

output:

after
explorers
giant
hoping
internet
into
.
.
.
virtual
world

However, I would like to only print out those strings who's first character is within the range m-z. I have been playing around with java.util.regex, with no success:

String pattern = "[^m-z]";

Do I have the right idea here? Or is there a simpler way of doing this? All I want to do is make sure I only print out those Strings in the TreeSet who's first character is within the range m-z.

[A]
seems like an homework but anyhow,
the "[^m-z]" means NOT m-z
try putting the "^" outside the "[]"
Have a look at the
Pattern
class
and BTW, try
```
String.matches()
```


q:
How can we write an update sql statement that would update records and the 'set' value changes every time?

For example:
If we have records like this

SomeNumber SomeV CurCode WhatCodeShouldBe
200802754 432 B08 B09
200802754 432 B08 B09
200802754 432 B08 B09
200808388 714 64B C00
200804119 270 64B C00

I wish to update each 'SomeNumber' record so that 'CurCode' will be same as 'WhatCodeShouldBe'

Thanks for any help!

[A]
```
UPDATE yourtable SET CurCode = WhatCodeShouldBe
```


q:
Each of these variables has an integer value.  But this syntax is not valid for some reason:

<xsl:when test="$nextAnswerListItemPos < $nextQuestionStemPos" >

[A]
You have to use
```
<
```
instead of
```
<
```
and
```
>
```
instead of
```
>
```
, because those are reserved characters.


q:
Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?

Edit:
Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.

I have classes which are doing C-style system calls on the back end and the juggling has started to become cumbersome. I have functions in object A which take in object B as a parameter and have to call a method in object B passing in itself as an argument. The end user could call the method in B and the system would fall apart.

[A]
I'm pretty sure what you're looking for is "protected" or "private", depending on your use case.
If you're defining an function in a class, and you only want it available to itself, you'll define it this way:
```
```
private function foo($arg1, $arg2) { /*function stuff goes here */ }
```
```
If you're defining a function in a class that you want to be available to classes which inherit from this class, but not available publicly, definite it this way:
```
```
protected function foo($arg1, $arg2)
```
```
I'm pretty sure that by default in PHP5, functions are public, meaning you don't have to use the following syntax, but it's optional:
```
```
public function foo($arg1, $arg2) { /*function stuff goes here */ }
```
```
You'll still have to instantiate the object before using a public function.  So I'll just be thorough and let you know that in order to use a function in a class without instantiating an object, be sure to use the following syntax:
```
```
static function foo($arg1, $arg2) { /*function stuff goes here */ }
```
```
That will allow you to use the function by only referencing the class, as follows:
```
```
MyClass::foo($a1, $a2);
```
```
Otherwise, you'll need to do the following:
```
```
$myObject = new MyClass();
$myObject->foo($a1, $a2);
```
```


q:
I've got a few dozen Linux machines running cron and I'd like to put the crontabs in some sort of revision control system.  For source control I use Mercurial (hg), so that'd be ideal, but if there's some other system that is better suited to this task I'd consider it.

One aspect which is specific to my situation is that all the crontabs belong to a common user (not a real person, but a placeholder "services" login).  I'd like the revision history to include the actual author of each change, rather than the special account where the cron jobs actually run.

[A]
http://joey.kitenet.net/code/etckeeper/
?
From that site:
etckeeper is a collection of tools to let /etc be stored in a git, mercurial, darcs, or bzr repository. It hooks into apt (and other package managers including yum and pacman-g2) to automatically commit changes made to /etc during package upgrades. It tracks file metadata that revison control systems do not normally support, but that is important for /etc, such as the permissions of
```
/etc/shadow
```
. It's quite modular and configurable, while also being simple to use if you understand the basics of working with revision control.


q:
For some reason my code won't work.

    from tan in TANS
    where tan.ID.ToString().Count() != 1
    select tan

I want to select all IDs that are duplicates in a table so I am using the count != 1 and I get this error.

NotSupportedException: Sequence operators not supported for type 'System.String'

Help please?

[A]
```
tan.ID.ToString()
```
is a string, not a collection so you can't apply Count().
I believe you want something like:  (This syntax is wrong, but close)
```
```
from tan in TANS
group tan by tan.ID into dups
where dups.Count() > 1
select dups.Key;
```
```
Update (after 5 years minus 5 days): (It's a bit weird to Google a problem and find an answer YOU wrote ..) At the core of this problem is the the LINQ statement is trying to build an SQL statement, and the database doesn't know how to apply Count() to a string.  However, if you use LINQ against a collection in memory, then it would treat the string as an IEnumerable and the Count() would work just fine.


q:
I am developing on a LAMP(erl) stack and know of several ways to store obscured passwords.  I'd like to hear from those who feel they have a best practice, given MySQL 4.1.1 and Perl 5.8, and the reasons why it's the best.

One option I have read about, using the MySQL ENCODE() and DECODE() functions, sounds pretty good to me... your thoughts?

[A]
Well, since there's a
```
DECODE()
```
function, I'd say no, for the simple fact that you probably want to store the password in hashed form, to prevent anyone obtaining your database/password file from casually reading passwords.
I'd recommend going with the classic salted hash method.


q:
I have just realized I've been coercing binding/dependency properties and not really fundamentally understanding the concept.

Heres the dependency property:

public string Problem
{
    get { return (string)GetValue(ProblemProperty); }
    set { SetValue(ProblemProperty, value); }
}

public static readonly DependencyProperty ProblemProperty =
    DependencyProperty.Register(
    "Problem",
    typeof(string),
    typeof(TextBox));

The XAML is as so:

<TextBlock Text="{Binding Path=Problem}"/>

I'm manually setting the Problem property to a value in the constructor of the object but it doesn't update the TextBlock accordingly . . . any ideas? I've tried Mode="OneWay" and Mode="TwoWay" on the binding and it still doesn't work.

I thought this was supposed to work automatically? Or am i fundamentally getting something wrong?

Thanks

[A]
The problem your having is definitely related to your DataContext. The {Binding} extension needs to know where the property lives that you are binding to. The default location it looks at is the elements DataContext which by default is always set to the DataContext of it's parent element. If you walk the DataContext up the logical tree to the parent window, The DataContext would be null (because the DataContext of your window is null). Therefore your {Binding} on your textblock is saying "Bind my Text property to the Problem roperty of my DataContext...which is null.
There are a couple of ways to solve this. One would be to do just like Jobi mentioned and set the Element property of you binding to point to the Window where the DependencyProperty is defined like this:
```
```
<TextBlock Text="{Binding Path=Problem,ElementName=_window}" />
```
```
Another option would be to set the DataContext of your Window to point to itself. That way all the elements contained in it's content will all have the DataContext of the window.
```
```
<Window ....
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
```
```
Now anytime you need to binding to properties defined in the window (like your Problem dependency property), then you can just do this:
```
```
<TextBlock Text="{Binding Problem}" />
```
```


q:
In the admin section of a website i am building i would like to put together a dashboard page, or 'quick look' type page where the most recent changes/additions/etc in several different areas can be viewed.

I was thinking the best way to do this would be to use partials and have each partial contain the markup for the data i need to display.

My question is, is this the best approach? and if so, how do i separate the logic and presentation of these partials? For instance how do i put the logic in the dashboard controller, but keep the presentation in the partial rhtml?

[A]
Partials are definitely the way to go, especially when you can pass in arbitrary data into them to make them do stuff. To answer your logic separation issue specifically, you would use:
```
```
<%= render :partial => "name_of_partial", :locals => { :some_var => @data_from_model } %>
```
```
Then, inside your partial, you'd have access to @data_from_model via the some_var variable.


q:
Not sure what's going on here.

I have a DateTime object, and when I try:

String.Format( "{0:dd/MM/yyyy}", _date)

the value returned is:

"24-05-1967"

What I want is

"24/05/1967"

Can anyone explain why my format string is being ignored?

A bit more background:
This is a web app which started out life as .net 1.1, and I'm in the process of moving it up to 2.0/3.5.

Update:

If I change the format to {0:dd:MM:yyyy}, it returns 24:05:1967 - it's only the / in the format string that gets changed to the - char.

Resolution:

When updating the app to run under 2.0, the asp.net globalization settings were messed up.

From the web site properties, ASP.NET tab, Edit Configuration, Application Tab - the culture and UI Culture were both set to the first item in the list (af-ZA) for some bizarre reason.

[A]
You likely want to use the
ToString()
method of your DateTime object to get the string representation you are after. A format string of
"dd'/'MM'/'yyyy"
will give you the format you described. Note that you need to escape literal characters in the format string using single quotes.
Example:
```
DateTime.Now.ToString("dd'/'MM'/'yyyy");
```


q: How do I setup a class that represents an interface?  Is this just an abstract base class?

[A]
Make a class with pure virtual methods. Use the interface by creating another class that overrides those virtual methods.
A pure virtual method is a class method that is defined as virtual and assigned to 0.
```
```
class IDemo
{
    public:
        virtual ~IDemo() {}
        virtual void OverrideMe() = 0;
};

class Child : public IDemo
{
    public:
        virtual void OverrideMe()
        {
            // do stuff
        }
};
```
```