q:
I mean what the most efficient way to get information about the quantity of your page's items and make sql query with LIMIT that you need. or I should get all items and then crop array with php functions?

now I do 2 queries: first to count all items and second to get items that I need with LIMIT.

OK, I'll be more concrete. For example I need to show a question on my page and 20 answers to this question. At the bottom there shold be page control: links to the next, prev page and so on. I want to show proper number of links (number of answers/20) and when I go to any link I want to recieve proper answers (for example 41 to 60 on the 3d page). So what's the best way to get number of items (answers) to show proper number of links and to get proper answers for each link?

[A]
I'm assuming you want a count of the number of rows you'll be reading so as to do some pagination or similar? I don't understand your need for the LIMIT in the context of your question. However, if you just want a count of how many rows have been found, use one of the following.
You select the count of all rows such as:
```
```
select count(*) as counted, name, address
from contact
```
```
Or found rows:
```
```
SELECT SQL_CALC_FOUND_ROWS, name, address
from contact
```
```
This may be mysql specific I'm not sure.
Update:
For pagination you would do something like the following - (Psuedocode)
$rows = array($result)
$num_rows = sql_calc_found_rows
$per_page = 20
$pages = ceil($num_rows / $per_page)
page
$rows_this_page = array()
$rows_this_page = get_values($rows, (min index)$page_number * $per_page - $per_page, (max index)$page_number * $per_page - 1)


q:
I have two machines setup to run Visual Studio 2008 (SP1) & NET Framework 3.5 (SP1). If I create a .tt file in a console appliaction on machine #1 it automatically creates the sub .cs file for me, however if I do the exact same on machine #2 then no sub .cs file is created.

I have tried toggling the "Show All Files" option, restarting visual studio (multiple times), added new .tt files (with the same outcome), tried it in both a C# and a VB.NET project and Google is drawing up blanks.

Is it possible for T4 text templates to have been disabled somehow? If so, then how the heck do I turn them back on, it's annoying :-).?

s: huggingface

c: devops

d: intermediate


q:
I've recently had my PC upgraded to Vista, which means it includes IIS7. The problem is that the ASP.NET website we're working on doesn't work anymore. I get an error because the application is trying to connect to the SQL Server with NT AUTHORITY/ANONYMOUS LOGON instead of my domain user, and anonymous isn't authorized. I've tried several things, but no solution yet:
- install and enable the 'IIS Metabase and IIS 6 configuration compatibility'
- enable Windows Authentication for this website
- created a different Application Pool with managed pipeline mode set to Classic
- enabled IIS6 WMI compatibility and IIS6 management console (getting desperate here)

In our web.config there's  and in our machine.config there's . I've tried putting impersonate to false and entering my domain  user and password in the machine.config (it used to be like this) but that didn't help either.

Are there things I'm missing? Has anyone else had a similar problem?

[A] How does your application authenticate with SQL Server? Does it use SQL or Windows Auth? I hope you are trying to use Windows Auth. In that case, your IIS worker process should be running under that Windows user account. If not, it should at the least impersonate a Windows user account that has necessary access rights to SQL Server. If you have impersonation enabled and if you are using the right Windows user account and if SQL Server authenticates using Windows auth and if you are still unable to access SQL Server, you may be running into the classic double hop issue. In other words, you are trying to authenticate to IIS once and you are using the same crdentials to authenticate to the SQL Server over a network next(which is your second hop) and Windows does not allow that for security reasons.


q:
I have an object I am using to store document meta data into a table.  The body text of the document can be very large, sometimes > 2GB so I will be storing it into a nvarchar(max) field in SQL 2008.  I'll use SQL 2008 later to index that field.  I won't be using filestreams because they are very restrictive to the database and prevents certain types of concurrency locking schemes.

This object is exposed to the developer via LinqToSQL.  My concern is that the field will be to large and I have seen .Net bomb out with an OutOfMemory exception if the text is > 1.5 GB.

So I am wondering, can I treat this blob as a stream with Linq?  Or do I have to bypass Linq altogether if I want to use a blob?

[A]
Given the answer to
"Can a LINQ query retrieve BLOBs [...]"
I
suspect
you're out of luck. The
System.Data.Linq.Binary
type doesn't have any mechanism for streaming - basically it's just an immutable byte array representation.
There may be some deep LINQ mojo you could invoke, but I suspect it would really have to be pretty deep.
It's possible that the Entity Framework would handle it - I haven't investigated that.


q:
How do I run a batch file each time windows boots up also I need to run it in the back ground(without that command window getting displayed)? I use Windows Xp.
My actuall requirement is I want to start the Tracd server using the command line commands whenever Windows boots up.

[A]
Add your program in the
registry
:
Run - These are the most common startup locations for programs to install auto start from. By default these keys are not executed in Safe mode. If you prefix the value of these keys with an asterisk, *, is will run in Safe Mode.
Registry Keys:
```
```
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run registry key
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run registry key
```
```
Then you can launch your batch in an
invisible mode
:
```
```
wscript.exe "C:\yourpath\invis.vbs" "your_file.bat"
```
```
In invis.vbs put...
```
```
CreateObject("Wscript.Shell").Run """" & WScript.Arguments(0) & """", 0, False
```
```


q: When interviewing for a programming position, did you ever get an answer to your question that you didn't quite expect? The answer could've been quite smart that you didn't even know or it could've been a dumbest answer you never expected. I'm expecting technical type of questions but anything interesting is fine.

[A]
As an interviewer I had not been surprised very often.  Most of the people have been respectful and intelligent.  I had only been surprised by how quiet and nervous some people get or how little they tried to answer some of the technical questions.
As an interviewee I've given answers that were not expected.  There was one occasion where I gave an answer at an early stage interviewer for large multinational company- and they simply did not understand the solution.  Lesson learned: never give a 'different' or 'out of the box' answer unless it is in writing and the person receiving it is technical in that area.  Otherwise, they may simply regard it as incorrect.  Give the answer you think will be the norm- because in most cases the early interviewer has a very short list of the 'possible' answers.
Update:
The interview I was referring to was a 4th or 5th stage phone screen- so I guess it is not as applicable.  The question was one of those ones that involve 'assume you have infinite memory' so I played on that coming up with some strange 'what if' scenario.  The 'best' answer was one that was more to the point using traditional methods.


q: How do I make icons for my exe file when compiling my Python program?

[A]
I was searching for this a while ago, and found this:
http://www.mail-archive.com/pygame-users@seul.org/msg05619.html
Quote from above link:
The setup.py File: PY_PROG =
'trek10.py' APP_NAME = 'Trek_Game'
cfg = {
```
```
'name':APP_NAME,
'version':'1.0',
'description':'',
'author':'',
'author_email':'',
'url':'',

'py2exe.target':'',
'py2exe.icon':'icon.ico', #64x64
'py2exe.binary':APP_NAME, #leave off the .exe, it will be added

'py2app.target':'',
'py2app.icon':'icon.icns', #128x128

'cx_freeze.cmd':'~/src/cx_Freeze-3.0.3/FreezePython',
'cx_freeze.target':'',
'cx_freeze.binary':APP_NAME,
}
```
```
--snip--


q:
I want to use Oracle exception to handle errors that might happen in the code below. If a user provides the book ID and/or employee ID that doesn't exist in the database,  NO_DATA_FOUND exception will be raised. Thus, how can I know which statement raises this exception.

CREATE OR REPLACE PROCEDURE TEST_EXCEPTION
(
    book_id_in IN book.book_id%TYPE,
    emp_id_in IN emp.emp_id%TYPE
)
IS

v_book_desc book.description%TYPE;
v_emp_name emp.emp_name%TYPE;

BEGIN

SELECT description into v_book_desc FROM book WHERE book_id = book_id_in;

...

SELECT emp_name into v_emp_name FROM emp WHERE emp_id = emp_id_in;

...

EXCEPTION
     WHEN NO_DATA_FOUND THEN
         /* Do something */

END TEST_EXCEPTION;

I appreciate any suggestion or guidance. Thank you.

[A]
You can set a variable before the given statements. Like;
```
```
CREATE OR REPLACE PROCEDURE TEST_EXCEPTION ( book_id_in IN book.book_id%TYPE, emp_id_in IN emp.emp_id%TYPE ) IS

v_book_desc book.description%TYPE; v_emp_name emp.emp_name%TYPE;
statementIndex number(1, 0);

BEGIN

statementIndex := 1;
SELECT description into v_book_desc FROM book WHERE book_id = book_id_in;

...

statementIndex := 2;
SELECT emp_name into v_emp_name FROM emp WHERE emp_id = emp_id_in;

...

EXCEPTION WHEN NO_DATA_FOUND THEN
if statementIndex = 1
then
/* Do something */
else
/* Do something */
endif;

END TEST_EXCEPTION;
```
```


q:
I have checked in a huge Eclipse project from my desktop computer to the SVN server.  I did it using the command line.  However, by mistake I committed all the compiled classes also in the server.

For every plug-in, there is a directory /bin/ that contains the compiled classes.

Is there a way to quickly delete in the server all directories that match this pattern using the command line?

Additionally, is there a way to tell svn to ignore bin directories by default?

[A]
From
here
(for the 'additionally part'):
Click on Window -> Preferences
Select Team -> Ignored Resources
Click on Add Pattern and enter "bin"
Click on Apply and then OK
For the bin directories, do you have svn 1.5 ?
Because if you do,
```
'svn rm --keep-local'
```
allows to pull them from version control but
not
delete it from your machine.
You can do it with
Tortoise
(Delete (keep local))


q: The C++ standard dictates that member variables inside a single access section must be layed out in memory in the same order they were declared in.  At the same time, compilers are free to choose the mutual ordering of the access sections themselves.  This freedom makes it impossible in theory to link binaries created by different compilers.  So what are the remaining reasons for the strict in-section ordering?  And does the <s>upcoming C++09</s> new C++11 standard provide a way to fully determine object layouts "by hand"?

[A]
This freedom makes it impossible in theory to link binaries created by different compilers.
It's impossible for a number of reasons, and structure layout is the most minor. vtables, implementations of
```
operator new
```
and
```
delete
```
, data type sizes...
So what are the remaining reasons for the strict in-section ordering?
C compatibility, I would have thought, so that a struct defined in C packs the same way it does in C++
for a given compiler set
.
And does the new C++
09
11 standard provide a way to fully determine object layouts "by hand"?
No, no more than the current standard does.
For a
```
class
```
or
```
struct
```
with no vtable and entirely private (or public) fields, though, it's already possible if you use the
```
[u]int[8|16|32|64]_t
```
types. What use case do you have for more than this?


q: I looked it up in Wikipedia, and there is only one line there. Anyone have a more detailed description for it? Ubuntu releases their OS with this notation, but I was unable to find a detailed description over what it means/includes. I've already read the Ubuntu notation but need a more general description, not how Ubuntu has implemented it.

[A]
From the Ubuntu Wiki:
LTS is an abbreviation for “Long Term
  Support”.
We issue a new desktop and server
  release every six months. That means
  you'll always have the latest and
  greatest applications that the open
  source world has to offer.
Ubuntu is designed with security in
  mind. You get free security updates
  for at least 18 months on the desktop
  and server.
With the Long Term Support (LTS)
  version you get three years support on
  the desktop, and five years on the
  server. There is no extra fee for the
  LTS version, we make our very best
  work available to everyone on the same
  free terms. Upgrades to new versions
  of Ubuntu are and always will be free
  of charge.


q:
The C++ standard imposes an ordering on class member variables in memory.  It says that the addresses of member variables have to increase in the order of declaration, but only inside one access section.  Very specifically, this does not seem to prevent compilers from laying out access sections in an interleaved way.  For example:

class X {
public:
   int i;
   int j;
private:
   int k;
   int n;
}

Does the standard allow compilers to lay out the data members in the order i, k, j, n?  This would give compilers some (limited) freedom in optimizing object layout without violating the standard.

[A]
And no, i think he is NOT trying to spam. This is a valid question and quite interesting i think.
Ok now i think compilers can do that. The standard says in 9.2. p12:
```
Implementation alignment require-
ments might cause two adjacent members not to be allocated immediately after each other; so might
requirements for space for managing virtual functions (10.3) and virtual base classes (10.1).
```


q:
How can I check which version of Apache is installed on a Debian machine?

Is there a command for doing this?

[A]
Try apachectl -V:
```
```
$ apachectl -V
Server version: Apache/2.2.9 (Unix)
Server built:   Sep 18 2008 21:54:05
Server's Module Magic Number: 20051115:15
Server loaded:  APR 1.2.7, APR-Util 1.2.7
Compiled using: APR 1.2.7, APR-Util 1.2.7
... etc ...
```
```
If it does not work for you, run the command with
```
sudo
```
.


q:
As being quite a newbie in linux, I have the follwing question.
I have list of files (this time resulting from svn status) and i want to create a script to loop them all and replace tabs with 4 spaces.

So I want from

....
D      HTML/templates/t_bla.tpl
M      HTML/templates/t_list_markt.tpl
M      HTML/templates/t_vip.tpl
M      HTML/templates/upsell.tpl
M      HTML/templates/t_warranty.tpl
M      HTML/templates/top.tpl
A  +   HTML/templates/t_r1.tpl
....

to something like

for i in <files>; expand -t4;do cp $i /tmp/x;expand -t4 /tmp/x > $i;done;

but I dont know how to do that...

[A]
I would use sed, like so:
```
```
for i in files
do
    sed -i 's/\t/    /' "$i"
done
```
```
That big block in there is four spaces. ;-)
I haven't tested that, but it
should
work.  And I'd back up your files just in case.  The -i flag means that it will do the replacements on the files in-place, but if it messes up, you'll want to be able to restore them.
This assumes that $files contains the filenames.  However, you can also use Adam's approach at grabbing the filenames, just use the sed command above without the "$i".


q:
HI,

I have 3 tables: Clips, Books and relationships between ClipBook

Problem is:
i need get book that has bookID=4 with some clips i mean many-to-many

in simple text sql it will be something like this:

select * from Clips where clipID in (select clipID from ClipBook where bookID=4)

Question is:

How can i do this with Linq without operator Join of course


q:
It's a simple case of a javascript that continuously asks "are there yet?" Like a four year old on a car drive.. But, much like parents, if you do this too often or, with too many kids at once, the server will buckle under pressure..

How do you solve the issue of having a webpage that looks for new content in the order of every 5 seconds and that allows for a larger number of visitors?

[A]
stackoverflow does it some way, don't know how though.
The more standard way would indeed be the javascript that looks for new content every few seconds.
A more advanced way would use a
push-like
technique, by using
Comet
techniques (long-polling and such). There's a lot of interesting stuff under that link.
I'm still waiting for a good opportunity to use it myself...
Oh, and here's a link from stackoverflow about it:
Is there some way to PUSH data from web server to browser?


q:
How do I get the difference in days between 2 dates in SQLite? I have already tried something like this:

SELECT Date('now') - DateCreated FROM Payment

It returns 0 every time.

[A]
```
```
SELECT julianday('now') - julianday(DateCreated) FROM Payment;
```
```


q:
I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.

I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.

Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.

[A]
I am afraid you cannot do it within a function
When you try to declare a function like:
```
```
create function dbo.textReplace(
@inText as text)
returns text
as
begin
    return 'a' -- just dummy code
end
```
```
You will get the following error:
```
```
The text data type is invalid for return values.
```
```
In other words you could not write a simple equivalent of REPLACE function for the text data type


q:
I am writing unit tests for a class, which has a static final variable.
However, since the state of the static final var is modified in each test, I need some way to reinitialize it.

How would this be possible? Would i need to use some sort of a custom classloader?

The variable is initialized as -

 static final CountdownLatch latch = new CountdownLatch(1);

[A]
One (not very efficient) approach assuming you are using junit and ant.
You could create a separate class for each test method, and then use a forkmode of
```
perTest
```
.
As the
Ant junit task documentation
states:
Controls how many Java Virtual Machines get created if you want to fork some tests. Possible values are "perTest" (the default), "perBatch" and "once". "once" creates only a single Java VM for all tests while "perTest" creates a new VM for each TestCase class. "perBatch" creates a VM for each nested <batchtest> and one collecting all nested <test>s. Note that only tests with the same settings of filtertrace, haltonerror, haltonfailure, errorproperty and failureproperty can share a VM, so even if you set forkmode to "once", Ant may have to create more than a single Java VM. This attribute is ignored for tests that don't get forked into a new Java VM. since Ant 1.6.2


q:
Since MySQL doesn't seem to have any 'boolean' data type, which data type do you 'abuse' for storing true/false information in MySQL?

Especially in the context of writing and reading from/to a PHP script.

Over time I have used and seen several approaches:

tinyint, varchar fields containing the values 0/1,

varchar fields containing the strings '0'/'1' or 'true'/'false'

and finally enum Fields containing the two options 'true'/'false'.

None of the above seems optimal. I tend to prefer the tinyint 0/1 variant, since automatic type conversion in PHP gives me boolean values rather simply.

So which data type do you use? Is there a type designed for boolean values which I have overlooked? Do you see any advantages/disadvantages by using one type or another?

[A]
I use TINYINT(1) in order to store boolean values in Mysql.
I don't know if there is any advantage to use this... But if i'm not wrong, mysql can store boolean (BOOL) and it store it as a tinyint(1)
http://dev.mysql.com/doc/refman/5.0/en/other-vendor-data-types.html


q:
I'm just starting to try out phpunit on some existing code. The naming convention we use is that the MyClass class should be in MyClass.class.php. PHPUnit seems to require that the file should be called MyClass.php.

Is there any way around this?

I noticed it while trying to generate a skeleton test class:

phpunit --skeleton-test MyClass.class

PHPUnit 3.3.4 by Sebastian Bergmann.

Could not find class "MyClass.class" in "/home/jd/skeleton/classes/MyClass.class.php".
Fatal error: Call to a member function getOutClassName() on a non-object in /usr/share/php/PHPUnit/TextUI/Command.php on line 470

[A]
Its not a requirement, its just assumptive. You can write your own test-cases.
Skeleton just makes a mock-up one "the easy way" that makes dummy functions for all your classes dummy functions.
Also,
```
```
phpunit --skeleton-test MyClass  MyClass.class.php
```
```
Might do what you want.
```
```
Usage: phpunit [switches] UnitTest [UnitTest.php]
       phpunit [switches] <directory>

--skeleton-class         Generate Unit class for UnitTest in UnitTest.php.
--skeleton-test          Generate UnitTest class for Unit in Unit.php.
```
```
so by that reasoning, if you don't tell it what file the class is in it will try guess, if you do tell it what file the class is in, it wont guess.


q:
During navigation of the java.lang.reflect.Method class I came across the method isBridge. Its Javadoc says that it returns true only if the Java spec declares the method as true.

Please help me understand what this is used for! Can a custom class declare its method as a bridge if required?

[A]
A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments.
You can find in this class
BridgeMethodResolver
a way to get the actual Method referred by a 'bridge method'.
See
Create Frame, Synchronize, Transfer Control
:
As an example of such a situation, consider the declarations:
```
```
class C<T> { abstract T id(T x); }
class D extends C<String> { String id(String x) { return x; } }
```
```
Now, given an invocation
```
```
C c = new D();
c.id(new Object()); // fails with a ClassCastException
```
```
The erasure of the actual method being invoked,
```
D.id(String)
```
differs in its signature from that of the compile-time method declaration,
```
C.id(Object)
```
. The former takes an argument of type String while the latter takes an argument of type Object. The invocation fails with a ClassCastException before the body of the method is executed.
Such situations can only arise if the program gives rise to an unchecked warning (
§5.1.9
).
Implementations can enforce these semantics by creating bridge methods. In the above example, the following bridge method would be created in class D:
```
```
Object id(Object x) { return id((String) x); }
```
```
This is the method that would actually be invoked by the Java virtual machine in response to the call
```
c.id(new Object())
```
shown above, and it will execute the cast and fail, as required.
See also
Bridge
:
as mentioned in the comment, bridge methods are also needed for
covariant overriding
:
In Java 1.4, and earlier, one method can override another if the signatures match
exactly.
In Java 5, a method can override another if the arguments match exactly
but the return type
of the overriding method, if it is a
subtype
of the return type of the other method.
Typically, a method
```
Object clone()
```
can be overridden by a
```
MyObject clone()
```
, but a bridge method will be generated by the compiler:
```
```
public bridge Object MyObject.clone();
```
```


q:
how do i make an autocomplete textbox in asp?
but i need to get the autocomplete data by querying the database.
I dont really know how to explain this, sory if theres not enough detail.
i cant use ajax, because i think i will have compability issues with my old app.
so im thinking of doing this using java script. or is there a way to do this by using .net?
im using C# for codebehind. thanks

[A]
It's going to be a lot of effort without using some third party autocomplete I think - not sure what you mean by 'I can't use ajax', but how about using the
ASP.NET AJAX autocomplete control
, setting the
```
ServiceMethod
```
property to a static Page Method in your code behind? That keeps it contained within your page at least.
The Page Method can go off to your database, and return a String[] of results.
If you decide to use it, you'll need to set the
```
EnablePageMethods
```
property to
```
true
```
in the
```
<asp:ScriptManager>
```
control.


q:
I have a webservice running under sharepoint, on a bog-standard Server2003/IIS6 setup.  This webservice needs to open and read a file from a share on another machine in the same domain. At the moment I am getting a

System.UnauthorizedAccessException: Access to the path '\strand\DROPBOXES\MattTrinder\SharepointShared\bd116dfa-be0e-4c58-93e6-3fb93fa0ef22.tmp' is denied.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)

What permissions do I need to grant to which accounts to allow this webservice to open and read the file ?

Using "\\sharepointserver\c$" works fine...

Thanks

Matt

[A]
The account you grant access to, has to exist on the target (where the share exists) as well (either the same domain account, or a local account with the same password). Since the IIS-user normally has an auto-generated password and is local, this is hard.
The way we solve this, is to run the website as a different user (that we created ourselves), and grant this user permissions to access the share on the remote PC. Note that both the sharing permissions have to be correct, and the file system permissions.


q: What is the best way to convert an Int value to the corresponding Char in Utf16, given that the Int is in the range of valid values?

[A]
```
```
int i = 65;
char c = Convert.ToChar(i);
```
```


q:
I have an arraylist that contains items called Room. Each Room has a roomtype such as kitchen, reception etc.
I want to check the arraylist to see if any rooms of that type exist before adding it to the list.
Can anyone recommend a neat way of doing this without the need for multiple foreach loops?

(.NET 2.0)

I havent got access to the linq technology as am running on .net 2.0. I should have stated that in the question.
Apologies

[A]
```
```
if (!rooms.Any (r => r.RoomType == typeToFind /*kitchen, ...*/))
  //add it or whatever
```
```


q: I have installed m2eclipse plugin from http://m2eclipse.codehaus.org/. Now I want to use that as a standalone build tool but I am unable to find the installation directory. Can anyone help me in this?

[A]
I am not sure to understand what you want.
m2eclipse is a
plugin
for Eclipse, thus it must be run inside Eclipse.
To have a standalone build tool, I suggest that you just download directly the
Maven2 binaries files
, and install it on your computer, if it is not already done!
For your information, all plugins are stored in the eclipse-dir/plugins directory, as a subdirectory or as a JAR file.


q:
What is the best approach to play a sequence of flv video files in Flash (with actionscript)? My goal is to have the transitions occur as smoothly as possible.

Currently i'm using the netStream class and capturing the onStatus events to play the next video when the current video has reached it's end duration. Althought this approach works fine, there is still a small gap between the ending of the current video and start of the next. Any ideas on how to optimize this method?

Thanks in advance :)

[A]
The problem is not the linq itself,
you need to be sure that the context or provider object is able to fetch the data.
try testing the
```
```
subnusMVCRepository<Categories> categories = new subnusMVCRepository<Categories>();
subnusMVCRepository<Post_Category_Map> postCategoryMap = new subnusMVCRepository<Post_Category_Map>();
```
```
objects and see if they are populated or if they behaving as required.
you may want to search the generated code for c__DisplayClass1 and see what you can see there. some times the generated code dose some weird things.
when you step into you code check the locals and the variable values. this may also give you some clues.
Edit :
Have you tried to return a List<> collection ? or an Enumerable type?
Edit :
What is the real type of the
item
and query may not be iterable


q:
Why EAccessViolation is raised when executing the code below?

uses
  Generics.Collections;
  ...

var
  list: TList<TNotifyEvent>;
  ...

begin
  list := TList<TNotifyEvent>.Create();
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);  // EAccessViolation at address...
  finally
    FreeAndNil(list);
  end;
end;

procedure myNotifyEvent(Sender: TObject);
begin
  OutputDebugString('event');  // nebo cokoliv jineho
end;

[A]
the above code is used in TForm1 ...
```
```
uses
  Generics.Collections;

procedure TForm1.Button1Click(Sender: TObject);
var
  list: TList<TNotifyEvent>;
begin
  list := TList<TNotifyEvent>.Create();
  try
    list.Add(myNotifyEvent);
    list.Remove(myNotifyEvent);  // EAccessViolation at address...
  finally
    FreeAndNil(list);
  end;
end;
procedure TForm1.myNotifyEvent(Sender: TObject);
begin
  OutputDebugString('event');  // nebo cokoliv jineho
end;
```
```


q:
In OOP languages like C# or VB.NET, if I make the properties or methods in a super class protected I can't access them in my Form - they can only be accessed in my class that inherits from that super class.

To access those properties or methods I need to make them public, which defeats encapsulation, or re-write them into my class, which defeats inheritance.

What is the right way to do this?

[A]
If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements.
Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it.  The car is no use to me.
Either make those members Public (or at least internal) and use them or ditch the class and use one that gives your consuming code the features it needs.
Perhaps what you are really looking for is an interface.  The interface contains the members your code needs and you implement that interface on your class.  The advantage here is that your class can determine that the members are being accessed via this Interface rather than an inheriting subclass.


q:
Why must Type.Equals(t1, t2) be used to determine equivalent types, and not the equality operator (e.g. for VB.NET, t1 = t2)?

It seems inconsistent with other parts of the .NET API.

Example in VB.NET:

If GetType(String) = GetType(String) Then
    Debug.Print("The same, of course")
End If

causes a compile-time error of "Operator '=' is not defined for types 'System.Type' and 'System.Type'."

[A]
Given the way types are loaded, that surprises me. Where did you hear this from?
The
docs for System.Type.Equals(Type)
suggest that it's comparing via the
UnderlyingSystemType
property, but I'm not sure under what circumstances two different Type objects would have the same underlying system type.
I'd be really interested to see an example where this mattered... my
guess
is that from anywhere in "user code" they'll be the same thing, but there may be some cunning BCL code where it matters.


q: There is a space of x*y for text to go on $im (GD Image Resource) how can I choose a font size (or write text such that) it does not overflow over that area?


q:
The assembly it's trying to find isn't the root assembly - it's a referenced one, but it's in the same folder, and Directory.GetCurrentDirectory() is the folder with all of the files in.

I'm stuck - any suggestions?

[A]
You can either:
Create a new
```
AppDomain
```
to load the assembly (and set the
```
AppDomain
```
's base directory to the directory containing all the assemblies).
Attach a handler for
```
AppDomain.AssemblyResolve
```
to help the CLR find the assembly's dependencies.
You might be able to add the directory in question to the list of paths to probe. However, it will need to reside somewhere under your application's directory. See the
probe
element for more info.


q: I can't find a pre-built set of MSVC++ libs for Boost 1.37.0, only the source. I don't understand how their weird build system works... are there any places I can find a download of a visual studio project or something?

[A]
Building it isn't difficult.
They have a fairly good expanaltion of the default process here:
http://www.boost.org/doc/libs/1_37_0/more/getting_started/windows.html#or-build-binaries-from-source
Download bjam (from sourceforge, there are links from the boost website), as well as the boost sources, make sure bjam is accessible from the boost dir, cd to the boost dir, and run something like the following:
bjam --build-dir= --prefix-dir= --toolset=msvc --build-type=complete install
where  is an temp dir where it can store intermediate files, and  is the final install location. There are all sorts of other options you can play around with, and not all of them are documented very well, but the basics are fairly simple.
For more help, you can run bjam --help from the boost source dir.


q:
I always hear that using "lastInsertId" (or mysql_insert_id() if you're not using PDO) is evil. In case of triggers it obviously is, because it could return something that's totally not the last ID that your INSERT created.

$DB->exec("INSERT INTO example (column1) VALUES ('test')");
// Usually returns your newly created ID.
// However when a TRIGGER inserts into another table with auto-increment:
// -> Returns newly created ID of trigger's INSERT
$id = $DB->lastInsertId();

What's the alternative?

[A]
It's not sophisticated and it's not efficient, but if the data you've inserted include unique fields, then a SELECT can obviously yield what you're after.
For example:
```
```
INSERT INTO example (column1) VALUES ('test');
SELECT id FROM example WHERE column1 = 'test';
```
```


q:
I have a need to populate a Word 2007 document from code, including repeating table sections - currently I use an XML transform on the document.xml portion of the docx, but this is extremely time consuming to setup (each time you edit the template document, you have to recreate the transform.xsl file, which can take up to a day to do for complex documents).

Is there any better way, preferably one that doesn't require you to run Word 2007 during the process?

Regards
Richard

[A]
I tried myself to write some code for that purpose, but gave up. Now I use a 3rd party product:
Aspose Words
and am quite happy with that component.
It doesn't need Microsoft Word on the machine.
"Aspose.Words enables .NET and Java applications to read, modify and write Word® documents without utilizing Microsoft Word®."
"Aspose.Words supports a wide array of features including document creation, content and formatting manipulation, powerful mail merge abilities, comprehensive support of DOC, OOXML, RTF, WordprocessingML, HTML, OpenDocument and PDF formats. Aspose.Words is truly the most affordable, fastest and feature rich Word component on the market."
DISCLAIMER
: I am not affiliated with that company.


q:
How to get the number of years between two java.util.Date?

Note: using only java.util.Date

[A]
How accurate do you need to be?  If approximate is good enough, then I'd do
```
```
long msDiff = date1.getTime() - date2.getTime();
int yearDiff = (int)(msDiff / 1000 / 60 / 60 / 24 / 365.25);
```
```


q:
Can I use Xpath node set function position() in Delphi's function selectNodes() to select only a certain number of element from a node list? If I do like this:

selectNodes('Item[1]')

its all fine and I get the element with index 1, but when I try

selectNodes('Item[position()<10]')

I get exception 'unknown method', when I try

selectNodes('Item[<10]')

I get 'unexpected token <'.
Im using delphi7 and I also imported new type library into my project with newer versions of msxml.

[A]
selectNodes requires a string, so you should try:
```
```
selectNodes('Item[position()<10]')
```
```
Or whatever xpath query.


q:
I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results.

Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.

[A]
I use
SQL Alchemy
with cPython (I don't know if it'll work with IronPython though).  It'll be pretty familiar to you if you've used Hibernate/nHibernate.  If that's a bit too verbose for you, you can use
Elixir
, which is a thin layer on top of SQL Alchemy.  To use either one of those, you'll need
pyodbc
, but that's a pretty simple install.
Of course, if you want to write straight SQL and not use an ORM, you just need pyodbc.


q:
I want to automate tests on my web application, and it uses postgresql. Does anyone know how define a restore point on a postgresql database and restore to an earlier state?
I heard something about point in time recovery, but i dont if this is what i need.

Thanks in advance


q:
Given the following class:

class TestClass {
  public void SetValue(int value) { Value = value; }
  public int Value { get; set; }
}

I can do

TestClass tc = new TestClass();
Action<int> setAction = tc.SetValue;
setAction.Invoke(12);

which is all good. Is it possible to do the same thing using the property instead of the method? Preferably with something built in to .net.

[A]
Properties are really wrappers around methods in .Net, so using reflection you should be able to get the delegate (set_PROPERTY and get_PROPERTY) and then execute them...
See
System.Reflection.PropertyInfo
If has two methods which you can use to get/ set the value - GetGetMethod and GetSetMethod.
So you could write:
```
```
var propertyInfo = typeof (TestClass).GetProperty ("Value");

var setMethod = property.GetSetMethod (); // This will return a MethodInfo class.
```
```


q: What does "Overloaded"/"Overload" mean in regards to programming?

[A]
It means that you are providing a function (method or operator) with the same name, but with a different signature.
For example:
```
```
void doSomething();
int doSomething(string x);
int doSomething(int a, int b, int c);
```
```


q:
I distribute my application using a VS2008 install package, which normally works great.  When I create new versions of the app, I go in and increment the Version property on the install package and verify the RemovePreviousVersions property is set to True.

This works just fine most of the time - I just run the install package for the newer version and the older version is uninstalled and the newer version replaces it.

However, occasionally the install package will run successfully, but when I start the program the old version starts up.  Apparently the old version of the .exe is still present.

I end up having to completely uninstall the software and install the new version, which always works, but is a pain.

The file isn't in use as far as I can tell and the install package doesn't tell me to reboot.

Any ideas about what's going on here?

[A]
Not a direct answer, but the key difference between an upgrade and an uninstall+ a reinstall is that any custom uninstall steps are not called in 2k8 but are in 2k5.
This is referenced in
Visual Studio 2005 -> 2008/10 Service Installer Project Upgrade issue
The other difference related to this is that in 2k8, the files get upgraded based on the version info resource - if your modules dont have newer versions, they dont get replaced.
In some cases whether you strong name also has effects, but I'm pretty confident the last paragraph covers the issue you're seeing.


q: In C++, is the return type considered part of the function signature? and no overloading is allowed with just return type modified.

[A]
Normal functions do not include the return type in their signature.
(
note
: i've rewritten this answer, and the comments below don't apply to this revision - see the edit-history for details).
Introduction
However, the matter about functions and function declarations in the Standard is complicated. There are two layers that have to be considered:
Declarations
Entities
The so-called
function declaration
may declare a function entity or a template entity. If a function entity is declared, then you either have to do with an explicit specialization of a function template (with all arguments specified), or a declaration of an ordinary function. If a template entity is declared, then you are declaring a primary function template, or an explicit specialization where some arguments are not specified. (This is very similar to the relation of "object declaration" and objects or references: The former may declare either an object or a reference. So an
object declaration
may not necessarily declare an object!).
The Standard defines the signature of a function to include the following at
```
1.3.10
```
:
The types of its parameters and, if the function is a class member, the cv- qualifiers (if any) on the function itself and the class in which the member function is declared. The signature of a function template specialization includes the types of its template arguments. (14.5.5.1)
It's missing the return type in this definition, which
is
part of the signature of a function template specialization (i.e a function declaration that declares a function which is a specialization of a template), as pointed out by
```
14.5.5.1
```
(recent C++0x working papers fixed that already to mention the return type in
```
1.3.10
```
too):
The signature of a function template specialization consists of the signature of the function template and of the actual template arguments (whether explicitly specified or deduced).
The signature of a function template consists of its function signature, its return type and its template parameter list.
So what exactly does a signature contain, again?
So, when we ask about the signature of a
function
, we have to give two answers:
For functions that are specializations of function templates, the signature includes the return type.
For functions that are not specializations, the return type is not part of the signature.
Notice, however, that the return type, in any case,
is
a significant part of the type of a function. That is, the following is not valid:
```
```
void f();
int (*pf)() = &f; // different types!
```
```
When is an overload invalid if only the return type differs?
Major compilers currently reject the following code:
```
```
int f();
double f(); // invalid
```
```
But accept the following code:
```
```
template<typename T> int f();
template<typename T> double f(); // invalid?
```
```
However, the
Standard does forbid a function declaration that only differs in the return type
(when defining when an overload is valid, and when not). It does not define precisely what "differs only by return type" means, though.
Standard paragraph references:
When can a function declaration be overloaded:
```
13.1
```
What is a function declaration:
```
7/2
```
and
```
7/5
```
What is the signature of a function template/specialization:
```
14.5.5.1
```
For reference, here is what the most recent C++0x draft n3000 says about "signature" in
```
1.3.11
```
, which is much more complete in its coverage of the different type of entities:
the name and the parameter type list (8.3.5) of a function, as well as the class or namespace of which it is a member. If a function or function template is a class member its signature additionally includes the cv-qualiﬁers (if any) and the ref-qualiﬁer (if any) on the function or function template itself. The signature of a function template additionally includes its return type and its template parameter list. The signature of a function template specialization includes the signature of the template of which it is a specialization and its template arguments (whether explicitly speciﬁed or deduced). [ Note: Signatures are used as a basis for name mangling and linking. — end note ]


q: I’m trying to make the routing module works with default action or controller, but it doesn’t. I always face with 404 page not found. Did I forget to do something? I really like routing in ASP.NET MVC feature, but I’m not sure I could do the same in MR. I’m using IIS7 with the build from castle trunk for .NET 3.5.

[A]
How are you configuring the routing? I had issues myself when trying to manage the routing-rules from web.config, but moving it to inline-code on application-start worked for me.
I tried to find an answer to why the xml-way didn't work, but never found one. They made a major rewrite of the routing-engine since RC3, that might have broken it.
Example from Application_OnStart()
```
var rule = new PatternRoute( "default", "/" )
    .DefaultForController().Is()
    .DefaultForAction().Is( "index" );

RoutingModuleEx.Engine.Add( rule );
```
Remember to load the RoutingEngineModule before the MonoRailHandler in web.config.


q:
I have an have an ASP.Net page which contains a button. This Page contains a ServerSide Paypal button.

When pushed my server does various clever things on the back end and then rewrites the response as a form and some javascript which posts this form to paypal..

This all works great.

However, if the user then elects to click back, they will arrive at my generated self-posting form and that will forward them again to Paypal.

I thought if I could find a way to have my generated form page not exist in the history, then this will solve my problem. but I have no idea how to correct this.

How can I remove my page from the history or just have it never appear?

Update: Thanks to all... Those are some great answers. Upvoted all good ones but went with splattne on account of clever use of hidden field rather than cookies for basis of decision.

[A]
As a web application, you'll never have full control of the user's browser.  Even if there was a way to instruct the browser to not store the page in history, which I doubt, you can't be sure it'll work.  For example, a clever user could tweak an open-source browser to store every page in history, no matter what.
I think you should try to approach the problem from another angle.  You could, for example, detect that it's the same form which is being forwarded and not send it to paypal the second time.  The important thing is to do it server-side.


q:
I just came over this syntax in some of the questions in this forum, but Google and any other searchengine tends to block out anything but letters and number in the search so it is impossible to search out "=>".

So can anyone tell me what it is and how it is used?

[A]
It's the lambda operator.
From C# 3 to C# 5, this was only used for
lambda expressions
. These are basically a shorter form of the
anonymous methods
introduced in C# 2, but can also be converted into
expression trees
.
As an example:
```
```
Func<Person, string> nameProjection = p => p.Name;
```
```
is equivalent to:
```
```
Func<Person, string> nameProjection = delegate (Person p) { return p.Name; };
```
```
In both cases you're creating a delegate with a
```
Person
```
parameter, returning that person's name (as a string).
In C# 6 the same syntax is used for
expression-bodied members
, e.g.
```
```
// Expression-bodied property
public int IsValid => name != null && id != -1;

// Expression-bodied method
public int GetHashCode() => id.GetHashCode();
```
```
See also:
What's the difference between anonymous methods (C# 2.0) and lambda expressions (C# 3.0)
What is a Lambda?
C# Lambda expression, why should I use this?
(And indeed many similar questions - try the
lambda
and
lambda-expressions
tags.)


q:
I've some experiences on build application with Asp.Net, but now MVC frameworks become more popular. I would like to try building new multilingual web application using with Asp.Net MVC or Castle MonoRail but I don't know which one is good for me. I don't like the web form view engine, but I like routing feature in Asp.Net MVC.

Could anyone tells about pros and cons between those?

Which ViewEngine is the better as well for overriding the master template?

[A]
MonoRail and ASP.NET MVC are fundamentally very similar, you should be well off using either one of them. MonoRail has existed much longer and has therefore more higher level features.
The main strength of ASP.NET MVC is it's routeing engine, to be fair MonoRail has pretty much an equivalent routing engine, and with some modification you can use the ASP.NET MVC routing engine with MonoRail as the routing engine is not really in ASP.NET MVC but in System.Web.Routing (Released in .NET 3.5 SP1). ASP.NET MVC and integration with Visual studio is also a plus, and will probably get better as we approach RTM of v1.
The MvcContrib project contains some great view engines, like Spark, NHaml and Brail. No one could be considered "Best", A personal favourite is Spark. For more on spark:
http://dev.dejardin.org/documentation/syntax
The WebForms engine has intellisense which is a great advantage that to my knowledge all alternative view engines lack.


q:
I'm a bit new to jQuery and hope somebody can help me out.

I'm trying to change an element (li) to another element (div) after the (li) has been dropped.

Sample code:

$("#inputEl>li").draggable({
    revert: true,
    opacity: 0.4,
    helper: "clone"
});
$("#dropEl")
    .droppable({
        accept: ".drag",
        hoverClass: "dropElhover",
        drop: function(ev, ui) {
            // change the li element to div here
        }
});

The problem is, when i use

drop: function(ev, ui) {
     $(ui.draggable).replaceWith("<div>Some content</div>");
}

the original draggable elements will be disabled when the function above is triggered.

I'm using the latest jQuery and jQuery UI stable versions.

[A]
So, what you want is to keep your original list intact and drop list items into dropEl?
How about this:
```
```
drop: function(ev,ui) {
     $(this).append("
Some content
");
}
```
```
Or, if you want to replace the list elements with a div element and also have the div element draggable, you could try this:
```
```
drop: function(ev, ui) {
        $(ui.draggable).replaceWith("
Some content
");
        $("#inputEl>div").draggable({
            revert: true,
            opacity: 0.4,
            helper: "clone"
        });
    }
```
```
The original draggable call only makes items draggable at the time it is called.  If you change or add elements and want them to be draggable, you will need to call the draggable() function again.


q: My organization is using CppUnit and I am trying to run the same test using different parameters. Running a loop inside the test is not a good option as any failure will abort the test. I have looked at TestDecorator and TestCaller but neither seems to really fit. Code samples would be helpful.

[A]
I'm not a C++ programmer but I can help with the unit-test concept:
Test-cases are meant to run isolated and with no dependency on external parameters. Additionally you should keep the number of test-cases down to the minimum which covers most of your code. There are cases, however (and I have already dealt with some), where some tests look the same, differing only by some minor parameters. The best bet then is to write a
fixture
which takes the parameter you're talking about, and then have one test-case for each of the parameters, calling the fixture with it. A generic example follows:
```
```
class MyTestCase

  # this is your fixture
  def check_special_condition(param)
    some
    complex
    tests
  end

  # these are your test-cases
  def test_1
    check_special_condition("value_1")
  end

  def test_2
    check_special_condition("value_2")
  end

end
```
```
Otherwise you're not writing true test-cases, because they're supposed to be reproducible without much knowledge from the one who is executing them. I imagine there are a handful of parameters which are all important as input to the tests. Then why not make each one explicit inside its own test-case? That's also the best way to document then, instead of writing a separate document to guide the programmer which will read the code years later.


q:
I have a Panel and I am adding controls inside this panel.  But there is a specific control that I would like to float. How would I go about doing that?

pnlOverheadDetails is the panel name

pnlOverheadDetails.Controls.Add(lnkCalcOverhead);

The control named lnkCalcOverhead is the control I'd like to float.

Thanks in advance

EDIT: By float I meant the css style not anything fancy :)

[A]
If you have a CSS class defined for the control, you could do this before calling the
```
Controls.Add
```
method:
```
```
lnkCalcOverhead.CssClass = "MyClass";
```
```
If you want to use the style attribute directly, try this:
```
```
lnkCalcOverhead.Style.Add("float", "left");
```
```


q:
I'm trying to create number of Evenement instances and set the date for them:

   for (int i=2004; i<2009; i++){
           evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
                           (Date)formatter.parse(i+"/07/03")));

But I can't seem to get it to work,

Any ideas?

[A]
You may want to use Calendar to create your dates.
```
```
for (int i=2004; i<2009; i++) {
    Calendar cal = Calendar.getInstance();
    cal.clear();
    // Calendar.JULY may be different depending on the JDK language
    cal.set(i, Calendar.JULY, 3); // Alternatively, cal.set(i, 6, 3);
    evenementen.add(new Evenement("Rock Werchter", "Rock", "Werchter", 200000,
            cal.getTime()));
}
```
```
Note that the months are zero-based, so July is 6.


q:
My website has been giving me intermittent errors when trying to perform any Ajax activities.  The message I get is

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.

Details: Error parsing near '

<!DOCTYPE html P'.

So its obviously some sort of server timeout or the server's just returning back mangled garbage.  This generally, unfortunately not always, happe

[A]
There is an excellent blog entry by Eilon Lipton. It contains of lot of tips on how to avoid this error:
Sys.WebForms.PageRequestManagerParserErrorException - what it is and how to avoid it
Read the comments too. There is a comment of somebody with the same problem: "
I solved it changing server idle time of my app pool on IIS
. It was only 5, so I incremented it and now works."
"The UpdatePanel control uses asynchronous postbacks to control which parts of the page get rendered. It does this using a whole bunch of JavaScript on the client and a whole bunch of C# on the server.
Asynchronous postbacks are exactly the same as regular postbacks except for one important thing: the rendering. Asynchronous postbacks go through the same life cycles events as regular pages (this is a question I get asked often).
Only at the render phase do things get different. We capture the rendering of only the UpdatePanels that we care about and send it down to the client using a special format. In addition, we send out some other pieces of information, such as the page title, hidden form values, the form action URL, and lists of scripts."
Most common reasons for that error:
Calls to Response.Write():
Response filters
HttpModules
Server trace is enabled
Calls to Server.Transfer()


q: We've all read the benchmarks and know the facts - event-based asynchronous network servers are faster than their threaded counterparts.  Think lighttpd or Zeus vs. Apache or IIS. Why is that?

[A]
I think event based vs thread based is not the question - it is a nonblocking Multiplexed I/O, Selectable sockets, solution vs thread pool solution.
In the first case you are handling all input that comes in regardless of what is using it- so there is no blocking on the reads- a single 'listener'.  The single listener thread passes data to what can be worker threads of different types- rather than one for each connection.  Again, no blocking on writing any of the data- so the data handler can just run with it separately.  Because this solution is mostly IO reads/writes it doesn't occupy much CPU time- thus your application can take that to do whatever it wants.
In a thread pool solution you have individual threads handling each connection, so they have to share time to context switch in and out- each one 'listening'.  In this solution the CPU + IO ops are in the same thread- which gets a time slice- so you end up waiting on IO ops to complete per thread (blocking) which could traditionally be done without using CPU time.
Google for non-blocking IO for more detail- and you can prob find some comparisons vs. thread pools too.
(if anyone can clarify these points, feel free)


q:
I am developing an application for PocketPC. When the application starts the custom function SetScreenOrientation(270) is called which rotates the screen. When the application closes the function SetScreenOrientation(0) is called which restores the screen orientation.

This way the screen orientation isn't restored if the user minimizes the application and this is not acceptable.

Does anyone know where (in which event handlers) should SetScreenOrientation(int angle) be called to set the screen orientation on application start, restore orientation on minimize, set the orientation on maximize and restore the orientation on close?

Actually I don't know which event handler handles the Minimize and Maximize event.

[A]
I don't know what these are called in the C++ world, but in .NET Compact Framework your application form's Resize event would be called when you minimize/maximize a window, and then in the event code you would check the WindowState property of the form to see if its minimized or mazimized.
Altering the state of your PDA from within your application is risky (although there are lots of good reasons to do it), because if your app crashes it will leave the PDA in whatever state it was in.  I've done a lot of kiosk-type (full-screen) apps in Windows Mobile, and one of the tricks to doing this effectively is to hide the WM title bar (the top row with the Windows start button) to keep it from flashing up for a split second every time you open a new form.  If the app crashes, the windows bar remains invisible until you reset the device, which isn't good.  At least with screen rotation the user can restore it manually.


q:
I would like to implement a sliding notification bar as the one in Firefox or IE for my java application. But I don't want to reinvent the wheel and I'm sure someone out there has already done it and is willing to share.
Do you know any open-source implementation of this in java/swing?

[A]
There's an example in
Swing Hacks
called "Slide Notes Out from the Taskbar" that seems pretty close to what you want (there's a
preview
on Google's Book Search at the moment).
The code is freely available from the
official O'Reilly Swing Hacks page
, under "examples."  Not sure what the license is, but it's worth a look (Chapter 6, hack 46).  At any rate, Swing Hacks is a worthy purchase at ~$20.


q:
Is it possible to retrieve variable set in onreadystatechange function from outside the function?

--edit--

Regarding execution of functions:

If its possible i would like to execute ajaxFunction()  with one click

 and then popup() with next click, or
somehow wait for ajax function to end and then call for alert box

In pseudocode:

function ajaxFunction(){
    //creating AJAX
    ...
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function (){
        if(ajaxRequest.readyState == 4){
            //success code
            ======>Here i want to set variable <=====
            var MyVariable='MyContent';
        }
    }
    //Retrieving page
    ....
}

function popup(){
    ajaxFunction();
    alert(MyVariable);
}

[A]
Why not change
```
MyVariable
```
's scope to outside of the function?
```
```
var MyVariable;
function ajaxFunction(){
    //creating AJAX
     ...
    // Create a function that will receive data sent from the server
    ajaxRequest.onreadystatechange = function (){
        if(ajaxRequest.readyState == 4){
            //success code
            ======>Here i want to set variable <=====
            MyVariable='MyContent';
        }
    }
    //Retrieving page
     ....
}

function popup(){
    ajaxFunction();
    alert(MyVariable);
}
```
```


q: What is the difference between HTML <input type='button' /> and <input type='submit' />?

[A]
```
<input type="button" />
```
buttons will not submit a form - they don't do anything by default. They're generally used in conjunction with JavaScript as part of an AJAX application.
```
<input type="submit">
```
buttons will submit the form they are in when the user clicks on them, unless you specify otherwise with JavaScript.
The first submit button of the form is also the one being clicked for
implicit submission
, f.e. by pressing enter in a text input.


q:
I have a query that works on Postgresql 7.4 but not on Postgresql 8.3 with same database.

Query:

SELECT * FROM login_session WHERE (now()-modified) > timeout;

Gets the following error:

ERROR:  operator does not exist: interval > integer
LINE 1: ...ELECT * FROM login_session WHERE (now()-modified) > timeout ...
                                                             ^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

Column modified is a timestamp and timeout is an integer.

Is there some settings I need to change on server?

I'm installing an application for a client on new server (ubuntu) so I can't change queries in the application.

[A]
There are a lot of changes between 7.4 and 8.3. Some of the most drastic were the removal of some automatic casts.
I suppose the "timeout" is in seconds? If so you could change the query to:
```
```
SELECT
    *
FROM
    login_session
WHERE
    (CURRENT_TIMESTAMP - modified) > (timeout * '1 sec'::interval);
```
```


q: What is the equivalent of Java's System.currentTimeMillis() in C#?

[A] The framework doesn't include the old seconds (or milliseconds) since 1970. The closest you get is DateTime.Ticks which is the number of 100-nanoseconds since january 1st 0001.


q: What do you use as a test client for your stateful web services? Is it possible to use SoapUI? Are there best practices in this area?

[A] I don't know whether it's practical to do this with SoapUI, but I've done things like this with both iTKO LISA and Parasoft SOATest.  It wasn't for testing stateful web services, but simply executing multiple testing steps, storing results that are used in following steps.  Both LISA and SOATest have the ability to define steps in the GUI that can store pieces of responses that are used in later requests.


q:
I'm trying to do something that gets a cs file in runtime from user make it meaningful to assembly get its properties, methods etc.

Is there a way to do this by reflection in C#?

[A]
You can compile it reasonably easily using the
CSharpCodeProvider
. You can download the source code for my snippet compiler, Snippy, from the
C# in Depth web site
. That uses CSharpCodeProvider, so you could use it as sample code.


q:
Lets say I have a web app which has a page that may contain 4 script blocks - the script I write may be found in one of those blocks, but I do not know which one, that is handled by the controller.

I bind some onclick events to a button, but I find that they sometimes execute in an order I did not expect.

Is there a way to ensure order, or how have you handled this problem in the past?

[A]
If order is important you can create your own events and bind callbacks to fire when those events are triggered by other callbacks.
```
```
$('#mydiv').click(function(e) {
    // maniplate #mydiv ...
    $('#mydiv').trigger('mydiv-manipulated');
});

$('#mydiv').bind('mydiv-manipulated', function(e) {
    // do more stuff now that #mydiv has been manipulated
    return;
});
```
```
Something like that at least.


q: I have a module that sends an email to a specified email address but I want to default the email recipient to the portal administrator.  How can I retrieve this information?

[A]
```
```
' get the current portal
Dim portSettings As PortalSettings = PortalController.GetCurrentPortalSettings

' get email address
Dim email as string = portSettings.Email
```
```


q:
I need to determine which pages of a Word document that a keyword occurs on.  I have some tools that can get me the text of the document, but nothing that tells me which pages the text occurs on.  Does anyone have a good starting place for me?  I'm using .NET

Thanks!

edit: Additional constraint: I can't use any of the Interop stuff.

edit2: If anybody knows of stable libraries that can do this, that'd also be helpful.  I use Aspose, but as far as I know that doesn't have anything.

[A]
This is how I get the text out,  I believe you can set set the selection range to a page, then you could test that text, might be a little backwards from what you need but could be a place to start.
```
```
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
object missing = Type.Missing;
object fileName = @"c:\file.doc";
object objFalse = false;

wordApplication.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
Microsoft.Office.Interop.Word.Document doc = wordApplication.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref objFalse, ref missing, ref missing, ref missing, ref missing);

//I belevie you can define a SelectionRange and insert here
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();

IDataObject data = Clipboard.GetDataObject();
string text = data.GetData(DataFormats.Text).ToString();

doc.Close(ref missing, ref missing, ref missing);
doc = null;

wordApplication.Quit(ref missing, ref missing, ref missing);
wordApplication = null;
```
```


q: I have SSRS Report being accessed from a Report Server. Is there any way I can give an error message of my own, if my report fails to open there?

[A]
You need to assign a Country instance to the Country property of the Person instance (not just set the ID).  Something like:
```
```
Person p = new Person();
p.Country = session.Load<Country>(countryId);
session.Save(p);
```
```
Then NHibernate will know what to do.  This will also not cause a DB hit to retrieve country, since the Load method will return a Country proxy and the only thing you're accessing is the Country instance's ID.


q:
I have a web server on port 80 and port 81. IE can connect to the server on either port. This worked fine until I installed an application with a file type (.TPJ) that had a MIME type of text/xml on the client PC. At that point IE no longer opened the web site, but offered to download a file serverName.TPJ. The file contained the correct information from the web site.

I changed the installer for the application so it didn't register the MIME type. Now IE on the client PC offers to download a file with unknown file type. Note that the application has never been installed on the server PC.

The problem occurs with IE7. It doesn't occur with Firefox, Safari, or Chrome.

Does anyone know how to work around this?

[A]
I found the answer. There is a left-over entry in the registry for the text/xml MIME type. It can be restored to the default value by re-registering the MSXML3.DLL.
```
```
regsvr32 msxml3.dll
```
```


q:
I'm trying to hide the "Title" field in a list.
This doesn't seem to work:

SPList myList;
...
SPField titleField = myList.Fields.GetField("Title");
//titleField.PushChangesToLists = true; <-- doesn't seem to make a difference
titleField.ShowInEditForm = false;
titleField.ShowInDisplayForm = false;
titleField.ShowInNewForm = false;
titleField.Update();
//myList.Update(); <-- make no difference

What am I doing wrong?

[A]
Make sure you are grabbing a
new
SPWeb instance.
```
```
using (SPSite site = new SPSite(webUrl))
{
    using (SPWeb web = site.OpenWeb())
    {
        try
        {
            //... Get SPList ...
        }
    }
}
```
```


q:
How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?

I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).

But, how do I do this in code?

[A]
This can be accomplished pretty easily with
Jquery
. You would add this to the onload:
```
```
$("div a[href^='http']").each(function() {
  $(this).attr("alt",altText);
  var oldClassAttributeValue = $(this).attr("class");
  if(!oldClassAttributeValue) {
   $(this).attr("class",newClassAttributeValue);
  }
});
```
```
You could modify this to add text. Class can also be modified using the
css
function.


q:
I would want to do something like:

>>> lst = [1, 2, 3, 4, 5]
>>> lst.find(lambda x: x % 2 == 0)
2
>>> lst.findall(lambda x: x % 2 == 0)
[2, 4]

Is there anything nearing such behavior in Python's standard libraries?

I know it's very easy to roll-your-own here, but I'm looking for a more standard way.

[A]
You can use the filter method:
```
```
>>> lst = [1, 2, 3, 4, 5]
>>> filter(lambda x: x % 2 == 0, lst)
[2, 4]
```
```
or a list comprehension:
```
```
>>> lst = [1, 2, 3, 4, 5]
>>> [x for x in lst if x %2 == 0]
[2, 4]
```
```
to find a single element, you could try:
```
```
>>> next(x for x in lst if x % 2 == 0)
2
```
```
Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch.  The () brackets make this a generator expression rather than a list comprehension.
Personally though I'd just use the regular filter/comprehension and take the first element (if there is one).
These raise an exception if nothing is found
```
```
filter(lambda x: x % 2 == 0, lst)[0]
[x for x in lst if x %2 == 0][0]
```
```
These return empty lists
```
```
filter(lambda x: x % 2 == 0, lst)[:1]
[x for x in lst if x %2 == 0][:1]
```
```


q:
Presently I have a some legacy code, which generates the op code. If the code has more number of macros then the code generation takes so much of time (In terms of hours!!).
I have gone through the logic, they are handling the macro by searching for it and doing a replace of each variable in it some thing like inlining.

Is there a way that I can optimize it without manipulating the string?

[A]
I have an application which has its own grammer. It supports all types of datatypes that a typical compiler supports (Even macros). More precisely it is a type of compiler which generates the opcodes by taking a program (which is written using that grammer) as input.
For handling the macros, it uses the text replacement logic
For Example:
Macro Add (a:int, b:int)
```
```
int c = a + b
```
```
End Macro
// Program Sum
..
int x = 10, y = 10;
Add(x, y);
..
// End of the program
After replacement it will be
// Program Sum
..
int x = 10, y = 10;
int c = x + y
..
// End of program
This text replacement is taking so much of time i.e., replacing the macro call with macro logic.
Is there a optimal way to do it?


q:
Hello I was writing a Regular Expression (first time in my life I might add) but I just can't figure out how to do what I want. So far, so good since I already allow only Letters and spaces (as long as it's not the first character) now what I'm missing is that I don't want to allow any numbers in between the characters...could anybody help me please?

/^[^\s][\sa-zA-Z]+[^\d\W]/

[A]
If you only want to allow letters and spaces, then what you have is almost correct:
```
```
/^[a-zA-Z][\sa-zA-Z]*$/
```
```
The
```
$
```
at the end signifies the end of the string.
Edited to correct answer, thanks to @Alnitak


q:
I am new to RESTful stuff.  But, I want to use it in my rails app.  When I add this to my routes.rb map.resources :notes I get routes to these methods created:

index

create

new

edit

show

update

destroy

What I am wondering is what is the difference between edit/update and create/new?  Is there any standard definitions of how these method pairs vary and what each one does?

[A]
When you use the scaffold generator in Rails 2
```
create
```
is the action called when the form from the
```
new
```
action is submitted.  Likewise,
```
update
```
is the action called when the form from the
```
edit
```
action is submitted.
As far as I know, you can blow that away and define them to do whatever you want depending on what
```
create/new/edit/update
```
means to your application.


q:
Does anyone know of a way to paste over a visually selected area without having the selection placed in the default register?

I know I can solve the problem by always pasting from an explicit register. But it's a pain in the neck to type "xp instead of just p

[A]
try -
```
```
:set guioptions-=a
:set guioptions-=A
```
```


q:
We have a major VB6 trading application which uses MS Access (Don't ask!) It is always blasting trades into an MS Access database.

The rest of the infrastructure here has moved on considerably and I want to read this Access database periodically and copy any new trades into a SQL server database.

The SQL and C# needed to do this is trivially easy.

BUT I want to make sure I do it in such a way that does not lock the Access database or cause problems for the VB6 app. In other words when populating my DataTable from Access I do NOT want to lock the database and prevent the VB6 app writing to it. I seem to remember from old ADO there were share modes you could use for this purpose.

What sort of connection string should I use from .NET to accomplish this?

[A]
Just an idea ... but have you thought about upgrading the database so that the tables themselves are actually stored in SQL Server and Access just become the front end?  It's been a little while, but if I remember correctly, Access should have a wizard (yuck!) to help you do this.
With old ADO you could set the cursor or lock type mechanism to one of the following:
Cursor Type
adOpenForwardOnly
This type of cursor can only be used to move forward through the recordset. This option is used when a list box or combo box is to be  populated.
adOpenKeyset
This is the best type of cursor to use when we expect a large recordset because we are not informed when changes are made to data that can affect our recordset.
adOpenDynamic
This cursor allows us to see all the changes made by other users that affect our recordset. It is the most powerful type of cursor but the slowest one.
adOpenStatic
The static cursor is useful when we have a small recordset.
Lock Type
adLockReadonly
This lock mode is used when no additions, updates or deletions are allowed from recordset
adLockPesimistic
In pessimistic locking, the record is locked as soon as editing begins and remains  locked until editing is completed.
adLockOptimistic
This occurs when the update method is called on the record. the record is unlocked even while edit but is temporarily locked when the changes are saved to the database
adLockBatchOptimistic
This option allows us to perform optimistic locking when we are updating a batch of records
Not sure how that exactly translates into the .NET world ... but maybe this can get you pointed in the right direction.


q:
I have a PHP script that processes file uploads. The script tries to organise the files that are uploaded and may create new folders to move the files into if needed. These files will be below the www root directory (ie, a web browser will be able to access them).

My question is, what permissions should I set for the folders that get created and for the files that are moved into them (using mkdir() and move_uploaded_file())?

[A]
Your webserver needs read and write permission in those folders, execute permission should be revoked (assuming UNIX-like systems). If not, a user could upload a script and have it executed by sending a HTTP request for it.
But IMO the whole concept is a potential security hole. Better store the files in a folder
outside
the webserver root, so that no direct acceess is possible. In your web application, you can have a PHP download page that scans the upload directory and displays a list of download links. These download links lead to another script, that reads the fiels from you storage dir und sends them to the user.
Yes, this is more work. But the scenario is very common, so you should be able to find some source code with example implementations easily. And it it much less work that having your server hacked...


q:
Let's say you got a file containing texts (from 1 to N) separated by a $
How can a slit the file so the end result is N files?

text1 with newlines $

  text2 $etc... $

  textN

I'm thinking something with awk or sed but is there any available unix app that already perform that kind of task?

[A]
Maybe
```
split -p
```
pattern
?
Hmm.  That may not be exactly what you want. It doesn't split a line, it only starts a new file when it sees the pattern.  And it seems to be supported only on BSD-related systems.
You could use something like:
```
```
awk 'BEGIN {RS = "$"} { ... }'
```
```
edit:
You might find some inspiration for the
```
{ ... }
```
part here:
http://www.gnu.org/manual/gawk/html_node/Split-Program.html
edit:
Thanks to comment from dmckee, but
```
csplit
```
also seems to copy the whole line on which the pattern occurs.


q:
I need an regular expression pattern to only accept positive whole numbers.  It can also accept a single zero.

I do not want to accept decimals, negative number and numbers with leading zeros.

Any suggestions?


q:
It's a tricky question I was asked the other day... We're working on a pretty complex telephony (SIP) application with mixed C++ and PHP code with MySQL databases and several open source components.

A telecom engineer asked us to estimate the performance of the application (which is not ready yet). He went like 'well, you know how many packets can pass through the Linux kernel per second, plus you might know how quick your app is, so tell me how many calls will pass through your stuff per second'.

Seems nonsense to me, as there are a million scenarios that might happen (well, literally...)

However... is there a way to estimate application performance (knowing the hardware it will run on, being able to run standard benchmarks on it, etc) before actual testing?

[A]
You certainly can bound the problem with upper (max throughput) limits.  There is nothing nonsense about that.  In fact, not knowing that stuff indicates a pretty haphazard approach to a problem - especially in the telephony world.
You can work through the problem yourself - what is the minimum "work" you have to accomplish for a transaction or whatever unit of task you have in your app?
Some messages to and from, some processing and a database hit for example? Getting information on the individual pieces will give you an idea of the fastest possible throughput. If you load up the system and see significantly lower performance then you can take time to figure out where you are possibly losing throughput with inefficient algorithms, etc.
EDIT
To do this exercise you need to know all the steps your app does for each use case. Then you can identify the max throughput for each use case. You should definitely know this stuff prior to release and going live.
I'm ignoring the worst case analysis as that - as you point out - is quite a bit harder.


q: What im wondering how to do is when someone edits a list item and it goes through my event code that is fired when a change is made and save is hit, i dont want anyone to be able to edit that list item itself while its still processnig that request. So i was wondering if while in that event i can disable the individual item from being edited by someone else untill it is done doing what it is doing.

[A]
Not sure if I understand exactly what you are want.
Try adding a field, hidden if you like, to the list or content type to use as a flag. When you enter your event code, make sure you check the flag first and if not set, set it and do your stuff. After you have done your stuff, unset the flag.
Here is some code to illustrate. Note that I have used a column named "updating". You can use the properties of the SPListItem as well if you do not care to add a column.
Oh, and don't forget to call DisableEventFiring before you to SPListItem.Update and then EnableEventFiring() afterwards. For get this and you will have a very nasty infinite loop on your hands.
.b
```
```
public override void ItemAdding(SPItemEventProperties properties)
    {
        if (properties.ListItem["updating"].ToString() == "updating")
        {
            properties.Cancel = true;
            properties.ErrorMessage = "Item is currently updating, please try again later";
        }
        else
        {
            properties.ListItem["updating"] = "updating";
            this.DisableEventFiring();
            properties.ListItem.Update();
            this.EnableEventFiring();

            // do your stuff

            properties.ListItem["updating"] = "";
            this.DisableEventFiring();
            properties.ListItem.Update();
            this.EnableEventFiring();
        }
    }
```
```


q:
Similar to this question, but for VB.NET since I learned this is a language thing.

For instance, would the compiler know to translate

Dim s As String = "test " + "this " +
  "function"

to

Dim s As String = "test this function"

and thus avoid the performance hit with the string concatenation?

[A]
While I'm looking it up,
here's the download page for the spec
.
Section 11.2 looks like it
would
be the right bit - it's basically the equivalent of 7.18 in the C# 3.0 spec - but it doesn't contain the same guarantee. I suspect the compiler still does it, but I can't see any guarantee. I'll have another look though.
Section 11.2 does state that "A constant expression is an expression
whose value can be fully evaluated at compile time
" (my emphasis) but I can't see that it actually guarantees that it
will
fully evaluate it at compile time. Frankly it would be odd to make a category of expression based on this condition but not actually use it.
A quick test shows that the current VB compiler does indeed do the concatenation at compile time, but there really
should
be a guarantee in the spec if that's the intention.
Section 7.3 get a bit closer:
When the operands of an expression are
  all primitive type constants, it is
  possible for the compiler to evaluate
  the expression at compile time. Such
  an expression is known as a constant
  expression.
Now String isn't a primitive type in terms of the CLR (
Type.IsPrimitive
would return false) but it
is
in terms of the VB spec.
It's still not saying that it
will
evaluate it though...


q: How can I validate a username and password against Active Directory? I simply want to check if a username and password are correct.

[A]
Probably easiest way is to PInvoke LogonUser Win32 API.e.g.
http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html
MSDN Reference here...
http://msdn.microsoft.com/en-us/library/aa378184.aspx
Definitely want to use logon type
```
```
LOGON32_LOGON_NETWORK (3)
```
```
This creates a lightweight token only - perfect for AuthN checks.  (other types can be used to build interactive sessions etc.)


q:
I want to write a script that will stop a scheduled task on a remote computer, do some stuff, and then start the schedule task back up.

How can I do it?

[A]
Note:
"schtasks"
(see the other, accepted response) has replaced
"at"
.  However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
```
C:\>at /?
The AT command schedules commands and programs to run on a computer at
a specified time and date. The Schedule service must be running to use
the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\\computername     Specifies a remote computer. Commands are scheduled on the
                   local computer if this parameter is omitted.
id                 Is an identification number assigned to a scheduled
                   command.
/delete            Cancels a scheduled command. If id is omitted, all the
                   scheduled commands on the computer are canceled.
/yes               Used with cancel all jobs command when no further
                   confirmation is desired.
time               Specifies the time when command is to run.
/interactive       Allows the job to interact with the desktop of the user
                   who is logged on at the time the job runs.
/every:date[,...]  Runs the command on each specified day(s) of the week or
                   month. If date is omitted, the current day of the month
                   is assumed.
/next:date[,...]   Runs the specified command on the next occurrence of the
                   day (for example, next Thursday).  If date is omitted, the
                   current day of the month is assumed.
"command"          Is the Windows NT command, or batch program to be run.
```


q:
I'm thinking of forming a Hackers Club at work.  My idea is that we would meet monthly and at each meeting one member would present an interesting hack he had created.  (The hacks presented wouldn't necessarily have to be software hacks; they could also be the sort of things you read about in MAKE magazine.)

There would also be ANSI standard pizza, veggie pizza, and beer and pop available for socializing afterward.  I'm even thinking of calling the club "TMRC" even though it will have nothing to do with model railroads.

Has anyone ever tried doing something like this or have any advice?

[A]
We do this at the office. I call it 'Developer Fight Club'
Usually do challenges of varying difficulty and compete against one another.
At the end of it, we go over our solutions, do code-reviews and discussions, and then use either benchmark results or other people as the deciding factor for who wins.
Typically, the loser has to buy lunch for the winner :)
For ideas of things to do, try stuff from
Top Coder
, programming questions on Stack Overflow, or even simple "
crackme
" applications available on different programming sites.
The main rules you'll need to adhere to are:
Make It Fun
Make It Educational Make
Make It Fair
Try to rotate the challenges, so either everyone is really good at the subject, equally bad, or at least mix it up often enough that it doesn't favor one person's skillset too much.


q:
I would like to begin developing for the Blackberry platform and, specifically, the Bold and also the Storm device which is coming out soon.  Do I need to get into Java and J2ME or can I develop sites in ASP.NET and just keep utilizing the skills I already have?

I am completely new to mobile platform development and have no idea what it will take to target these Blackberry devices.  I am hoping to continue to use my ASP skills.

[A]
Are you talking about websites (because you say "develop sites in ASP.NET") or native Blackberry applications (because you say "developing for the Blackberry platform")?
Applications which run on the Blackberry use J2ME. If your application is accessed from a browser on the Blackberry, then it's the server the web app runs on that determines the language, not that it's being accessed from the Blackberry browser.
Then there's Blackberry MDS for integration with enterprise apps. I don't know much about this (never used it or seen an application that uses it) but it's described here:
http://na.blackberry.com/eng/services/mobile.jsp
Paul


q:
For both .NET Winforms and Windows Presentation Foundation, if I have a text box that the user has just entered text into, and a button, if the user clicks the button the "LostFocus" event fires before the button click event fires.  However if the user uses a keyboard shortcut for the button (e.g. Button's text is "&Button" or "_Button" and user performs Alt+B), then the "LostFocus" event fires after the button click event, which is less useful.

Do you know of reasonable workarounds?  We have various things that we want to occur in LostFocus before ButtonClick.

[A]
What would happen if you did this first of all in the button handler? (or perhaps subclass the button and override OnClick to apply this logic "worldwide").
```
```
Button b = (Button) sender;
b.Focus();
```
```
Would that get round the issue?


q:
I have a table which has a field sort_id. In this field there are numbers from 1 to n, that define the order of the data sets.
Now I want to delete some elements and afterwards I want to reorder the table. Therefore I need a query that "finds" the gaps and changes the sort_id field according to the modifications.

Sure, I could do something like this:

SELECT sort_id FROM table WHERE id = 5

Then save the sort_id and afterwards:

DELETE FROM table WHERE id = 5
UPDATE table SET sort_id = sort_id - 1 WHERE sort_id > {id from above}

But I'd like to do the reordering process in one step.

[A]
for sql server 2005:
this is how you get the new sequence:
```
```
SELECT row_number() over(order by sort_id) as RN
FROM table
```
```
updating the table means you should join that select to your update:
```
```
update t1
set sort_id = t2.RN
FROM table t1
     join (SELECT row_number() over(order by sort_id) as RN FROM table) t2
        on t1.UniqueId = t2.UniqueId
```
```


q:
I feel like I'm re-inventing the wheel here, but I need to find a way of taking a URL from a catchall,and redirecting that to another route.

The reason for this is because I need to do some things like adding session cookies for certain urls, and then pass them on to their relevant action.

What's the best way of implementing this?

Thanks in advance for any help!

[A]
If I understand question...
Looking at your previous question (
redirect-to-controller-but-with-a-different-master-using-a-catchall-wildcard
) you want to take the wildcard from:
```
```
routes.MapRoute(
    "Partner",
    "partners/{partner}/{*wildcard}",
    new { controller = "Partners", action = "PartnerRedirect" }
);
```
```
And in the Partners/PartnerRedirect action, send it to the right controller/action specified in the wildcard?
I have no idea the best way to do this, but looking at ways to unit test url routing brought up this:
http://weblogs.asp.net/stephenwalther/archive/2008/07/02/asp-net-mvc-tip-13-unit-test-your-custom-routes.aspx
I'm not sure if it is an exact fit (ie. might not have to mock stuff), but it looks like all the data is returned from GetRouteData to pass to RedirectToAction method.


q:
We're looking to encrypt a field using DB-side encryption via NHibernate (most examples we've come across are app-side, which is not what we would like). The issue has been raised a couple of times, but no answers yet it seems.

On SQL Server 2005, for instance, and forgetting key-related issues for now, this means INSERTing EncryptByKey(Key_GUID(MyKey), MyValueToEncrypt) and SELECTing DecryptByKey(MyEncryptedField). The property might be a string, whereas the field has to be a varbinary.

We've vaguely got somewhere - using upper() and lower() instead of encryption functions - by combining paired properties, one mapped with a custom user type and the other with a formula attribute.

However if anyone has any ideas on how to do this in a nicer way, we'd be most grateful for a few pointers :o)

[A]
There is a project on SourceForge, MindLib, that has useful NHibernate utility functions and libraries.  One of those is an EncryptedString library which allows you to store an encrypted string.  Unfortunately, this is not doing it on the server side, as you originally requested.
I've been looking for something similar.  The only thing I could come up with is to create a User Function in SQL Server to encrypt the string.  Something like
this
.
MindLib EncryptedString


q:
I have a list of n GUIDs and I need to hash them into a single value.  This value could be the size of a Guid object or the size of an Int32, it doesn't really matter, but it does need to be statistically unique (say with a probably similar to MD5).

So one approach could be to sort them, concatenate the bytes and take an MD5 hash of all the bytes... but this isn't very quick.

Another idea: I notice that it is fairly standard practice in .NET to implement the GetHashCode method of a composing object as the XOR of the hash codes of the composed objects.  Therefore could it be mathematically sensible to XOR my list of GUIDs?

Any ideas welcome!

[A]
If you want the hash to be valid for the
set
(i.e. order doesn't matter) then XORing the hashcode of each GUID is a good choice.
If you've actually got a
sequence
of GUIDs and the order matters then I'd suggest using the same approach I wrote about
in another answer
- repeatedly add/multiply.
(Note that XORing the hashcodes probably won't get you the same answer as XORing the GUIDs themselves and then hashing the result. It may be, but that depends on the implementation of GUID.GetHashCode(). I'd hash each value and XOR the results together - aside from anything else, that's trivial to implement.)


q:
My stored procedure has an output parameter:

@ID INT OUT

How can I retrieve this using ado.net?

using (SqlConnection conn = new SqlConnection(...))
{
    SqlCommand cmd = new SqlCommand("sproc", conn);
    cmd.CommandType = CommandType.StoredProcedure;

    // add parameters

    conn.Open();

    // *** read output parameter here, how?
    conn.Close();
}

[A]
Not my code, but a good example i think
source:
http://www.eggheadcafe.com/PrintSearchContent.asp?LINKID=624
```
```
using System;
using System.Data;
using System.Data.SqlClient;

class OutputParams
{
    [STAThread]
    static void Main(string[] args)
    {

    using( SqlConnection cn = new SqlConnection("server=(local);Database=Northwind;user id=sa;password=;"))
    {
        SqlCommand cmd = new SqlCommand("CustOrderOne", cn);
        cmd.CommandType=CommandType.StoredProcedure ;

        SqlParameter parm= new SqlParameter("@CustomerID",SqlDbType.NChar) ;
        parm.Value="ALFKI";
        parm.Direction =ParameterDirection.Input ;
        cmd.Parameters.Add(parm);

        SqlParameter parm2= new SqlParameter("@ProductName",SqlDbType.VarChar);
        parm2.Size=50;
        parm2.Direction=ParameterDirection.Output;
        cmd.Parameters.Add(parm2);

        SqlParameter parm3=new SqlParameter("@Quantity",SqlDbType.Int);
        parm3.Direction=ParameterDirection.Output;
        cmd.Parameters.Add(parm3);

        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();

        Console.WriteLine(cmd.Parameters["@ProductName"].Value);
        Console.WriteLine(cmd.Parameters["@Quantity"].Value.ToString());
        Console.ReadLine();
    }
}
```
```


q:
Where can I setup custom errors for directories in my application such as App_Code, App_Browsers, etc.?  I already have customErrors configured in the web.config and that works as expected.  For example,

http://www.mysite.com/bla.aspx > redirects to 404 page

but

http://www.mysite.com/App_Code/ > displays "The system cannot find the file specified."

There's no physical App_Code directory for my site.  Is this something that I can change in IIS?

[A]
One way is to provide a redirect in the global.asax file:
```
```
void Application_Error(object sender, EventArgs e)
{
    //uncomment this to narrow down 'helpful' microsoft messages
    //HttpRequest request = ((HttpApplication)sender).Context.Request;

    Exception ex = Server.GetLastError();
    //ErrorManager is a custom error handling module
    ErrorManager.ProcessError(ex);
    Response.Redirect("~/error.aspx?error=" + HttpUtility.UrlEncode(ex.Message), true);
}
```
```
{ On a side note, I was getting an exception that I just couldn't track down - it just said 'file not found' but didn't say which file was missing. It turned out to be a broken image reference in a css file - breaking on line two of the code above helped identify the missing file }


q: It seems like v2 of Log4j has been in development for literally years.  The Apache Log4J site no longer lists a roadmap, the dev mailing list seems almost entirely about 1.2 (which is appreciated!), use of v1.3 is discouraged, and the 2.0 branch is listed as "experimental".  What's a believer to believe?

[A]
Well then I guess you already answered your own question, the devs have obviously stopped focusing on 2.0 builds a long time ago and have instead decided to continue the 1.x codebase.
And if you are on their mailing list, then ask them, the source of the issue.


q:
how do i insert items into an html listbox from a database?
im using asp c#. i cant make the listbox run at server because the application wont work if i do that. so i have to insert values from a database into an html listbox. I just need to display 1 column of data. cheers..

[A]
There are two ways of doing this I can think of:
First, you can place an
```
<asp:Placeholder />
```
tag on the page and generate the listbox in code:
```
```
var select = new HtmlSelect() { Size = 5 };

//assuming the data has been placed in an IEnumarble
foreach (var item in items)
{
    select.Items.Add(new ListItem() { Value = item });
}
selectPlaceholder.Controls.Add(select);
```
```
Second, you could create a WebService or ashx handler to provide the data and populate the list from javascript.