q:
I have created a class to dynamically put together SQL function statements within a project. I have found this class to be pretty useful and would like to incorporate into future projects

namespace connectionClass

{

 public class connClass

 {

     NpgsqlConnection conn = new NpgsqlConnection(projectName.Properties.Settings.Default.ConnString);

 }

}

I want to be able to dynamically input the project name without having to do it myself for every different class! the connection string will be defined within the properties settings in VS.

Any help would be greatly appreciated:)

[A]
One option is to have the connection class use the ConfigurationManager to get the name from the App.Config file - but this still means setting the name in there. Something like
```
```
ConfigurationManager.AppSettings["PROJECT_NAME"];
```
```


q: Is there an easy way within C# to check to see if a DateTime instance has been assigned a value or not?

[A]
The only way of having a variable which hasn't been assigned a value in C# is for it to be a local variable - in which case at compile-time you can tell that it isn't definitely assigned by trying to read from it :)
I suspect you really want
```
Nullable<DateTime>
```
(or
```
DateTime?
```
with the C# syntactic sugar) - make it
```
null
```
to start with and then assign a normal
```
DateTime
```
value (which will be converted appropriately). Then you can just compare with
```
null
```
(or use the
```
HasValue
```
property) to see whether a "real" value has been set.

s: huggingface

c: devops

d: intermediate


q: Yes we're talking about ASCII codes. My appologies I'm not the Delphi dev here.

[A]
It depends what your definition of conversion is. If you want to map the 127 lowest characters to the Unicode equivalent, you can use an explicit cast. But this creates garbage if the string contains higher characters.
If you want mappings like ë -> e and û -> u, you can write your own code. But be aware that there are always characters that can't be converted.


q:
We have two web servers with load balancing. We need to share some files between those servers. These would be uploaded files, session files, various files that php applications create.

We don't want to use a heavyweight, no longer maintained or a commercial solution. We're looking for some lightweight open-source software that would work as shared file system. It should be really easy to set up, must be HA available, must be very fast. It should work with RedHat Linux.

We looked at such solutions like drbd with synchronous file sharing but we can't use them because it can't work on an underlying filesystem like ext3.

[A]
DRBD is good for syncing over a network (direct crossover connection if at all possible), but EXT3 is not designed to be aware of changes that occur underneath it, at the block device level. For that reason you need a filesystem designed for such purposes such as the Global File System (GFS). To the best of my knowledge Red Hat has support for GFS.
The DRBD manual will give you an overview of how to use GFS with DRBD.
http://www.drbd.org/users-guide/ch-gfs.html
Don't take this as a final answer - I have not researched or used a multi-master system  before, but at least this might give you something to go on.
Ideally, you would only sync the part of the data that's shared between the webservers.


q: I am putting together a build system and wanted to know if there is a reliable way to find out if a checked out SVN folder needs updating (i.e. is it out of sync with the repository).  I want to avoid a nightly build unless something has changed.  I could write a script that parses the results of the svn update command I guess, but I wondered if there as a command that would tell me if an update is actually required?

[A]
Use the
show updates option
of the status command:
```
```
svn status -u
```
```
or
```
```
svn status --show-updates
```
```


q:
I have an Informix SQL query which returns a set of rows. It was slightly modified for the new version of the site we've been working on and our QA noticed that the new version returns different results. After investigation we've found that the only difference between two queries were in the number of fields returned.

FROM, WHERE and ORDER BY clauses are identical and the column names in the SELECT part did not affect the results. It was only the number of fields which caused the problem.

Any ideas?

[A]
Adding
```
--+ ORDERED
```
join-order directive fixes the problem by allowing you to get your results in predictable order each time.
The links goes to the description of how the directive works
http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls.doc/sqls1144.htm
Use the ORDERED join-order directive
  to force the optimizer to join tables
  or views in the order in which they
  appear in the FROM clause of the
  query.
```
```
SELECT --+ ORDERED
   name, title, salary, dname
FROM dept, job, emp WHERE title = 'clerk' AND loc = 'Palo Alto'
   AND emp.dno = dept.dno
   AND emp.job= job.job;
```
```


q:
I am using iText to generate PDF invoices for a J2EE web application and included on the page is an image read from a URL constructed from the request URL. In the development and test environments this works fine, but in production I get a java.io.IOException:  is not a recognized imageformat.

If I paste the url into my browser then the correct image is returned, however the request is redirected from http to https. In my code if I hard code the redirect URL then the image is displayed correctly.

So it seems that when retrieving the image using com.lowagie.text.Image.getInstance(URL), the redirects on the URL are not being followed. How can I output an image from a redirected URL using iText?

[A]
Is there a reason you have to get this using the URL??  Do you have to match the image that the url is pointing to?  What if it changes or gets removed?
I am not sure of your requirement, but it may be easier to save the image from the url and place it somewhere within your project.  Then you can add it to your pdf with:
```
```
Image.getInstance("yourimage.gif");
```
```


q:
Okay i am working on someone elses code. They do alot of this:

char description[256];
description[0]=0;

I know this would put a \0 in the first spot of the character array. But is this even a safe way to erase a string?

Also visual studio keeps reporting memory leaks, and i've pretty much tied this done to the strings that are used.

Ps. Yes i know about std::string, yes i use that. This isn't my code.

[A]
This string is allocated on the stack, so there's no way to free the memory it uses until the function that it's called in returns (when it will happen automatically). Unless you're calling this function recursively*, there's no way this will end up being a memory leak, because once the function returns the space is used for future stack frames. And if you're concerned about security, you should just loop through and zero out the elements of the string.
If you want a free()-able memory block, you could do the following and allocate the array on the heap:
```
```
char *str = malloc(256*sizeof(char)); // str now is a pointer to a 256-char array
...
// some code here
...
free(str); // free the memory
```
```
*this is not an acutal memory leak, but some people say "memory leak" when they mean "run out of memory". In any case, stack space is much more limited than heap space, so you have to watch the size of memory blocks you use there.


q:
Is there an Iterator implementation that merges multiple iterators?

class MergedIterator<T> implements Iterator<T>
{
     MergedIterator(Iterator<T>... iters)
     ....
}

And the next method should move on to iters[1] when !iters[0].hasNext() etc

[A]
I'd call that a ConcatenatedIterator myself - a MergedIterator should merge the results of several iterators e.g. based on sorting
Naming aside, I'm sure there'll be an implementation in a 3rd party library somewhere. Just off to check
Google collections
...
EDIT: Bingo -
Iterators.concat


q:
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list.
In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do

type(X) in (list, tuple)

but there may be other sequence types I'm not aware of, and no common base class.

-N.

Edit: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.

[A]
I think what I would do is check whether the object has certain methods that indicate it is a sequence.  I'm not sure if there is an official definition of what makes a sequence.  The best I can think of is, it must support slicing.  So you could say:
```
```
is_sequence = '__getslice__' in dir(X)
```
```
You might also check for the particular functionality you're going to be using.
As pi pointed out in the comment, one issue is that a string is a sequence, but you probably don't want to treat it as one.  You could add an explicit test that the type is not str.


q:
For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands:

.tables
.dump

using the Python sqlite3 API.

Is there anything like that?

[A]
I'm not familiar with the Python API but you can always use
```
```
SELECT * FROM sqlite_master;
```
```


q: Is there any way to have a reset button in the SSRS parameter window?

[A]
No, or i haven't heard how to do it. But you can simulate it.
One way to do this is to create a textbox that has an action set to jump to itself. You can or jump to the default values, or jump to itself with some parameters already assigned.


q:
I am writing an unit test for a mvc web application that checks if a returned list of anonymous variables(in a jsonresult) is correct. therefore i need to iterate through that list but i cannot seem to find a way to do so.

so i have 2 methods

1) returns a json result . In that json result there is a property called data. that property is of type object but internally it's a list of anonymous variables

2) the method calls method 1 and checks if the returned jsonresult is ok.

if i run the test and i break the debugger i can hover over the result and see the items in it. i just don't find a way to do so in code.(just using a foreach isn't possible because at the point i need it i'm not in the method that created the anonymous method)

[A]
I think you mean "anonymous type" everywhere you've said "anonymous variable" - but you can still iterate over the list with
```
foreach
```
, just declaring the iteration variable as type
```
object
```
:
```
```
foreach (object o in myList)
{
    // Not sure what you're actually trying to do in here...
}
```
```
If you need to check the contents, you can use the fact that anonymous types override
```
ToString
```
in a useful way. Your test can check the result of projecting each element to a string. Indeed, you could convert your result object to a sequence of strings quite easily:
```
```
var strings = ((IEnumerable) result).Cast<object>.Select(x => x.ToString());
```
```
Then test
```
strings
```
possibly using
```
SequenceEqual
```
.


q: How do I accomplish text wrapping of table fields in SSRS Report, and proper landscaping when rendering the report to PDF format?

[A]
To ensure line breaks are inserted correctly, use
```
```
=Replace(Fields!MyField.Value, vbLf, Environment.NewLine)
```
```
Set CanGrow = True.


q:
If any one can help me with Python code:
If I input a letter, How can I print all the words start with that word?

[A]
There are many ways of doing this, e.g.:
```
```
words = ["zwei", "peanuts", "were", "walking", "down", "the", "strasse"]
letter = "w"
output = [x for x in words if x[0] == letter]
```
```
The contents of
```
output
```
will be:
```
```
['were', 'walking']
```
```
Some notes:
If the code needs to be
fast
you should put the wordlist in some kind of tree.
If you need more flexibility, you should build a regular expression for matching


q: I am starting a normal Java SE project and i am planning to use JPA/Hibernate. I was wondering if anyone could enlighten me as to what is considered the best way to interact with Hibernate in this environment (data access layers)?

[A]
I'm not sure what's considered the best approach to this, but at my workplace, we have based most of our Hibernate interaction on these articles:
Don't let Hibernate steal your identity
and
Generic Data Access Objects
They show you how to make your mapped classes in a smart way, and how to implement a generic DAO that can be reused for any persistent class. This has worked out nicely for us.


q:
I need to upload a file using C# from a windows mobile app to a website. It's running PHP as the webservice on the other side, though I guess it really doesn't have to if there's another way to be able to get the file up there. There is no server-side ASP support, however. My problem really isn't the PHP, it's the mobile C# code.

Also, System.net.WebClient does NOT exist in the compact framework, so unfortunately, that simple solution is gone.

Let me apologize in advance, because I know this is a relatively commonly asked question, but I just can't seem to find an answer. I've spent an unseemly amount of time on this one particular problem with no solution, so any help at all would be greatly greatly appreciated. Thanks a lot!

[A]
Have a look at this article
Improving .NET Compact Framework HTTP Communications using HttpWebRequest and Custom ASP.NET Providers
in MSDN. It is specific for ASP technology,
but the Compact Framework remains the same. Basically it uses an HttpWebRequest with a PUT method. If you aren't allowed to do so in the server, you need to create a sequence of POST requests yourself and handle them accordingly.


q:
Is there a way to query the current DATEFORMAT SQLServer 2005 is currently using with T-SQL?

I have an application that reads pregenerated INSERT-statements and executes them against a database. To make the data to be inserted culture independent I store datetime-values represented in the invariant culture (month/day/year...) . The database server may run under different locales, depending on the system locale (maybe using day/month/year) , so the insert may crash because the datetime cannot be parsed.

I know there are the "SET LANGUAGE" and "SET DATEFORMAT" statements in T-SQL to set the locale to be used.

I do not want to make these changes permanent (are they permanent?), so I'm looking for a way to read the DATEFORMAT from the DB, store it, change the format to my liking and reset it to the stored value after the data has been inserted.

Any ideas where to find that value in the server?

[A]
Set Language and Set DateFormat only affect the current session.  If you Disconnect from the database and connect again, the language and Dateformat are set back to their default values.
There is a 'trick' you could use to determine if the DateFormat is m/d/y, or d/m/y.
```
```
Select DatePart(Month, '1/2/2000')
```
```
This date is valid either way.  It's Jan 2, or Feb 1.  If this query returns a 1, then you have MDY.  If it returns a 2, you have DMY.


q:
I have a program in which the user adds multiple objects to a scene. These objects are all represented as a classes.
Now I want the user to be able to save the scenario, so it can be loaded again.

Is there some genereic save method I can use, or do I have to write my own that saves the values of all properties and such and then create new objects and insert the saved values into them when the user loads the scenario again.

/P

Edit: Thanks for the quick replys guys.
I'm actually storing default values for the objects in a SQL compact 3.5 database right now. So if anyone knows how to serialize to SQL, that would be great info.

Edit 2: Thanks again! I'm going to serialize to xml, then store it as a string to the SQL database.

[A]
Usually one would use a database to do this kind of thing. That's probably the recommended practise.
However if you want a quick and dirty method you can serialise to Xml or Binary with relatively little code. Check out the System.Runtime.Serialization stuff. The trade-off of Xml or Binary is that versioning sucks big time.
Consider a collection of xml files containing objects from your 1.0 app. If you've added fields to those objects since 1.0 then they wont be compatible with any new 1.1 objects. To get around this you have to write a manual update sequence from type 1.0 -> 1.1. Even worse if you use autodiscovery code (which automatically serialises) such as they xml or binary serializer you may even have to name your objects different names Product1 / Product1.1 / etc, it's either that or write your own serialisation code.
If your app starts approaching any level of seriousness I'd say you'll probably want to use a database. SqlLite is very nice and simple for 1 user apps, anything bigger and you'll want a proper RDBMS.


q:
Access can open DBF (dBase) files, but instead of physically converting the data into MDB format, it has the ability to link to the DBF table itself. This way the DBF is "linked" to the MDB.

Is it possible to attach a DBF file in such manner using C#?

Edit: I would like to use Jet and avoid using MS Access directly.

[A]
Perhaps this code from
How to quickly copy tables from an ODBC source to MS Access within a C# project
might help:
The VB function you’ll need to put
  into MS Access is quite simple, and
  basically calls the TransferDatabase
  method by passing it a DSN (pointing
  to the source database), a source
  table name and target table name. The
  code is as follows:
```
```
Public Function Import(dsnName As String, sourceTableName As String, targetTableName As String)
‘ if the table already existsm, delete it.
   On Error GoTo CopyTable
   DoCmd.DeleteObject acTable, targetTableName
CopyTable:
   DoCmd.TransferDatabase _
   acImport, _
   "ODBC Database", _
   "ODBC;DSN=" + dsnName, _
   acTable, _
   sourceTableName, _
   targetTableName
End Function
```
```
Changing the VBA to read acLink rather than acImport should allow linking.
And then the C# code:
```
```
object accessObject = null;
try
{
   accessObject = Activator.CreateInstance(Type.GetTypeFromProgID("Access.Application"));

   accessObject.GetType().InvokeMember(
      "OpenCurrentDatabase",
      System.Reflection.BindingFlags.Default  System.Reflection.BindingFlags.InvokeMethod,
      null,
      accessObject,
      new Object[] { "AccessDbase.mdb" });

   accessObject.GetType().InvokeMember(
      "Run",
      System.Reflection.BindingFlags.Default  System.Reflection.BindingFlags.InvokeMethod,
      null,
      accessObject,
      new Object[] { "Import", "DSN Name", "Source table name", "Target table name" });

   accessObject.GetType().InvokeMember(
      "CloseCurrentDatabase",
      System.Reflection.BindingFlags.Default  System.Reflection.BindingFlags.InvokeMethod,
      null,
      accessObject,
      null);

   MessageBox.Show("Copy succeeded.");
}
catch (Exception ex)
{
   string message = ex.Message;
   while (ex.InnerException != null)
   {
      ex = ex.InnerException;
      message += "\r\n----\r\n" + ex.Message;
   }
   MessageBox.Show(message);
}
finally
{
   if (accessObject != null)
   {
      System.Runtime.InteropServices.Marshal.ReleaseComObject(accessObject);
      accessObject = null;
   }
}
```
```
Edit re comments
I cannot help with c#, but here is some VBScript that links a table from
one MDB to another.
```
```
strLinkFile = "C:\Docs\Link.mdb"
strAccessFile = "C:\Docs\LTD.mdb"

'Create Link... '
Set cn = CreateObject("ADODB.Connection")
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
       "Data Source=" & strAccessFile & ";" & _
       "Persist Security Info=False"

Set adoCat = CreateObject("ADOX.Catalog")
Set adoCat.ActiveConnection = cn

Set adoTbl = CreateObject("ADOX.Table")

Set adoTbl.ParentCatalog = adoCat
adoTbl.Name = "LinkTable"

adoTbl.properties("Jet OLEDB:Link Datasource") = strLinkFile
adoTbl.properties("Jet OLEDB:Link Provider String") = "MS Access"
adoTbl.properties("Jet OLEDB:Remote Table Name") = "Table1"
adoTbl.properties("Jet OLEDB:Create Link") = True

'Append the table to the tables collection '
adoCat.Tables.Append adoTbl
```
```
It is modified from:
http://support.microsoft.com/kb/240222


q:
This question exists because it has
  historical significance, but it is not
  considered a good, on-topic question
  for this site, so please do not use it
  as evidence that you can ask similar
  questions here.

More info: https://stackoverflow.com/faq

Anyone knows if it's possible to find all A records, CNAME or subzone records configured for a domain name?

For example, domain.com:

www IN CNAME domain.com.
subdomain1 IN CNAME domain.com.
subdomain2 IN CNAME domain.com.

subdomain1 IN A 123.4.56.78.
subdomain2 IN A 123.4.56.79.

I want to keep a sub-domain private where I'll run an admin application (it will be password protected and on a special port, but I would prefer to keep it as private as possible).

[A]
It used to be possible with:
```
```
host -a -l domain.com
```
```


q:
I wanted to pass calendar1.Selecteddate in a query string from gridview in one page to another gridview (I have written sqlquery in that gridview) in another page. As seen in the below code I tried passing it but this did not work. Can anyone tell me how to pass the selected date from calendar in query string

      <asp:HyperLinkField DataNavigateUrlFields="LocalIP"
                DataNavigateUrlFormatString="DailyResults.aspx?
           Terms={0}&column=LocalIP&
               startdate=Calendar1.SelectedDate.Date.Date.ToShortDateString()
                DataTextField="LocalIP" HeaderText="User" />

[A]
In the example you've provided it would treat that calendar part of the string as a literal and pass the exact value you have typed.
In order to obtain the data using you would need to do something similar to:
```
```
<asp:HyperLinkField DataNavigateUrlFormatString="<%=GetSelectedDate()%>....
```
```
where this is a method on the code behind class (or you could use a property) that creates the string you intend, including the {0} placeholder for the LocalIP bound data field.


q:
I am writing a QT application and I need to embed a terminal (we say,xterm) within a QDialog, like some KDE application (see kdevelop/kate/...).

I've been trying with:
- QX11EmbedContainer placed into the QLayout of my QDialog
- QProcess for the program I want to excecute

I expect the QProcess running within the QX11EmbedContainer, but it does not work.

The problem is that I can't put the xterm into the QX11EmbedContainer, the only thing I obtain is an xterm window (unfortunately separated from my QDialog).
Does anybody got the same problem?

[A]
You need to pass the window ID of the container to the xterm.
If you look at the example in the Qt help for QX11EmbedContainer,  it just passes the window id to the QProcess. Change this to
```
```
QProcess process(&container);
 QString executable(app.arguments()[1]);
 QStringList arguments;
 arguments << "-into" << QString::number(container.winId());
 process.start(executable, arguments);
```
```
where "-into" has been added to the arguments. From the XTerm man page:
-into windowId
Given an X window identifier (a decimal integer), xterm
    will reparent its top-level shell
    widget to that window.  This is  used
    to embed xterm within other applications.


q:
I'm using SQL Server 2005 and the the Dynamic Management View sys.dm_db_missing_index_details. It continues to tell me that Table1 really needs an index on ColumnX and ColumnY, but that index already exists! I've even dropped and re-created it a couple times to no avail.

More specifics: The view lists Column1 under equality_columns.  Column2 is listed under inequality_columns, so the index I have created is:

create index IndexA on Table1 (Column1 asc, Column2 asc)

Isn't this exactly the index sys.dm_db_missing_index_details is telling me I need?

[A]
If you have dropped & created the index, sp_update_stats shouldn't affect it (problem is not with statistics)
Perhaps it's because of the DMV data is obsolete already
Does Actual Execution Plan suggest the Missing Index in SSMS as well?
From
Books Online
Information returned by
  sys.dm_db_missing_index_details is
  updated when a query is optimized by
  the query optimizer, and is not
  persisted. Missing index information
  is kept only until SQL Server is
  restarted. Database administrators
  should periodically make backup copies
  of the missing index information if
  they want to keep it after server
  recycling.
To determine which missing index
  groups a particular missing index is
  part of, you can query the
  sys.dm_db_missing_index_groups dynamic
  management view by equijoining it with
  sys.dm_db_missing_index_details based
  on the index_handle column.


q:
I cannot figure out a way to disable a container AND its children in Swing. Is Swing really missing this basic feature?

If I do setEnabled(false) on a container, its children are still enabled.

My GUI structure is pretty complex, and doing a traversion of all elements below the container is not an option. Neither is a GlassPane on top of the container (the container is not the entire window).

[A]
JXLayer
might be what you're looking for, according to
this post
:
Wrap your container with the JXLayer and call
```
JXLayer.setLocked(true)
```
after that - all components inside will be disabled
alt text http://www.java.net/download/javadesktop/blogs/alexfromsun/2007.06.25/LayerDemo.PNG


q:
Greetings to all!  This is my first question here on stackoverflow.  I have a WPF application that I am writing for the fellow developers in my department, and there are a couple of settings that I need to check for at startup and update if they are not set (one is the location of an executable on the users computer, we all have it, just not in the same place).  So when my app starts up for the first time, I need to pop a filechooser to have them select the location.

What I need to do is write the location of that to the appSettings, but I just can't seem to get it, and I searched Google pretty hard last night trying to find a way to do it.  Most answers I saw involved reading the app.config file as straight XML, and that doesn't seem right.

So, I just need a way to update values in the appSettings for my application.  I can read from them just fine, just haven't figured out how to write to them.  Thanks so much!

James

[A]
Have you looked into the ConfigurationManager class? It provides a more robust interface to the app.config file and you can do something like this:
```
```
Configuration oConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
oConfig.AppSettings.Settings["PreferenceToRemember"].Value = "NewValue";
oConfig.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("appSettings");
```
```
Just remember to import
```
System.Configuration
```
into your project. It isn't added by default.


q:
I am using LLBL Gen Pro v2.6 and am attempting to create a means of auditing changes made to the database. Now, I know that LLBL Gen has auditing built into it using AuditorBase and dependency injection. The question I have is; I need to track not only the stuff that LLBL Gen exposes as auditable, but also the User who made the changes. From what I've seen there isn't a built in way of gathering this information. Has anyone used LLBL Gen's built in auditing and determined a way to do this?

Wayne E. Pfeffer

[A]
I have used LLBLGens Auditing classes. Determining the user is really something that you will have to handle. There are too many variables for LLBLGen to actually do this for you. How are your users handled? Is this a winforms or asp.net application?
The best solution would be to store the UserId in a session variable or static variable depending on which is more appropriate for your application. In your implementation of the Auditing class you can just pull the UserId from its storage place.
Another potential solution would be to override the Entity Class or the Data Adapter classes and pass the UserId in to your save methods. However, this would be a lot more work.


q:
Need to locate the following pattern:

The letter I followed by a space then three alpha numerics followed by a space

"I ALN "
"I H21 "
"I 31M "

these items are also followed by a lat/lon that is trapped by this expression:

Dim regex As New Regex("\d{6} \d{7}")

Can the expressions be combined to return a match that would look like:

"H21 ###### #######"

Thanks,

Dave

[A]
```
```
I ([a-zA-Z\d]{3} \d{6} \d{7})
```
```
Match group 1 would contain the three alphanumerics plus the numbers you already catch with your other regex.
EDIT: Does not work because the pattern described in the question does not reflect what the author meant in the first place. What really was meant was first clarified in the comments.


q:
How to get the last selected item in a .Net Forms multiselect ListBox? Apparently if I select an item in the listbox and then select another 10 the selected item is the first one.

I would like to obtain the last element that I selected/deselected.

[A]
Not sure I understand the question, but the last selected item will be the last in the SelectedItems array, so something like this should work:
```
```
ListItem i = list.SelectedItems[list.SelectedItems.Length-1];
```
```


q:
Excuting the line of SQL:

SELECT *
  INTO assignment_20081120
  FROM assignment ;

against a database in oracle to back up a table called assignment gives me the following ORACLE error:
ORA-00905: Missing keyword

[A]
Unless there is a single row in the
```
ASSIGNMENT
```
table and
```
ASSIGNMENT_20081120
```
is a local PL/SQL variable of type
```
ASSIGNMENT%ROWTYPE
```
, this is not what you want.
Assuming you are trying to create a new table and copy the existing data to that new table
```
```
CREATE TABLE assignment_20081120
AS
SELECT *
  FROM assignment
```
```


q:
I'm writing a simple .bat file and I've run into some weird behavior.  There are a couple places where I have to do a simple if/else, but the code inside the blocks don't seem to be working correctly.

Here's a simple case that demonstrates the error:

@echo off

set MODE=FOOBAR

if "%~1"=="" (
  set MODE=all
  echo mode: %MODE%
) else (
  set MODE=%~1
  echo mode: %MODE%
)
echo mode: %MODE%

The output I'm getting is:

C:\>test.bat test
mode: FOOBAR
mode: test

Why is the echo inside the code block not getting the new value of the variable?  In the actual code I'm writing I need to build a few variables and reference them within the scope of the if/else.  I could switch this to use labels and gotos instead of an if/else, but that doesn't seem nearly as clean.

What causes this behavior?  Is there some kind of limit on variables within code blocks?

[A]
You are running into the problem of cmd's static variable expansion. The MODE variable is only evaluated once. You can see this if you omit the @echo off line.
From the set /? documentation:
Finally, support for delayed environment variable expansion has
  been added.  This support is always
  disabled by default, but may be
  enabled/disabled via the /V command
  line switch to CMD.EXE.  See CMD /?
Delayed environment variable expansion is useful for getting around
  the limitations of the current
  expansion which happens when a line of
  text is read, not when it is executed.
  The following example demonstrates the
  problem with immediate variable
  expansion:
```
```
set VAR=before
 if "%VAR%" == "before" (
     set VAR=after
     if "%VAR%" == "after" @echo If you see this, it worked
 )
```
```
would never display the message, since
  the %VAR% in BOTH IF statements is
  substituted when the first IF
  statement is read, since it logically
  includes the body of the IF, which is
  a compound statement.  So the IF
  inside the compound statement is
  really comparing "before" with "after"
  which will never be equal.  Similarly,
  the following example will not work as
  expected:
```
```
set LIST=
for %i in (*) do set LIST=%LIST% %i
echo %LIST%
```
```
in that it will NOT build up a list of
  files in the current directory, but
  instead will just set the LIST
  variable to the last file found.
  Again, this is because the %LIST% is
  expanded just once when the FOR
  statement is read, and at that time
  the LIST variable is empty. So the
  actual FOR loop we are executing is:
```
```
for %i in (*) do set LIST= %i
```
```
which just keeps setting LIST to the
  last file found.
Delayed environment variable expansion
  allows you to use a different
  character (the exclamation mark) to
  expand environment variables at
  execution time.  If delayed variable
  expansion is enabled, the above
  examples could be written as follows
  to work as intended:
```
```
set VAR=before
if "%VAR%" == "before" (
    set VAR=after
    if "!VAR!" == "after" @echo If you see this, it worked
)

set LIST=
for %i in (*) do set LIST=!LIST! %i
echo %LIST%
```
```


q:
Does anyone know of any C container libraries? I am looking for something which gives standard implementations of linked lists, arrays, hash tables etc, much in the same way as the C++ STL does. Key concerns are:

Client code should be able to create containers for multiple different data types without modifying the library.

The interface for creating and using the containers should be intuitive.

[A]
Chuck Falconer
has a decent hash library written in C that includes a C++ interface, click on hashlib.zip on the webpage to download.
Ben Pfaff
has very nice and extremely well-documented binary and balanced tree library,
GNU libavl
, that implements most major tree structures including binary search trees, AVL trees, red-black trees and threaded versions of each.
libavl is licensed under the LGPL (as of version 2.0.3), hashlib is GPL.
I'm not sure what you are looking for as far as arrays and linked lists go as the former is supported directly by the language and the latter is generally trivial enough to implement without warranting a library.


q:
What are the advantages/disadvantages to running time based jobs using:

windows services

Application_BeginRequest to start seperate threads / timers.

One disadvantage of running the jobs in the context of a asp.net web appplication is during .net recycling things will have to be setup again, any others?

[A]
If you have administrative access to the server, I would either run a Windows Service or a scheduled SQL job depending on what you are trying to achieve.
It is nice to be able to stop/start and log these jobs independent of your web application. Also, if you have problems or errors in the job, it could adversely affect your website.
Finally, you are forcing the web application to go through code at
every
request to see if the timer has elapsed, which is an unnecessary overhead.
As I said to start with, the implementation depends on what the job is. If it is simply to update a number of database records, I'd use a scheduled job in SQL Server. If you need file I/O or access to external services, then a Windows Service might be more appropriate.
It is worth noting that you need to build in your own scheduling and thread safety into Windows Services. An alternative is to build a console application and use an application like
FireDaemon
for the scheduling.


q: I need to signal a running application (Windows service) when certain things happen in SQL Server (2005). Is there a possibility to send a message from a trigger to an external application on the same system?

[A]
You can send an email from a trigger, but it isn't a recommended practice becasue if the email ssystem is down, no data changes can be made to the table.
Personally if you can live with less than realtime, I would information about the event you are interested in to another table (so the real change of data can go smoothly even if email is down for some reason.) Then I would have a job that checks that table every 5-10 minutes for any new entries and emails those out.


q:
My application caches some data on disk.  Because the cache may be large, it should not be stored on a network drive.  It should persist between invocations of the application.  I have a mechanism for the user to choose a location, but would like the default to be sensible and "the right thing" for the platform.

What is the appropriate location for such a cache?  Is there an API for determining the appropriate location?  How do I call it from Python?

[A]
Perhaps the
```
tempfile
```
module provides what you need. It uses the Windows Temp directory (which probably is not on a network drive) but you can specify a directory if you want to. Also for security reasons this module should be the right tool - if you use
```
tempfile.mkstemp()
```
the file is readable and writable only by the creating user ID.
Oh. I see you have just edited your question and that you need file persistence between invocations of the app. Then
```
tempfile
```
is not that ideal (even though you could choose not to delete your cache between invocations).


q:
I've seen this syntax a couple times now, and it's beginning to worry me,

For example:

iCalendar iCal = new iCalendar();
Event evt = iCal.Create<Event>();

[A]
It's calling a generic method - so in your case, the method may be declared like this:
```
```
public T Create<T>()
```
```
You can specify the type argument in the angle brackets, just as you would for creating an instance of a generic type:
```
```
List<Event> list = new List<Event>();
```
```
Does that help?
One difference between generic
methods
and generic
types
is that the compiler can try to infer the type argument. For instance, if your
```
Create
```
method were instead:
```
```
public T Copy<T>(T original)
```
```
you could just call
```
```
Copy(someEvent);
```
```
and the compiler would infer that you meant:
```
```
Copy<Event>(someEvent);
```
```


q:
I am working on a tool where I need to convert string values to their proper object types. E.g. convert a string like "2008-11-20T16:33:21Z" to a DateTime value. Numeric values like "42" and "42.42" must be converted to an Int32 value and a Double value respectively.

What is the best and most efficient approach to detect if a string is an integer or a number? Are Int32.TryParse or Double.TryParse the way to go?

[A]
In terms of efficiency, yes, TryParse is generally the preferred route.
If you can know (for example, by reflection) the target type in advance - but don't want to have to use a big
```
switch
```
block, you might be interested in using
```
TypeConverter
```
- for example:
```
```
DateTime foo = new DateTime(2008, 11, 20);
        TypeConverter converter = TypeDescriptor.GetConverter(foo);
        string s = converter.ConvertToInvariantString(foo);
        object val = converter.ConvertFromInvariantString(s);
```
```


q:
I'm looking to add support for reading and writing video files in my application.  If you had to choose exactly one file format and codec combination that would satisfy the majority of users, which would you choose:

1) MPEG-4/H.264 (.mp4)
2) AVI/DiVX (.avi)
3) Ogg/Theora (.ogg)
4) Windows Media Video (.wmv)

I'm leaning towards MPEG-4/H.264 given that it is supported in Linux, Mac OS X, the Flash player, iPods, Playstation 3, XBox360, and support is forthcoming in Microsoft Silverlight,and Windows Media Player 12.

Am I missing anything?  Is there something better I could be choosing?

[A]
It depends on what your application is doing.  If you want to process videos recorded from a video capture card, you'll probably need to be able to read .mpg files with mpeg2 embedded.  A large number of videos use the .avi or .wmv container.  Microsoft is pushing .wmv, but .avi has a lot better support amongst free tools.  Not many tools support .mp4 containers on Windows (Mac is probably different).  H.264, mpeg2, and mpeg4 are my favorite codecs.  H.264 is great quality/bitrate-wise but makes precise and fast seeks hard and is extremely CPU-intensive.  mpeg4 is almost as good as h.264 in terms of quality/bitrate, but it is much less CPU-intensive.  mpeg2 requires many more bits to achieve the same quality, but it's supported pretty much everywhere and it's really easy to decode and seek in those files.
If you don't mind using LGPL code, I'd suggest looking at
ffmpeg
's libavcodec and libavformat.  It'll let you do everything you mention on all platforms (though I'm not sure about Ogg & Theora--I haven't used them).


q: I am just getting started creating an AJAX application using server side push. I am using Grizzly Comet on Glassfish V2. Almost all the sample applications use IFrames for updating content on the client side. I want to stick to using JavaScript only. Are there any such sample applications (preferably ones that do not use a JavaScript library)?

[A]
The point about the push is that the HTTP request never ends. Not all client implementations handle that correctly. As I see it, it's possible to do it with pure javascript in Firefox with its extensive API, but the XMLHTTPRequest object would timeout and would not be able to stream you the content.
IFrame is good, you could also try the object tag if its about standard compliance.
Before XMLHTTPRequest and Ajax had no name, we used to get data from the servers through IFrames.


q:
I am porting some queries from Access to T-SQL and those who wrote the queries used the Avg aggregate function on datetime columns.  This is not supported in T-SQL and I can understand why - it doesn't make sense.  What is getting averaged?

So I was about to start reverse engineering what Access does when it aggregates datetime using Avg, but thought I would throw the question out here first.

[A]
I'd imagine that Access is averaging the numeric representation of the dates.  You could do similar in T-SQL with the following...
```
```
select AverageDate = cast(avg(cast(MyDateColumn as decimal(20, 10))) as datetime)
from    MyTable
```
```


q:
I have a series of Eclipse projects containing a number of plugins and features that are checked into CVS. I now need to run an automated build of these plugins. Ideally I'd like to do it without having to hardcode large numbers of Eclipse library locations by hand, which has been the problem with the automatically generated Ant files that Eclipse provides. The build also needs to run headlessly.

Does anyone have experience of this sort of set-up with Eclipse, and recommendations for how to achieve it?

[A]
You could write some sort of a script that finds those libraries for you and puts them into a format understandable by Ant.
For example, it could build a eclipse.lirbaries.properties file, then you could read in that file using:
```
```
<property file="eclipse.libraries.properties" />
```
```
You could also use the FileSet attribute:
http://ant.apache.org/manual/Types/fileset.html
Or even a combination of both.
1) Call Ant Script
2) Ant Script calls bash (or whatever scripting language) script which builds eclipse.libraries.properties
3) Ant loads eclipse.libraries.properties
4) Ant goes on with the build


q:
I was always wondering why it is a big deal having version control support inside an IDE.

I always preferred to use a command-line/standalone version of the version control of choice and never found IDE integration helpful.

I know it can be helpful sometimes, for example to automatically keep track of renames, but I was bitten by version control plugins a couple of times (especially the ClearCase Eclipse plugin) that I'm now finding it counter productive compared to the command-line version, where I have better control.

What is your opinion?

[A]
I like how
some
IDE's implement this.
Ankh-SVN
for Visual Studio is not that great and is a bit buggy, however
Subeclipse
I find to work exceedingly well when I'm using Eclipse.
I think it really depends on the IDE you're using and the quality of that plug-in. It's going to work well for some setups and terrible for others.
That's why I like Subversion with Tortoise SVN so much. I can choose to use the IDE integration when and where it makes sense, otherwise, just like you said, I can simply use the command line or in my case, the windows explorer based client!


q:
I'm working with some schema which defines an abstract complex type, eg.

<xs:complexType name="MyComplexType" abstract="true">

This type is then referenced by another complex type in the schema:

<xs:complexType name="AnotherType">
  <xs:sequence>
    <xs:element name="Data" type="MyComplexType" maxOccurs="unbounded"/>
  </xs:sequence>
</xs:complexType>

When I run "xsd.exe /d /l:CS MySchema.xsd" I get this error:

Error: There was an error processing MySchema.xsd'.
    - Error generating code for DataSet ''.
    - Unable to convert input xml file content to a DataSet. DataSet cannot instantiate an abstract ComplexType for the node Data.
    - DataSet cannot instantiate an abstract ComplexType for the node Data.

It doesn't seem to be invalid schema.  Has anyone else run into this issue?

Thanks

Nick

[A]
I have never run into this problem, but I quickly learned that xsd.exe has a lot of shortcomings.  We started using
CodeXS
a long time ago.  The product is a web service, but the code is available as a command-line tool.
It has its own warts, but the code it generates is much better and it is free. Plus, it is extensible, and adding your own plug-ins for it is actually pretty easy.
Possibly, it won't have the same limitation?


q:
The program that I am currently assigned to has a requirement that I copy the contents of a table to a backup table, prior to the real processing.

During code review, a coworker pointed out that

INSERT INTO BACKUP_TABLE
SELECT *
FROM PRIMARY_TABLE

is unduly risky, as it is possible for the tables to have different columns, and different column orders.

I am also under the constraint to not create/delete/rename tables. ~Sigh~

The columns in the table are expected to change, so simply hard-coding the column names is not really the solution I am looking for.

I am looking for ideas on a reasonable non-risky way to get this job done.

[A]
You could try something like:
```
```
CREATE TABLE secondary_table AS SELECT * FROM primary_table;
```
```
Not sure if that automatically copies data. If not:
```
```
CREATE TABLE secondary_table AS SELECT * FROM primary_table LIMIT 1;
INSERT INTO secondary_table SELECT * FROM primary_table;
```
```
Edit:
Sorry, didn't read your post completely: especially the constraints part. I'm afraid I don't know how. My guess would be using a procedure that first describes both tables and compares them, before creating a lengthy insert / select query.
Still, if you're using a backup-table, I think it's pretty important it matches the original one exactly.


q:
I am developing some school grading software and decided to use Github to host the project.  After building some code on my Ubuntu box I pushed it to Github and then cloned it down to my MacBook Pro. After editing the code on the MBP I pushed it back to Github. The next morning I tried to update my repo on the Ubuntu box with a git pull and it gave me all kinds of trouble.

Whats the best way to work in this situation? I don't want to fork my own repo and I don't really want to send myself emails or pull requests. Why can't I just treat Github like a master and push/pull from it onto all of my personal repos on different computers?

[A]
I'll assume your problem was that the machine on which you first created the repo crapped out when you tried to issue the
```
git pull
```
command.
When you clone an existing git repository (like you did on your 2nd machine, the MacBook Pro), you're automatically set up to so your
```
git pull
```
commands will automatically merge the remote with your local changes.
However, when you initially create a repo and then share it on a remote repository, you have to issue a few commands to make things as automated as a on cloned repo.
```
```
# GitHub gives you that instruction, you've already done that
# git remote add origin git@github.com:user_name/repo_name.git

# GitHub doesn't specify the following instructions
git config branch.master.remote origin
git config branch.master.merge refs/heads/master
```
```
These last few instructions configure git so future
```
git pull
```
's from this repo will merge all remote changes automatically.
The following is a bit of shameless self-promotion. If you use Ruby, I have created a Ruby-based tool that lets you deal with all these kinds of things with git remote branches. The tool is called, unsurprisingly,
git_remote_branch
:-)
If you don't use Ruby, my tool is probably gonna be too much of a hassle to install. What you can do is look at
an old post on my blog
, where most of the stuff grb can do for you was explicitly shown. Whip out your git notes file :-)


q:
I have a project where multiple developers are using a copy of the same windows Virtual PC image (W2K3 SE SP2).  Because our solution is tied to the machine-name (less than ideal, i know) all of the developers have the same machine name.

We use a VPN to connect to a remote system, upon connection we get the "Windows Error: A duplicate name exists on the network" error.

Since all development is happening locally, we're not dependent on other machines connecting to us -- only outbound connections.

I know it's best practice to change the machine name, but what's the reasoning behind this?  What impact would this have?

[A]
If you are able to use a reference, you can retain the same use syntax. However, your reference has to be initialised straight away in the constructor, so your ctor absolutely must be defined out-of-line. (You will also need to free the object in the destructor too.)
```
```
// bar.h
class foo;

class bar {
    foo& foo_;

public:
    bar();
    ~bar();
};

// bar.cc
bar::bar() : foo_(*new foo)
{
    // ...
}

bar::~bar()
{
    // ...
    delete &foo_;
}
```
```
Your mileage may vary. :-)


q:
What do you think is the best way to implement an interactive grid similar to a Sudoku board for a native iPhone application?  I did not see an object to fill this need in the SDK.

Should I make a custom control for an individual cell, then initialize as many of them as I need in a grid form?

(source: 4thewww.com)

Any and all comments are welcome.
Thanks!

[A] The grid is a means of viewing contents, not of storing the representation.  Ultimately, your grid is made of cells which have contents and therefor your underlying model object is perhaps best embodied by the cell. There are a number of ways to design the underlying storage for a Sudoku game and the bigger challenge will certainly lie in the generation of puzzles. However, the advice to take from this is to not determine your model based on how it appears on screen - the view layer is totally separate and so doing something like storing the board a a two-dimensional array would be a bad idea.


q:
For a new project I have to import the pre-existing data from MySql.

In this site I have found many options, some including the installation of drivers. What is the fastest & easiest way to do it?

Update: this would be just a one time import

[A]
If you have access to phpMyAdmin you could run an export of the entire database. It will generate a long list of SQL commands to create all the schema and optionally insert all the data into their respective places.
It is also possible to perform all this from the command line.
If you have a lot of data you may want to do it all in pieces, single SQL scripts for each table and the inserts into each.
Then on the M$ SQL side just create the database, connect to it with SQL Query Analyzer or SQL Management Studio, copy-n-paste your SQL scripts into the window and execute.
Chances are a majority of your MySQL code will just work in M$SQL. If you run into issues, you can set a compatibility level on the MySQL export to fit your destination environment better.
If your just doing data, as long as the schema's match up, all you have to script is the data import/export, don't script the schema and CERTAINLY DON'T script drops!!!
EDIT: if you had to do any transformations, I believe you can export to M$ Excel, certainly to a CSV, then on the M$SQL import do your mappings and such.


q:
I have a form containing a web browser control. This browser control will load some HTML from disk and display it. I want to be able to have a button in the HTML access C# code in my form.

For example, a button in the HTML might call the Close() method on the form.

Target platform: C# and Windows Forms (any version)

[A]
This is possible, but I haven't done it in .NET.
A few years back I had a C++ application that hosted a web browser control (ActiveX).  From the HTML in the control, it was possible to call 'out' to the ActiveX control and get it to do things.
The same should be possible in .NET, although HTML DOM/JavaScript won't know about C#.  But if you wrap your .NET functionality in a COM object, you should be able to call methods on the COM/ActiveX objects which will in-turn call your C# code.
Hope this helps.


q:
I have a control, VideoControl, which displays video using DirectShow - it's set as the owner of an IVideoWindow.  I have another control, AreaControl, which is supposed to show a dashed rectangle over the video control.  AreaControl is set to be transparent using SetStyle(ControlStyles.SupportsTransparentBackColor, true).  If I place AreaControl over any other control, it works as expected, showing a dashed rectangle over the controls behind it.  But when I place the dashed rectangle control over the video control, the AreaControl is filled in with the VideoControl's BackColor.

What do I need to do to get the video to display through the AreaControl, with the dashed rectangle overlaid on it?  Is there a way to get the VideoControl to paint itself with the video, rather than just drawing its BackColor?

[A]
As far as I know, there is no way of doing, what you want to do directly. The problem is, the implementation of the transparent style of a control. A control with this style attribute basically just draws, what is behind it making it appear transparent. (In reality it isn't really transparent at all).
The only solution that comes to my mind is to use a window (Form) and put the control in that. A Form can be made transparent by setting its Opacity property to something less than 1.0. A value of 0.0 will be totally transparent (read: Invisible). The dashed border should be totally black. With a opacity of f.e. 0.4 it will appear gray.
Alternatively, you may have some luck with TransparencyKey Property of the Form. Setting this to white may have the desired effect, but I haven't tested this one.
In either case the Form should be completely borderless. You may have to add some code to reposition the form, when the video form moves.


q:
I am creating a C# WinForms application. I would like to have a Custom Form Border. And I want to create a black custom window (with border and controls) like that of Adobe Lightroom. For example -

How do I create it, please help?

[A]
If the custom-chrome tools don't provide you with the look-and-feel that you want, this kind of thing is easy to do yourself in C#.  Basically, you create a borderless form (FormBorderStyle = None) and then create all the controls and borders yourself, by placing controls where you need them (a label for the title bar, command buttons for close and minimize etc.) and/or drawing directly on the form's surface using the Graphics object.
You also have to implement code to allow the form to be dragged around by its "fake" title bar (see
this answer
for a sample of how to do this).  You may also have to implement your own resizing mechanism (if you need the forms to be resizable).
Finally, although the custom-form code might be a bit clunky, you can implement it on a single form and then have all the other forms in your application inherit from this form, which makes it a very useful technique for custom-skinning an entire application.


q:
I'm starting to learn about using Memcached with PHP and I was wondering; is there a point at which you should start using it? Is it always more efficient to cache data or does it only become effective once your site gets a certain number of hits? Presumably there is an overhead associated with Memcached, so when does the speed benefit outweigh this?

Thanks in advance for any advice.

[A]
You should start using memcached when not using it starts to affect your site / server.
So when you just have 100 visitors a day and your site still responds quickly, don't bother using it.
But when you have running times somewhere near 200ms or more per page, and the site feels slow too, you should look out for the bottlenecks using some PHP profiler (XDebug integrates one that you can use in combination with WinCacheGrind or KCacheGrind).
Especially caching database requests should save you some load time.


q:
I need a CSS selector that can find the 2nd div of 2 that has the same class. I've looked at nth-child() but it's not what I want since I can't see a way to further clarify what class I want. These 2 divs will be siblings in the document if that helps.

My HTML looks something like this:

<div class="foo">...</div>
<div class="bar">...</div>
<div class="baz">...</div>
<div class="bar">...</div>

And I want the 2nd div.bar (or the last div.bar would work too).

[A]
Selectors can be combined:
```
```
.bar:nth-child(2)
```
```
means "thing that has class
bar
" that is also the 2nd child.


q: Currently i have a NotInheritable class in App_Code that hold some variables that need to be access thur-out the application but i don't think it's a good way to manage global variables.

[A]
Usually, this kind of thing calls for a
Singleton
. However, I'd recommend never coding a singleton yourself, and using a Dependency Injection/IoC framework to handle the life-cycle of services.
The other thing you have to remember with ASP.NET is that the ASP.NET process automatically recycles itself every now-and-then, so you'll need to persist changes to permenant storage (such as file-system or database)


q: I suppose there could be historical reasons for this naming and that other languages have similar feature, but it also seems to me that parameters always had a name in C#. Arguments are the unnamed ones. Or is there a particular reason why this terminology was chosen?

[A]
Yes, you're absolutely right (to my mind, anyway). Ironically, although I'm usually picky about these terms, I still use "parameter passing" when I should probably talk about "argument passing". I suppose one could argue that prior to C# 4.0, if you're calling a method you don't care about the parameter names, whereas the names become part of the significant metadata when you can specify them on the arguments as well.
I agree that it makes a difference, and that terminology is important.
"Optional parameters" is definitely okay though - that's adding metadata to the parameter when you couldn't do so before :) (Having said that, it's not going to be optional in terms of the generated IL...)
Would you like me to ask the team for their feedback?


q:
I am trying to write a decorator to do logging:

def logger(myFunc):
    def new(*args, **keyargs):
        print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
        return myFunc(*args, **keyargs)

    return new

class C(object):
    @logger
    def f():
        pass

C().f()

I would like this to print:

Entering C.f

but instead I get this error message:

AttributeError: 'function' object has no attribute 'im_class'

Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.

[A]
It seems that while the class is being created, Python creates regular function objects. They only get turned into unbound method objects afterwards. Knowing that, this is the only way I could find to do what you want:
```
```
def logger(myFunc):
    def new(*args, **keyargs):
        print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__)
        return myFunc(*args, **keyargs)

    return new

class C(object):
    def f(self):
        pass
C.f = logger(C.f)
C().f()
```
```
This outputs the desired result.
If you want to wrap all the methods in a class, then you probably want to create a wrapClass function, which you could then use like this:
```
```
C = wrapClass(C)
```
```


q: I have a groovy script that needs a library in a jar. How do I add that to the classpath? I want the script to be executable so I'm using #!/usr/bin/env groovy at the top of my script.

[A]
If you really have to you can also load a JAR at runtime with:
```
```
this.getClass().classLoader.rootLoader.addURL(new File("file.jar").toURL())
```
```


q:
I am following a VB tutorial to do some HTML manipulation using LINQ

It has the following construct

Imports <xmlns="http://www.w3.org/1999/xhtml">

How do I do the same in C#?

There appears to be something called an XMLNamespaceManager that may hold the solution, but I am too foolish to understand how to work it, and I am not sure it is the correct tree to bark up.

Got any advice?

[A]
VB.Net has a feature called
```
XML Literals
```
that is not present in C#.  This import statement adds a namespace for use with those literals.
In researching this information, I found this link helpful:
http://blogs.msdn.com/bethmassi/archive/2007/10/30/quickly-import-and-export-excel-data-with-linq-to-xml.aspx
It's also very informative for working with Excel xml docs, but that's a side issue ;)


q:
I am embarking on a new RIA project with Java on the backend. I'm the only developer, and the app is a line-of-business application. My current stack looks like this:

MySQL || Spring(JdbcTemplate for data access) || BlazeDS (remoting) || Flex(Cairngorm)

My question is: what changes can I make to improve productivity? Manually coding SQL, server-side entity objects, client-side value objects and all the Cairngorm stuff is obviously a drag, but I'm not sure what higher-level frameworks to introduce.

What Flex/Java stack has served you well?

[A]
Manually coding SQL
Hibernate
is an option to cut this out.
One thing that may be of interest is Grails with the available Flex Plugin. It's built on Spring, Hibernate and BlazeDS, so it's all there for you. It was unbelieveably easy to get it remoting stored objects and responding to AMF calls. I was using this and then moved over to a RESTful E4X implementation as I found it a lot easier to debug and tweak as I could inspect the server output in a browser and have tighter control over exactly what I returned to my Flex app (lazy loading problems in collections using BlazeDS were a headache at times).
Here is a quick tutorial showing how easy the whole Grails + Flex Plugin stack is:
BlazeDS  in Grails


q:
I have a list of error codes I need to reference, kinda like this:

Code / Error Message
A01 = whatever error
U01 = another error
U02 = yet another error type

I get the Code returned to me via a web service call and I need to display or get the readable error.  So I need a function when passed a Code that returns the readable description. I was just going to do a select case but thought their might be a better way. What is the best way / most effieient way to do this?

[A]
Use a Dictionary, (in C#, but the concept and classes are the same):
```
```
// Initialize this once, and store it in the ASP.NET Cache.
Dictionary<String,String> errorCodes = new Dictionary<String,String>();

errorCodes.Add("A01", "Whatever Error");
errorCodes.Add("U01", "Another Error");

// And to get your error code:

string ErrCode = errorCodes[ErrorCodeFromWS];
```
```


q:
Back in 2000 (when .NET was unleashed upon us IIRC) it was an innovative cutting edge language (last time I used it was 2003).

From what I read though, Sun has only evolved the language exceedingly slowly. I've even read that where the language has evolved, such as the addition of Generics, developers have complained about poor implementation.

Are these accurate perceptions, and if so, any thoughts on why, particularly with the seemingly obvious competition from C#?

[A]
Java has certainly been evolving very slowly - especially if you compare it with C# and VB. I personally feel that they made the wrong decision with generics in terms of keeping backward compatibility at the cost of execution-time safety and efficiency. The .NET approach works a lot better in
almost
every way, IMO.
Java 7 has a
long list of
potential
features
- both language and platform - but it's been an awfully long time in the making, and there's still significant question marks over many of the features.
I wouldn't like to place any "blame" on why this has happened, however.


q:
I've been trying to create a custom control that works exactly like the Panel control except surrounded by a few divs and such to create a rounded box look. I haven't been able to find a decent example of how to do this.

I need to be able to place text and controls inside the control and access it directly without referencing the panel (exactly the way the Panel control works).

Does anyone have any examples of this?

[A]
There are two ways to do this. One is to implement
```
INamingContainer
```
on your control, and it takes a lot of effort.
The other way is to inherit from Panel, and override the RenderBeginTag and RenderEndTag methods to add your custom markup. This is easy.
```
```
public class RoundedCornersPanel : System.Web.UI.WebControls.Panel
{
    public override RenderBeginTag (HtmlTextWriter writer)
    {
        writer.Write("Your rounded corner opening markup");
        base.RenderBeginTag(writer);
    }

    public override RenderEndTag (HtmlTextWriter writer)
    {
        base.RenderEndTag(writer);
        writer.Write("Your rounded corner closing markup");
    }
}
```
```


q:
Is there a 4 byte unsigned int data type in MS SQL Server?

Am I forced to use a bigint?

[A]
It doesn't seem so.
Here's an article describing how to create your own rules restricting an
```
int
```
to positive values.  But that doesn't grant you positive values above
```
2^31-1
```
.
http://www.julian-kuiters.id.au/article.php/sqlserver2005-unsigned-integer


q:
Why does the following behave unexpectedly in Python?

>>> a = 256
>>> b = 256
>>> a is b
True           # This is an expected result
>>> a = 257
>>> b = 257
>>> a is b
False          # What happened here? Why is this False?
>>> 257 is 257
True           # Yet the literal numbers compare properly

I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100.

Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the is operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?


q: How do you create a custom control (not an ASCX control) and, more importantly, use it in your project? I'd prefer not to create a separate project for it or compile it as a DLL

[A]
Create the class for the control and build the solution. If everything goes well the control should now be available on the toolbox.
Sometimes the VS doesn't update the toolbox. If that happens add the Register directive to the page:
```
```
<%@ Register Assembly="NAME_OF_THE_ASSEMBLY" Namespace="NAMESPACE_OF_THE_CUSTOM_CONTROL" TagPrefix="cc1" %>
```
```
then just use the control on the page:
```
```
<cc1:mycustompanel id="MyCustomPanel1" runat="server"><asp:TextBox id="TextBox1" runat="server"></asp:TextBox></cc1:mycustompanel>
```
```


q:
How do I retrieve an item at random from the following list?

foo = ['a', 'b', 'c', 'd', 'e']

[A]
Use
```
random.choice()
```
:
```
```
import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))
```
```
For
cryptographically secure
random choices (e.g., for generating a passphrase from a wordlist), use
```
secrets.choice()
```
:
```
```
import secrets

foo = ['battery', 'correct', 'horse', 'staple']
print(secrets.choice(foo))
```
```
```
secrets
```
is new in Python 3.6. On older versions of Python you can use the
```
random.SystemRandom
```
class:
```
```
import random

secure_random = random.SystemRandom()
print(secure_random.choice(foo))
```
```


q:
I have this Trigger in Postgresql that I can't just get to work (does nothing). For understanding, there's how I defined it:

CREATE TABLE documents (
    ...
    modification_time timestamp with time zone DEFAULT now()
);

CREATE FUNCTION documents_update_mod_time() RETURNS trigger
AS $$
    begin
    new.modification_time := now();
    return new;
    end
$$
    LANGUAGE plpgsql;

CREATE TRIGGER documents_modification_time
    BEFORE INSERT OR UPDATE ON documents
    FOR EACH ROW
    EXECUTE PROCEDURE documents_update_mod_time();

Now to make it a bit more interesting.. How do you debug triggers?

[A]
You can use 'raise notice' statements inside your trigger function to debug it.  To debug the trigger not being called at all is another story.
If you add a 'raise exception' inside your trigger function, can you still do inserts/updates?
Also, if your update test occurs in the same transaction as your insert test, now() will be the same (since it's only calculated once per transaction) and therefore the update won't seem to do anything.  If that's the case, either do them in separate transactions, or if this is a unit test and you can't do that, use clock_timestamp().
I have a unit test that depends on some time going by between transactions, so at the beginning of the unit test I have something like:
```
```
ALTER TABLE documents
   ALTER COLUMN modification_time SET DEFAULT clock_timestamp();
```
```
Then in the trigger, use "set modification_time = default".
So normally it doesn't do the extra calculation, but during a unit test this allows me to do inserts with pg_sleep in between to simulate time passing and actually have that be reflected in the data.


q:
In designing a fluid layout, how do you use borders without ruining the layout.

More specifically, I have a HTML widget which consists of five divs.  I would like the five divs to take up all the room in the containing element.  I would also like to have a 1px border around each.

I tried:
.box { float: left; height: 100%; width: 100%; border: 1px solid red; }
This doesn't work:  there will be an extra 10px in width causing the boxes to wrap.  Reducing the width percentage doesn't work as it will not take up the correct amount of space and for certain page sizes, will still wrap.

Whats the proper way to manage the interaction between these elements?

[A]
Only put
```
width: 100%
```
on the outermost div, and don't put a border on it.  If you do this, then the inner boxes will fill the space (assuming you haven't floated them or anything) since they're block elements, and you won't have to worry about borders adding to the total size.
If you really need the appearance of five solid single pixel nested borders, you can do something like this (with properly semantic names, hopefully):
```
```

        etc.

```
```
As you can see, you can fake the second border using padding and background colors on the second div (might even cut down on the total number of divs by doing this; just remember you can't pad the outmost div without screwing up your width).


q:
Let's say I need to implement domain model for StackOverflow.

If I am doing ORM, how can I define (and map) property for fetching "last comments" and other "last" things?
It looks to me like this should be reflected in the domain model.

Sometimes I might need "all comments" though...


q: How can I get a list of the running applications? I'm referring to the ones in the panel at the bottom of the screen.

[A]
The panel you are referring to is the GNOME panel. So this is a GNOME question, not a GTK question.
There is not a well-defined concept of "multi-window application" in GNOME that I know of. The panel task list is probably build by querying the window manager for the list of windows and grouping the windows by their "class" property.
There are also various window manager hints that must be taken into account, for example to ignore panels and other utility windows. In your place, I would look at the source code of the taskbar applet. There is maybe some documentation somewhere that covers the status-quo, but I do know where it would be.


q:
Is there a clever way to determine which field is causing 'string or binary data would be truncated' with LINQ.

I've always ended up doing it manually by stepping through a debugger, but with a batch using 'SubmitChanges' I have to change my code to inserting a single row to find the culprit in a batch of rows.

Am I missing something or in this day and age do I really have to still use a brute force method to find the problem.

Please dont give me advice on avoiding this error in future (unless its something much cleverer than 'validate your data'). The source data is coming from a different system where I dont have full control anyway - plus I want to be lazy.

PS. Does SQL Server 2008 actually tell me the field name. Please tell me it does! I'll upgrade!

[A]
Assuming you are processing a large batch of records and you don't want to (can't) validate the data before hand and you just want db constraints to catch any errors?
Change your program to catch the exception and print out the current record details to a log file or something.
```
```
Record # 9999
Caused "string or binary data would be truncated" error
Field1: "Data" Length: 55
Field2: 9999
etc.
```
```


q:
I'm writing a script to display the 10 most recently "active" WordPress blog posts (i.e. those with the most recent comments). Problem is, the list has a lot of duplicates. I'd like to weed out the duplicates. Is there an easy way to do this by changing the MySQL query (like IGNORE, WHERE) or some other means?  Here's what I have so far:

<?php

function cd_recently_active() {
    global $wpdb, $comments, $comment;
    $number = 10; //how many recently active posts to display? enter here

if ( !$comments = wp_cache_get( 'recent_comments', 'widget' ) ) {
    $comments = $wpdb->get_results("SELECT comment_date, comment_author, comment_author_url, comment_ID, comment_post_ID, comment_content FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT $number");

    wp_cache_add( 'recent_comments', $comments, 'widget' );
}
?>

[A]
Look at the
DISTINCT
option for the SELECT statement. Or alternatively the GROUP BY syntax (look at the same link). Though they work in different ways, these would be the two methods most likely to help you get exactly what you want.


q:
I have the following command which will loop over all the subdirectories in a specific location and output the full path:

for /d %i in ("E:\Test\*") do echo %i

Will give me:

E:\Test\One
E:\Test\Two

But how do I get both the full path, and just the directory name, so the do command might be something like:

echo %i - %j

And the output might be something like:

E:\Test\One - One
E:\Test\Two - Two

Thanks in advance!

[A]
The following command syntax can be used to return the full path or directory name only:
```
```
%~fI        - expands %I to a fully qualified path name
%~nI        - expands %I to a file name only
```
```
Using your example, the following command will list directories in the format that you specified:
```
```
for /d %i in ("E:\Test*") do echo %~fi - %~ni
```
```


q:
I have a bit of code that looks like this:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff));

I need to pass in a 2nd parameter like this:

text = reg.Replace(text, new MatchEvaluator(MatchEvalStuff, otherData));

Is this possible, and what would be the best way to do this?

[A]
MatchEvaluator is a delegate so you can't change its signature.  You can create a delegate that calls a method with an additional parameter.  This is pretty easy to do with lambda expressions:
```
```
text = reg.Replace(text, match => MatchEvalStuff(match, otherData));
```
```


q:
I have written a KornShell (ksh) script that sets an array the following way:

set -A fruits Apple Orange Banana Strawberry

but when I am trying to run it from within cron, it raises the following error:

Your "cron" job on myhost
/myScript.sh

produced the following output:

myScript.sh: -A: bad option(s)

I have tried many crontab syntax variants, such as:

Attempt 1:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script/myScript.sh

Attempt 2:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * /path/to/script/./myScript.sh

Attempt 3:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script && ./myScript.sh

Any workaround would be sincerely appreciated. Thanks much in advance!

[A]
Although I'm not sure it's the best way to do it, I've managed to solve it this way:
Attempt 4:
```
```
0,5,10,15,20,25,30,35,40,45,50,55 * * * * cd /path/to/script && ksh ./myScript.sh
```
```


q: How do you get a list of files within a directory so each can be processed?

[A]
But
```
boost::filesystem
```
can do that:
http://www.boost.org/doc/libs/1_37_0/libs/filesystem/example/simple_ls.cpp


q:
With WinForms, I can use Control.Scale to scale a control larger.  When I do that, all child controls are repositioned and scaled correctly, but font size remains the same.

Is there an easy way to force font to scale up/down, or is the only way to manually update font for all controls when control is being scaled?

Background:  I'm working on a program in which I need to support zoom in/out to make labels, textboxs, etc. more readable for users with poor eyesight.

[A]
Do it the other way around.  Change the font size, the controls will automatically scale to accommodate the larger font.  For example:
```
```
public partial class Form1 : Form {
    float mDesignSize;
    int mIncrement;
    public Form1() {
      InitializeComponent();
      mDesignSize = this.Font.SizeInPoints;
    }
    private void adjustFont() {
      float size = mDesignSize * (1 + mIncrement / 7f);
      this.Font = new Font(this.Font.FontFamily, size);
    }
    private void btnIncreaseFontSize_Click(object sender, EventArgs e) {
      mIncrement += 1;
      adjustFont();
    }
    private void btnDecreateFontSize_Click(object sender, EventArgs e) {
      mIncrement -= 1;
      adjustFont();
    }
  }
```
```


q:
I'm trying to figure out how to write this function:

template <typename Bound>
Bound::result_type callFromAnyList(Bound b, list<any> p)
{
}

Then, if I had some function:

double myFunc(string s, int i)
{
    return -3.0;
}

I could call it by doing something like this:

list<any> p;
p.push_back((string)"Hello");
p.push_back(7);
double result = callFromAnyList(bind(myFunc, _1, _2), p);

Is it possible to write something like my callFromAnyList function?  Can you inspect the result type and the parameter types from the type returned from bind?  And then call any_cast<P1>(*p.begin()), etc?  I've tried to understand the bind code, but it's a little hard to follow, and it doesn't appear as though they wrote it with inspection in mind.

[A]
As you updated your concerns in the comment sections, here the answer. Just getting the return type of a function is possible:
```
```
template<typename>
struct return_of;

template<typename R>
struct return_of<R(*)()> {
    typedef R type;
};

template<typename R, typename P1>
struct return_of<R(*)(P1)> {
    typedef R type;
    typedef P1 parameter_1;
};

void foo(int);

template<typename Func>
typename return_of<Func>::parameter_1 bar(Func f) {
    return 42;
}

// call: bar(foo);
```
```
I guess you see what this comes down to :) You can use boost function types which already has solved it:
http://www.boost.org/doc/libs/1_37_0/libs/function_types/doc/html/index.html


q:
I recently started building a console version of a web application. I copied my custom sections from my web.config. to my app.config. When I go to get config information i get this error:

An error occurred creating the configuration section handler for x/y: Could not load type 'x' from assembly 'System.Configuration

The line that it is not liking is:

return ConfigurationManager.GetSection("X/Y") as Z;

Anyone run into something like this?

I was able to add

<add key="IsReadable" value="0"/>

in the appSettings and read it.

Addition:

I do actually have this defined about the custom section:

  <configSections>
    <sectionGroup name="x">
      <section name="y" type="zzzzz"/>
    </sectionGroup>

  </configSections>

[A]
it sounds like your config-section handler is not defined
```
```
<configSection>
    <section
            name="YOUR_CLASS_NAME_HERE"
            type="YOUR.NAMESPACE.CLASSNAME, YOUR.NAMESPACE, Version=1.1.0.0, Culture=neutral, PublicKeyToken=PUBLIC_TOKEN_ID_FROM_ASSEMBLY"
            allowLocation="true"
            allowDefinition="Everywhere"
          />
</configSection>
```
```


q:
Is it possible to have a file belong to multiple subpackages? For example:

/**
 * Name
 *
 * Desc
 *
 * @package    Core
 * @subpackage  Sub1
 * @subpackage  Sub2
 */

Thanks!

[A]
It appears that PHPDoc does not allow you to do it for namespacing reasons. From the
PHPDoc Docs
:
NOTE: The @subpackage tag is intended to help categorize the elements that are in an actual @package value. Since PHP itself doesn't allow you to have two functions with the same name in the same script, PhpDocumentor also requires all names in an @package to be unique... meaning, @subpackage does not allow further "naming separation" inside that @package. What it does do is allow a level of visual grouping/separation of the elements inside that @package.
It seems that because PHPDoc's @package is a way to pseudo-namespace your functions and classes, but @subpackage is simply for categorization. Have you tried adding more than one subpackage? If so, what were the results?


q:
I have a layout similar to this:

<div id="..."><img src="..."></div>

and would like to use a jQuery selector to select the child img inside the div on click.

To get the div, I've got this selector:

$(this)

How can I get the child img using a selector?

[A]
Try this code:
```
```
$(this).children()[0]
```
```


q:
I am trying to deserialize a stream but I always get this error "End of Stream encountered before parsing was completed"?

Here is the code:

        //Some code here
        BinaryFormatter b = new BinaryFormatter();
        return (myObject)b.Deserialize(s);//s---> is a Stream object that has been fill up with data some line over here

Any one have ideas?

[A]
Try to set the position to 0 of your stream and do not use your object but the object type.
```
```
BinaryFormatter b = new BinaryFormatter();
        s.Position = 0;
        return (YourObjectType)b.Deserialize(s);
```
```


q:
I'm just getting into unit testing, and have written some short tests to check if function called isPrime() works correctly.

I've got a test that checks that the function works, and have some test data in the form of some numbers and the expected return value.

How many should I test? How do I decide on which to test? What's the best-practices here?

One approach would be to generate 1000 primes, then loop through them all, another would be to just select 4 or 5 and test them. What's the correct thing to do?

[A]
Ask yourself. What EXACTLY do I want to test. And test the most important. Test to make sure it basically does what you are expecting it to do in the expected cases.
Testing all those nulls and edge-cases - I - don't think is real, too time consuming and someone needs to maintain that later!
And...your test code should be simple enough so that you do not need to test your test code!
If you want to check that your function correctly applied the algorithm and works in general - probably will be enough some primes.
If you want prove that the method for finding primes is CORRECT - 100000 primes will not be enough :)
But you don't want to test the latter (probably)...
Only you know what you want to test! :)
PS I thnik using loops in unit tests is not always wrong but I would think twice before doing that. Test code should be VERY simple. What if something goes wrong and there is a bug in your test???? :)
However, you should try to avoid test code duplication as regular code duplication. Someone has to maintain test code.
PEOPLE PLEASE COMMENT WHY YOU THINK THIS WAS WORTH TWO DOWNVOTES :)


q: I need to create some functionality in our SharePoint app that populates a list or lists with some simple hierarchical data.  Each parent record will represent a "submission" and each child record will be a "submission item."  There's a 1-to-n relationship between submissions and submission items.  Is this practical to do in SharePoint?  The only types of list relationships I've done so far are lookup columns, but this seems a bit different.  Also, once such a list relationship is established, then what's the best way to create views on this kind of data.  I'm almost convinced that it'd be easier just to write this stuff to an external database, but I'd like to give SharePoint a shot in order to take advantage of the automated search capabilities.

[A]
Do it in a separate database, create a page(s) with controls that surfaces the data and run search over that. Loses quite a bit of the SharePoint features though.
Otherwise it may be okay to create a custom field control that will allow you to lookup the data in the other list.
The custom field control can be the one to "view" the related data.
I know we have done it for parent child relationships between pages on the same list. Not 1-to-N though.
Tough choice either way.


q:
I am implementing a validation class in classic ASP. How should the validation class interface with my other classes?

My current setup:
The User class's set methods call the appropriate validation method in the validation class. Any errors that occur are stored in User.mError. For example, here's my set method for the Email member variable in ASP Classic:

Class User
  Property Let Email(EmailInput)
     If (myValidation.isEmail(EmailInput)) then
        mEmail = EmailInput
     Else
        mError = "Invalid Email Address format."
     End If

I don't like how I'm going to need an error member variable for every object that calls my validation class. Suggestions on a better setup?

Any suggestions for a validation architecture I should review as a benchmark?

[A]
I would suggest looking at Validator related classes provided by .net framework.
In your case, you can have a Validator Class (EmailValidator to be specific), which could have a method named Validate which takes a string, returns a boolean
You could also pass ErrorMessage as one of the parameters of the Validate function
e.g.
```
```
Psuedo Code.

class EmailValidator
...
function Validate(byval EmailAddress as string, optional byval Result as string) as boolean)
..
if (condition success)
result = success
elseif (emailafddress doesnt have @)
result = "invalid email address. missing @"
endif
end function
end class
```
```
You can take error message out, if you want to have control over it.
I invite fellow SO guys to suggest any shortcomings in this.


q:
How can I retrieve raw time-series data from a Proficy Historian/iHistorian?

Ideally, I would ask for data for a particular tag between two dates.

[A]
A coworker of mine put this together:
In web.config:
```
```
<add name="HistorianConnectionString"
     providerName="ihOLEDB.iHistorian.1"
     connectionString="
       Provider=ihOLEDB.iHistorian;
       User Id=;
       Password=;
       Data Source=localhost;"
/>
```
```
In the data layer:
```
```
public DataTable GetProficyData(string tagName, DateTime startDate, DateTime endDate)
{
    using (System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection())
    {
        cn.ConnectionString = webConfig.ConnectionStrings.ConnectionStrings["HistorianConnectionString"];
        cn.Open();

        string queryString = string.Format(
                "set samplingmode = rawbytime\n select value as theValue,Timestamp from ihrawdata where tagname = '{0}' AND timestamp between '{1}' and '{2}' and value > 0 order by timestamp",
                tagName.Replace("'", "\""), startDate, endDate);

        System.Data.OleDb.OleDbDataAdapter adp = new System.Data.OleDb.OleDbDataAdapter(queryString, cn);
        DataSet ds = new DataSet();

        adp.Fill(ds);
        return ds.Tables[0];
    }
}
```
```
Update:
This worked well but we ran into an issue with tags that don't update very often. If the tag didn't update near the start or end of the requested startDate and endDate, the trends would look bad. Worse, still were cases where there were no explicit points during the window requested--we'd get no data back.
I resolved this by making three queries:
The previous value
before
the start-date
The points between startDate and endDate
The next value
after
the endDate
This is a potentially inefficient way to do it but It Works:
```
```
public DataTable GetProficyData(string tagName, DateTime startDate, DateTime endDate)
{
    DataSet ds = new DataSet();
    string queryString;
    System.Data.OleDb.OleDbDataAdapter adp;

    using (System.Data.OleDb.OleDbConnection cn = new System.Data.OleDb.OleDbConnection())
    {
        cn.ConnectionString = proficyConn.ConnectionString;
        cn.Open();

        // always get a start value
        queryString = string.Format(
             "set samplingmode = lab\nselect value as theValue,Timestamp from ihrawdata where tagname = '{0}' AND timestamp between '{1}' and '{2}' order by timestamp",
            tagName.Replace("'", "\""), startDate.AddMinutes(-1), startDate);
        adp = new System.Data.OleDb.OleDbDataAdapter(queryString, cn);
        adp.Fill(ds);

        // get the range
        queryString = string.Format(
             "set samplingmode = rawbytime\nselect value as theValue,Timestamp from ihrawdata where tagname = '{0}' AND timestamp between '{1}' and '{2}' order by timestamp",
            tagName.Replace("'", "\""), startDate, endDate);
        adp = new System.Data.OleDb.OleDbDataAdapter(queryString, cn);
        adp.Fill(ds);

        // always get an end value
        queryString = string.Format(
             "set samplingmode = lab\nselect value as theValue,Timestamp from ihrawdata where tagname = '{0}' AND timestamp between '{1}' and '{2}' order by timestamp",
        tagName.Replace("'", "\""), endDate.AddMinutes(-1), endDate);
        adp = new System.Data.OleDb.OleDbDataAdapter(queryString, cn);
        adp.Fill(ds);

        return ds.Tables[0];
    }
}
```
```
And yes, I know, those queries should be parameterized.


q:
I always have this notion that writing SQL queries in the code behind is not good compared to writing it using a SqlDataSource

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds, "Categories");

myGridView.DataSource = ds;

myGridView.DataBind();

vs.

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:myConnection %>"
  SelectCommand="SELECT * FROM Categories" />

I feel using SqlDataSource is secure, easy to maintain.
Is my concern true? Please justify.

[A]
I wouldn't write SQL queries in code behind full stop. How about a data access layer?
What happens if you want to change your backing store? You're going to have to re-write all your code-behind.
What happens where you need to use the data in more than one place? You duplicate code.
You need think seriously about how you're architecting your solution before writing SQL queries in your code behind. Think about separation and maintainability long before you question the 'security' of SqlDataSource objects. Seriously.


q:
If a line of text is wrapped to an additional line, how do I determine programmatically the point in the string where it was broken.

Example: Input string = "This is a test of a wrapped line of text".

      Based on the width of the richTextBox it could display:

            This is a test of a wrapped line of
            text.

What I need to determine is offset in the line of the word(s) that got wrapped. In the above case the word "text".

When I extract the Xaml from the richTextBox, I get the original text unwrapped.

Thanks,

Bob Kerlinger

[A]
The trick I found uses the TextPointer class and its GetCharacterRec method.
RichTextBox holds a FlowDocument. Text in flow documents is contained in a Run object (bit of a simplification, but it works). The code finds the TextPointer at the start of the first Run. It then gets the bounding rectangle of that first character. Next the code walks forward one character at a time, gets a new bounding rectangle and checks if the bottom of the new rectangle is different from the original rectangle. If the bottom is different then we are on a new line. TextPointer can then get the text either before or after the break.
```
```
public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    private void inspect(object sender, RoutedEventArgs e)
    {
        TextPointer pointer = FindRun(inBox.Document);

        string textAfterBreak = FindBreak(pointer);

        outBox.Text = textAfterBreak;
    }

    private string FindBreak(TextPointer pointer)
    {
        Rect rectAtStart = pointer.GetCharacterRect(LogicalDirection.Forward);

        pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
        Rect currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);

        while (currentRect.Bottom == rectAtStart.Bottom)
        {
            pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward);
            currentRect = pointer.GetCharacterRect(LogicalDirection.Forward);
        }

        string textBeforeBreak = pointer.GetTextInRun(LogicalDirection.Backward);
        string textAfterBreak = pointer.GetTextInRun(LogicalDirection.Forward);

        return textAfterBreak;
    }

    private TextPointer FindRun(FlowDocument document)
    {
        TextPointer position = document.ContentStart;

        while (position != null)
        {
            if (position.Parent is Run)
                break;

            position = position.GetNextContextPosition(LogicalDirection.Forward);
        }

        return position;
    }
}

<Window x:Class="LineBreaker.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <RichTextBox Grid.Row="0" Name="inBox">
        </RichTextBox>
        <Button Grid.Row="1" Click="inspect">Find Break</Button>
        <TextBox Name="outBox" Grid.Row="2"/>
    </Grid>
</Window>
```
```


q:
I have this application installed on my Macbook Pro that allows me to disable a core on my CPU. It got me wondering: How does disabling a core affect the running processes?

I am also interested if disabling a core has an affect on the following

Battery Life

Heat generation

Increased performance when the processor would normally be using less than 40% of both cores?

[A]
I don't know about power consumption, but I expect you would save some margin.  This depends upon the percentage of power used within the MBP by the CPU.
As for impact on raw processing power, it depends upon the nature of the applications you're running.  Most applications aren't designed to utilise multiple cores, although most top-end apps are.  So, if you're using Photoshop or video editing software then you'll notice a significant peak performance reduction in cases where the performance bottleneck is the CPU (and not network IO or disk IO).


q:
I have a table in my MYSQL database which does not have a primary key, but has a unique key on two columns.  When using MyEclipse's Hibernate reverse engineer tool to create a mapping for that table, it generates two classes, one for named after the table itself, and one with an "Id" suffix.  It seems most of the useful methods ended up in the Id class, so it seems that is the one you would instantiate and save to persist data.  I can appreciate the fact that the Id class is created in order to represent a unique row in the table / mapped object, but what is the use of splitting out this into two classes, and what, then is the use of the non-Id-suffixed class?

My colleague argues you can accomplish the same with just one class and scoffs at using the reverse engineering for these tables which don't have a primary key.  I, on the other hand, assume MyEclipse developers are much smarter than me and that there is a really good reason to do it this way.  Is there?

[A]
You want to use:
```
```
Collections.<String>emptyList();
```
```
If you look at the source for what emptyList does you see that it actually just does a
```
```
return (List<T>)EMPTY_LIST;
```
```


q:
I have a Freemarker template which contains a bunch of placeholders for which values are supplied when the template is processed. I want to conditionally include part of the template if the userName variable is supplied, something like:

[#if_exists userName]
  Hi ${userName}, How are you?
[/#if_exists]

However, the FreeMarker manual seems to indicate that if_exists is deprecated, but I can't find another way to achieve this. Of course, I could simple providing an additional boolean variable isUserName and use that like this:

[#if isUserName]
  Hi ${userName}, How are you?
[/#if]

But if there's a way of checking whether userName exists then I can avoid adding this extra variable.

[A]
To check if the value exists:
```
```
[#if userName??]
   Hi ${userName}, How are you?
[/#if]
```
```
Or with the standard freemarker syntax:
```
```
<#if userName??>
   Hi ${userName}, How are you?
</#if>
```
```
To check if the value exists and is not empty:
```
```
<#if userName?has_content>
    Hi ${userName}, How are you?
</#if>
```
```


q: What is the most efficient way to detect duplicates in a 10 column / 50K row table? I'm using MSSQL 8.0

[A]
You can use
```
group by
```
on all columns and then
```
count(*)>1
```


q:
How do I check if the timestamp date of a record is before midnight today?

datediff is driving me nuts...

[A]
Try:
```
```
WHERE dtColumn < DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
```
```