q:
I am currently using...

select Table_Name, Column_name, data_type, is_Nullable
from information_Schema.Columns

...to determine information about columns in a given database for the purposes of generating a DataAccess Layer.

From where can I retrieve information about if these columns are participants in the primary key of their table?

[A]
Here is one way (replace 'keycol' with the column name you are searching
for):
```
```
SELECT  K.TABLE_NAME ,
    K.COLUMN_NAME ,
    K.CONSTRAINT_NAME
FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
        JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K ON C.TABLE_NAME = K.TABLE_NAME
                                                         AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
                                                         AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
                                                         AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE   C.CONSTRAINT_TYPE = 'PRIMARY KEY'
        AND K.COLUMN_NAME = 'keycol';
```
```


q:
I want to change a flash object enclosed within  with jQuery after an onClick event. The code I wrote, essentially:

$(enclosing div).html('');
$(enclosing div).html(<object>My New Object</object>);

works in Firefox but not in IE. I would appreciate pointers or suggestions on doing this. Thanks.

[A]
The
```
empty()
```
method is the better way of deleting content. Don't know if that will solve your problem though :)
```
```
$('#mydiv').empty();
```
```
You could also try the
```
replaceWith(content)
```
method.

s: huggingface

c: devops

d: intermediate


q: After using array_unique, an array without the duplicate values is removed. However, it appears that the keys are also removed, which leaves gaps in an array with numerical indexes (although is fine for an associative array). If I iterate using a for loop, I have to account for the missing indexes and just copy the keys to a new array, but that seems clumsy.

[A]
```
$foo = array_values($foo);
```
will re-number an array for you


q:
Does anybody use Scrum & Sprint for Infrastructure.

I'm struggling with the concept of a Sprint that never finishes  i.e. a Network enhancement project.

Also any suggestions on how Item time can be built up to a Product Backlog, so that I can sanity check that resources are not overcommited on the sprint.

[A]
I would suggest that you might start by refreshing your memory about the whole concept of Scrum (
http://en.wikipedia.org/wiki/Scrum
might be a good place to start).
For example I don't believe that there should be such thing as a 'never finishing sprint'. If you have some very long and/or recurring task just break it into more specific ones. Network enhancement is very generic - break it down to:
a spike to research new network equipment
a spike to review your cables layout
a task to draw the equipment physical locations and wires diagram
Estimate these and put them into your Backlog.
etc.
Then plan short (1-2) week sprints or iterations. Assign a specific goal to each of them. Add some of your tasks from the backlog to the iteration. Complete it.
Review the results, adjust the process, repeat.


q:
If you provide 0 as the dayValue in Date.setFullYear you get the last day of the previous month:

d = new Date(); d.setFullYear(2008, 11, 0); //  Sun Nov 30 2008

There is reference to this behaviour at mozilla. Is this a reliable cross-browser feature or should I look at alternative methods?

[A]
I would use an intermediate date with the first day of the next month, and return the date from the previous day:
```
```
int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
```
```


q: I have a list of about 600 jobs that I can't delete from the command line because they are attached to changelists.  The only way I know how to detach them is via the GUI, but that would take forever.  Does anyone know a better (i.e., faster) way?

[A]
I figured it out using the "fix" and "fixes" commands.  Here's the procedure:
Dump the output of the "fixes" command to a file
```
```
p4 fixes > tmp.txt
```
```
The file will contain a bunch of lines like this:
```
```
job005519 fixed by change 3177 on 2007/11/06 by raven@raven1 (closed)
job005552 fixed by change 3320 on 2007/12/11 by raven@raven1 (closed)
job005552 fixed by change 3318 on 2007/12/10 by raven@raven1 (closed)
...
```
```
Use your trusty text editor (and I'm not talking about Notepad here) to whip up a macro that converts the lines to Perforce commands to detach jobs from changelists, (p4 fix -d):
```
```
p4 fix -d -c 3177 job005519
p4 fix -d -c 3320 job005552
p4 fix -d -c 3318 job005552
...
```
```
Save the file as a .bat or .cmd file and run it, and bada bing, bada boom... all your jobs are detached from changelists and you can delete them using the GUI, or with a procedure similar to the one I just outlined and the output of the "jobs" command:
```
```
p4 jobs > tmp.txt
```
```


q:
I am having trouble using the attribute XPath Selector in ElementTree, which I should be able to do according to the Documentation

Here's some sample code

XML

<root>
 <target name="1">
    <a></a>
    <b></b>
 </target>
 <target name="2">
    <a></a>
    <b></b>
 </target>
</root>

Python

def parse(document):
    root = et.parse(document)
    for target in root.findall("//target[@name='a']"):
        print target._children

I am receiving the following Exception:

expected path separator ([)

[A]
The syntax you're trying to use is new in
ElementTree 1.3
.
Such version is shipped with
Python 2.7
or higher.
If you have Python 2.6 or less you still have ElementTree 1.2.6 or less.


q:
Using MVC with an observer pattern, if a user action requires polling a device (such as a camera) for data, should the polling be done in the Controller and the result passed off the Model or should a request be sent to the Model and the Model itself performs the polling.

This question is my attempt to reconcile everything I am reading that touts the "skinny Controllers" maxim with my gut intuition that the Model should only be acting on data not acquiring it.

(Note: This question might be subjective.  I'm not entirely sure that there is a one-true-answer to this question.  If not, feel free to retag as I will be very interested to hear opinions on the subject.)


q:
Does anyone know what the character entity for a tab is in xhtml?
(Um if there is one)...

[A]
Try
```

```
. The TAB is ASCII character #9.
But it may not show up as you'd expect, anyway, since HTML ignores whitespace in most instances.


q: Being a application developer, do I need to know Unicode?

[A] Unicode is an industry agreed standard for consistently representing text that has capacity to represent the World's character systems. All developers need to know about it, as Globalization is a growing concern.


q:
I've got a PHP script that needs to invoke a shell script but doesn't care at all about the output. The shell script makes a number of SOAP calls and is slow to complete, so I don't want to slow down the PHP request while it waits for a reply. In fact, the PHP request should be able to exit without terminating the shell process.

I've looked into the various exec(), shell_exec(), pcntl_fork(), etc. functions, but none of them seem to offer exactly what I want. (Or, if they do, it's not clear to me how.) Any suggestions?

[A]
If it "doesn't care about the output", couldn't the exec to the script be called with the
```
&
```
to background the process?
EDIT
- incorporating what @
AdamTheHut
commented to this post, you can add this to a call to
```
exec
```
:
```
```
" > /dev/null 2>/dev/null &"
```
```
That will redirect both
```
stdio
```
(first
```
>
```
) and
```
stderr
```
(
```
2>
```
) to
```
/dev/null
```
and run in the background.
There are other ways to do the same thing, but this is the simplest to read.
An alternative to the above double-redirect:
```
```
" &> /dev/null &"
```
```


q:
I have a database table on a development server that is now fully populated after I set it running with an import routine for a CSV file containing 1.4 million rows.

I ran the Database Publishing Wizard on the table, and now I have a 286MB SQL script on my local machine.  The problem is, I can't figure out how to run it.  If I load it into SQL Server Management Studio Express I get an alert window that says "The operation could not be completed".

Any ideas on how I can get this SQL script to run?

[A]
use the
sqlcmd
tool to execute the file..
```
```
sqlcmd -S myServer\instanceName -i C:\myScript.sql
```
```
In case your have an unexplained "script error" for large sql files (> 100MB) which includes several INSERT, just replace "INSERT INTO" by "GO INSERT INTO" in your file, which will reduce size of transaction.


q: Java is the key here. I need to be able to delete files but users expect to be able to "undelete" from the recycle bin.  As far as I can tell this isn't possible.  Anyone know otherwise?

[A]
For various reasons Windows
has no concept of a folder that simply corresponds to the Recycle Bin
.
The correct way is to use JNI to invoke the Windows
```
SHFileOperation
```
API, setting the
```
FO_DELETE
```
flag in the
```
SHFILEOPSTRUCT
```
structure.
SHFileOperation documention
Java example for copying a file using SHFileOperation
(the Recycle Bin link in the same article doesn't work)


q:
These two methods exhibit repetition:

public static Expression<Func<Foo, FooEditDto>> EditDtoSelector()
{
    return f => new FooEditDto
    {
        PropertyA = f.PropertyA,
        PropertyB = f.PropertyB,
        PropertyC = f.PropertyC,
        PropertyD = f.PropertyD,
        PropertyE = f.PropertyE
    };
}

public static Expression<Func<Foo, FooListDto>> ListDtoSelector()
{
    return f => new FooDto
    {
        PropertyA = f.PropertyA,
        PropertyB = f.PropertyB,
        PropertyC = f.PropertyC
    };
}

How can I refactor to eliminate this repetition?

UPDATE: Oops, I neglected to mention an important point.  FooEditDto is a subclass of FooDto.

[A]
The repetition is in the names, but C# has no idea that PropertyA in one class is connected with PropertyA in another. You have to make the connection explicitly. The way you did it works fine. If you had enough of these, you might consider using reflection to write one method that could do this for any pair of classes.
Do pay attention to the performance implications of whatever method you choose. Reflection by itself is slower. However, you could also use reflection to  emit IL that would, once it's emitted, run just as fast as what you have written. You could also generate an expression tree and convert it to a compiled delegate. These techniques are somewhat complicated, so you have to weigh the trade-offs.


q:
At the moment my code looks like this:

# Assign values for saving to the db
$data = array(
    'table_of_contents' => $_POST['table_of_contents'],
    'length' => $_POST['length']
);

# Check for fields that may not be set
if ( isset($_POST['lossless_copy']) )
{
   $data = array(
       'lossless_copy' => $_POST['lossless_copy']
    );
}

// etc.

This would lead to endless if statements though... Even with the ternary syntax it's still messy. Is there a better way?

[A]
```
```
foreach ($_POST as $key => $value) {
  $data[$key] = $value;
}
```
```
remember to sanitize your $_POST values!
edit
: if you're looking to match up optional $_POST values with fields that may or may not exist in your table, you could do something like this (i'm assuming you're using mysql):
```
```
$fields = array();
$table  = 'Current_Table';

// we are not using mysql_list_fields() as it is deprecated
$query  = "SHOW COLUMNS from {$table}";
$result = mysql_query($query);
while ($get = mysql_fetch_object($result) ) {
  $fields[] = $get->Field;
}

foreach($fields as $field) {
  if (isset($_POST[$field]) ) {
    $data[$field] = $_POST[$field];
  }
}
```
```


q:
I have something like the following in an ASP.NET MVC application:

IEnumerable<string> list = GetTheValues();
var selectList = new SelectList(list, "SelectedValue");

And even thought the selected value is defined, it is not being selected on the view.  I have this feeling I'm missing something here, so if anyone can put me out my misery!

I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to.

EDIT: This problem has been fixed by ASP.NET MVC RTM.

[A]
Try this instead:
```
```
IDictionary<string,string> list = GetTheValues();
var selectList = new SelectList(list, "Key", "Value", "SelectedValue");
```
```
SelectList (at least in Preview 5) is not clever enough to see that elements of IEnumerable are value type and so it should use the item for both value and text.  Instead it sets the value of each item to "null" or something like that.  That's why the selected value has no effect.


q:
Pexpect can be used to automate tasks in python (does not need TCL to be installed). One of the simplest routines of this class is the 'run()' routine. It accepts a dictionary of expected question patterns as keys and the responses as values. For example

pexpect.run ('scp foo myname@host.example.com:.', events={'(?i)password': mypassword})

I know that usually '?' is used to indicate 0 or 1 occurrences of previous literal in the string (for regular expressions that is). However, over here, this does not seem to be the meaning.

Can experts comment on what is it?

[A]
https://docs.python.org/library/re.html#regular-expression-syntax
(?...)    This is an extension
  notation (a "?" following a "(" is not
  meaningful otherwise). The first
  character after the "?" determines
  what the meaning and further syntax of
  the construct is. Extensions usually
  do not create a new group;
  (?P...) is the only exception to
  this rule. Following are the currently
  supported extensions.
(?iLmsux)    (One or more letters from
  the set "i", "L", "m", "s", "u", "x".)
  The group matches the empty string;
  the letters set the corresponding
  flags (re.I, re.L, re.M, re.S, re.U,
  re.X) for the entire regular
  expression. This is useful if you wish
  to include the flags as part of the
  regular expression, instead of passing
  a flag argument to the compile()
  function.
Note that the (?x) flag changes how
  the expression is parsed. It should be
  used first in the expression string,
  or after one or more whitespace
  characters. If there are
  non-whitespace characters before the
  flag, the results are undefined.
So in this case the string is a regular expression, and is set to be case-insensitive.


q:
To use Google Analytics, you put some JavaScript code in your web page which will make an asynchronous request to Google when the page loads.

From what I have read, this shouldn't block or slow down page load times if you include it directly before the end of your HTML Body.  To verify this, I want to make the request after some period of time.  The user should be able to log into my site regardless of the time it takes for the request to Google or if it comes back at all (the tracking code is on the login page).

There is a 'pageTracker._trackPageview()' function call in the Google Tracking code.  Is this where the request is sent to Google?

If so, should I just do:

window.setTimeout(pageTracker._trackPageview(), 5000);

any help is appreciated, especially if you have worked with Google Analytics and have this same problem.

[A]
That should do it. Put some quotes around the call:
```
```
window.setTimeout("pageTracker._trackPageview()", 5000);
```
```
You can check this using Firebug if you want to see the request go through.


q: Has anyone here ever used C++'s "placement new"? If so, what for? It looks to me like it would only be useful on memory-mapped hardware.

[A]
It is useful if you are building a kernel - where do you place the kernel code you read from disk or the pagetable? You need to know where to jump to.
Or in other, very rare circumstances such as when you have loads of allocated room and want to place a few structures behind each other. They can be packed this way without the need for the offsetof() operator. There are other tricks for that too, though.
I also believe some STL implementations make use of placement new, like std::vector. They allocate room for 2^n elements that way and don't need to always realloc.


q:
I have a few questions related:

1) Is possible to make my program change filetype association but only when is running? Do you see anything wrong with this behavior?

2) The other option that I'm seeing is to let users decide to open with my application or restore default association ... something like: "capture all .lala files" or "restore .lala association". How can I do this? What do you think that is the best approach?

[A]
It can probably be done but I think it would end up being cumbersome.  All file type associations are stored in the registry so you would have to write/revert registry entries every time your app starts and stops.  Also, depending on how frequently you do it the new associations may not be picked up in Windows explorer immediately.
The associations are listed under HKEY_CLASSES_ROOT in the registry and can be mapped a whole myriad of ways (mime types/progIDs/etc).
Many apps I have seen ask if you want to associate certain file types with the application during install time, and give you the ability to opt-out and leave the current settings.
I don't think I'd recommend "on the fly" file type associations


q:
I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like CSS Utils are overkill for this project).

Basically I'd like jsmin.py for CSS. A single script with no dependencies.

Any ideas?

[A]
I don't know of any ready made python css minifiers, but like you said css utils has the option. After checking and verifying that the license allows for it, you could go through the source code and snip out the portions that do the minifying yourself. Then stick this in a single script and voila! There you go.
As a head start, the csscombine function in .../trunk/src/cssutils/script.py seems to do the work of minifying somewhere around line 361 (I checked out revision 1499). Note the boolean function argument called "minify".


q:
I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn't seem to be an option to do list.Clone().

Is there an easy way around this?

[A]
For a shallow copy, you can instead use the GetRange method of the generic List class.
```
```
List<int> oldList = new List<int>( );
// Populate oldList...

List<int> newList = oldList.GetRange(0, oldList.Count);
```
```
Quoted from:
Generics Recipes


q:
A UITableViewCell comes "pre-built" with a UILabel as its one and only subview after you've init'ed it. I'd really like to change the background color of said label, but no matter what I do the color does not change. The code in question:

UILabel* label = (UILabel*)[cell.contentView.subviews objectAtIndex:0];
label.textColor = [UIColor whiteColor];
label.backgroundColor = [UIColor darkGrayColor];
label.opaque = YES;

[A]
Your code snippet works fine for me, but it must be done after the cell has been added to the table and shown, I believe. If called from the
```
initWithFrame:reuseIdentifier:
```
, you'll get an exception, as the
```
UILabel
```
subview
has not yet been created.
Probably the best solution is to add your own
```
UILabel
```
, configured to your standards, rather than relying on this (very rickety) path to the built-in one.


q:
If you create a class library that uses things from other assemblies, is it possible to embed those other assemblies inside the class library as some kind of resource?

I.e. instead of having MyAssembly.dll, SomeAssembly1.dll and SomeAssembly2.dll sitting on the file system, those other two files get bundled in to MyAssembly.dll and are usable in its code.

I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET? Are all .NET assemblies DLLs, but not all DLLs are .NET assemblies? Why do they use the same file format and/or file extension?

[A]
Take a look at
ILMerge
for merging assemblies.
I'm also a little confused about why .NET assemblies are .dll files. Didn't this format exist before .NET?
Yes.
Are all .NET assemblies DLLs,
Either DLLs or EXE normally - but can also be netmodule.
but not all DLLs are .NET assemblies?
Correct.
Why do they use the same file format and/or file extension?
Why should it be any different - it serves the same purpose!


q:
I would like to know the complexity in Big O notation of the STL multiset, map and hash map classes when:

inserting entries

accessing entries

retrieving entries

comparing entries

[A]
map, set, multimap, and multiset
These are implemented using a
red-black tree
, a type of
balanced binary search tree
.  They have the following asymptotic run times:
Insertion: O(log n)
Lookup: O(log n)
Deletion: O(log n)
hash_map, hash_set, hash_multimap, and hash_multiset
These are implemented using
hash tables
.  They have the following runtimes:
Insertion: O(1) expected, O(n) worst case
Lookup: O(1) expected, O(n) worst case
Deletion: O(1) expected, O(n) worst case
If you use a proper hash function, you'll almost never see the worst case behavior, but it is something to keep in mind — see
Denial of Service via Algorithmic Complexity Attacks
by Crosby and Wallach for an example of that.


q: What libraries are available for writing xml-rpc clients in native C++ or C?

[A]
You might want to check out either
xmlrpc-c
or
xmlrpc++
.


q:
I'm lead to believe that I cannot count on the order of items added to a dictionary for enumeration purposes.

Is there a class (generic if possible) to which items may be added with a key and which can be enumerated in addition order or which can be retrieved by key?

Clarification: I do not want to enumerate in Key Order. I want to enumerate in addition order. Which is to say that I want to be able to retrieve the items via enumeration on a FIFO ( first in first out) basis.

[A]
You can achieve the effect you want just by using a
```
List
```
that stores the keys in order of addition. Then you can enumerate that list in order, and retrieve the values from the
```
Dictionary
```
.
However, if you want to do all this with a single existing collection type, I'm not aware of a type that does this without you needing to provide a comparer or without the key being part of the item. For the former, you could try
```
SortedDictionary
```
and for the latter, you could derive a new collection from
```
KeyedCollection
```
(not entirely sure that this would maintain the order without a comparer so you'd need to experiment to confirm that).


q:
In a WinForms UserControl, I would pass data to the main GUI thread by calling this.BeginInvoke() from any of the control's methods.  What's the equivalent in a Silverlight UserControl?

In other words, how can I take data provided by an arbitrary worker thread and ensure that it gets processed on the main displatch thread?

[A]
Use the Dispatcher property on the UserControl class.
```
```
private void UpdateStatus()
{
  this.Dispatcher.BeginInvoke( delegate { StatusLabel.Text = "Updated"; });
}
```
```


q:
I am creating a desktop app in Delphi and plan to use an embedded database.  I've started the project using SQlite3 with the DISQLite3 library. It works but documentation seems a bit light.  I recently found Firebird (yes I've been out of Windows for a while) and it seems to have some compelling features and support.

What are some pros and cons of each embedded db?  Size is important as well as support and resources.  What have you used and why?

[A]
I'm using Firebird 2.1 Embedded and I'm quite happy with it.I like the fact that the database size is practically unlimited (tested with > 4 GB databases and it works) and that the database file is compatible with the Firebird Server so I can use standard tools for database management and inspection. Distribution consists of dropping few files in your exe folder.
Simultaneous access from multiple programs is not supported but simultaneous access from multiple threads is (as long as you ensure that only one 'connect' operation is in progress at any given moment).


q:
I am working on a simple portal application using the ASP.NET membership and login controls. I would like to use the PasswordRecovery control to send emails containing forgotten passwords, however my portal requires localization. I have an existing Content Management System that I am pulling the localized strings out of and I would like to link the PasswordRecovery control to that system.

But, it appears that the PasswordRecovery control will ONLY accept a .txt file for the email body...the property is PasswordRecovery1.MailDefinition.BodyFileName

I do not want to use a file on disk, I would like to use the localized content in my CMS.

Is there any way to do this? It occurred to me that I might be able to use the SendingMail event to send my OWN email through the normal System.Net namespace, but that seems sorta cludgy...

Any thoughts?

Thanks,
Max

[A]
Found this by googling "BodyFileName localization":
http://forums.asp.net/t/1118242.aspx
:
Just bind the property to a key in
  your page's localresource file. The
  page's local resource file is the file
  located in a subdirectory called
  app_localresources in your page's
  directory. Just use visual studio's
  "tools -> create local resource"
  option in design view for it be
  created for you.
In that file, create a string
  key/value pair with something like
Name: myBodyFileName
Value: myDefaultBodyFile.txt
Then bind this to the BodyFileName
  property of the login control with
  something like
'>
Then just create the sattelite local
  resource files for other cultures and
  map that key/value pair in those
  resources to other body text files.
By the way, if you used visual studio
  to create the resource file for you,
  then the binding may have been done
  for you automatticaly. Just search for
  a
  "MyChangePasswordControlResource1.BodyFileName"
  key in the resource file or something
  similar.
Regards, Jorge


q:
I have an HTML input box

<input type="text" id="foo" value="bar">

I've attached a handler for the 'keyup' event, but if I retrieve the current value of the input box during the event handler, I get the value as it was, and not as it will be!

I've tried picking up 'keypress' and 'change' events, same problem.

I'm sure this is simple to solve, but at present I think the only solution is for me to use a short timeout to trigger some code a few milliseconds in the future!

Is there anyway to obtain the current value during those events?

EDIT: looks like I had a caching problem with my js file as I checked the same code later on and it worked just fine. I would delete the question, but not sure if that loses rep for the kind folk who posted ideas :)

[A]
Can you post your code? I'm not finding any issue with this. Tested on Firefox 3.01/safari 3.1.2 with:
```
```
function showMe(e) {
// i am spammy!
  alert(e.value);
}
....
<input type="text" id="foo" value="bar" onkeyup="showMe(this)" />
```
```


q:
I am using Visual Studio 2008 SP1 (version 9.0.30729.1). My problem is that the only reporting-related toolbox items I see are 3 "Textbox" controls. Where are the other stuff? Do I need to add a reference to a different assembly?

Here are the steps I take:

   1) Open Visual Studio

   2) Add new project --> "Reports Application"

   3) Open Report1.rdlc

   4) Open the toolbox and no controls are available (except the repeating 3 Textbox controls)

Thanks for your help.

[A]
Here is a book reference available through Google Books:
http://books.google.com/books?id=b9j0MKXhnygC&pg=PA419&lpg=PA419&dq=vs+2008+Reports+Application+toolbox&source=web&ots=awTO1ibUZH&sig=7iHAUSCZ46_uAjC5lAfLeiXZt_Q&hl=en&sa=X&oi=book_result&resnum=7&ct=result#PPA433,M1
I also did the same (on same VS2008 SP1) and had the exact same items available.


q:
I have the following tuple, which contains tuples:

MY_TUPLE = (
    ('A','Apple'),
    ('C','Carrot'),
    ('B','Banana'),
)

I'd like to sort this tuple based upon the second value contained in inner-tuples (i.e., sort Apple, Carrot, Banana rather than A, B, C).

Any thoughts?

[A]
```
```
from operator import itemgetter

MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=itemgetter(1)))
```
```
or without
```
itemgetter
```
:
```
```
MY_SORTED_TUPLE = tuple(sorted(MY_TUPLE, key=lambda item: item[1]))
```
```


q:
I wanted to compare the datetime which is in this format "7/20/2008" with the ones in the database which is in format "7/20/2008 7:14:53 AM".

I tried using "like" clause but it did not work beacuse the "like" clause uses only string and the one which I am using is date time format.

Can anyone tell how to convert and compare it in database and pull up datetime.

  protected void User_Querytime()
    {
    DataClasses2DataContext dc1 = new DataClasses2DataContext();
    DateTime date1;

    string date = Request.QueryString.Get("TimeOfMessage");
    date1 = Convert.ToDateTime(date);

    var query7 = from u in dc1.syncback_logs
                 where u.TimeOfMessage = date1
                 orderby u.TimeOfMessage descending
                 select u;
    GridView1.DataSource = query7;
    GridView1.DataBind();
    }

[A]
Although I cannot test your exact problem, I was able to compare dates with the following code.
```
```
// Random Date Collection
    List<DateTime> dateTimes = new List<DateTime>();
    dateTimes.Add(DateTime.Parse("7/20/2008 7:14:53 AM"));
    dateTimes.Add(DateTime.Parse("7/20/2008 7:14:54 AM"));
    dateTimes.Add(DateTime.Parse("7/20/2009 7:14:53 AM"));

    DateTime myDateTime = DateTime.Parse("7/20/2008");

    var query = from d in dateTimes
                where d.ToShortDateString() == myDateTime.ToShortDateString()
                select d;
```
```


q:
What is the simplest way to get: http://www.[Domain].com in asp.net?

There doesn't seem to be one method which can do this, the only way I know is to do some string acrobatics on server variables or Request.Url. Anyone?

[A]
```
```
System.Web.UI.Page.Request.Url
```
```


q:
How do you retain the indentation of numbered lists?  I have a page where the numbers are pushed off the page.  How can I prevent this?

<ol style="padding: 0">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ol>

[A]
With a CSS rule like this:
```
```
ol { margin-left: 30px; }
```
```
Here's some information about the
CSS box model
.


q:
I have a canvas inside a scrollview. I attached a keydown event handler to the scrollview. For most keys, the handler gets called.

However, for the arrow keys, the handler does not get called. Instead, the scrollview gets scrolled in the appropriate direction.

I also attached a keyup handler to the scrollview and the keyup does get called for the arrow keys.

Is there any way to get the arrow key down event here?

[A]
I found this silly hack to make it work. Setting the scrollview to not be a tabstop keeps it from eating the key events.. but then I had another textbox on the page that all of a sudden ALWAYS had focus because the scrollview didn't anymore. So I fixed that by letting an invisible textbox get focus.
```
```
scrollView.IsTabStop = false;

invisibleTextBox.Foreground = new SolidColorBrush(Colors.Transparent);
invisibleTextBox.Background = new SolidColorBrush(Colors.Transparent);
Canvas.SetZIndex(invisibleTextBox, -1000);
invisibleTextBox.KeyDown += new KeyEventHandler(HandleKeyDown);
invisibleTextBox.KeyUp += new KeyEventHandler(HandleKeyUp);
```
```
Edit: I also had to move the text box off the canvas because despite being invisible, its outline still showed up.
2nd Edit:
I used a textbox because that was the first thing I found that could capture KeyDown events. However, a UserControl can. So it would probably be better practice to use a UserControl instead of an invisible text box. You can call Focus() on the UserControl if needed.


q:
I have a WPF window for editing database information, which is represented using an Entity Framework object.  When the user closes the window, I'd like to notice in the Closing event whether the information has changed and show a message box offering to save the changes to the database.

Unfortunately, changes to the currently focused edit aren't assigned to the binding source until the edit loses focus, which happens at some point after the Closing event has been processed.

Ideally, there would be a routine which commits all changes in the view hierarchy that I could call before checking to see if my entity has been modified.  I've also looked for information on programmatically clearing the focus in the control with focus, but can't figure out how to do it.

My question is, how is this typically handled?

[A]
This should get you pretty close:
```
```
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
    ForceDataValidation();
}

private static void ForceDataValidation()
{
    TextBox textBox = Keyboard.FocusedElement as TextBox;

    if (textBox != null)
    {
        BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);
        if (be != null && !textBox.IsReadOnly && textBox.IsEnabled)
        {
            be.UpdateSource();
        }
    }

}
```
```


q: Is there a more efficient way to convert an HTMLCollection to an Array, other than iterating through the contents of said collection and manually pushing each item into an array?

[A]
```
```
var arr = Array.prototype.slice.call( htmlCollection )
```
```
will have the same effect using "native" code.
Edit
Since this gets a lot of views, note (per @oriol's comment) that the following more concise expression is
effectively
equivalent:
```
```
var arr = [].slice.call(htmlCollection);
```
```
But note per @JussiR's comment, that unlike the "verbose" form, it does create an empty, unused, and indeed unusable array instance in the process.  What compilers do about this is outside the programmer's ken.
Edit
Since ECMAScript 2015 (ES 6) there is also
Array.from
:
```
```
var arr = Array.from(htmlCollection);
```
```
Edit
ECMAScript 2015 also provides the
spread operator
, which is functionally equivalent to
```
Array.from
```
(although note that
```
Array.from
```
supports a mapping function as the second argument).
```
```
var arr = [...htmlCollection];
```
```
I've confirmed that both of the above work on
```
NodeList
```
.
A performance comparison for the mentioned methods:
http://jsben.ch/h2IFA


q: Is there a way to do a mysql database query in Corel Draw 13(X3)?

[A]
If I recall correctly, CorelDraw uses VBA as scripting language, no?
If so, if it is not restricted, you can probably use ODBC to do that. See
MySQL Connector/ODBC
for details.


q: I have generated linq to sql entites but cannot figure out how to assign null to a nullable column. whenever i try to assign null to it it says "there is no implicit type conversion between int and ". BTW the type of the field is int? and the database column is also nullable.

[A]
It seems as though the column isn't really nullable. Check the properties of the column and see that it really is marked as nullable. If it isn't, check your database model and try to recreate the
LINQ to SQL
model if it's nullable in the database.
Mind that you can't simply mark it as nullable in the
LINQ to SQL
model and not in the database, since these kinds of discrepancies may cause your
LINQ to SQL
model to stop working.
Post edit update:
I can see that the field type is
```
int?
```
which is the same as
```
Nullable<int>
```
so there shouldn't be a problem to set it to null. However, when getting the integer value, you should use the
```
Value
```
property of the
```
int?
```
. Is that the problem?


q:
What's the difference between:

class Child(SomeBaseClass):
    def __init__(self):
        super(Child, self).__init__()

and:

class Child(SomeBaseClass):
    def __init__(self):
        SomeBaseClass.__init__(self)

I've seen super being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.

[A]
The benefits of
```
super()
```
in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
However, it's almost impossible to use multiple-inheritance without
```
super()
```
. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended
```
Child
```
and a mixin, their code would not work properly.


q:
I like LINQ to SQL, but it seems like the classes it generates are tightly coupled to the database they are stored in, which seems like a Bad Thing.

For example, using ye olde Northwind database, if I create the dbml with the Products table, a Product class is generated. I can use this class in any other tier, which is all well and good, but if I decide I'd rather use plain old ADO.NET (or switch databases), I'll have to recreate the Product class, along with every other "model."

Is there a way around this? Or to create your object models separately, and then have the tables mapped to them? I've played around with the various mapping classes provided, but haven't found a satisfactory answer yet.

[A]
Scott Hanselman did a screen talking about asp.net DynamicData where he used Linq To Sql classes.  Although he wasn't addressing the particular issue I think the general concept would still work. His approach was to create a separate
partial
class that had the same name as the class,
```
Product
```
in your case, that was generated by the dbml.  Then you should always have a
```
Product
```
class that exists outside of what LINQ generates and just "extends" what it does.


q:
I want to expose few web services but thinking of hosting those as Windows Service as against hosting in IIS.

Is it a good practice?

If yes? How do I make it secured?

I want to authenticate the users who are accessing it (against our custom security database and also want to make sure that the request is originating from our business partner (X.509 certificates???? not worked much with this).

appreciate your pointers in this regards.

Thanks & Regards,
Ajay

[A] If you are using IIS6, using a Windows Service is a must for many scenarios. Windows Services are 100% supported and a 100% safe way to host WCF. You can secure them with the same options as in IIS.


q:
I've been arguing with some friends on the university, and we can't get to a point to which is the framework with more scalability for web applications (and still very fast).

One calls for jsp, the other one for ruby other for php and so on. Could i ask you to clarify us on what as more scalability potential?

Tks, hope I'm not duplicating anything I've searched but didn't found any previous question like this.

Edit: If you could point a comparison about this it would be good :)

[A]
Algorithms will count more for scalability than the language used.
That said, there will be differences in execution speed between the languages. I believe that Java (Servlets and JSPs compile to servlets, i.e., native code) will be faster than Ruby and PHP by some amount). There are also a tonne of web frameworks for Java that will encourage you to do things the best way for scalability.
Also design your app so that it can run happily behind a load balancer, and scalability becomes a lot easier :) This isn't my field of expertise however.


q:
I have the following class which uses BinaryReader internally and implements IDisposable.

class DisposableClass : IDisposable
    {
        private BinaryReader reader;
        public DisposableClass(Stream stream)
        {
            reader = new BinaryReader(stream);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                ((IDisposable)reader).Dispose();
//                reader.Dispose();// this won't compile
            }
        }

        public void Dispose()
        {
            this.Dispose(true);
        }
    }

I have already figured out that I need to cast BinaryReader to IDisposable to be able to call Dispose on it, but I don't understand why I can't just call the Dispose() method directly without casting to IDisposable?

[A]
It won't work because the
```
Dispose
```
method on
```
BinaryReader
```
has been explicitly implemented.
Instead of being implicitly implemented, as in:
```
```
public void Dispose()
{
}
```
```
...it has been explicitly implemented, as in:
```
```
void IDisposable.Dispose()
{
}
```
```
...which means it can only be accessed via the
```
IDisposable
```
interface. Therefore, you have to cast the instance to
```
IDisposable
```
first.


q:
I was wondering about the best practices regarding this?  I know there are two ways to use IIS and host multiple websites.

The first is to have an IP for every website

The second is to use host headers, and a single IP Address for IIS

I was wondering which was the best practice, and why one should be preferred over the other?

Thanks!

[A]
I personally separate sites based on the relation to each other.  For example all of my business sites share a single IP adddress (1 domain currently).  All of my personal/community sites share a second IP address.
The differences can come over time when it comes to sending e-mail as I know that IP comes into play in some blacklisting systems, so if one site with a shared IP address causes problems it CAN cause issues for the other sites using that IP.
I am sure there are other items, reasons, and justifications, but those are at least mine...


q: TF-IDF (term frequency - inverse document frequency) is a staple of information retrieval.  It's not a proper model though, and it seems to break down when new terms are introduced into the corpus.  How do people handle it when queries or new documents have new terms, especially if they are high frequency.  Under traditional cosine matching, those would have no impact on the total match.

[A]
Er, nope, doesn't break down.
Say I have two documents, A "weasel goat" and B "cheese gopher". If we actually represented these as vectors, they might look something like:
A [1,1,0,0]
B [0,0,1,1]
and if we've allocated these vectors in an index file, yeah, we've got a problem when it comes time to add a new term. But the trick of it is,
that vector never exists
. The key is the
inverted index
.
As far as new terms not affecting a cosine match, that might be true depending on what you mean. If I search my corpus of (A,B) with the query "marmoset kungfu", neither marmoset nor kungfu exist in the corpus. So the vector representing my query will be orthogonal to all the documents in the collection, and get a bad cosine similarity score. But considering none of the terms match, that seems pretty reasonable.


q:
Imagine a base class with many constructors and a virtual method

public class Foo
{
   ...
   public Foo() {...}
   public Foo(int i) {...}
   ...
   public virtual void SomethingElse() {...}
   ...
}

and now i want to create a descendant class that overrides the virtual method:

public class Bar : Foo
{
   public override void SomethingElse() {...}
}

And another descendant that does some more stuff:

public class Bah : Bar
{
   public void DoMoreStuff() {...}
}

Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?

Is there no way to inherit constructors? Is there no way to encourage code reuse?

[A]
Yes, you will have to implement the constructors that make sense for each derivation and then use the
```
base
```
keyword to direct that constructor to the appropriate base class or the
```
this
```
keyword to direct a constructor to another constructor in the same class.
If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like
```
null
```
and only expose the necessary ones through their constructors.
Update
In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.


q:
I would like to create an application that serves web pages internally and can be run in multiple instances on the same machine.  To do so, I would like to create an HttpListener that listens on a port that is:

Randomly selected

Currently unused

Essentially, what I would like is something like:

mListener = new HttpListener();
mListener.Prefixes.Add("http://*:0/");
mListener.Start();
selectedPort = mListener.Port;

How can I accomplish this?

[A]
How about something like this:
```
```
static List<int> usedPorts = new List<int>();
    static Random r = new Random();

    public HttpListener CreateNewListener()
    {
        HttpListener mListener;
        int newPort = -1;
        while (true)
        {
            mListener = new HttpListener();
            newPort = r.Next(49152, 65535); // IANA suggests the range 49152 to 65535 for dynamic or private ports.
            if (usedPorts.Contains(newPort))
            {
                continue;
            }
            mListener.Prefixes.Add(string.Format("http://*:{0}/", newPort));
            try
            {
                mListener.Start();
            }
            catch
            {
                continue;
            }
            usedPorts.Add(newPort);
            break;
        }

        return mListener;
    }
```
```
I'm not sure how you would find all of the ports that are in use on that machine, but you should get an exception if you try to listen on a port that is already being used, in which case the method will simply pick another port.


q:
I'm looking for a database of commonly installed Windows software. At minimum I need the name of the software and the executable name, but it'd also be nice to have the publisher and the common installation path, etc. Basically, I'd like to be able to query it to find all the software by Adobe and the associated executable name, etc.

Basically I'm looking to be able to do

SELECT * FROM Software WHERE Publisher = 'Microsoft'
SELECT * FROM Software WHERE Executable = 'devenv.com'

I came across an effort to create such a database a long time ago, but can't seem to find it now. Maybe it fizzled out. Any help would be greatly appreciated. Thanks.

[A]
You can do some
screen scraping
with some website that contain
list of software
and build yourself a database of all software and publisher.
Here is some website that contain some list of software:
http://www.digital-digest.com/software/index.php
http://www.bestshareware.net/allsoftware-w.htm


q:
I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.

How do I do that, but then be able to turn it off for the release version?

[A]
All calls to
```
System.Diagnostics.Debug.Print()
```
will be removed when you switch to a release version.


q:
I have a simple SQL Server 2005 Reporting Services report with a bar chart. When I print directly from the preview window in Visual Studio everything looks good, but if I export the report to a PDF file and print it then the labels and even some of the vertical lines come out pixelated. How can I increase the resolution of the PDF export?

EDIT:

Setting HumanReadablePDF=True makes the PDF much larger (4 mb vs. 20 kb), but the chart still looks the same.

I can print directly from the preview window to a PDF file (using PrimoPDF) and the chart looks good -- maybe there's a way to do that instead of using the SSRS export function?

[A]
Try messing with the device information settings, in particular the HumanReadiblePdf attribute.
http://msdn.microsoft.com/en-us/library/ms154682.aspx
IIRC the setting is actually the opposite of what the documentation hints at compression wise.
Also take a look here:
http://blogs.msdn.com/donovans/pages/reporting-services-pdf-renderer-faq.aspx


q:
I'm running Oracle 10g and have columns with Type_Name

TIMESTAMP(6) WITH TIME ZONE

When inflated into java classes they come out as

oracle.sql.TIMESTAMPTZ

But DbUnit can't handle converting Oracle specific classes to Strings for writing to XML. I'm wondering if there's any easy way for me to convert (say, in my SELECT statement somehow) from these Oracle specific timestamps to something in java.sql.


q:
Say you have a web form with some fields that you want to validate to be only some subset of alphanumeric, a minimum or maximum length etc.

You can validate in the client with javascript, you can post the data back to the server and report back to the user, either via ajax or not. You could have the validation rules in the database and push back error messages to the user that way.

Or any combination of all of the above.

If you want a single place to keep validation rules for web application user data that persist to a database, what are some best practices, patterns or general good advice for doing so?

[edit]

I have edited the question title to better reflect my actual question! Some great answers so far btw.

[A]
all of the above:
client-side validation is more convenient for the user
but you can't trust the client so the code-behind should also validate
similarly the database can't trust that you validated so validate there too
EDIT: i see that you've edited the question to ask for a single point of specification for validation rules. This is called a "Data Dictionary" (DD), and is a Good Thing to have and use to generate validation rules in the different layers. Most systems don't, however, so don't feel bad if you never get around to building such a thing ;-)
One possible/simple design for a DD for a modern 3-tier system might just include - along with the usual max-size/min-size/datatype info - a Javascript expression/function field, C# assembly/class/method field(s), and a sql expression field. The javascript could be slotted into the client-side validation, the C# info could be used for a reflection load/call for server-side validation, and the sql expression could be used for database validation.
But while this is all good in theory, I don't know of any real-world systems that actually do this in practice [though it "sounds" like a Good Idea].
If you do, let us know how it goes!


q:
Having difficulty articulating this correlated subquery.  I have two tables fictitious tables, foo and bar. foo has two fields of foo_id and total_count. bar has two fields, seconds and id.

I need to aggregate the seconds in bar for each individual id and update the total_count in foo. id is a foreign key in bar for foo_id.

I've tried something similar without much luck:

UPDATE foo f1 set total_count = (SELECT SUM(seconds) from bar b1 INNER JOIN foo f2     WHERE b1.foo_id = f2.id) WHERE f1.foo_id = bar.id;

[A]
I hope I understood your question right.
You have the following tables:
table
```
foo
```
- columns:
```
id
```
and
```
total_count
```
table
```
bar
```
- columns:
```
foo_id
```
(references
```
foo.id
```
) and
```
seconds
```
The following query should work (update all
```
total_count
```
rows in table
```
foo
```
):
```
```
UPDATE foo AS f1
SET total_count = (
  SELECT SUM(seconds)
  FROM bar INNER JOIN foo
  WHERE foo_id = f1.id
);
```
```
I'm not sure what you are trying to do with your last
```
WHERE
```
clause (
```
WHERE f1.foo_id = bar.id;
```
).


q:
I'm new to Rails development, and I'm trying to figure out how to use an older version of Rails with Apatana's RadRails IDE.  I'm trying to help out a friend who has a site built on older version than the one that automatically gets downloaded by RadRails, and I'm pretty sure the two versions wouldn't be compatible (the site is using some pre 2.0 version, not sure of the exact number offhand).

Is there a way to tell RadRails to get and use a specific version of Rails?  Or is there something I can do at the command line to change the installed version of Rails? I'm only vaguely familiar with the "gem" package system, but I'm assuming it would involve that.

Any help would be much appreciated!

[A]
Use the Rake task
```
rails:freeze:gems
```
in your rails project and give it the version you want to use.  For example:
```
```
rake rails:freeze:gems VERSION=2.1.0
```
```
That will put the right version of Rails into
```
vendor/rails
```
, which is loaded by default if it exists.


q:
Say you create a form using ASP.NET MVC that has a dynamic number of form elements.

For instance, you need a checkbox for each product, and the number of products changes day by day.

How would you handle that form data being posted back to the controller? You can't set up parameters on the action method because you don't know how many form values are going to be coming back.

[A]
Depending on your data, you could either output a 'CheckboxList' (which is not possible in the newer versions any more) and use a
```
string[]
```
parameter, or you could set up multiple forms and just modify the action.


q: I'd like to write a Ruby snippet that gets run when my Gem is first installed via [sudo ]gem install mygem.  Can it be done?

[A]
You can try to do this using call of OS commands. I'll quote eample from irb but you can do same in your scripts too.
```
```
irb(main):001:0> system 'gem list | grep rails'
rails (2.1.1, 2.1.0)
=> true
irb(main):002:0> system 'gem list | grep railssssss'
=> false
```
```
You can use result of this command as the condition of your snippet execution.


q:
I am trying to call a COM object from PHP using the COM interop extension. One function requires an OLE_COLOR as an argument? Is there any way to pass this kind of value from PHP?

I have tried passing a simple integer value with no success.

$this->oBuilder->Font->Color = 255;

[A]
When I've called COM functions from PHP, I just passed them in the call.  So my old code has:
```
$myComObject = new COM("MY_COM_OBJECT");
$myComObject->Myfunction( myVar1, myVar2, 'my string var');
```


q:
How do I pull out the filename from a full path using regular expressions in C#?

Say I have the full path C:\CoolDirectory\CoolSubdirectory\CoolFile.txt.

How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figure this one out.

Also, in the course of trying to solve this problem, I realized that I can just use  System.IO.Path.GetFileName, but the fact that I couldn't figure out the regular expression is just making me unhappy and it's going to bother me until I know what the answer is.

[A]
Why must you use regular expressions? .NET has the built-in
```
Path.GetFileName()
```
method specifically for this which works across platforms and filesystems.


q: How can I create a Delphi TSpeedButton or SpeedButton in C# 2.0?

[A]
Does
this
help? Looks like you would have to handle the OnPaint event, and not take focus...


q:
I want to do something like

insert into my table (select * from anothertable where id < 5)

What is the correct MSSQL syntax?

Thanks!

[A]
Is this what you're looking for?
```
```
INSERT INTO MyTable
SELECT * FROM AnotherTable
WHERE AnotherTable.ID < 5
```
```


q:
In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.

Is there any way to add files to the sub-tree or group for a Windows Form class?

[A]
You need to edit the csproj directly. There is a DependentUpon tag that you have to add as a child tag of the file you want to place under MyForm.cs.
Example:
```
```
<Compile Include="MyForm.MyCoolSubFile.cs">
  <DependentUpon>MyForm.cs</DependentUpon>
</Compile>
```
```


q:
I have a simple query like this:

select * from mytable where id > 8

I want to make the 8 a variable.  There's some syntax like

declare @myvar int
myvar = 8

but I don't know the exact syntax.

What is it?

Thanks!

[A]
```
```
declare @myvar int

select @myvar = 8
```
```


q:
Even a simple Notepad application in C# consumes megabytes of RAM as seen in the task manager. On minimizing the application the memory size in the task manager goes down considerably and is back up when the application is maximized.

I read somewhere that the .NET process reserves a lot of memory for runtime allocation in advance. That's why .NET applications have a larger memory footprint to start with. But this memory can be released using Win32 API calls. A trade-off is that runtime allocation becomes slow -  is that true?

[A]
The reason for the large memory footprint is that the JIT compiler and
Windows Forms
engine are being loaded with your process. To reduce this, you can do the following:
```
```
[DllImport("psapi.dll")]
static extern int EmptyWorkingSet(IntPtr hwProc);

static void MinimizeFootprint()
{
    EmptyWorkingSet(Process.GetCurrentProcess().Handle);
}
```
```
This should remove as much as possible from your memory footprint. There may be a way that you can also reduce the amount of memory that is set aside for runtime memory allocation.


q:
What is MySQL equivalent of the Nz Function in Microsoft Access? Is Nz a SQL standard?

In Access, the Nz function lets you return a value when a variant is null. Source

The syntax for the Nz function is:

Nz ( variant, [ value_if_null ] )

[A]
You might want to look at
```
IFNULL
```
or
```
COALESCE
```
. If I recall correctly,
```
IFNULL
```
works for MySQL.


q:
This may not be the correct way to use controllers, but I did notice this problem and hadn't figured out a way to correct it.

public JsonResult SomeControllerAction() {

    //The current method has the HttpContext just fine
    bool currentIsNotNull = (this.HttpContext == null); //which is false

    //creating a new instance of another controller
    SomeOtherController controller = new SomeOtherController();
    bool isNull = (controller.HttpContext == null); // which is true

    //The actual HttpContext is fine in both
    bool notNull = (System.Web.HttpContext.Current == null); // which is false

}

I've noticed that the HttpContext on a Controller isn't the "actual" HttpContext that you would find in System.Web.HttpContext.Current.

Is there some way to manually populate the HttpContextBase on a Controller? Or a better way to create an instance of a Controller?

[A]
Is it that you want to use some functionality from the controller? Or have the controller perform an action?
If it's the former, maybe that's some code that should be split out into another class. If it's the latter, you can do this to simply have that controller do a specific action:
```
```
return RedirectToAction("SomeAction", "SomeOtherController", new {param1 = "Something" });
```
```


q:
I'm trying to have a new layer appear above existing content on my site when a link/button is clicked.  I am using jquery - but the code I have doesn't seem to work as expected.

Here is what I have:

 $(document).ready(function(){
  $("#button").click(function () {
  $("#showme").insertAfter("#bodytag")
  $("#showme").fadeIn(2000);
});

});

The effect I'm after is to have <div id="showme">...</div> appear directly after the #bodytag.  <div id="showme">...</div> has a z-index higher than anything else on the site, so it should just appear above the content directly after the #bodytag.

Thanks for the assistance.

[A]
Make sure
```
#showme
```
has a
```
position
```
other than
```
static
```
.


q: What are pros and cons of having dedicated application pools over keeping web applications in one default app pool?

[A]
Dedicated app pools typically will keep problems occurring in one site from effecting the others.  If you share app pools across sites, you could bring down all sites on the box when an error condition exists for only a specific site (or app pool).
Also, if you are mixing versions of ASP.Net on the same web server, you will need different app pools per ASP.Net version at a minimum, or do it per website.
I can't think of a good reason not to separate app pools, it is so easy to do.


q:
url = "http://example.com/file.xml"
data = urllib2.urlopen(url)
data.read()

The question is, when exactly will the file be downloaded from the internet? When i do urlopen or .read()? On my network interface I see high traffic both times.

[A]
I think I remember reading about a bug relating to this in TortoiseSVN that's been fixed in the latest release.  Check the latest
release notes
.


q:
How does the Chinese GB18030 code set differ from Unicode?

What special techniques are required for handling GB18030?

Are there any (open source) libraries for handling GB18030?

[A]
As per the
Wikipedia article on GB18030
, "GB18030 can be be considered a Unicode Transformation Format (i.e. an encoding of all Unicode code points) that maintains compatibility with a legacy character set." That is, all Unicode characters can be encoded in GB18030, but they will be encoded with different byte sequences than would be generated with UTF-8 or UTF-16. Handling the GB18030 encoding doesn't require any more special techniques than are required for any other non-Unicode encoding.
The
ICU project
is an open source library (for C or Java) that has full support for many different encodings, including GB18030. Information on converting between different encodings with ICU can be found
here
.


q:
I would like my GWT program to be able to determine whether it's in hosted mode or in web mode.  Is there a way to do this?

Thanks!

[A]
GWT.isScript() returns true in non hosted mode and false in hosted mode.
http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/com/google/gwt/core/client/GWT.html#isScript()


q: I have a static object at runtime that is basically a list of other objects (ints, strings, Dictionary, other objects, etc).  Is there way to determine the memory used by my static "list of other objects" object at runtime?  This would be handy for instrumentation and reporting purposes.

[A]
You are probably asking for something you could call from your code (which I would like to know too), but I felt I should mention Ants profiler [
http://www.red-gate.com/Products/ants_profiler/index.htm]
in case others aren't looking for something as specific. It will tell you all kinds of information about your code while it's executing including how much memory is being used.
From their website...
Profile memory to understand how your
  application uses memory, and to locate
  memory leaks. The memory profiler
  allows you to take snapshots at any
  point in the execution of your
  program, so you can see what memory is
  in use at that point. You can take
  multiple snapshots at different times
  while your application is running, so
  you can compare application memory
  states.


q: What is the Perl equivalent of strlen()?

[A]
```
length($string)
```
```
perldoc -f length

   length EXPR
   length  Returns the length in characters of the value of EXPR.  If EXPR is
           omitted, returns length of $_.  Note that this cannot be used on an
           entire array or hash to find out how many elements these have.  For
           that, use "scalar @array" and "scalar keys %hash" respectively.

           Note the characters: if the EXPR is in Unicode, you will get the num-
           ber of characters, not the number of bytes.  To get the length in
           bytes, use "do { use bytes; length(EXPR) }", see bytes.
```


q:
I've just started learning linq and lambda expressions, and they seem to be a good fit for finding duplicates in a complex object collection, but I'm getting a little confused and hope someone can help put me back on the path to happy coding.

My object is structured like list.list.uniqueCustomerIdentifier

I need to ensure there are no duplicate uniqueCustomerIdentifier with in the entire complex object. If there are duplicates, I need to identify which are duplicated and return a list of the duplicates.

[A]
There is a linq operator Distinct( ), that allows you to filter down to a distinct set of records if you only want the ids. If you have setup your class to override equals you or have an
IEqualityComparer
you can directly call the Distinct extension method to return the unique results from the list. As an added bonus you can also use the Union and Intersect methods to merge or filter between two lists.
Another option would be to group by the id and then select the first element.
```
```
var results = from item in list
              group item by item.id into g
              select g.First();
```
```


q:
Which industry-class database has the most unique features? (with "unique" meaning that no other RDBMS has them)

I think my choice here is Oracle 11g:

Flashback query (you can estract data as it was a moment in the past)

ASM - automatic storage management

Native code compilation of stored procedures

Audit features (tracing everything, from logins to statements)

and many others.

[A]
http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems
&&
http://en.wikipedia.org/wiki/Comparison_of_object-relational_database_management_systems
would be where I'd start.
As to truly "unique" features? I've seen things I thought were unique that turned out to be common once I did more digging :)


q:
I get to dust off my VBScript hat and write some classic ASP to query a SQL Server 2000 database.

Here's the scenario:

I have two datetime fields called fieldA and fieldB.

fieldB will never have a year value that's greater than the year of fieldA

It is possible the that two fields will have the same year.

What I want is all records where fieldA >= fieldB, independent of the year.  Just pretend that each field is just a month & day.

How can I get this?  My knowledge of T-SQL date/time functions is spotty at best.

[A]
```
```
select *
from t
where datepart(month,t.fieldA) >= datepart(month,t.fieldB)
      or (datepart(month,t.fieldA) = datepart(month,t.fieldB)
            and datepart(day,t.fieldA) >= datepart(day,t.fieldB))
```
```
If you care about hours, minutes, seconds, you'll need to extend this to cover the cases, although it may be faster to cast to a suitable string, remove the year and compare.
```
```
select *
from t
where substring(convert(varchar,t.fieldA,21),5,20)
         >= substring(convert(varchar,t.fieldB,21),5,20)
```
```


q: I would like to append a path to the PATH environment variable in a Visual Studio 2005 deployment project.  How does one do this?

[A]
You need to add a row to the Environment Table of the MSI file to do this.  You can find information on that table here,
http://msdn.microsoft.com/en-us/library/aa368369(VS.85).aspx
.  You can use Orca to do this or automate the procedure with some VB Script.  The platform SDK contains the VB script file, WiRunSQL.vbs that can you used to automate build actions for your program.


q:
Question:

((lambda (x y) (x y)) (lambda (x) (* x x)) (* 3 3))

This was #1 on the midterm, I put "81 9" he thought I forgot to cross one out lawl, so I cross out 81, and he goes aww. Anyways, I dont understand why it's 81.

I understand why (lambda (x) (* x x)) (* 3 3) = 81, but the first lambda I dont understand what the x and y values are there, and what the [body] (x y) does.

So I was hoping someone could explain to me why the first part doesn't seem like it does anything.

[A]
This needs some indentation to clarify
```
```
((lambda (x y) (x y))
 (lambda (x) (* x x))
 (* 3 3))
```
```
```
(lambda (x y) (x y))
```
; call
```
x
```
with
```
y
```
as only parameter.
```
(lambda (x) (* x x))
```
; evaluate to the square of its parameter.
```
(* 3 3)
```
; evaluate to 9
So the whole thing means: "call the square function with the 9 as parameter".
EDIT: The same thing could be written as
```
```
((lambda (x) (* x x))
 (* 3 3))
```
```
I guess the intent of the exercise is to highlight how evaluating a scheme form involves an implicit function application.


q:
Aspell-net is a port of the GNU Aspell for .Net Framework. The library itself is open source, and is under the LGPL license, but the english dictionary for aspell is mentioned as copyrighted on the sourceforge.net project home page at http://aspell-net.sourceforge.net/

Did any of you guys use aspell-net before? and what license did you release your software under? The project I work on is a commercial one, and do you guys forsee any problem? Should I pay for the aspell english dictionary?

Thanks.


q:
Simple question that keeps bugging me.

Should I HTML encode user input right away and store the encoded contents in the database, or should I store the raw values and HTML encode when displaying?

Storing encoded data greatly reduces the risk of a developer forgetting to encode the data when it's being displayed. However, storing the encoded data will make datamining somewhat more cumbersome and it will take up a bit more space, even though that's usually a non-issue.

[A]
i'd strongly suggest encoding information on the way out. storing raw data in the database is useful if you wish to change the way it's viewed at a certain point. the flow should be something similar to:
```
```
sanitize user input -> protect against sql injection -> db -> encode for display
```
```
think about a situation where you might want to display the information as an RSS feed instead. having to redo any HTML specific encoding before you re-display seems a bit silly. any development should always follow the "don't trust input" meme, whether that input is from a user or from the database.


q:
Is there a way to Invoke an overloaded method using reflection in .NET (2.0).  I have an application that dynamically instantiates classes that have been derived from a common base class.  For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without.  I need to call the parameterless method via the Invoke method.  Right now, all I get is an error telling me that I'm trying to call an ambiguous method.

Yes, I could just cast the object as an instance of my base class and call the method I need.  Eventually that will happen, but right now, internal complications will not allow it.

Any help would be great!  Thanks.

[A]
Yes. When you invoke the method pass the parameters that match the overload that you want.
For instance:
```
```
Type tp = myInstance.GetType();

//call parameter-free overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,
   Type.DefaultBinder, myInstance, new object[0] );

//call parameter-ed overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,
   Type.DefaultBinder, myInstance, new { param1, param2 } );
```
```
If you do this the other way round(i.e. by finding the MemberInfo and calling Invoke) be careful that you get the right one - the parameter-free overload could be the first found.


q: I'm writing a small application in VB.NET and I would like some of the classes to be able to write themselves out to XML to serve as a "save" feature.  I have seen XSD files used to generate VB classes that can serialize themselves into and out of XML very easily.  How would I do this if I do have any pre-existing XML format that I need to conform to as I'm just creating the classes myself?

[A]
Since you asked about making it 'easy', then there are three rules to follow that will help keeps things very simple:
Only use property types that are serializable
Don't use collections or arrays as properties that need to be serialized
Don't have properties with "bad" side-effects.  By 'bad', I mostly mean two public properties that are backed by the same underlying private field.
Note that if you break these rules you can probably still serialize your class, but it's likely to be a lot more work.
For item #2, a quick fix is using a datatable or dataset, since those are serializable.


q:
I am looking for a solution or recommendation to a problem I am having.  I have a bunch of ASPX pages that will be localized and have a bunch of text that needs to be supported in 6 languages.

The people doing the translation will not have access to Visual Studio and the likely easiest tool is Excel.  If we use Excel or even export to CSV, we need to be able to import to move to .resx files.  So, what is the best method for this?

I am aware of this question, Convert a Visual Studio resource file to a text file? already and the use of Resx Editor but an easier solution would be preferred.

[A]
I'm not sure how comprehensive an answer you're looking for, but if you're really just using [string, string] pairs for your localization, and you're just looking for a quick way to load resource (.resx) files with the results of your translations, then the following will work as a fairly quick, low-tech solution.
The thing to remember is that .resx files are just XML documents, so it should be possible to manually load your data into the resource from an external piece of code.  The following example worked for me in VS2005 and VS2008:
```
```
namespace SampleResourceImport
{
    class Program
    {
        static void Main(string[] args)
        {

            XmlDocument doc = new XmlDocument();
            string filePath = @"[file path to your resx file]";
            doc.Load(filePath);
            XmlElement root = doc.DocumentElement;

            XmlElement datum = null;
            XmlElement value = null;
            XmlAttribute datumName = null;
            XmlAttribute datumSpace = doc.CreateAttribute("xml:space");
            datumSpace.Value = "preserve";

            // The following mocks the actual retrieval of your localized text
            // from a CSV or ?? document...
            // CSV parsers are common enough that it shouldn't be too difficult
            // to find one if that's the direction you go.
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("Label1", "First Name");
            d.Add("Label2", "Last Name");
            d.Add("Label3", "Date of Birth");

            foreach (KeyValuePair<string, string> pair in d)
            {
                datum = doc.CreateElement("data");
                datumName = doc.CreateAttribute("name");
                datumName.Value = pair.Key;
                value = doc.CreateElement("value");
                value.InnerText = pair.Value;

                datum.Attributes.Append(datumName);
                datum.Attributes.Append(datumSpace);
                datum.AppendChild(value);
                root.AppendChild(datum);
            }

            doc.Save(filePath);
        }
    }
}
```
```
Obviously, the preceding method won't generate the code-behind for your resource, however opening the resource file in Visual Studio and toggling the accessibility modifier for the resource will (re)generate the static properties for you.
If you're looking for a completely XML-based solution (vs. CSV or Excel interop), you could also instruct your translators to store their translated content in Excel, saved as XML, then use XPath to retrieve your localization info.  The only caveat being the file sizes tend to become pretty bloated.
Best of luck.


q: Is there a way to manually increase / decrease the timeout of a specific aspx page?

[A]
In the web.config:
```
```
<configuration>
      <location path="~/Default.aspx">
        <system.web>
          <httpRuntime executionTimeout="1000"/>
        </system.web>
      </location>
   </configuration>
```
```


q: We have a product but we are doing some rebranding so we need to be able to build and maintain two versions.  I used resource files combined with some #if stuff to solve the strings, images, and whatever else, but the program icon is giving me trouble.  I couldn't figure it out from msdn or a google search.  Thanks!

[A]
Set the icon in normal code, and you should be able to use the same techniques as you have elsewhere. You'll need both icons in the resources file (at least so I suspect) but it should work.
Alternatively, set a prebuild step to copy the appropriate icon into a common filename - e.g. copying debug.ico or release.ico into app.ico. A bit hacky, but I think it would work. That way you only end up with one icon in the finished binaries.
Yet another option: look into the build file and see how the icon is built in, then conditionalise it. Marc Gravell did this for references in
MiscUtil
- the project can be built targeting either .NET 2.0 or 3.5, depending on configuration. I suspect that resources could be conditionalised in a very similar way.


q:
Say I need some very special multiplication operator. It may be implemented in following macro:

macro @<<!(op1, op2)
{
    <[ ( $op1 * $op2 ) ]>
}

And I can use it like

def val = 2 <<! 3

And its work.

But what I really want is some 'english'-like operator for the DSL Im developing now:

macro @multiply(op1, op2)
{
    <[ ( $op1 * $op2 ) ]>
}

and if I try to use it like

def val = 2 multiply 3

compiler fails with 'expected ;' error

What is the problem? How can I implement this infix-format macro?

[A]
Straight from the compiler source code:
```
```
namespace Nemerle.English
{
  [assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "and", false, 160, 161)]
  [assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "or", false, 150, 151)]
  [assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "not", true, 181, 180)]

  macro @and (e1, e2) {
    <[ $e1 && $e2 ]>
  }

  macro @or (e1, e2) {
    <[ $e1 || $e2 ]>
  }

  macro @not (e) {
    <[ ! $e ]>
  }
```
```
You need to sprinkle OperatorAttributes around and it will work. Btw, OperatorAttribute is defined as follows:
```
```
public class OperatorAttribute : NemerleAttribute
{
  public mutable env : string;
  public mutable name : string;
  public mutable IsUnary : bool;
  public mutable left : int;
  public mutable right : int;
}
```
```


q:
I want to know how to use variables for objects and function names in Python. In PHP, you can do this:

$className = "MyClass";

$newObject = new $className();

How do you do this sort of thing in Python? Or, am I totally not appreciating some fundamental difference with Python, and if so, what is it?

[A]
In Python,
```
```
className = MyClass
newObject = className()
```
```
The first line makes the variable
```
className
```
refer to the same thing as
```
MyClass
```
. Then the next line calls the
```
MyClass
```
constructor through the
```
className
```
variable.
As a concrete example:
```
```
>>> className = list
>>> newObject = className()
>>> newObject
[]
```
```
(In Python,
```
list
```
is the constructor for the
```
list
```
class.)
The difference is that in PHP, you represent the name of the class you want to refer to as a string, while in Python you can reference the same class directly. If you
must
use a string (for example if the name of the class is created dynamically), then you will need to use other techniques.


q:
When I try to create a new RegionInfo with certain ISO 3166 country codes ("BD" for Bangladesh, "SO" for Somalia, "LK" for Sri Lanka), I get an ArgumentException that says it's not recognized.

What's the deal? The Intellisense of RegionInfo(string) says it conforms to ISO 3166, but these country/region codes are not supported?

I don't get it.

[A]
.NET doesn't provide all Cultures/Regions out-of-the-box. Note the 'predefined' RegionInfos here:
http://msdn.microsoft.com/en-us/library/system.globalization.regioninfo(VS.80).aspx
.
Unfortunately, if you want to use non-predefined Regions, you have to define them yourself. Here's the MSDN how-to:
http://msdn.microsoft.com/en-us/library/ms172469(VS.80).aspx
.


q:
How to copy file(s) from one solaris 9 machine to another solaris 9 machine using only java?

We have ssh access to both machines. The java program will run on one of those two machines.

Update: rsync is not really an option. can't install it easily (UNIX team is, hum, hard to deal with)


q:
I was wondering if there is any way to escape a CDATA end token (]]>) within a CDATA section in an xml document. Or, more generally, if there is some escape sequence for using within a CDATA (but if it exists, I guess it'd probably only make sense to escape begin or end tokens, anyway).

Basically, can you have a begin or end token embedded in a CDATA and tell the parser not to interpret it but to treat it as just another character sequence.

Probably, you should just refactor your xml structure or your code if you find yourself trying to do that, but even though I've been working with xml on a daily basis for the last 3 years or so and I have never had this problem, I was wondering if it was possible. Just out of curiosity.

Edit:

Other than using html encoding...

[A]
You have to break your data into pieces to conceal the
```
]]>
```
.
Here's the whole thing:
```
<![CDATA[]]]]><![CDATA[>]]>
```
The first
```
<![CDATA[]]]]>
```
has the
```
]]
```
.  The second
```
<![CDATA[>]]>
```
has the
```
>
```
.


q:
I have a regexp I'm using with sed, but now I need to make it work in PHP also. I can't use system calls as they are disabled.

$ cat uglynumber.txt:
Ticket number : 303905694, FOO:BAR:BAR: Some text
Case ID:123,456,789:Foobar - Some other text
303867970;[FOOBAR] Some text goes here
Case Ref: 303658850 - Some random text here - host.tld #78854w

$ cat uglynumbers.txt | sed "s/[, ]//g;s/.*\([0-9]\{9\}\).*/\1/g"
303905694
123456789
303867970
303658850

So, how to do the same with PHP?

I found one example like this, but I can't inject that regexp into that.

if (preg_match("/.../", $line, $matches)) {
  echo "Match was found";
  echo $matches[0];
}

[A]
Assuming that you've checked all of the obvious things - such as ensuring that the main bind configuration file is what you think it is. Firstly check that the that you think named is using are the right ones - sometimes it's easy to edit a file that's in the wrong directory and wonder why changes aren't noticed.
Also have you used named-checkconf and named-checkzone
It is hard enough to debug bind, but without seeing the config files it is almost impossible, so please add them  to the original post.
(I've added this as a comment to the question - I've posted as an answer because the OP is new here).


q:
I have a DataSet consisting of XML data, I can easily output this to a file:

DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
ds.Load(reader, LoadOption.PreserveChanges, ds.Tables[0]);
ds.WriteXml("C:\\test.xml");

However what I want to do is compress the XML into a ZIP or other type of compressed file and then just save this file to disk while splitting the ZIP file into 1MB chunks. I do not really want to save the uncompressed file, and then zip it, then split it.

What I'm looking for specifically is:

a suitable compression library that I can stream the XML to and have the zip file(s) saved to disk

some sample C# code that can show me how to do this.

[A]
I've managed to compress a DataSet's XML stream using .NET 2.0's gzip compression.
Here's the blog post I made a few years ago about it:
Saving DataSets Locally With Compression
... and here's the code I added to my DataSet's partial class to write the compressed file (the blog post has the reading code too):
```
```
public void WriteFile(string fileName)
{
    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        Stream s;
        if (Path.GetExtension(fileName) == ".cmx")
        {
            s = new GZipStream(fs, CompressionMode.Compress);
        }
        else if (Path.GetExtension(fileName) == ".cmz")
        {
            s = new DeflateStream(fs, CompressionMode.Compress);
        }
        else
        {
            s = fs;
        }
        WriteXml(s);
        s.Close();
    }
}
```
```
Note that this code uses different compression schemes based on the file's extension. That was purely so I could test one scheme against the other with my DataSet.


q:
I'm pretty sure stackoverflow.com is created with ASP.NET, but no matter where I click I see no .aspx extension in the address bar.
How it is done and is there a particular reason for this?

[A]
You can do this and more with ISAPI rewrite (for IIS).  It allows you to create friendly urls without all the ugly query strings.  It gives users a friendlier interface and can make your content more searchable.
If you are using Apache, use mod_rewrite.
The basic premise of both is that they take a friendly url (like the one you see for this site), then they transform it using a series of rules (typically regexs that you specify) to internal urls or query strings that are easily understood by the code.
An example would be that they convert
```
posts/edit/<postnumber>
```
to
```
editPost.aspx?postNumber=<postnumber>
```
by using a transform rule.


q:
In a previous question, I asked about various ORM libraries. It turns out Kohana looks very clean yet functional for the purposes of ORM. I already have an MVC framework that I am working in though. If I don't want to run it as a framework, what is the right fileset to include to just give me the DB and ORM base class files?

Update:

I jumped in and started looking at the ORM source code.. One thing was immediately confusing to me.. all the ORM classes have the class name appended with _CORE i.e. ORM_Core ORM_Iterator_Core, but the code everywhere is extending the ORM class. Problem is, I've searched the whole code base 6 different ways, and I've never seen a plain ORM class def nor an ORM interface def or anything.. Could someone enlighten me on where that magic happens?

[A]
It turns out that Kohana uses magic class loading so that if a defined class with an _Core extention doesn't exist as a class
i.e. ORM_Core exists, but ORM doesn't, so Kohana will magically define an ORM class
Since the package uses 100% magic class loading.
In case anyone is interested, I'm documenting my finds here so everyone can find it later:
```
```
From Kohana.php in the system directory:

<-- snip if ($extension = self::find_file($type, self::$configuration['core']['extension_prefix'].$class))
{
// Load the extension
require $extension;
}
elseif ($suffix !== 'Core' AND class_exists($class.'_Core', FALSE))
{
// Class extension to be evaluated
$extension = 'class '.$class.' extends '.$class.'_Core { }';
-->

<-- snip

// Transparent class extensions are handled using eval. This is
// a disgusting hack, but it gets the job done.
eval($extension);

-->
```
```
So it does an eval..


q:
I am new to MySQL and PHP(as you can probably tell) and I was wondering if anybody knew an easy way to import a CSV file into a MySQL table.

"There are any number of ways to input
  csv into mysql depending in what kind
  of access you have, if you can use the
  mysql client directly there is a
  command to load delimited data,
  something like that could basically be
  entered directly in cron and keep
  itself up to date. Otherwise there are
  various php scripts to do that sort of
  thing."

That is something a friend told me to do, is that the easiest/best way to do it? If it is would someone mind explaining it to me?

Thank you

[A]
Use the "load data infile"  command. By deafulat it will treat incoming files as csv, although you can define a custom file type to import. Documentation for load data infile is here:
http://dev.mysql.com/doc/refman/5.0/en/load-data.html
FTA, in its simplest form the command looks just like this:
```
```
LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
```
```
That assumes the columns in the data file and in your text file line up.
The rest of the documentation explains how to get non-lined up fields imported, and also how to deal with windows vs unix style line terminations.


q:
What is the most efficient way in C# 2.0 to check each character in a string and return true if they are all valid hexadecimal characters and false otherwise?

Example

void Test()
{
    OnlyHexInString("123ABC"); // Returns true
    OnlyHexInString("123def"); // Returns true
    OnlyHexInString("123g"); // Returns false
}

bool OnlyHexInString(string text)
{
    // Most efficient algorithm to check each digit in C# 2.0 goes here
}

[A]
I use
```
Int32.TryParse()
```
to do this.
Here's the MSDN page on it
.


q:
This is what I have, which works in IE7, but not in Firefox:

@media screen { @import 'screen.css'; }

It works outside of the @media block in Firefox:

@import 'screen.css';

UPDATE:

This works:

@media screen {

    .yui-d3f
    {
        border: 1px solid #999;
        height: 250px;
    }

}

What am I missing?

[A]
Ok, so Firefox doesn't like the method I chose, favouring:
```
```
@import 'stylesheet.css' media_type;
```
```
But IE7 doesn't understand this method, but this could be good:
```
```
@import 'firefox-screen.css' screen;
@media screen { @import 'IE7-screen.css'; }
```
```


q:
I've figured out how to set VC++ to compile code into a .lib file instead of a .exe, but I'm having trouble getting a lib to link together with my other .obj files.

Here is how I have the library and application folders set up.  (I'm not sure if this is right)

AppFolder
  App.sln
  App.ncb
  *.h
  *.cpp
  Debug
    *.obj
    App.exe

and somewhere else on the hard drive...

LibraryFolder
  lib
    Library.lib
  include
    LibrarySolutionFolder
      Library.sln
      Library.ncb
      *.h
      *.cpp
      Debug
        *.obj
        Library.lib

I've been #including the library *.h files from my app's cpp files, and everything compiles fine.  It's just when it links I get a list of all the .lib
files that are being searched, and Library.lib isn't on there even though I have it listed in VC++ directories.
How can I get this to link?  (And am I structuring the library folders correctly?)

[A]
On the project properties:
Configuration Properties -> Linker -> Input -> Additional Dependancies
Add it in there.
Or, in your .h file for the library, add:
```
```
#pragma comment(lib, "Library")
```
```
This will do it automatically for you.


q: I researched this a while ago and can't remember how to do it. I want to be able to prevent Firefox from running it's spell-checking functionality on certain input fields from within the page. I know it's possible but can't remember how to set it up.

[A]
Talk about having a big "duh" moment! I found the answer after some trial & error:
```
```
<textarea spellcheck="false"></textarea>
```
```


q:
Note: I am just consuming webservice I have no control over webservice code.

So in .net 2.0 I reference the webservice and see a class in the webservice namespace, say foobar. It's defined as:

public class foobar : System.Web.Services.Protocols.SoapHttpClientProtocol

but in .net 3.5 when i add a reference to the same webservice I no longer have this foobar class available. I do see foobarSoap which is an interface which exposes all of the methods in the foobar class above. It's defined as:

public interface foobarSoap

However it doesn't expose the properties (for obvious reasons).

I need to access these properties. How do I do it?

[A]
You can try using the
Web Service Description Language Tool
(
```
Wsdl.exe
```
) to generate an actual class file:
```
wsdl.exe /language:cs http://www.example.com/FooService.wsdl
```
You can get more information about the
WSDL Tool
on it's
MSDN Page
.


q:
Is there an easy way to convert between color models in Java (RGB, HSV and Lab).

Assuming RGB color model:

How do I calculate black body spectrum color palette? I want to use it for a heatmap chart.

How about single-wavelength spectrum?

Edit: I found that the ColorSpace class can be used for conversions between RGB/CIE and many other color models.

[A]
You can build such a palette using the HSV color-model. That's easy once you have the HSV to RGB code in place and play around with the numbers for some minutes.
However, I think it's not worth it to add the code to your project just to generate a little palette.
It's much easier and less work to extract the palettes you need from a file and add them as a static array.
Photoshop let's you edit palettes and comes with a very nice black body palette as a preset.
You can simply save these as a .act file. The file itself is just a simple 256 color á 3 byte file (order is read, green, blue. 8 bits per channel).


q:
I need to perform a filtered query from within a django template, to get a set of objects equivalent to python code within a view:

queryset = Modelclass.objects.filter(somekey=foo)

In my template I would like to do

{% for object in data.somekey_set.FILTER %}

but I just can't seem to find out how to write FILTER.

[A]
You can't do this, which is by design.  The Django framework authors intended a strict separation of presentation code from data logic.  Filtering models is data logic, and outputting HTML is presentation logic.
So you have several options.  The easiest is to do the filtering, then pass the result to
```
render_to_response
```
.  Or you could write a method in your model so that you can say
```
{% for object in data.filtered_set %}
```
.  Finally, you could write your own template tag, although in this specific case I would advise against that.


q:
Because of several iframes, XUL browser elements, and so forth, I have a number of window objects in my XULRunner application. I'm looking for the best way to find the window object that a specified node belongs to using JavaScript.

So, to be more specific, given node x, I need to find the specific window object that contains x.

[A]
You may want to use
self
.  self is a reference to the current document.
From within the iframe:
```
```

Example!

```
```
Traversing Multiple Window Objects:
Within the browser object model, the primary window object is referred to as
top
.  Other global objects are arranged in a tree structure which stems from top.  With a reference to
top
, you can navigate to the other global objects in the tree by using their
names and relationships
, much in the same way as you
traverse the DOM
.
When you have multiple window objects, as you do in the case of an iframe (of with old school framesets), the frame has a
name attribute
.  Given the objects position relative to the top window object, you can use the name of the child to access the object.
```
<iframe src ="/default.html" name="advertisement"></iframe>
```
and then from the context of the top window:
```
self.advertisement
```


q:
StateServer or SQLServer?

What is the best solution for storing ASP.NET session variables?

What are the pros and cons of each?

Are one better then other in any particular situation?

[A]
I think the assumption would be that you are using a web farm of some sort.
One use of state service is in a Web Garden (multiple worker-processes on the same machine).  In this case, you can use load-balancing to keep a user's connection going to a particular server, and have the n worker processes all sharing the same state service.
EDIT: In the web garden + state service or sql server scenario, you also have the benefit of being able to recycle the worker processes on that machine w/o the connected clients losing their session.
I'm not as familiar with using SQL Server as a session state store, but I would think you would gain robustness by using an SQL Server in a cluster. In this case, you could still have multiple worker processes and multiple servers, but you would not have to use a sticky session (server affinity).
And one more note, you can use state service on a second machine, and have all server in the farm hit that machine, but you would then have a single point of failure.
And finally, there are 3rd party (and some home-grown) distributed state-service-like applications.  Some of these have performance benefits over the other options, plus Session_End event will actually fire. (In both State Service and SQL Server session backing, there the Session_End in Global.asax will not fire (there may be a way of hooking into SQL Server)).


q:
What is the most elegant way to calculate the previous business day in shell ksh script ?

What I got until now is :

#!/bin/ksh

set -x

DAY_DIFF=1
case `date '+%a'` in
"Sun")
   DAY_DIFF=2
   ;;
"Mon")
   DAY_DIFF=3
   ;;
esac

PREV_DT=`perl -e '($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time()-${DAY_DIFF}*24*60*60);printf "%4d%02d%02d",$year+1900,$mon+1,$mday;'`

echo $PREV_DT

How do I make the ${DAY_DIFF} variable to be transmitted as value and not as  string ?

[A]
Well, if running Perl counts as part of the script, then develop the answer in Perl.  The next question is - what defines a business day?  Are you a shop/store that is open on Sunday?  Saturday?  Or a 9-5 Monday to Friday business?  What about holidays?
Assuming you're thinking Monday to Friday and holidays are temporarily immaterial, then you can use an algorithm in Perl that notes that wday will be 0 on Sunday through 6 on Saturday, and therefore if wday is 1, you need to subtract 3 * 86400 from time(); if wday is 0, you need to subtract 2 * 86400; and if wday is 6, you need to subtract 1 * 86400.  That's what you've got in the Korn shell stuff - just do it in the Perl instead:
```
```
#!/bin/perl -w
use strict;
use POSIX;
use constant SECS_PER_DAY => 24 * 60 * 60;
my(@days) = (2, 3, 1, 1, 1, 1, 1);
my($now) = time;
my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($now);
print strftime("%Y-%m-%d\n", localtime($now - $days[$wday] * SECS_PER_DAY));
```
```
This does assume you have the POSIX module; if not, then you'll need to do roughly the same printf() as you used.  I also use ISO 8601 format for dates by preference (also used by XSD and SQL) - hence the illustrated format.


q:
Can someone please point me to the easiest way to have a timer in a Win32 service?

I suppose I could create a dummy window for this purpose or have a second thread do tick counts, but what's best? Is there a more elegant way?

Thanks in advance.

[A]
You can use SetTimer to set the timer, then catch the WM_TIMER message in your message loop.
Example:
// Set a timer to expire in 10 seconds
SetTimer(hwnd,IDT_TIMER1, 10000,(TIMERPROC) NULL);
... then in message loop:
switch (wParam)
```
```
{

    case IDT_TIMER1:

        // Boom goes the dynamite
```
```
You can also decleare a function of type TIMERPROC and have that be called when the timer expires, if you don't want to do the message loop handling.