q:
What is an efficient way to shrink a two dimensional array to a smaller size in C#?

For example:

var bigArray = new object[100, 100];
var smallArray = new object[10, 10];

bigArray[0, 0] = 1;
bigArray[0, 1] = 2;
...
bigArray[99, 99] = 100000;

startRowIndex = 0;
startColumnIndex = 0;
endRowIndex = 9;
endColumnIndex = 9;

smallArray = bigArray.SomeShirnkingMethod(startRowIndex, startColumnIndex, endRowIndex, endColumnIndex);

How will you write SomeShrinkingMethod() ?

Thanks!

EDIT: I'm simply trying to get the first 10 rows and columns of the bigArray into the smallArray but I'm not sure if a looping through the array is the most efficient method.

[A]
You've got to create a new array of the desired size (in your code, you've already done this) and copy the content. I'm not sure what the “shrinking” operation needs to do in your case. However, you cannot modify the dimensions of an existing array.
The function you proposed is defective because it can't know the dimensions of the target array. Either you pass it the dimensions and dimension the new array internally or you pass it the target array and simply copy the contents.
Edit:
In response to your edit: Yes, looping will be the reasonable way to do this and this is also reasonably fast. I'm not aware of a block-copying mechanism in .NET that can be applied to multidimensional arrays.


q:
We are doing some performance tests on our website and we are getting the following error a lot:

*** 'C:\inetpub\foo.plex' log message at: 2008/10/07 13:19:58
DBD::ODBC::st execute failed: [Microsoft][SQL Native Client]String data, right truncation (SQL-22001) at C:\inetpub\foo.plex line 25.

Line 25 is the following:

SELECT DISTINCT top 20 ZIP_CODE, CITY, STATE FROM Zipcodes WHERE (ZIP_CODE like ?) OR (CITY like ?) ORDER BY ZIP_CODE

And lastly, this is perl code.

Any ideas?

EDIT: the issue here was that I was searching in the zip file with the string "74523%" which is too long.  I ended up just not adding the % if they give five digits.

[A]
Either the parameter supplied for
```
ZIP_CODE
```
is larger (in length) than
```
ZIP_CODE
```
s column width or the parameter supplied for
```
CITY
```
is larger (in length) than
```
CITY
```
s column width.
It would be interesting to know the values supplied for the two
```
?
```
placeholders.

s: huggingface

c: devops

d: intermediate


q:
I've got a UI front end which talks to and manipulates a SQL Server database, and one of the things it can do is run reports on the data in the database.

This UI can be installed on multiple computers, and so far I've just been keeping the reports in a folder with the install, but this means that any time a new report is added is has to manually be copied to every single UI install out there.

I was thinking of storing the .rpt files in the database itself (As Blobs) and having some mechanism for the UI to fetch them when needed as a way to centralize the reports and eliminate this issue.

Has anybody tried this, and did it work well? Or if you haven't, can you think of anything I should take into account before moving forward with this? Are the any tips, tricks, or caveats you can think of that might be helpful to me?

[A]
Here's great podcast with Paul Randal (he wrote parts of DBCC!) where they talk about the new filestream feature in sql server 2008  for handling blobs, but they also go into the sizes of files that do and don't work well
as blobs as part of the talk. I think it would help you.
http://www.runasradio.com/default.aspx?showNum=74
I just found out that the 25-page FILESTREAM whitepaper Paul wrote has has been published on MSDN.
http://msdn.microsoft.com/en-us/library/cc949109.aspx
.
Based on the research cited later in this white paper, BLOBs smaller than 256 kilobytes (KB) (such as widget icons) are better stored inside a database, and BLOBs larger than 1 megabyte (MB) are best stored outside the database. For those sized between 256 KB and 1 MB, the more efficient storage solution depends on the read vs. write ratio of the data, and the rate of “overwrite”. Storing BLOB data solely within the database (e.g., using the varbinary(max) data type) is limited to 2 gigabytes (GB) per BLOB.


q:
So, I have a nice domain model built.  Repositories handle the data access and what not.  A new requirements has popped up that indicates that reasons need to be logged with deletes.  Up until now, deletes have been fairly simple => Entity.Children.Remove(child).  No internal change tracking was happening as my ORM tool was handling state management.  However, I'm not sure exactyl how to handle this.

1) I could keep a deleted children collection in the parent entity and pull the change tracking out of nHibernate and handle it myself.

2) ??????

[A]
Could you implement the
IInterceptor interface
and override the onDelete functionality to pull the information you need from the entity and send it to logger before you delete (using NHibernate of course)?
example


q: I would like to ask for some simple examples showing the uses of <div> and <span>. I've seen them both used to mark a section of a page with an id or class, but I'm interested in knowing if there are times when one is preferred over the other.

[A]
```
<div>
```
is a block-level element and
```
<span>
```
is an inline element.
If you wanted to do something with some inline text,
```
<span>
```
is the way to go since it will not introduce line breaks that a
```
<div>
```
would.
As noted by others, there are some semantics implied with each of these, most significantly the fact that a
```
<div>
```
implies a logical division in the document, akin to maybe a section of a document or something, a la:
```
```

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Duis congue vehicula purus.

Nam eget magna nec sapien fringilla euismod. Donec hendrerit.

```
```


q:
I am trying to install newgem on my linux box (sudo gem install newgem) and i am getting the following error:

Building native extensions.  This could take a while...
ERROR:  Error installing newgem:
ERROR: Failed to build gem native extension.

/usr/bin/ruby1.8 extconf.rb install newgem
extconf.rb:1:in `require': no such file to load -- mkmf (LoadError)
from extconf.rb:1

Gem files will remain installed in /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4 for inspection.
Results logged to /usr/lib/ruby/gems/1.8/gems/RedCloth-4.0.4/ext/redcloth_scan/gem_make.out

What could the problem be?

[A]
```
mkmf
```
is a Ruby module which generates Makefiles.  It is supposed to be part of the standard Ruby install, but Debian (and derivatives) split it out into the
```
ruby1.8-dev
```
package.
If you can't find
```
mkmf.rb
```
in any of the directories outputted by
```
ruby -e'print $:.join("\n")'
```
, then you should figure out what you need to install.


q: What tool is there for generating C# classes from NHibernate mappings files?

[A]
On the
NHibernate resources page
under 'Helpful tools', there are a few code generators listed:
http://nhibernate.info/doc/nh/en/index.html


q:
Why does Visual studio take so long to delete a file from the solution tree?  The app freezes and sits there for what feels like an eternity.

If I delete the file from the file system first, then delete it in the solution it happens instantly.

Is there an option I can set somewhere to avoid this?

[A] I've found that this is sometimes a symptom of project size. Deleting a file from a project with hundreds of files can take 30 seconds on my (admittedly slow) work computer. But deleting one of two files in a project is usually instant.


q:
Is there a way to select manually a node in virtualizing TreeView and then bring it into view?

The data model I'm using with my TreeView is implemented based on the VM-M-V model. Each TreeViewItem's IsSelected property is binded to a corresponing property in ViewModel. I've also created a listener for TreeView's ItemSelected event where I call BringIntoView() for the selected TreeViewItem.

The problem with this approach seems to be that the ItemSelected event won't be raised until the actual TreeViewItem is created. So with the virtualization enabled node selection won't do anything until the TreeView is scrolled enough and then it jumps "magically" to the selected node when the event is finally raised.

I'd really like to use virtualization because I have thousands of nodes in my tree and I've already seen quite impressive performance improvements when the virtualization has been enabled.

[A]
Here is an example taken from an
MSDN Question
public void ScrollToItem(int index)
```
```
{

        Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background,

            (System.Windows.Threading.DispatcherOperationCallback)delegate(object arg)

            {

                int N = fileList.Items.Count;

                if (N == 0)

                    return null;

                if (index < 0)

                {

                    fileList.ScrollIntoView(fileList.Items[0]); // scroll to first

                }

                else

                {

                    if (index < N)

                    {

                        fileList.ScrollIntoView(fileList.Items[index]); // scroll to item

                    }

                    else

                    {

                        fileList.ScrollIntoView(fileList.Items[N - 1]); // scroll to last

                    }

                }

                return null;

            }, null);

    }
```
```


q:
I have this code that performs an ajax call and loads the results into two duplicate divs every time a dropdown is changed. I want the results to be faded into the div, to give a more obvious indication that something has changed, as its so seamless its sometimes hard to notice the change!

print("$('.ajaxdropdown').change(function(){

        $.ajax({
            type: "GET",
            url: "/includes/html/gsm-tariff.php",
            data: "c_name="+escape($(this).val()),
            success: function(html){
                $("#charges-gsm").html(html);
                                    //i want to fade result into these 2 divs...
                $("#charges-gsm-faq").html(html);
                $("#charges-gsm-prices").html(html);
            }
        });
    });");

I've tried appending the fadein method and a few other things, but no joy.

[A]
You'll have to
```
hide()
```
it before you can use
```
fadeIn()
```
.
UPDATE:
Here's how you'd do this by chaining:
```
```
$("#charges-gsm-faq").hide().html(html).fadeIn();
$("#charges-gsm-prices").hide().html(html).fadeIn();
```
```


q:
select distinct constraint_type from user_constraints;

C
-
C
P
R
U

Seems P means primary key and R means foreign key, correct?  What are U and C?

[A]
```
```
Code Description                Acts On Level
---------------------------------------------
C    Check on a table           Column
O    Read Only on a view        Object
P    Primary Key                Object
R    Referential (Foreign Key)  Column
U    Unique Key                 Column
V    Check Option on a view     Object
```
```


q:
my goal is to write a stored proc that can collect all field values from multiple rows into one single output variable (maybe varchar(some_length)). It may seem strange solution but i've quite positive its the only one i can use at that situation im in. I have not used Firebird before and stored procs look way different than in other well-known  db systems.
My Firebird is 1.5 and dialect 3 (not sure what it means).
So maybe someone could help me with a algorithm example.

[A]
The following procedure does what you describe:
```
```
SET TERM !!;
CREATE PROCEDURE concat_names
  RETURNS (concat VARCHAR(2000))
AS
DECLARE VARIABLE name VARCHAR(100);
BEGIN
  concat = '';
  FOR SELECT first_name || ' ' || last_name FROM employee INTO :name
  DO BEGIN
    concat = concat || name || ', ';
  END
END!!
SET TERM ;!!
EXECUTE PROCEDURE concat_names;
```
```
But I question the wisdom of this solution.  How do you know the VARCHAR is long enough for all the rows in your desired dataset?
It's far easier and safer to run a query to return the result to an application row by row.  Every application programming language has methods to concatenate strings, but more importantly they have more flexible methods to manage the growth of data.
By the way, "dialect" in Firebird and InterBase refers to a compatibility mode that was introduced so that applications developed for InterBase 5.x can work with later versions of InterBase and Firebird.  That was almost ten years ago, and AFAIK there's no need today to use anything lower than dialect 3.


q: Does anyone know if there is a good equivalent to Java's Set collection in C#? I know that you can somewhat mimic a set using a Dictionary or a HashTable by populating but ignoring the values, but that's not a very elegant way.

[A]
Try
HashSet
:
The HashSet(Of T) class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order...
The capacity of a HashSet(Of T) object is the number of elements that the object can hold. A HashSet(Of T) object's capacity automatically increases as elements are added to the object.
The HashSet(Of T) class is based on the model of mathematical sets and provides high-performance set operations similar to accessing the keys of the
Dictionary(Of TKey, TValue)
or
Hashtable
collections. In simple terms, the HashSet(Of T) class can be thought of as a
Dictionary(Of TKey, TValue)
collection without values.
A HashSet(Of T) collection is not sorted and cannot contain duplicate elements...


q: I am building a blog type page, and I want to load items into the page as the user scrolls down, much like Google Reader, or Soup.io. How would you go about achieving this effect? I've seen some examples which read the height of the page, and have an onScroll even attached to the window so that as the user scrolls down we can test to see if they've scrolled down far enough to warrant loading more items. Soup.io's implementation seems to remove the old items as you scroll down so that the browser isn't dealing with an ever-increasingly large DOM tree. Which javascript libraries would be best suited to this task?

[A]
Unspace had an article demonstrating this functionality:
Endless Pageless: No More Next Page
.  Their demonstration page is
here
(dead, for reference).
This particular example uses RoR and
Prototype.


q:
I have two collections which have property Email in both collections. I need to get a list of the items in the first list where Email does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?

So far I have a join, like...

var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };

But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.

[A]
I don't know if this will help you but..
```
```
NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;

var query =
    from c in dc.Customers
    where !(from o in dc.Orders
            select o.CustomerID)
           .Contains(c.CustomerID)
    select c;

foreach (var c in query) Console.WriteLine( c );
```
```
from
The NOT IN clause in LINQ to SQL
by
Marco Russo


q:
Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

>>> 6/3
2
>>> 6//3
2

[A]
```
//
```
is floor division. It will always give you the integer floor of the result.  The other is 'regular' division.


q:
Is there any way to clean up this type of loop using LINQ?

  List<Car> result;
  List<string> makes;
  List<string> models;

  for (int i = 0; i < makes.Count() && i < models.Count(); i++)
  {
    result.Add(new Car() { Make = makes[i], Model = models[i] });
  }

Basically I'm looking for some way to collate multiple arrays of individual fields into a single array of objects made up of those fields.

[A]
You could use
```
Enumerable.Range
```
, like so:
```
```
List<Car> result = Enumerable.Range(0, Math.Min(makes.Count, models.Count))
    .Select(i => new Car { Make = makes[i], Model = models[i] }).ToList();
```
```
If
```
makes
```
and
```
models
```
always contain the same number of items, you can use more compact syntax:
```
```
List<Car> result = makes.Select((make, i) => new Car { Make = make, Model = models[i] }).ToList();
```
```


q:
I'm working on a home project that involves comparing images to a database of images (using a quadrant - or so - histogram approach).  I wanted to know what my options are in regards to web cams or other image capture devices that:

Are easy to work with with the
Windows SDK (particularly
DirectShow, which I plan to use
with C#)

Have drivers for both
64-bit and 32-bit Windows Vista (and
Server 2008)

I'm asking primarily so I can avoid pitfalls that other people may have experienced with web cams and to see if there are other image capture devices (or C# usable APIs) available that I should look at.  I suspect that any old web cam will do but I'd rather be safe than sorry.

[A]
As per
ScottGu
,
One tip to take advantage of is the relative path fix-up support provided by the head runat="server" control.  You can use this within Master Pages to easily reference a .CSS stylesheet that is re-used across the entire project (regardless of whether the project is root referenced or a sub-application):
The path fix-up feature of the head control will then take the relative .CSS stylesheet path and correctly output the absolute path to the stylesheet at runtime regardless of whether it is a root referenced web-site or part of a sub-application.


q:
How do I do forward referencing / declaration in C++ to avoid circular header file references?

I have the #ifndef guard in the header file, yet memory tells me I need this forward referencing thing - which i've used before >< but can't remember how.

[A]
You predeclare the class without including it.  For example:
```
```
//#include "Foo.h" // including Foo.h causes circular reference
class Foo;

class Bar
{
...
};
```
```


q:
In the following code below:

Image img = new Image();
img.Source = new BitmapImage(new Uri("http://someURL/somefilename.jpg", UriKind.Absolute));

how can I determine if the image successfully loaded (when there's a valid URI)? i.e., The URI is a valid format, but the file may not exist.

[A]
```
Image
```
has an
```
ImageFailed
```
event.
```
BitmapSource
```
(base for
```
BitmapImage
```
) has an
```
IsDownloading
```
property, as well as
```
DownloadProgress
```
,
```
DownloadCompleted
```
, and
```
DownloadFailed
```
events.


q:
Say you've loaded a text file into a string, and you'd like to convert all Unicode escapes into actual Unicode characters inside of the string.

Example:

"The following is the top half of an integral character in Unicode '\u2320', and this is the lower half '\U2321'."

[A]
The answer is simple and works well with strings up to at least several thousand characters.
Example 1:
```
```
Regex  rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, match => ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString() );
```
```
Example 2:
```
```
Regex  rx = new Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } );
```
```
The first example shows the replacement being made using a lambda expression (C# 3.0) and the second uses a delegate which should work with C# 2.0.
To break down what's going on here, first we create a regular expression:
```
```
new Regex( @"\\[uU]([0-9A-F]{4})" );
```
```
Then we call Replace() with the string 'result' and an anonymous method (lambda expression in the first example and the delegate in the second - the delegate could also be a regular method) that converts each regular expression that is found in the string.
The Unicode escape is processed like this:
```
```
((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); });
```
```
Get the string representing the number part of the escape (skip the first two characters).
```
```
match.Value.Substring(2)
```
```
Parse that string using Int32.Parse() which takes the string and the number format that the Parse() function should expect which in this case is a hex number.
```
```
NumberStyles.HexNumber
```
```
Then we cast the resulting number to a Unicode character:
```
```
(char)
```
```
And finally we call ToString() on the Unicode character which gives us its string representation which is the value passed back to Replace():
```
```
.ToString()
```
```
Note: Instead of grabbing the text to be converted with a Substring call you could use the match parameter's GroupCollection, and a subexpressions in the regular expression to capture just the number ('2320'), but that's more complicated and less readable.


q:
echo $_POST["name"]; //returns the value a user typed into the "name" field

I would like to be able to also return the text of the key. In this example, I want to return the text "name". Can I do this?

[A]
```
```
array_keys($_POST)
```
```
Manual


q:
I'd like all queries like

http://mysite.com/something/otherthing?foo=bar&x=y

to be rewritten as

http://mysite.com/something/otherthing.php?foo=bar&x=y

In other words, just make the .php extension optional, universally.

[A]
Something like...
```
```
RewriteRule /something/(.+)?(.+) /something/$1.php?$2
```
```
would probably work.


q:
How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?

To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?

[A]
In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records.  So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration.  If they don't offer some sort of API, this might get tricky.
Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case).  I've never explored this option before but I suspect most of the consumer registrars do not.  I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.


q:
I can't find this anywhere in the Domino Designer help. It seems so straightforward!

All I need to do is find the position of a character in a string.

[A]
(edited) Please see the answer from charles ross instead.
https://stackoverflow.com/a/19437044/11293
My less efficient method is below.
If you really need the character position though you could do this:
```
```
REM {
    S  Source string
    F  Character to find
    R  Location of character in string or 0
};

S := "My string";
F := "t";
LEN_S := @Length(S);
R := 0;

@For(I := 1; I < LEN_S; I := I + 1;
    @If(@Middle(S; I; 1) = F;
        @Do(R := I; I := LEN_S);
        @Nothing
    )
);
```
```


q:
Can an XML attribute be the empty string?

In other words, is

<element att="" />

valid XML?

[A]
Yes, this is well-formed XML.
An easy way to test this (on Windows) is to save the sample in a
```
test.xml
```
file and open it with Internet Explorer. IE will display an error message if the document is not well-formed.


q:
When I debug locally in fire fox 2.0x many times my page won't have the styles added properly or the page will not completely render (the end is seemingly cut off). Sometimes it takes multiple refreshes or shift-refreshes to fix this. Is this a common issue or is it just me? Any solutions?

I want to add that this is happening in fire fox 3.x to me as well. I add my javascript to the pages dynamically and this might be part of the issue. This is when I am working locally with Visual Studio.

Update: This does happen in IE but it happens much more often in Fire Fox. The issue seems to be only javascript and CSS files not loading. For example I get jQuery is not defined, $ is not defined etc. I don't think I have local IIS to test this on but from the server it always works perfectly. Fire Bug shows all my css and javascript files to be requested and received.

[A] One thing to do would be to check the source of the page(s) in question. My guess would be that the local server that VS runs is not giving you the entire source of the page. One way to verify this would be to run exactly the same code in the debug environment, as well as from a "real" server like IIS 6. If the same behavior is seen on loading the page from both servers, as well as insuring that the full page source is being recieved by the browser(s), then it is a bug in Firefox and should be reported. This is especially true if other browsers, ie. IE, Chrome, Safari, Opera, render the page fully.


q:
Possible Duplicate:

  What is the correct way to create a single instance application?

How to force C# .net app to run only one instance in Windows?

[A]
I prefer a mutex solution similar to the following.  As this way it re-focuses on the app if it is already loaded
```
```
using System.Threading;

[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
   bool createdNew = true;
   using (Mutex mutex = new Mutex(true, "MyApplicationName", out createdNew))
   {
      if (createdNew)
      {
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm());
      }
      else
      {
         Process current = Process.GetCurrentProcess();
         foreach (Process process in Process.GetProcessesByName(current.ProcessName))
         {
            if (process.Id != current.Id)
            {
               SetForegroundWindow(process.MainWindowHandle);
               break;
            }
         }
      }
   }
}
```
```


q:
Suppose there is a fully populated array of data String[n][3] myData.

I want to do this:

for (String[] row : myData)
{
   SQL = "update mytable set col3 = row[2]
   where col1 = row[0] and col2=row[1];"
}

Obviously I've left a lot out, but I want to express the idea as succinctly as possible.

Is there a simple way of doing this in a single DB command?
How about a not so simple way?

EDITS:
Data is not coming from another table (it's a web form submission - Multiple Choice exam)

Seeing as the app is web facing, It's got to be injection proof.  Parameterized Queries are my preferred way of going.

I'm using MS-SQL Server 2005

EDIT:Closing, and re-asking as Multiple DB Updates:

EDIT: Re-opened, as this appears to be a popular question

[A]
You can make a big string like:
```
```
for (String[] row : myData)
{
   SQL += "update mytable set col3 = row[2]
   where col1 = row[0] and col2=row[1];"
}

sqlDriver.doInsertQuery(SQL); // change this to your way of inserting into the db
```
```
And just commit it all at once. I'm not very good with SQL so that's how i would do it.
The sql engine will just split it by the ';' and do separate inserts on its own. It's ok to add it all in a string though. It's kind the same as if u copy a big string with multiple updates/inserts into the sql prompt


q:
I want to have a reusable button which can be registered for one of many different callbacks, determined by an external source. When a new callback is set, I want to remove the old. I also want to be able to clear the callback externally at any time.

public function registerButtonCallback(function:Function):void
{
  clearButtonCallback();

  button.addEventListener(MouseEvent.CLICK, function, false, 0, true);
}

public function clearButtonCallback():void
{
  if (button.hasEventListener(MouseEvent.CLICK) == true)
  {
    // do something to remove that listener
  }
}

I've seen suggestions on here to use "arguments.callee" within the callback, but I don't want to have that functionality tied to the callback - for example, I might want to be able to click the button twice.

Suggestions?

[A]
I am presuming that you want only one callback function at any given time.  If that's teh case then why not have a single callback function associated with the click event on the button which itself called a function and have that function be settable...
```
```
<mx:Button click="doCallback()" .../>

public var onClickFunction:Function = null;
private function doCallback():void
{
    if (onClickFunction != null)
    {
        onClickFunction(); // optionally you can pass some parameters in here if you match the signature of your callback
    }
}
```
```
A consumer of your control which houses your button would set the onClickFunction with the appropriate function.  In fact you could set it as often as you liked.
If you wanted to go one step further you could subclass the AS3 Button class and wrap all of this inside it.


q: One problem I have with open-source is not often the product or documentation, but the level of community involvement and support. Response time for some questions on official forums can take more than a week, which can honestly make a big difference when choosing a platform for commercial services use. However, I find that evaluating the community beforehand is very difficult. How do I know what are the most common issues, and whether or not people are getting support for them? How do I know what problems I personally might encounter based upon my project, which would require some level of community support? Do you have a formula for performing this evaluation?

[A]
If your question is posed because you don't want to pay for support, then I think your best bet is to ask questions about a specific project on neutral forums like this and see what others have experienced in terms of support and timeliness of resolution to issues.
If you are willing to pay for support, there are companies that provide commercial support for open source projects, like
OpenLogic
as an example that could factor into your formula.


q:
I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.

Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.

Net::HTTP doesn't look like the best idea. curb is looking good.

[A]
Ok, here's a simple example using curb.
```
```
require 'yaml'
require 'curb'

# prepare post data
post_data = fields_hash.map { |k, v| Curl::PostField.content(k, v.to_s) }
post_data << Curl::PostField.file('file', '/path/to/file'),

# post
c = Curl::Easy.new('http://localhost:3000/foo')
c.multipart_form_post = true
c.http_post(post_data)

# print response
y [c.response_code, c.body_str]
```
```


q: I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.

[A]
Here's what I came up with:
```
```
import os

def CreateNewChangeList(description):
    "Create a new changelist and returns the changelist number as a string"
    p4in, p4out = os.popen2("p4 changelist -i")
    p4in.write("change: new\n")
    p4in.write("description: " + description)
    p4in.close()
    changelist = p4out.readline().split()[1]
    return changelist

def OpenFileForEdit(file, changelist = ""):
    "Open a file for edit, if a changelist is passed in then open it in that list"
    cmd = "p4 edit "
    if changelist:
        cmd += " -c " + changelist + " "
    ret = os.popen(cmd + file).readline().strip()
    if not ret.endswith("opened for edit"):
        print "Couldn't open", file, "for edit:"
        print ret
        raise ValueError
```
```


q:
Using the SharePoint API, how can I modify an extended webapp web.config file?

I have to do some changes in this file to specify the connection string, membershipprovider, etc... for using Forms Authentication.

Currently, I can change the "master" webapplication web.config file, but not the extended one.

Edited

I'm using Sp 2007. I'm already using SPWebConfigModification class to modify the parent webapp. Thoses modifications are propagated to the extended webapp. I have to change ONLY the extended one. But I don't find the way to do it.

What I'm trying to achieve, is to program a little wizard that:

Shows a WebApp list so the user can select one

Extend that selected webapp to a different zone

Configure that extended zone to use Forms Authentication

Thanks

[A]
Quick answer: look into the SPWebConfigModification class. I am assuming you're using SharePoint 2007. The best way to learn about this is to dig into open source projects:
Google code search:
http://www.google.com/codesearch?q=spwebconfigmodification&hl=en&btnG=Search+Code
This project on CodePlex looks like it's one big SPWebConfigModification:
http://www.codeplex.com/ajaxifymoss/Release/ProjectReleases.aspx?ReleaseId=13360


q:
We may start converting an old VS2003 MFC project to use the fancy new features provided by the MFC Feature Pack and VS2008. Several of the new UI controls would be very nice except for one thing - they automatically save their information to the registry. I don't have a problem with the registry, but for the multiple environments the users use out program from, it's much easier to save user data to the database.

So, I'm hoping that there is one main "access the registry" function that could be overloaded to point the database. But brief investigation hasn't turned up anything. Has anyone else had any success doing something similar?

[A]
The MFC feature pack uses code supplied by BCGSoft and they added this feature (so you can save state to an XML file, database, etc.) way back in 2001.  I don't have the feature pack on this PC but try looking for a class called something like
```
CMFCRegistrySP
```
.
I will check myself tomorrow.
Does the
```
StateCollection
```
sample do this?
http://msdn.microsoft.com/en-us/library/bb983406.aspx


q:
What exactly does the word patch mean when referring to 'submitting a patch'?

I've seen this used a lot, especially in the open source world. What what does it mean and what exactly is involved in submitting a patch?

[A]
It's a file with a list of differences between the code files that have changed.  It's usually in the format generated by doing a
diff -u
on the two files.  Most version control systems allow the easy creation of patches but it's generally in that same format.
This allows the code change to be easily applied to someone else's copy of the source code using the
patch
command.
For example:
Let's say I have the following code:
```
```
<?php
  $foo = 0;
?>
```
```
and I change it to this:
```
```
<?php
  $bar = 0;
?>
```
```
The patch file might look like this:
```
```
Index: test.php
===================================================================
--- test.php    (revision 40)
+++ test.php    (working copy)
@@ -3,7 +3,7 @@
         <?php
-            $foo = 0;
+            $bar= 0;
         ?>
```
```


q:
I know there are libraries out there for working with ZIP files. And, you can alternatively use the functionality built into Windows for working ZIP files.

But, I'm wondering if anyone has worked out how to use the tools built into the System.IO.Compression namespace within .NET for reading/writing ZIP files? Or, is it not possible using only this namespace?

UPDATED: I've seem someone comment that the System.IO.Packaging namespace might be usefull with this also. Does anyone know exactly how to do it?

[A]
MSDN has a complete
example
http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx
using the ZipPackage class.   Requires .NET 3.5.


q:
I have this .NET regex:

^(?<prefix>("[^"]*"))\s(?<attrgroup>(\([^\)]*\)))\s(?<suffix>("[^"]*"))$

It properly matches the following strings:

"some prefix" ("attribute 1" "value 1") "some suffix"
"some prefix" ("attribute 1" "value 1" "attribute 2" "value 2") "some suffix"

It fails on...

"some prefix" ("attribute 1" "value (fail) 1") "some suffix"

...due to the right paren after "fail".

How can I modify my regex so that the attrgroup match group will end up containing "("attribute 1" "value (fail) 1")"? I've been looking at it for too long and need some fresh eyes. Thanks!

Edit: attrgroup won't ever contain anything other than pairs of double-quoted strings.

[A]
```
```
^(?<prefix>"[^"]*")\s+(?<attrgroup>\(.*\))\s+(?<suffix>"[^"]*")$
```
```
fixed it for me.
I removed the extraneous unnamed groups and simplified (down to "any character") the attribute group.
A
very
worthwhile investment would be JG Soft's RegexBuddy
Edit: This won't validate the attribute group as pairs of quoted strings, but that should/could be done in a separate regex/validation step.


q:
I know that primary keys based on Guids do not have the best performance (due to the fragmentation), but they are globally unique and allow replication scenarios.

Integral identifiers, on the other side, have greater performance at the cost of scalability.

But in what scenarios would someone want to use sequential uniqueidentifier as the primary key? I think, that it beats the purpose of GUID, but still I see mentioning of the sequentals now and then.

What do I miss here?

[A]
What is commonly known as a sequential guids in SQL Server 2005 (generated by NEWSEQUENTIALID()) are an attempt to overcome the issues with normal guids.
They
are
still universally unique but also are always ascending.  This means that they can be used for replication
and
have much better insert performance than traditional GUIDs.
The one drawback is that they are not "secure" because it is possible to guess the next sequential guid.
http://msdn.microsoft.com/en-us/library/ms189786.aspx


q:
I display data into an html table, w/ a drop down box with a list of venues. Each volunteer will be assigned a venue. I envision being able to go down thru the html table and assigning each volunteer a venue. The drop down box contains all the possible venues that they can be assigned to.

<select>
<option value="1">Setup</option>
<option value="2">Check in</option>
etc...
</select>

Then once I am done assigning each volunteer, I want to hit submit and it will assign the appropriate value for each volunteer.

How would I go about doing that, I know how to do that, but only one at a time.

[A]
I can't think of any way. You can put multiple SQL statements into 1 MySQL query:
```
```
UPDATE volunteer SET venue = 1 WHERE id = 2;
UPDATE volunteer SET venue = 2 WHERE id = 3;
...
```
```
I wish there was a way, but I'm thinking that the where will be too different in each query to make it into one.


q: I am trying to retrieve an image stored in an oracle blob and place it in a new System.Drawing.Image instance. I know I can write the stream to a temp.bmp file on the disk and read it from there but thats just not l33t enough for me.  How do I convert the blob object directly to an image?

[A]
I know this uses sql but it should be similar for your needs
```
```
Dim cn As SqlConnection = Nothing
        Dim cmd As SqlCommand = Nothing
        Dim da As SqlDataAdapter = Nothing
        Dim ms As MemoryStream = Nothing
        Dim dsImage As Data.DataSet = Nothing
        Dim myBytes() As Byte = Nothing
        Dim imgJPG As System.Drawing.Image = Nothing
        Dim msOut As MemoryStream = Nothing

        Try
            cn = New SqlConnection(ConnectionStrings("conImageDB").ToString)
            cmd = New SqlCommand(AppSettings("sprocGetImage").ToString, cn)
            cmd.CommandType = Data.CommandType.StoredProcedure

            cmd.Parameters.AddWithValue("@dmhiRowno", irowno)

            da = New SqlDataAdapter(cmd)

            dsImage = New Data.DataSet
            da.Fill(dsImage, "image")

            If dsImage.Tables(0).Rows.Count = 0 Then
                Throw New Exception("No results returned for rowno")
            End If
            myBytes = dsImage.Tables(0).Rows(0)("Frontimage")

            ms = New MemoryStream
            ms.Write(myBytes, 0, myBytes.Length)

            imgJPG = System.Drawing.Image.FromStream(ms)

            'Export to JPG Stream
            msOut = New MemoryStream
            imgJPG.Save(msOut, System.Drawing.Imaging.ImageFormat.Jpeg)
            imgJPG.Dispose()
            imgJPG = Nothing
            ms.Close()
            sFrontImage = Convert.ToBase64String(msOut.ToArray())

            dsImage = New Data.DataSet
            da.Fill(dsImage, "image")
            myBytes = dsImage.Tables(0).Rows(0)("Backimage")

            ms = New MemoryStream
            ms.Write(myBytes, 0, myBytes.Length)

            imgJPG = System.Drawing.Image.FromStream(ms)
            sBackImage = Convert.ToBase64String(ms.ToArray)

        Catch ex As System.IO.IOException ' : An I/O error occurs.
            Throw ex
        Catch ex As System.ArgumentNullException ': buffer is null.
            Throw ex
        Catch ex As System.NotSupportedException ': The stream does not support writing. For additional information see System.IO.Stream.CanWrite.-or- The current position is closer than count bytes to the end of the stream, and the capacity cannot be modified.
            Throw ex
        Catch ex As System.ArgumentOutOfRangeException ': offset or count are negative.
            Throw ex
        Catch ex As System.ObjectDisposedException ' : The current stream instance is closed.
            Throw ex
        Catch ex As System.ArgumentException
            Throw ex
        Catch ex As System.Runtime.InteropServices.ExternalException ': The image was saved with the wrong image format
            Throw ex
        Catch ex As Exception
            Throw ex
        Finally
            If cn IsNot Nothing Then
                cn.Close()
                cn.Dispose()
                cn = Nothing
            End If

            If cmd IsNot Nothing Then
                cmd.Dispose()
                cmd = Nothing
            End If

            If da IsNot Nothing Then
                da.Dispose()
                da = Nothing
            End If

            If ms IsNot Nothing Then
                ms.Dispose()
                ms = Nothing
            End If

            If msOut IsNot Nothing Then
                msOut.Close()
                msOut.Dispose()
                msOut = Nothing
            End If

            If dsImage IsNot Nothing Then
                dsImage.Dispose()
                dsImage = Nothing
            End If

            If myBytes IsNot Nothing Then
                myBytes = Nothing
            End If

            If imgJPG IsNot Nothing Then
                imgJPG.Dispose()
                imgJPG = Nothing
            End If

        End Try
```
```
This code pulls back a tiff wrapped jpeg for the front image so the code is a bit different than for the back image.


q:
I see in C++ there are multiple ways to allocate and free data and I understand that when you call malloc you should call free and when you use the new operator you should pair with delete and it is a mistake to mix the two (e.g. Calling free() on something that was created with the new operator), but I'm not clear on when I should use malloc/ free and when I should use new/ delete in my real world programs.

If you're a C++ expert, please let me know any rules of thumb or conventions you follow in this regard.

[A]
Unless you are forced to use C, you should
never use
```
malloc
```
.  Always use
```
new
```
.
If you need a big chunk of data just do something like:
```
```
char *pBuffer = new char[1024];
```
```
Be careful though this is not correct:
```
```
//This is incorrect - may delete only one element, may corrupt the heap, or worse...
delete pBuffer;
```
```
Instead you should do this when deleting an array of data:
```
```
//This deletes all items in the array
delete[] pBuffer;
```
```
The
```
new
```
keyword is the C++ way of doing it, and it will ensure that your type will have its
constructor called
.  The
```
new
```
keyword is also more
type-safe
whereas
```
malloc
```
is not type-safe at all.
The only way I could think that would be beneficial to use
```
malloc
```
would be if you needed to
change the size of your buffer
of data.  The
```
new
```
keyword does not have an analogous way like
```
realloc
```
.  The
```
realloc
```
function might be able to extend the size of a chunk of memory for you more efficiently.
It is worth mentioning that you cannot mix
```
new
```
/
```
free
```
and
```
malloc
```
/
```
delete
```
.
Note: Some answers in this question are invalid.
```
```
int* p_scalar = new int(5);  // Does not create 5 elements, but initializes to 5
int* p_array  = new int[5];  // Creates 5 elements
```
```


q: PNG images appear "fuzzy" in flash CS3. They are very blocky and appear unanti-aliased (if that is a word) Does anyone have a fix for this? Is there some setting I'm missing?

[A]
Are you loading them into your SWF through a loader? Or are they imported into your library as bitmap symbols? If they are loaded in try calling Bitmap.smoothing = true; or if they are in your library go to the Bitmap's properties and click Allow smoothing.
Other than that I would check to make sure you don't have some crazy above 1 alpha setting or that you aren't messing with the scale of it in your code at any time. Those two options tend to mess with bitmap images fuzziness.
If all else fails you'd probably want to look into turning your images into vector based graphics, then they'd always look exactly how you'd want them to regardless of scaling.


q:
I am currently using Rails 2.1.0 and want to upgrade to Rails 2.1.1. After issuing the following command

gem update rails

I suppose that I need to change this line

RAILS_GEM_VERSION = '2.1.0' unless defined? RAILS_GEM_VERSION

in environment.rb

What other actions should I take to ensure that my application is using the latest version? Are there some other files that need an update?

[A]
As far as I know, that right there defines what version of rails your application as a whole will use. I know for a project I'm in right now I had to override that to 2.1.1 to work on my VM because I had installed the latest, and had not specified the 2.1.0 as required by the project.
The biggest thing you have to watch out for is plugins and extensions that may override this setting, as well as incompatibility that will likely arise from changing versions.
Also there are some known issues with 2.1.1, unless there is a feature you absolutely need now, you may want to wait.


q:
I downloaded a VM image of a web application that uses MySQL.

How can I monitor its space consumption and know when additional space must be added?

[A]
If only MySQL is available, use the SHOW TABLE STATUS command, and look at the Data_length column for each table, which is in bytes.
If you have other languages available on the machine, a script in any of them that runs regularly (cron), checks disk free space or size of database directory, and updates you over e-mail or otherwise. There are far too many options to suggest a particular solution -- it depends on your situation.


q:
If I have two variables containing binary values, how do I append them together as one binary value?  For example, if I used WMI to read the registry of two REG_BINARY value, I then want to be able to concatenate the values.

VBScript complains of a type mismatch when you try to join with the '&' operator.

[A]
Perhaps...
```
```
result = CStr(val1) & CStr(val2)
```
```


q:
Is there a way to do this in one line?

$x =~ s/^\s+//;
$x =~ s/\s+$//;

In other words, remove all leading and trailing whitespace from a string.


q:
I have topics(id*) and tags(id*,name) and a linking table topic_tags(topicFk*,tagFk*).

Now I want to select every single topic, that has all of the good tags (a,b,c) but none of the bad tags (d,e,f).

How do I do that?

[A]
Here's a solution that would work, but requires a join for every tag you require.
```
```
SELECT *
FROM topics
WHERE topic_id IN
    (SELECT topic_id
    FROM topic_tags a
    INNER JOIN topic_tags b
      on a.topic_id=b.topic_id
      and b.tag = 'b'
    INNER JOIN topic_tags c
      on b.topic_id=c.topic_d
      and c.tag = 'c'
    WHERE a.tag = 'a')
AND topic_id NOT IN
    (SELECT topic_id
    FROM topic_tags
    WHERE tag = 'd' or tag = 'e' or tag = 'f')
```
```


q:
I have a situation where I have two models, companies and permissions, where companies is in a separate database from my permissions database.  This is a has and belongs to many relationship because each company can have many permissions and each permission can belong to many companies.

The reason the two databases are split is because the company database runs a high demand production application and the permissions database controls the permissions for another application.

With rails, it looks for the join table in the same database as the primary table.  For instance, if I do company.permissions, it looks in the company database for company_permissions.  If I do permission.companies it looks in the permissions database.

What is the best solution to using a has and belongs to many relationship with multiple databases?

[A]
If the companies data does not change very often, perhaps you could synchronize the data into the permissions database, then do your join naturally. A CMS I inherited is doing something like that where the user authentication is in its own database, and the permissions and such are all stored there, and user accounts are synch'd to the local database for each site. This way user accounts could be shared (especially for administration) across multiple sites with 1 login.
May not be the best because a synch is involved. Ideally you should just store the company data in the permissions db if you can't move permissions out. Unless of course you are joining on company elsewhere.


q: What is the best comment in source code you have ever encountered?

[A]
```
```
//ALL YOUR BASE ARE BELONG TO US
```
```
...it made my boss think someone had hacked in. He didn't know the joke.


q:
What is the best way to copy a list? I know the following ways, which one is better? Or is there another way?

lst = ['one', 2, 3]

lst1 = list(lst)

lst2 = lst[:]

import copy
lst3 = copy.copy(lst)

[A]
If you want a shallow copy (elements aren't copied) use:
```
```
lst2=lst1[:]
```
```
If you want to make a deep copy then use the copy module:
```
```
import copy
lst2=copy.deepcopy(lst1)
```
```


q: I've read (and re-read) Martin Fowler's Mocks Aren't Stubs.  In it, he defines two different approaches to TDD: "Classical" and "Mockist".  He attempts to answer the question "So should I be a classicist or a mockist?", but he admits that he has never tried mockist TDD on "anything more than toys."  So I thought I'd ask the question here.  Good answers may repeat Fowler's arguments (but hopefully more clearly) or add arguments that he didn't think of or that others have come up with since Fowler last updated the essay back in January 2007.

[A]
I don't think you need to choose one over the other. Both have their advantages and disadvantages and both are tools for your toolbox.
"Mockist" tdd makes you a bit more flexible in what you can test while classical TDD makes your tests a bit less brittle because they tend to look more at the input/vs output instead of looking at the actual implementation. When doing mockist unit testing I seem to have more tests break when changing the implementation.
I try to use classical tdd whenever possible (although i often use a mocking framework to set up the stubs quickly). Sometimes I notice I start testing too much at one time or i need too many objects to set up a test. That's when mockist testing can often help you set up smaller tests.
This is all quite abstract so I hope i make sense


q:
Let's say that you have a product that is written in Visual Studio and you provide your customers and users with an installer for that product.

Then, you have some minor changes that you want to deploy to your users; you don't want your users to have to go through an uninstall process, backing up the configuration and then reinstalling the product again and restoring the configuration.

Instead, you want to provide a "hot-fix" that the users can simply copy over the already installed product. Using Visual Studio or some Microsoft tools, how would you go about this?

I don't know if it matters, but lets say that the product is 1) partially a web application, 2) partially a windows service and 3) partially a windows application.

[A]
Use
WiX
.
It can deal with all those things (installation web applications, services, etc), and it's very flexible, free, and it's what Microsoft uses to build their installers.
You can install
Votive
to work with WiX inside of Visual Studio.
The details of how to do exactly what you're asking is a bit complex, and depends on the specifics of the situation. In general, you need to build your initial MSI to have an upgrade code. Then, subsequent upgrade installers will use the same product code and  upgrade code, but change the version. You can read the details of how to do this with WiX as
part 4 of the tutorial
.
IF you have existing installs, they may or may not have an upgrade code already set. You can find out by examining them using
ORCA
(
MSDN how to here
).
This can also be done via the .Net Setup projects built into Visual Studio, but I advise against that. They are not as flexible as WiX. If you care about your installation, and have something as complicated as what you're describing to install, WiX is the best way to go.


q:
I'm using SimpleDateFormat with the pattern EEE MM/dd  hh:mma, passing in the date String Thu 10/9  08:15PM and it's throwing an Unparseable date exception. Why? I've used various patterns with SimpleDateFormat before so I'm fairly familiar with its usage. Maybe I'm missing something obvious from staring at it too long.

The other possibility is funky (technical term) whitespace. The context is a screen-scraping app, where I'm using HtmlCleaner to tidy up the messy html.  While I've found HtmlCleaner to be pretty good overall, I've noticed strange issues with characters that look like whitespace but aren't recognized as such with a StringTokenizer, for example. I've mostly worked around it and haven't dug into the character encoding or anything like that but am starting to wonder.

[A]
Try this instead for your pattern:
```
```
EEE MM/d hh:mma
```
```
The difference is the single
```
d
```
instead of double
```
dd
```
, since your date is for 10/9 instead of 10/09.


q:
Which of these pieces of code is faster?

if (obj is ClassA) {}

if (obj.GetType() == typeof(ClassA)) {}

Edit:
I'm aware that they don't do the same thing.

[A]
This should answer that question, and then some.
The second line,
```
if (obj.GetType() == typeof(ClassA)) {}
```
, is faster, for those that don't want to read the article.
(Be aware that they don't do the same thing)


q:
Can someone give me step by step instructions or point to the correct references in the correct order

so that I can determine the root cause of this issue?

[A]
You can get a memory dump of the process and look into it WinDbg. It will at least give you a list of exceptions and the threads' current state(s). Doing so will recycle the process though.  It is also possible to attach to a QA style machine in a remote debug mode from visual studio. However I've not done this, and it would hang every other request while you debug.
If w3wp is running locally, you can right click on the process in the task manager and select debug to get a look at in in WinDbg.
Otherwise you want something like Debug Diag on your production/test machine to create a full user dump. See:
http://msdnrss.thecoderblogs.com/2008/05/21/debugdiag-11-or-windbg-which-one-should-i-use-and-how-do-i-gather-memory-dumps/
I did all this back in February, and haven't needed to since. the full step by step is actually somewhat painful due to getting symbols for WinDbg and configuring environment variables for where they should be stored etc.
For information on setting up WinDbg for ASP.NET inspection look at this article:
http://support.microsoft.com/kb/892277


q:
I have a form that is sending in sizes of things, and I need to see what the strings are equal to so that I can set the price accordingly. When i try to do this, it says that they are not equal, and i get no prices. This is the code i'm using:

if ($_POST['sizes'] == "Small ($30)"){$total = "30";}
if ($_POST['sizes'] == "Medium ($40)"){$total = "40";}
if ($_POST['sizes'] == "Large ($50)"){$total = "50";}
else {$total = $_POST['price'];}

What am i doing wrong here? I can echo $_POST['sizes'] and it gives me exactly one of those things.

[A]
Try using single quotes
```
```
if ($_POST['sizes'] == 'Small ($30)'){$total = "30";}
elseif ($_POST['sizes'] == 'Medium ($40)'){$total = "40";}
elseif ($_POST['sizes'] == 'Large ($50)'){$total = "50";}
else {$total = $_POST['price'];}
```
```
Double quoted strings use variable interpolation, so the $ symbol becomes significant! See
this manual page
for the differences in how you can declare string literals in PHP.
(Edited to correct the logic error - as others noted, a switch would be much clearer here)


q:
Like it is the case with jpeg images for example?
What's about mp3 or ogg vorbis audio files?

[A]
It all depends on the definition of "loading" and "saving".
If the program in question actually decodes mp3/ogg upon loading and encodes in back when saving (this could be detected by noticeable time it takes to save a file), then yes - you could experience degradation in quality. Especially if the encoding uses different settings (lower bitrate, etc).
On the other hand, a loseless mp3 splitter, for example, could take mp3 and split it into several smaller mp3's without re-encoding them.
So you need to consult a manual of the software in question, there is no generic answer.


q: What is the difference between a deep copy and a shallow copy?

[A]
In short, it depends on what points to what. In a shallow copy, object B points to object A's location in memory. In deep copy, all things in object A's memory location get copied to object B's memory location.
This wiki article has a great diagram.
http://en.wikipedia.org/wiki/Object_copy


q:
I have a windows c# application and I want to display a pdf file, located on a webserver, in an acrobat com object added to my form.

pdf.loadfile(@"http://somewhere.com/nowwhere.pdf")

As my pdf is large, the application seems to hang till the entire file is loaded.

I want to read the large file without the user being under the perception that the application is hung.

[A]
Three suggestions.
the first would be to break it and load a page at a time like some online books do. This is a bit annoying but would save you the loading time. I think ItextSharp has some functionality to do this.
Second try compression. again itextsharp has tools that allow for this
My third suggestion would be to check out
This thread
. choose a few nerdy loading phrases and use an animated gif to distract your client from the long loading time. Obviously this is a last resort, but could useful.


q: I have a (Wordpress powered) website, and Google is indexing some of the sub-directories. How can I stop Apache from showing users the directory listing? I know I can edit .htaccess to password-protect a directory, but I would prefer a 403 / custom redirect if possible.

[A]
Look at your robots.txt rules, and make sure apache is not serving-up directory listings.
see
http://httpd.apache.org/docs/2.0/howto/htaccess.html
&&
http://www.webmasterworld.com/forum92/5272.htm


q:
I swear there used to be a way in X to start capturing all terminal traffic to a file on your host. It may have been a HummingBird extension, but I thought it was standard. Now, I can't find the trick. Am I hallucinating (happens when you get old), or is it possible?

I'm not talking about 'tee'. I want to be able to send a xterm control-sequence to stdout, giving a file name, and have everthing shown in the window from that time onward saved to the file (until the bookend cancel is issued).

[A]
I am a little bit confused by the way you asked your question. First you mention Xterm then X and then terminal, are you simply looking for the "tee" (
```
man tee
```
) command?


q:
I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:

<a href="#" onclick="foo()">Click</a>

But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing.


q: I just want to enable or disable the button inside a ControlTemplate for a WPF Editor that I'm using.

[A]
You really shouldn't be doing that explicitly, but instead be setting it with Triggers in the
```
ControlTemplate
```
itself. These Triggers would be reacting to some other change, and would set the
```
Enabled
```
property of the
```
Button
```
.


q:
I have a webapp which resizes its window to exactly fit its contents:

window.resizeTo(200,300)

People do like having the page fit its window in this way. However with Firefox the next browser window the user opens comes up at the same size, which is ridiculously small.

Is there a way to tell Firefox to resize the current window, but not change its notion of how large subsequent windows should be?

[A]
People do like having the page fit its window in this way.
Which
people?! I'd be seriously annoyed if a web page did anything to the size of my browser window. Fortunately, FF also allows users to disable moving or resizing existing windows, a feature i've taken advantage of for several years.
You should be able to open a
new
window at a specific size using
```
window.open
```
, so you could use that... or better yet, just allow your document to resize / reflow to fit into whatever window size the user prefers.


q:
I just noticed that java.beans.Introspector getBeanInfo does not pickup any superinterface's properties. Example:

public interface Person {
    String getName();
}
public interface Employee extends Person {
    int getSalary();
}

Introspecting on Employee only yields salary even though name is inherited from Person.

Why is this? I would rather not have to use reflection to get all the getters.

[A]
Try using
```
```
public static BeanInfo getBeanInfo(Class<?> beanClass, Introspector.USE_ALL_BEANINFO);
```
```
and see if this yields the result you're looking for.


q:
Is there a way to test the type of an element in JavaScript?

The answer may or may not require the prototype library, however the following setup does make use of the library.

function(event) {
  var element = event.element();
  // if the element is an anchor
  ...
  // if the element is a td
  ...
}

[A]
```
```
if (element.nodeName == "A") {
 ...
} else if (element.nodeName == "TD") {
 ...
}
```
```


q:
Environment:

Windows Server 2003 R2 Enterprise 64bit, SP2

.NET framework is supposedly installed (2.0 SP2, 3.0 SP2, 3.5 SP1)

I say "supposedly" because they are listed as installed under Add/Remove programs. I'm not sure it's properly installed, because the "ASP.NET" tab isn't added to any of the sites in IIS.

In the IIS Web Service Extensions section, I have both "ASP.NET v2.0.50727" (Allowed), and "ASP.NET v2.0.50727 (32-bit)" (Prohibited).

The site in question has script-execute enabled.

Problem:

I created a super-simple ASP.NET/C# website: Default.aspx with a label id="Label1", and a code-behind with: Label1.text = "Hello World"; and the error I'm getting is:

%1 is not a valid Win32 application.

[A]
Have you tried running:
```
```
aspnet_regiis -i
```
```
from the command line?


q:
In emacs there is a handy way to launch the gdb and gui options for gdb, the C debugger.

Is there a similar option in gvim?

[A]
I don't think there is.  I use different windows.
The only thing I can think of is
```
```
!gdb blah blah blah
```
```
but that may not be what you are looking for.  It tends to be used to generate batch text that gets plugged back into the file you are editing.
Hope this helps.


q:
I would like to be able to spawn a linux process that would only have access to stdin, stdout, and stderr (nothing more and nothing less). Can I do this at the process level itself? I am also implicitly stating (oxymoron) that I don't want the spawned process to be able to change the "thing" that the other end of the stream points to.

Metaphorically:

the process has a input pipe that comes from somewhere, it cannot change where the pipe starts from, so it cannot control where input comes from.

the process has output and error pipes that go somewhere, it cannot change where the other end of the output pipes point to, so it cannot control where output goes to.

it cannot create any new pipes.

I am also currently looking at SElinux. Would this allow me to create a process that only had access to these three streams? Thank you.

[A]
If you're root, you can chroot to a directory, drop privileges so that you no longer have filesystem write access, then exec.  That will prevent a program from creating new files.  But there's no way to prevent a program from creating pipes and sockets (well, no-sockets is possible with SELinux), and there's no way to prevent a program from rearranging and closing its file descriptors.
Well, I suppose you could use
```
ptrace
```
to trap all syscalls, and only allow the ones that you approve of, so when I say "there's no way" I mean "there's no easy way".  This incurs a noticable overhead, but if you're careful enough you can make it secure.  The
```
strace
```
or
UMview
projects may be good starting points if you decide to go down this path.


q:
Can you please let me know the SQL to split date ranges when they overlap?

Data (sample data with a date range and possibly other columns):

    Col1 FromDate ToDate
 1. 1    1/1/2008 31/12/2010
 2. 1    1/1/2009 31/12/2012
 3. 1    1/1/2009 31/12/2014

Output:

   Col1  From Date ToDate
1. 1     1/1/2008 31/12/2008 (from row 1 above)
2. 1     1/1/2009 31/12/2010 (from rows 1,2 and 3 above)
3. 1     1/1/2011 31/12/2012 (from rows 2 and 3 above)
4. 1     1/1/2013 31/12/2014 (from row 3 above)

[A]
This should do the trick (MySQL dialect, but easily adaptable)
Initial setup
```
```
SQL query: SELECT * FROM `test` LIMIT 0, 30 ;
Rows: 3
start       end
2008-01-01  2010-12-31
2009-01-01  2012-12-31
2009-01-01  2014-12-31
```
```
Query
```
```
SELECT
  `start` , min( `end` )
FROM (
  SELECT t1.start, t2.end
  FROM test t1, test t2
  WHERE t1.start < t2.end
  UNION
  SELECT t1.end + INTERVAL 1 DAY , t2.end
  FROM test t1, test t2
  WHERE t1.end + INTERVAL 1 DAY < t2.end
  UNION
  SELECT t1.start, t2.start - INTERVAL 1 DAY
  FROM test t1, test t2
  WHERE t1.start < t2.start - INTERVAL 1 DAY
) allRanges
GROUP BY `start`
```
```
Result
```
```
start       min( `end` )
2008-01-01  2008-12-31
2009-01-01  2010-12-31
2011-01-01  2012-12-31
2013-01-01  2014-12-31
```
```


q:
I have a bit of html like so:

<a href="#somthing" id="a1"><img src="something" /></a>
<a href="#somthing" id="a2"><img src="something" /></a>

I need to strip off the links so I'm just left with a couple of image tags. What would be the most efficient way to do this with jQuery?

[A]
```
```
$("a > img").parent()   // match all , select  parents
   .each( function()    // for each link
   {
      $(this).replaceWith(              // replace the
         $(this).children().remove() ); // with its detached children.
   });
```
```


q:
I have a module in the parent directory of my script and I would like to 'use' it.

If I do

use '../Foo.pm';

I get syntax errors.

I tried to do:

push @INC, '..';
use EPMS;

and .. apparently doesn't show up in @INC

I'm going crazy!  What's wrong here?

[A]
You have to have the
```
push
```
processed before the
```
use
```
is -- and
```
use
```
is processed early.  So, you'll need a
```
BEGIN { push @INC, ".."; }
```
to have a chance, I believe.


q:
Say if I have a dropdown in a form and I have another nested class inside of this class .
Now what's the best way to access this dropdown from the nested class?

[A]
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference.  Raymond Chen has an example describing the differences here :
C# nested classes are like C++ nested classes, not Java inner classes
.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
```
```
// C#
class OuterClass
{
    string s;
    // ...
    class InnerClass
    {
       OuterClass o_;
       public InnerClass(OuterClass o) { o_ = o; }
       public string GetOuterString() { return o_.s; }
    }
    void SomeFunction() {
        InnerClass i = new InnerClass(this);
        i.GetOuterString();
    }

}
```
```
Note that the InnerClass can access the "
```
s
```
" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "
```
string s;
```
" is
```
private
```
because no other access permission was specified.


q: How can I get Environnment variables and if something is missing, set the value?

[A]
Use the
System.Environment
class.
The methods
```
```
var value = System.Environment.GetEnvironmentVariable(variable [, Target])
```
```
and
```
```
System.Environment.SetEnvironmentVariable(variable, value [, Target])
```
```
will do the job for you.
The optional parameter
```
Target
```
is an enum of type
```
EnvironmentVariableTarget
```
and it can be one of:
```
Machine
```
,
```
Process
```
, or
```
User
```
. If you omit it, the default target is the
current process.


q: I'm programming something that allows users to store documents and pictures on a webserver, to be stored and retrieved later.  When users upload files to my server, PHP tells me what filetype it is based on the extension.  However, I'm afraid that users could rename a zip file as somezipfile.png and store it, thus keeping a zip file on my server.  Is there any reasonable way to open an uploaded file and "check" to see if it truly is of the said filetype?

[A]
Sort of. Most file types have some bytes reserved for marking them so that you don't have to rely on the extension.  The site
http://wotsit.org
is a great resource for finding this out for a particular type.
If you are on a unix system, I believe that the file command doesn't rely on the extension, so you could shell out to it if you don't want to write the byte checking code.
For PNG (
http://www.w3.org/TR/PNG-Rationale.html
)
The first eight bytes of a PNG file always contain the following values:
(decimal)              137  80  78  71  13  10  26  10
(hexadecimal)           89  50  4e  47  0d  0a  1a  0a
(ASCII C notation)    \211   P   N   G  \r  \n \032 \n


q:
I would like to access a class everywhere in my application, how can I do this?

To make it more clear, I have a class somewhere that use some code. I have an other class that use the same code. I do not want to duplicate so I would like to call the same code in both place by using something. In php I would just include("abc.php") in both... I do not want to create the object everytime I want to use the code.

[A]
The concept of global classes in C# is really just a simple matter of referencing the appropriate assembly containing the class. Once you have reference the needed assembly, you can refer to the class of choice either by it's fully qualified Type name, or by importing the namespace that contains the class. (
Concrete instance or Static access
to that class)
Or
You can have a
Singleton class
to use it everywhere but some people won't recommend you this way to proceed.


q:
RDBMS packages today offer a tremendous amount of functionality beyond standard data storage and retrieval.  SQL Server for example can send emails, expose web service methods, and execute CLR code amongst other capabilities.  However, I have always tried to limit the amount of processing my database server does to just data storage and retrieval as much as possible, for the following reasons:

A database server is harder to scale than web servers

In a lot of projects I've worked on, the DB server is a lot busier than the web servers, and thus has less spare capacity

It potentially exposes your database server to a security attack (web services for example)

My question is, how do you decide how much functionality or code should be implemented directly on your database server versus other servers in your architecture?  What recommendations do you have for people starting new projects?

[A]
The vendors have one set of best practices.  You, however, voice concerns with that.
Years ago I supported a
Major Software Product
. Major.
They said "The database is relational storage.  Nothing more."  Every user conference people would ask about stored procedure, triggers, and all that malarkey.
Their architect was firm.  As soon as you get away from plain-old-SQL, you've got a support and maintenance nightmare.  They did object-relational mapping from the DB into their product, and everything else was in their product.
This scales well.  Multiple application servers can easily share a single database server.


q:
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?

The regular expression should match any of the following:

RunFoo.py
RunBar.py
Run42.py

It should not match:

myRunFoo.py
RunBar.py1
Run42.txt

The SQL equivalent of what I am looking for is ... LIKE 'Run%.py' ....

[A]
This probably doesn't fully comply with file-naming standards, but here it goes:
```
```
/^Run[\w]*?\.py$/
```
```


q:
I have some System.Diagnotics.Processes to run.  I'd like to call the close method on them automatically.  Apparently the "using" keyword does this for me.

Is this the way to use the using keyword?

foreach(string command in S) // command is something like "c:\a.exe"
{
    try
    {
        using(p = Process.Start(command))
        {
            // I literally put nothing in here.
        }
    }
    catch (Exception e)
    {
        // notify of process failure
    }
}

I'd like to start multiple processes to run concurrently.

[A]
```
```
try
{
   foreach(string command in S) // command is something like "c:\a.exe"
   {
      using(p = Process.Start(command))
      {
        // I literally put nothing in here.
      }

    }
}
catch (Exception e)
{
    // notify of process failure
}
```
```
The reason it works is because when the exception happens, the variable p falls out of scope and thus it's Dispose method is called that closes the process is how that would go.  Additionally, I would think you'd want to spin a thread off for each command rather than wait for an executable to finish before going on to the next one.


q:
While working on a C# app I just noticed that in several places static initializers have dependencies on each other like this:

static private List<int> a = new List<int>() { 0 };
static private List<int> b = new List<int>() { a[0] };

Without doing anything special that worked. Is that just luck? Does C# have rules to resolve this?

Edit: (re: Panos) In a file lexical order seems to be king? what about across files?

In looking I tried a cyclical dependency like this:

static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { a[0] };

and the program didn't run the same (the test suit failed across the board and I didn't look further).

[A]
It seems to depend on the sequence of lines. This code works:
```
```
static private List<int> a = new List<int>() { 1 };
static private List<int> b = new List<int>() { a[0] };
```
```
while this code does not work (it throws a
```
NullReferenceException
```
)
```
```
static private List<int> a = new List<int>() { b[0] };
static private List<int> b = new List<int>() { 1 };
```
```
So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain...
EDIT - What's happening "across files"? If we declare these two classes:
```
```
public class A {
    public static List<int> a = new List<int>() { B.b[0] };
}
public class B {
    public static List<int> b = new List<int>() { A.a[0] };
}
```
```
and try to access them with this code:
```
```
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); }
try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); }
```
```
we are getting this output:
```
```
The type initializer for 'A' threw an exception.
Object reference not set to an instance of an object.
The type initializer for 'A' threw an exception.
```
```
So the initialization of
```
B
```
causes an exception in static constructor
```
A
```
and lefts field
```
a
```
with the default value (null). Since
```
a
```
is
```
null
```
,
```
b
```
can not also be initialized properly.
If we do not have cyclical dependencies, everything works fine.
EDIT: Just in case you didn't read the comments,
Jon Skeet
provides a very interesting reading:
The differences between static constructors and type initializers
.


q:
In ASP.NET, I have an XML file (within my project) that I would like to deserialize.  FileStream objects do not allow you to open a file via URL.

What is the easiest way to open the file so that I can deserialize it?

[A]
Generally, we put it all in one file. This isn't Java or C++.
Start with a single file until you get some more experience with Python.  Unless your files are gargantuan, it will work fine.
For example, Django encourages this style, so copy their formula for success.  One module for the model.  A module for each application; each application imports a common model.
Your Database and superclass stuff can be in your
```
__init__.py
```
file, since it applies to the entire package.  That may reduce some of the circularity.


q:
I am working on a web application that was recently converted from Visual Studio 2003 to Visual Studio 2008.  The application contained some web services that were written using the .NET 1.1 Framework and Web Service Enhancements 2.0.  They were converted to the .NET 3.5 framework using the VS 2008 Conversion Wizard Tool.

A client application which is still written using the .NET 1.1 framework has a reference to the updated web service and try to consume the web service and received the following error:

System.Web.Services.Protocols.SoapException: Server did not recognize the value of HTTP Header SOAPAction: (web service URI)

The URL Behavior is set to static for the reference and the proxy class inheritance was changed from System.Web.Services.Protocols.SoapHttpClientProtocol namespace to Microsoft.Web.Services2.WebServicesExtension namespace

If you need additional information or need to see some source code, please let me know.

[A]
Does the web service work otherwise?  Is it possible your new updated 2.0 web service exists in the same application domain as a 1.1 application?  In that case you'll want to make your own app-domain.
If its not local try using Fiddler to see everything that is going back and forth.


q:
There's a lot of interest these days in Erlang as a language for writing parallel programs on multicore. I've heard people argue that Erlang's message-passing model is easier to program than the dominant shared-memory models such as threads.

Conversely, in the high-performance computing community the dominant parallel programming model has been MPI, which also implements a message-passing model. But in the HPC world, this message-passing model is generally considered very difficult to program in, and people argue that shared memory models such as OpenMP or UPC are easier to program in.

Does anybody know why there is such a difference in the perception of message-passing vs. shared memory in the IT and HPC worlds? Is it due to some fundamental difference in how Erlang and MPI implement message passing that makes Erlang-style message-passing much easier than MPI? Or is there some other reason?

[A] Regarding MPI vs OpenMP/UPC: MPI forces you to slice the problem in small pieces and take responsibility for moving data around.  With OpenMP/UPC, "all the data is there", you just have to dereference a pointer.  The MPI advantage is that 32-512 CPU clusters are much cheaper than 32-512 CPU single machines.  Also, with MPI the expense is upfront, when you design the algorithm.  OpenMP/UPC can hide the latencies that you'll get at runtime, if your system uses NUMA (and all big systems do) - your program won't scale and it will take a while to figure out why.


q:
My company has login integration with GroupWise, and Exchange 5.5/2000+.  The Exchange 5.5/GroupWise logic is done using wldap32.dll (win32), and so the login code is in a managed c++ class.  When the configuration tool (or the backend service) tries to load the dll built off this managed c++ project on my XP development box, it works fine.  On QA/Customer Windows 2003 boxes, a FileLoadException is thrown.

First off, this used to work fine.  Secondly, I've validated the same working code on my box fails on the qa box.

How can I track down the cause of this exception?

[A]
Not to answer my own question, but support just updated the bug with the text following this paragraph.  I'm still interested in thoughts on tracking down situations like this.
Resolved by downloading and installing the Visual C++ 2008 Redistributable
Package for Windows on the IMS:
http://www.microsoft.com/downloads/details.aspx?FamilyID=a5c84275-3b97-4ab7-a40d-3802b2af5fc2&DisplayLang=en


q: I would like MATLAB to tell me if I have an input file (.m file) that contains some variables with their numbers (i.e., a = 5, b = 6, c = 7) so that I can then use that .m file in another program (main .m file) that uses these variables to calculate S = a + b + c. How can I then read the input file from the main file? Assume the input file is called INP and the main MAIN.

[A]
If your "input" file is an m-file, just use the name of the file in your "main" m-file.  For example you might have a file called input.m that looks like this:
```
```
% File: inputs.m
a = 5;
b = 6;
c = 7;
```
```
Then, you can use it in the file main.m like this:
```
```
% File: main.m
inputs;
S = a + b + c;
```
```


q:
I have a view that supports landscape and portrait viewing, with the controls all moving around when you switch from one to the other. I'm currently doing this by setting the .center of each one of my controls when the user rotates the phone. The problem is that this is tedious, and requires a lot of code, and seems to defeat the purpose of using Interface Builder in the first place.

My question is: is there a way in Interface Builder for one view to support multiple looks (one for landscape one for portrait)? If not how do other people do this with IB? Do you set up 2 views?

Edit: Just to clarify my landscape and portrait views look different, I don't want a straight transform, I actually display the data differently in landscape mode

[A] I'm not 100% sure if it's possible, but have you considered using different view controllers for landscape and portrait?


q:
Anyone know of a good memory/disk caching library for AIR? Extra points for being compatible with Flash CS3, and being free (as in beer).

I'd like to cache results of http requests: both binary and text (xml).

[A]
The
bulk-loader
project might have what you're looking for. I haven't used it myself but in the description it says (among other things):
Cache management
Various asset types (XML, NetStreams, Swfs, Images, Sound, Text Files)
From quickly looking at the code and some of the examples in the wiki it looks like it has memory (but not disk) caching capabilities.


q:
Is it possible to do something like this?

var pattern = /some regex segment/ + /* comment here */
    /another segment/;

Or do I have to use new RegExp() syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.

[A]
Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:
```
```
var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
              segment_part + /* that was defined just now */
              "another segment");
```
```
If you have two regular expression literals, you can in fact concatenate them using this technique:
```
```
var regex1 = /foo/g;
var regex2 = /bar/y;
var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
var regex3 = new RegExp(expression_one.source + expression_two.source, flags);
// regex3 is now /foobar/gy
```
```
It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.


q: I have months stored in SQL Server as 1,2,3,4,...12. I would like to display them as January,February etc. Is there a function in SQL Server like MonthName(1) = January? I am trying to avoid a CASE statement, if possible.

[A]
A little hacky but should work:
```
```
SELECT DATENAME(month, DATEADD(month, @mydate-1, CAST('2008-01-01' AS datetime)))
```
```


q: What is the largest heap you have personally used in a managed environment such as Java or .NET?  What were some of the performance issues you ran into, and did you end up getting a diminishing returns the larger the heap was?

[A]
I am unsure what you mean by heap,  but if you mean memory used, I have used quite a bit, 2GB+. I have a web app that does image processing and it requires loading 2 large scan files into memory to do analysis.
There were performance issues. Windows would swap out lots of ram, and then that would create a lot of page faults. There was never any need for anymore than 2 images at a time as all requests were gainst those images (I only allowed  1 session per image set at a time)
For instance, to setup the files for initial viewing would take about 5 seconds. Doing simple analysis and zooming would be fairly fast once in memory, in the order of .1 to .5 seconds.
I still had to optimize, so I ended up preparsung the files and chopping into smaller peices and worked only with the peices that were required by the user at the time.


q:
I would like to remove the domain/computer information from a login id in C#.  So, I would like to make either "Domain\me" or "Domain\me" just "me".  I could always check for the existence of either, and use that as the index to start the substring...but I am looking for something more elegant and compact.

Worse case scenario:

int startIndex = 0;
int indexOfSlashesSingle = ResourceLoginName.IndexOf("\");
int indexOfSlashesDouble = ResourceLoginName.IndexOf("\\");
if (indexOfSlashesSingle != -1)
    startIndex = indexOfSlashesSingle;
else
    startIndex = indexOfSlashesDouble;
string shortName = ResourceLoginName.Substring(startIndex, ResourceLoginName.Length-1);

[A]
I always do it this way:
```
```
string[] domainuser;
    string Auth_User = Request.ServerVariables["AUTH_USER"].ToString().ToLower();
    domainuser = Auth_User.Split('\\');
```
```
Now you can look at domainuser.Length to see how many parts are there and domainuser[0] for the domain and domainuser[1] for the username.


q:
This is an age-old question where given a table with attributes 'type', 'variety' and 'price', that you fetch the record with the minimum price for each type there is.

In SQL, we can do this by:

select f.type, f.variety, f.price
from (  select type, min(price) as minprice from table group by type ) as x
inner join table as f on f.type = x.type and f.price = x.minprice;`

We could perhaps imitate this by:

minprices = Table.minimum(:price, :group => type)
result = []
minprices.each_pair do |t, p|
   result << Table.find(:first, :conditions => ["type = ? and price = ?", t, p])
end

Is there a better implementation than this?

[A]
```
```
Table.minimum(:price, :group => :type)
```
```
See
http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html#method-i-minimum
for more.


q:
I couldn't really find this in Rails documentation but it seems like 'mattr_accessor' is the Module corollary for 'attr_accessor' (getter & setter) in a normal Ruby class.

Eg. in a class

class User
  attr_accessor :name

  def set_fullname
    @name = "#{self.first_name} #{self.last_name}"
  end
end

Eg. in a module

module Authentication
  mattr_accessor :current_user

  def login
    @current_user = session[:user_id] || nil
  end
end

This helper method is provided by ActiveSupport.

[A]
Rails extends Ruby with both
```
mattr_accessor
```
(Module accessor) and
```
cattr_accessor
```
(as well as _
```
reader
```
/
```
_writer
```
versions).  As Ruby's
```
attr_accessor
```
generates getter/setter methods for
instances
,
```
cattr/mattr_accessor
```
provide getter/setter methods at the
class
or
module
level.  Thus:
```
```
module Config
  mattr_accessor :hostname
  mattr_accessor :admin_email
end
```
```
is short for:
```
```
module Config
  def self.hostname
    @hostname
  end
  def self.hostname=(hostname)
    @hostname = hostname
  end
  def self.admin_email
    @admin_email
  end
  def self.admin_email=(admin_email)
    @admin_email = admin_email
  end
end
```
```
Both versions allow you to access the module-level variables like so:
```
```
>> Config.hostname = "example.com"
>> Config.admin_email = "admin@example.com"
>> Config.hostname # => "example.com"
>> Config.admin_email # => "admin@example.com"
```
```


q:
I wonder if this would be doable ? To insert an array into one field in the database.

For instance I have a title, I want to have that title with only one id, but it's going to be bilingually used on the website.

It feels a bit unnecessary to make another table to have their global ids and then another table with the actual titles linked to the table with the global id.

I just want to have something like this

ID      TITLE
1       Array("english title", "nederlandse titel");

I'm using PHP/MSYQL, so if it would be doable could you please explain in these languages.

Oh yeah I figured that I could format it funky and use the split function to turn it into an array again. But I wonder if I could just store it as an array right away, I case the user might type something with the same formatting (one out of a million)

[A]
There's really only two reasonable choices here:
Join with another table
pros: unlimited titles in unlimited languages
cons: join overhead is more computationally expensive, SQL is marginally more complex to update/insert etc
Multiple columns
eg: TITLE_EN, TITLE_NL, TITLE_DE
pros: fast to insert, select, etc
cons: limited number of languages, adding more is an ALTER TABLE
Given our two choices, you usually should should pick the first one.  Unless you're dealing with just an obscene amount of transactions that cannot be parallelized, or you absosmurfly can ensure that you will never add languages, the extra flexibility in schema layout will save you headaches in the long run.


q:
I am having a doubt in page_init, page preinit, load.
I need to know when we use this also where we need to call our objects in different stages of our life cycle.

Please let me know how they will process for each events raised

[A]
Its called the Page lifecycle because at different stages of the page request, different objects are populated with different information.
Here are some good links to read up on:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
http://www.15seconds.com/issue/020102.htm


q:
Has anybody been successful in integrating the Enterprise Library v4.0 with SharePoint WSS 3.0?  I created a very simple .ASPX page.  It's only purpose will to be to connect to an Oracle database and display some values in a DropDownList.  But right now, all it does is displays Hello World.  I've added the necessary references and everything compiles fine.  When I test the page, it displays Hello World.  But once I add the using Microsoft.Practices.EnterprisesLibrary.Data, the page no longer works. I just get the standard Unknown Error message.  Is there a log file I can check?

I'm looking for any steps or tips that I can use to get this up and running.  I use this Enterprise Library in all my ASP.NET applications and it works great.  Trying to get this to work in SharePoint seems like a natural fit.  But why does it seem so difficult?  And why does there seem to be a lack of information?

Anyways, thank you so much for any information anybody can provide.

[A]
Are you able to debug and see where the failure is occurring in your code?  Is it occurring on an Enterprise Library related call?  If so I would capture the exception that is being thrown and evaluate the message that it provides using; try {} catch (Exception ex) {}.
One thing I have seen with Enterprise Library that if it is not properly configured it will sometimes log messages to the Event Log on the server.
I'm sorry I can't get much more information without more technical details about your implementation.  I can assure you though that Enterprise Library works very well with SharePoint and that for the past few years I have used Enterprise Library in all of my SharePoint solution work.


q:
I have a UIImageView and the objective is to scale it down proportionally by giving it either a height or width.

UIImage *image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];

//Add image view
[self.view addSubview:imageView];

//set contentMode to scale aspect to fit
imageView.contentMode = UIViewContentModeScaleAspectFit;

//change width of frame
CGRect frame = imageView.frame;
frame.size.width = 100;
imageView.frame = frame;

The image did get resized but the position is not at the top left. What is the best approach to scaling image/imageView and how do I correct the position?

[A]
I think you can do something like
```
```
image.center = [[imageView window] center];
```
```


q:
I'd like to know if Flash/AS3 has any nice way to convert an AS3 'Date' object to/from rfc-850 timestamp format (as used by HTTP date and last-modified).

This question is very similar to this question about rfc 3339, except it's specific to AS3 and rfc-850.

RFC-850 is like: Thu, 09 Oct 2008 01:09:43 GMT

[A]
The
as3corelib
libraries have DateUtil.toRFC822() and DateUtil.parseRFC822() methods (among others). Don't know if these are exactly what you are looking for.
The specific docs for the DateUtil class is here:
http://as3corelib.googlecode.com/svn/trunk/docs/com/adobe/utils/DateUtil.html


q:
I'm trying to create a user control that allows users to make something like the following:

  <uc1:MyControl id="controlThing" runat="server">

    <uc1:BoundColumn id="column1" Column="Name" runat="server" />
    <uc1:CheckBoxBoundColumn id="column2" Column="Selector" runat="server" />
    <uc1:BoundColumn id="column3" Column="Description" runat="server" />

     ...etc

  </uc1:MyControl>

There are only certain controls I would allow, in addition to the fact that you can have many of any type. I can picture this in XSD, but I'm not entirely sure for ASP.NET.

My ASP.NET voodoo is drawing a blank right now.. any thoughts?

[A]
Is it possible for you to override an existing control such as a ListView or GridView? That's your simplest option.
But to create your own custom templated control you need to use ITemplate.
I haven't done one but a quick google returned this:
http://www.developerfusion.com/article/4410/in-depth-aspnet-using-adonet/2/
it looked good.
I have a book "Developing Microsoft ASP.NET Server Controls and Components" which covers it but I haven't read through it indepth yet (
http://www.amazon.com/exec/obidos/ASIN/0735615829/nikhilkothari-20
)


q:
How to parse the DOM and determine what row is selected in an ASP.NET ListView? I'm able to interact with the DOM via the HtmlElement in Silverlight, but I have not been able to locate a property indicating the row is selected.

For reference, this managed method works fine for an ASP.NET ListBox

var elm = HtmlPage.Document.GetElementById(ListBoxId);

foreach (var childElm in elm.Children)
{
    if (!((bool)childElm.GetProperty("Selected")))
    {
       continue;
    }
}

[A]
I don't have my dev environment up to test this, but could you call GetProperty('selectedIndex') on the ListBoxID element? Then from that you figure out which child is selected and return that child using the elm.Children.
Edit:
Got my dev environment up this morning and did some testing. Here is a code snippet that worked for me:
```
```
HtmlElement elem = HtmlPage.Document.GetElementById("testSelect");
int index = Convert.ToInt32(elem.GetProperty("selectedIndex"));
var options = (from c in elem.Children
              let he = c as HtmlElement
              where he.TagName == "option"
              select he).ToList();

output.Text = (string)options[index].GetProperty("innerText");
```
```
Of course, you'll have to change "textSelect" to the name of your html select element. The linq query is needed since the Children property is made up of ScriptableObjects and only about half of them are the option elements which is what you care about.


q:
I'm using the zlib.NET library to try and inflate files that are compressed by zlib (on a Linux box, perhaps).  Here's what I'm doing:

zlib.ZInputStream zinput =
    new zlib.ZInputStream(File.Open(path, FileMode.Open, FileAccess.Read));

while (stopByte != (data = zinput.ReadByte()))
{
  // check data here
}

zinput.Close();

The data bytes match the compressed data bytes, so I must be doing something wrong.

[A]
Other than failing to use a "using" statement to close the stream even in the face of an exception, that looks okay to me. Is the data definitely compressed? Are you able to decompress it with zlib on the linux box?
Having looked at the source code, it's pretty ghastly - a call to
```
int Read(buffer, offset, length)
```
will end up calling its internal
```
int Read()
```
method
```
length
```
times for example. Given that sort of shaky start, I'm not sure I'd trust the code particularly heavily, but I'd have expected it to work at least
slightly
! Have you tried using
SharpZipLib
?